Completed
Branch BUG/update-unit-tests (7b5400)
by
unknown
07:51 queued 05:38
created
form_sections/strategies/normalization/EE_Int_Normalization.strategy.php 2 patches
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -33,7 +33,7 @@  discard block
 block discarded – undo
33 33
         if (is_int($value_to_normalize) || is_float($value_to_normalize)) {
34 34
             return (int) $value_to_normalize;
35 35
         }
36
-        if (! is_string($value_to_normalize)) {
36
+        if ( ! is_string($value_to_normalize)) {
37 37
             throw new EE_Validation_Error(
38 38
                 sprintf(
39 39
                     esc_html__('The value "%s" must be a string submitted for normalization, it was %s', 'event_espresso'),
@@ -70,7 +70,7 @@  discard block
 block discarded – undo
70 70
         }
71 71
         // this really shouldn't ever happen because fields with a int normalization strategy
72 72
         // should also have a int validation strategy, but in case it doesn't use the default
73
-        if (! $validation_error_message) {
73
+        if ( ! $validation_error_message) {
74 74
             $default_validation_strategy = new EE_Int_Validation_Strategy();
75 75
             $validation_error_message = $default_validation_strategy->get_validation_error_message();
76 76
         }
Please login to merge, or discard this patch.
Indentation   +74 added lines, -74 removed lines patch added patch discarded remove patch
@@ -10,88 +10,88 @@
 block discarded – undo
10 10
  */
11 11
 class EE_Int_Normalization extends EE_Normalization_Strategy_Base
12 12
 {
13
-    /*
13
+	/*
14 14
      * regex pattern that matches for the following:
15 15
      *      * optional negative sign
16 16
      *      * one or more digits
17 17
      */
18
-    const REGEX = '/^(-?)(\d+)(?:\.0+)?$/';
18
+	const REGEX = '/^(-?)(\d+)(?:\.0+)?$/';
19 19
 
20 20
 
21 21
 
22
-    /**
23
-     * @param string $value_to_normalize
24
-     * @return int|mixed|string
25
-     * @throws \EE_Validation_Error
26
-     */
27
-    public function normalize($value_to_normalize)
28
-    {
29
-        if ($value_to_normalize === null) {
30
-            return null;
31
-        }
32
-        if (is_int($value_to_normalize) || is_float($value_to_normalize)) {
33
-            return (int) $value_to_normalize;
34
-        }
35
-        if (! is_string($value_to_normalize)) {
36
-            throw new EE_Validation_Error(
37
-                sprintf(
38
-                    esc_html__('The value "%s" must be a string submitted for normalization, it was %s', 'event_espresso'),
39
-                    print_r($value_to_normalize, true),
40
-                    gettype($value_to_normalize)
41
-                )
42
-            );
43
-        }
44
-        $value_to_normalize = filter_var(
45
-            $value_to_normalize,
46
-            FILTER_SANITIZE_NUMBER_FLOAT,
47
-            FILTER_FLAG_ALLOW_FRACTION
48
-        );
49
-        if ($value_to_normalize === '') {
50
-            return null;
51
-        }
52
-        $matches = array();
53
-        if (preg_match(EE_Int_Normalization::REGEX, $value_to_normalize, $matches)) {
54
-            if (count($matches) === 3) {
55
-                // if first match is the negative sign,
56
-                // then the number needs to be multiplied by -1 to remain negative
57
-                return $matches[1] === '-'
58
-                    ? (int) $matches[2] * -1
59
-                    : (int) $matches[2];
60
-            }
61
-        }
62
-        // find if this input has a int validation strategy
63
-        // in which case, use its message
64
-        $validation_error_message = null;
65
-        foreach ($this->_input->get_validation_strategies() as $validation_strategy) {
66
-            if ($validation_strategy instanceof EE_Int_Validation_Strategy) {
67
-                $validation_error_message = $validation_strategy->get_validation_error_message();
68
-            }
69
-        }
70
-        // this really shouldn't ever happen because fields with a int normalization strategy
71
-        // should also have a int validation strategy, but in case it doesn't use the default
72
-        if (! $validation_error_message) {
73
-            $default_validation_strategy = new EE_Int_Validation_Strategy();
74
-            $validation_error_message = $default_validation_strategy->get_validation_error_message();
75
-        }
76
-        throw new EE_Validation_Error($validation_error_message, 'numeric_only');
77
-    }
22
+	/**
23
+	 * @param string $value_to_normalize
24
+	 * @return int|mixed|string
25
+	 * @throws \EE_Validation_Error
26
+	 */
27
+	public function normalize($value_to_normalize)
28
+	{
29
+		if ($value_to_normalize === null) {
30
+			return null;
31
+		}
32
+		if (is_int($value_to_normalize) || is_float($value_to_normalize)) {
33
+			return (int) $value_to_normalize;
34
+		}
35
+		if (! is_string($value_to_normalize)) {
36
+			throw new EE_Validation_Error(
37
+				sprintf(
38
+					esc_html__('The value "%s" must be a string submitted for normalization, it was %s', 'event_espresso'),
39
+					print_r($value_to_normalize, true),
40
+					gettype($value_to_normalize)
41
+				)
42
+			);
43
+		}
44
+		$value_to_normalize = filter_var(
45
+			$value_to_normalize,
46
+			FILTER_SANITIZE_NUMBER_FLOAT,
47
+			FILTER_FLAG_ALLOW_FRACTION
48
+		);
49
+		if ($value_to_normalize === '') {
50
+			return null;
51
+		}
52
+		$matches = array();
53
+		if (preg_match(EE_Int_Normalization::REGEX, $value_to_normalize, $matches)) {
54
+			if (count($matches) === 3) {
55
+				// if first match is the negative sign,
56
+				// then the number needs to be multiplied by -1 to remain negative
57
+				return $matches[1] === '-'
58
+					? (int) $matches[2] * -1
59
+					: (int) $matches[2];
60
+			}
61
+		}
62
+		// find if this input has a int validation strategy
63
+		// in which case, use its message
64
+		$validation_error_message = null;
65
+		foreach ($this->_input->get_validation_strategies() as $validation_strategy) {
66
+			if ($validation_strategy instanceof EE_Int_Validation_Strategy) {
67
+				$validation_error_message = $validation_strategy->get_validation_error_message();
68
+			}
69
+		}
70
+		// this really shouldn't ever happen because fields with a int normalization strategy
71
+		// should also have a int validation strategy, but in case it doesn't use the default
72
+		if (! $validation_error_message) {
73
+			$default_validation_strategy = new EE_Int_Validation_Strategy();
74
+			$validation_error_message = $default_validation_strategy->get_validation_error_message();
75
+		}
76
+		throw new EE_Validation_Error($validation_error_message, 'numeric_only');
77
+	}
78 78
 
79 79
 
80 80
 
81
-    /**
82
-     * Converts the int into a string for use in teh html form
83
-     *
84
-     * @param int $normalized_value
85
-     * @return string
86
-     */
87
-    public function unnormalize($normalized_value)
88
-    {
89
-        if ($normalized_value === null || $normalized_value === '') {
90
-            return '';
91
-        }
92
-        if (empty($normalized_value)) {
93
-            return '0';
94
-        }
95
-        return "$normalized_value";
96
-    }
81
+	/**
82
+	 * Converts the int into a string for use in teh html form
83
+	 *
84
+	 * @param int $normalized_value
85
+	 * @return string
86
+	 */
87
+	public function unnormalize($normalized_value)
88
+	{
89
+		if ($normalized_value === null || $normalized_value === '') {
90
+			return '';
91
+		}
92
+		if (empty($normalized_value)) {
93
+			return '0';
94
+		}
95
+		return "$normalized_value";
96
+	}
97 97
 }
Please login to merge, or discard this patch.
core/libraries/form_sections/inputs/EE_Form_Input_Base.input.php 2 patches
Spacing   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -199,7 +199,7 @@  discard block
 block discarded – undo
199 199
         if (isset($input_args['validation_strategies'])) {
200 200
             foreach ((array) $input_args['validation_strategies'] as $validation_strategy) {
201 201
                 if ($validation_strategy instanceof EE_Validation_Strategy_Base && empty($input_args['ignore_input'])) {
202
-                    $this->_validation_strategies[ get_class($validation_strategy) ] = $validation_strategy;
202
+                    $this->_validation_strategies[get_class($validation_strategy)] = $validation_strategy;
203 203
                 }
204 204
             }
205 205
             unset($input_args['validation_strategies']);
@@ -210,7 +210,7 @@  discard block
 block discarded – undo
210 210
         // loop thru incoming options
211 211
         foreach ($input_args as $key => $value) {
212 212
             // add underscore to $key to match property names
213
-            $_key = '_' . $key;
213
+            $_key = '_'.$key;
214 214
             if (property_exists($this, $_key)) {
215 215
                 $this->{$_key} = $value;
216 216
             }
@@ -230,7 +230,7 @@  discard block
 block discarded – undo
230 230
         if (isset($input_args['ignore_input'])) {
231 231
             $this->_normalization_strategy = new EE_Null_Normalization();
232 232
         }
233
-        if (! $this->_normalization_strategy) {
233
+        if ( ! $this->_normalization_strategy) {
234 234
                 $this->_normalization_strategy = new EE_Text_Normalization();
235 235
         }
236 236
         $this->_normalization_strategy->_construct_finalize($this);
@@ -239,7 +239,7 @@  discard block
 block discarded – undo
239 239
             $this->set_default($input_args['default']);
240 240
             unset($input_args['default']);
241 241
         }
242
-        if (! $this->_sensitive_data_removal_strategy) {
242
+        if ( ! $this->_sensitive_data_removal_strategy) {
243 243
             $this->_sensitive_data_removal_strategy = new EE_No_Sensitive_Data_Removal();
244 244
         }
245 245
         $this->_sensitive_data_removal_strategy->_construct_finalize($this);
@@ -256,10 +256,10 @@  discard block
 block discarded – undo
256 256
      */
257 257
     protected function _set_default_html_name_if_empty()
258 258
     {
259
-        if (! $this->_html_name) {
259
+        if ( ! $this->_html_name) {
260 260
             $this->_html_name = $this->name();
261 261
             if ($this->_parent_section && $this->_parent_section instanceof EE_Form_Section_Proper) {
262
-                $this->_html_name = $this->_parent_section->html_name_prefix() . "[{$this->name()}]";
262
+                $this->_html_name = $this->_parent_section->html_name_prefix()."[{$this->name()}]";
263 263
             }
264 264
         }
265 265
     }
@@ -291,7 +291,7 @@  discard block
 block discarded – undo
291 291
     protected function _get_display_strategy()
292 292
     {
293 293
         $this->ensure_construct_finalized_called();
294
-        if (! $this->_display_strategy || ! $this->_display_strategy instanceof EE_Display_Strategy_Base) {
294
+        if ( ! $this->_display_strategy || ! $this->_display_strategy instanceof EE_Display_Strategy_Base) {
295 295
             throw new EE_Error(
296 296
                 sprintf(
297 297
                     esc_html__(
@@ -459,7 +459,7 @@  discard block
 block discarded – undo
459 459
                 $validation_strategy instanceof $validation_strategy_classname
460 460
                 || is_subclass_of($validation_strategy, $validation_strategy_classname)
461 461
             ) {
462
-                unset($this->_validation_strategies[ $key ]);
462
+                unset($this->_validation_strategies[$key]);
463 463
             }
464 464
         }
465 465
     }
@@ -670,7 +670,7 @@  discard block
 block discarded – undo
670 670
             if (is_array($raw_input)) {
671 671
                 $raw_value = array();
672 672
                 foreach ($raw_input as $key => $value) {
673
-                    $raw_value[ $key ] = $this->_sanitize($value);
673
+                    $raw_value[$key] = $this->_sanitize($value);
674 674
                 }
675 675
                 $this->_set_raw_value($raw_value);
676 676
             } else {
@@ -703,7 +703,7 @@  discard block
 block discarded – undo
703 703
      */
704 704
     public function html_label_id()
705 705
     {
706
-        return ! empty($this->_html_label_id) ? $this->_html_label_id : $this->html_id() . '-lbl';
706
+        return ! empty($this->_html_label_id) ? $this->_html_label_id : $this->html_id().'-lbl';
707 707
     }
708 708
 
709 709
 
@@ -853,9 +853,9 @@  discard block
 block discarded – undo
853 853
                 $validation_strategy->get_jquery_validation_rule_array()
854 854
             );
855 855
         }
856
-        if (! empty($jquery_validation_rules)) {
856
+        if ( ! empty($jquery_validation_rules)) {
857 857
             foreach ($this->get_display_strategy()->get_html_input_ids(true) as $html_id_with_pound_sign) {
858
-                $jquery_validation_js[ $html_id_with_pound_sign ] = $jquery_validation_rules;
858
+                $jquery_validation_js[$html_id_with_pound_sign] = $jquery_validation_rules;
859 859
             }
860 860
         }
861 861
         return $jquery_validation_js;
@@ -977,7 +977,7 @@  discard block
 block discarded – undo
977 977
     public function html_class($add_required = false)
978 978
     {
979 979
         return $add_required && $this->required()
980
-            ? $this->required_css_class() . ' ' . $this->_html_class
980
+            ? $this->required_css_class().' '.$this->_html_class
981 981
             : $this->_html_class;
982 982
     }
983 983
 
@@ -1052,7 +1052,7 @@  discard block
 block discarded – undo
1052 1052
                 $button_css_attributes .= '';
1053 1053
         }
1054 1054
         $this->_button_css_attributes .= ! empty($other_attributes)
1055
-            ? $button_css_attributes . ' ' . $other_attributes
1055
+            ? $button_css_attributes.' '.$other_attributes
1056 1056
             : $button_css_attributes;
1057 1057
     }
1058 1058
 
@@ -1090,8 +1090,8 @@  discard block
 block discarded – undo
1090 1090
         // now get the value for the input
1091 1091
         $value = $this->findRequestForSectionUsingNameParts($name_parts, $req_data);
1092 1092
         // check if this thing's name is at the TOP level of the request data
1093
-        if ($value === null && isset($req_data[ $this->name() ])) {
1094
-            $value = $req_data[ $this->name() ];
1093
+        if ($value === null && isset($req_data[$this->name()])) {
1094
+            $value = $req_data[$this->name()];
1095 1095
         }
1096 1096
         return $value;
1097 1097
     }
@@ -1133,13 +1133,13 @@  discard block
 block discarded – undo
1133 1133
     public function findRequestForSectionUsingNameParts($html_name_parts, $req_data)
1134 1134
     {
1135 1135
         $first_part_to_consider = array_shift($html_name_parts);
1136
-        if (isset($req_data[ $first_part_to_consider ])) {
1136
+        if (isset($req_data[$first_part_to_consider])) {
1137 1137
             if (empty($html_name_parts)) {
1138
-                return $req_data[ $first_part_to_consider ];
1138
+                return $req_data[$first_part_to_consider];
1139 1139
             } else {
1140 1140
                 return $this->findRequestForSectionUsingNameParts(
1141 1141
                     $html_name_parts,
1142
-                    $req_data[ $first_part_to_consider ]
1142
+                    $req_data[$first_part_to_consider]
1143 1143
                 );
1144 1144
             }
1145 1145
         } else {
Please login to merge, or discard this patch.
Indentation   +1257 added lines, -1257 removed lines patch added patch discarded remove patch
@@ -14,1261 +14,1261 @@
 block discarded – undo
14 14
  */
15 15
 abstract class EE_Form_Input_Base extends EE_Form_Section_Validatable
16 16
 {
17
-    /**
18
-     * the input's name attribute
19
-     *
20
-     * @var string
21
-     */
22
-    protected $_html_name;
23
-
24
-    /**
25
-     * id for the html label tag
26
-     *
27
-     * @var string
28
-     */
29
-    protected $_html_label_id;
30
-
31
-    /**
32
-     * class for teh html label tag
33
-     *
34
-     * @var string
35
-     */
36
-    protected $_html_label_class;
37
-
38
-    /**
39
-     * style for teh html label tag
40
-     *
41
-     * @var string
42
-     */
43
-    protected $_html_label_style;
44
-
45
-    /**
46
-     * text to be placed in the html label
47
-     *
48
-     * @var string
49
-     */
50
-    protected $_html_label_text;
51
-
52
-    /**
53
-     * the full html label. If used, all other html_label_* properties are invalid
54
-     *
55
-     * @var string
56
-     */
57
-    protected $_html_label;
58
-
59
-    /**
60
-     * HTML to use for help text (normally placed below form input), in a span which normally
61
-     * has a class of 'description'
62
-     *
63
-     * @var string
64
-     */
65
-    protected $_html_help_text;
66
-
67
-    /**
68
-     * CSS classes for displaying the help span
69
-     *
70
-     * @var string
71
-     */
72
-    protected $_html_help_class = 'description';
73
-
74
-    /**
75
-     * CSS to put in the style attribute on the help span
76
-     *
77
-     * @var string
78
-     */
79
-    protected $_html_help_style;
80
-
81
-    /**
82
-     * Stores whether or not this input's response is required.
83
-     * Because certain styling elements may also want to know that this
84
-     * input is required etc.
85
-     *
86
-     * @var boolean
87
-     */
88
-    protected $_required;
89
-
90
-    /**
91
-     * css class added to required inputs
92
-     *
93
-     * @var string
94
-     */
95
-    protected $_required_css_class = 'ee-required';
96
-
97
-    /**
98
-     * css styles applied to button type inputs
99
-     *
100
-     * @var string
101
-     */
102
-    protected $_button_css_attributes;
103
-
104
-    /**
105
-     * The raw post data submitted for this
106
-     * Generally unsafe for usage in client code
107
-     *
108
-     * @var mixed string or array
109
-     */
110
-    protected $_raw_value;
111
-
112
-    /**
113
-     * Value normalized according to the input's normalization strategy.
114
-     * The normalization strategy dictates whether this is a string, int, float,
115
-     * boolean, or array of any of those.
116
-     *
117
-     * @var mixed
118
-     */
119
-    protected $_normalized_value;
120
-
121
-
122
-    /**
123
-     * Normalized default value either initially set on the input, or provided by calling
124
-     * set_default().
125
-     * @var mixed
126
-     */
127
-    protected $_default;
128
-
129
-    /**
130
-     * Strategy used for displaying this field.
131
-     * Child classes must use _get_display_strategy to access it.
132
-     *
133
-     * @var EE_Display_Strategy_Base
134
-     */
135
-    private $_display_strategy;
136
-
137
-    /**
138
-     * Gets all the validation strategies used on this field
139
-     *
140
-     * @var EE_Validation_Strategy_Base[]
141
-     */
142
-    private $_validation_strategies = array();
143
-
144
-    /**
145
-     * The normalization strategy for this field
146
-     *
147
-     * @var EE_Normalization_Strategy_Base
148
-     */
149
-    private $_normalization_strategy;
150
-
151
-    /**
152
-     * Strategy for removing sensitive data after we're done with the form input
153
-     *
154
-     * @var EE_Sensitive_Data_Removal_Base
155
-     */
156
-    protected $_sensitive_data_removal_strategy;
157
-
158
-    /**
159
-     * Whether this input has been disabled or not.
160
-     * If it's disabled while rendering, an extra hidden input is added that indicates it has been knowingly disabled.
161
-     * (Client-side code that wants to dynamically disable it must also add this hidden input).
162
-     * When the form is submitted, if the input is disabled in the PHP form section, then input is ignored.
163
-     * If the input is missing from the request data but the hidden input indicating the input is disabled, then the input is again ignored.
164
-     *
165
-     * @var boolean
166
-     */
167
-    protected $disabled = false;
168
-
169
-
170
-
171
-    /**
172
-     * @param array                         $input_args       {
173
-     * @type string                         $html_name        the html name for the input
174
-     * @type string                         $html_label_id    the id attribute to give to the html label tag
175
-     * @type string                         $html_label_class the class attribute to give to the html label tag
176
-     * @type string                         $html_label_style the style attribute to give ot teh label tag
177
-     * @type string                         $html_label_text  the text to put in the label tag
178
-     * @type string                         $html_label       the full html label. If used,
179
-     *                                                        all other html_label_* args are invalid
180
-     * @type string                         $html_help_text   text to put in help element
181
-     * @type string                         $html_help_style  style attribute to give to teh help element
182
-     * @type string                         $html_help_class  class attribute to give to the help element
183
-     * @type string                         $default          default value NORMALIZED (eg, if providing the default
184
-     *       for a Yes_No_Input, you should provide TRUE or FALSE, not '1' or '0')
185
-     * @type EE_Display_Strategy_Base       $display          strategy
186
-     * @type EE_Normalization_Strategy_Base $normalization_strategy
187
-     * @type EE_Validation_Strategy_Base[]  $validation_strategies
188
-     * @type boolean                        $ignore_input special argument which can be used to avoid adding any validation strategies,
189
-     *                                                    and sets the normalization strategy to the Null normalization. This is good
190
-     *                                                    when you want the input to be totally ignored server-side (like when using
191
-     *                                                    React.js form inputs)
192
-     *                                                        }
193
-     */
194
-    public function __construct($input_args = array())
195
-    {
196
-        $input_args = (array) apply_filters('FHEE__EE_Form_Input_Base___construct__input_args', $input_args, $this);
197
-        // the following properties must be cast as arrays
198
-        if (isset($input_args['validation_strategies'])) {
199
-            foreach ((array) $input_args['validation_strategies'] as $validation_strategy) {
200
-                if ($validation_strategy instanceof EE_Validation_Strategy_Base && empty($input_args['ignore_input'])) {
201
-                    $this->_validation_strategies[ get_class($validation_strategy) ] = $validation_strategy;
202
-                }
203
-            }
204
-            unset($input_args['validation_strategies']);
205
-        }
206
-        if (isset($input_args['ignore_input'])) {
207
-            $this->_validation_strategies = array();
208
-        }
209
-        // loop thru incoming options
210
-        foreach ($input_args as $key => $value) {
211
-            // add underscore to $key to match property names
212
-            $_key = '_' . $key;
213
-            if (property_exists($this, $_key)) {
214
-                $this->{$_key} = $value;
215
-            }
216
-        }
217
-        // ensure that "required" is set correctly
218
-        $this->set_required(
219
-            $this->_required,
220
-            isset($input_args['required_validation_error_message'])
221
-            ? $input_args['required_validation_error_message']
222
-            : null
223
-        );
224
-        // $this->_html_name_specified = isset( $input_args['html_name'] ) ? TRUE : FALSE;
225
-        $this->_display_strategy->_construct_finalize($this);
226
-        foreach ($this->_validation_strategies as $validation_strategy) {
227
-            $validation_strategy->_construct_finalize($this);
228
-        }
229
-        if (isset($input_args['ignore_input'])) {
230
-            $this->_normalization_strategy = new EE_Null_Normalization();
231
-        }
232
-        if (! $this->_normalization_strategy) {
233
-                $this->_normalization_strategy = new EE_Text_Normalization();
234
-        }
235
-        $this->_normalization_strategy->_construct_finalize($this);
236
-        // at least we can use the normalization strategy to populate the default
237
-        if (isset($input_args['default'])) {
238
-            $this->set_default($input_args['default']);
239
-            unset($input_args['default']);
240
-        }
241
-        if (! $this->_sensitive_data_removal_strategy) {
242
-            $this->_sensitive_data_removal_strategy = new EE_No_Sensitive_Data_Removal();
243
-        }
244
-        $this->_sensitive_data_removal_strategy->_construct_finalize($this);
245
-        parent::__construct($input_args);
246
-    }
247
-
248
-
249
-
250
-    /**
251
-     * Sets the html_name to its default value, if none was specified in teh constructor.
252
-     * Calculation involves using the name and the parent's html_name
253
-     *
254
-     * @throws EE_Error
255
-     */
256
-    protected function _set_default_html_name_if_empty()
257
-    {
258
-        if (! $this->_html_name) {
259
-            $this->_html_name = $this->name();
260
-            if ($this->_parent_section && $this->_parent_section instanceof EE_Form_Section_Proper) {
261
-                $this->_html_name = $this->_parent_section->html_name_prefix() . "[{$this->name()}]";
262
-            }
263
-        }
264
-    }
265
-
266
-
267
-
268
-    /**
269
-     * @param $parent_form_section
270
-     * @param $name
271
-     * @throws EE_Error
272
-     */
273
-    public function _construct_finalize($parent_form_section, $name)
274
-    {
275
-        parent::_construct_finalize($parent_form_section, $name);
276
-        if ($this->_html_label === null && $this->_html_label_text === null) {
277
-            $this->_html_label_text = ucwords(str_replace("_", " ", $name));
278
-        }
279
-        do_action('AHEE__EE_Form_Input_Base___construct_finalize__end', $this, $parent_form_section, $name);
280
-    }
281
-
282
-
283
-
284
-    /**
285
-     * Returns the strategy for displaying this form input. If none is set, throws an exception.
286
-     *
287
-     * @return EE_Display_Strategy_Base
288
-     * @throws EE_Error
289
-     */
290
-    protected function _get_display_strategy()
291
-    {
292
-        $this->ensure_construct_finalized_called();
293
-        if (! $this->_display_strategy || ! $this->_display_strategy instanceof EE_Display_Strategy_Base) {
294
-            throw new EE_Error(
295
-                sprintf(
296
-                    esc_html__(
297
-                        "Cannot get display strategy for form input with name %s and id %s, because it has not been set in the constructor",
298
-                        "event_espresso"
299
-                    ),
300
-                    $this->html_name(),
301
-                    $this->html_id()
302
-                )
303
-            );
304
-        } else {
305
-            return $this->_display_strategy;
306
-        }
307
-    }
308
-
309
-
310
-
311
-    /**
312
-     * Sets the display strategy.
313
-     *
314
-     * @param EE_Display_Strategy_Base $strategy
315
-     */
316
-    protected function _set_display_strategy(EE_Display_Strategy_Base $strategy)
317
-    {
318
-        $this->_display_strategy = $strategy;
319
-    }
320
-
321
-
322
-
323
-    /**
324
-     * Sets the sanitization strategy
325
-     *
326
-     * @param EE_Normalization_Strategy_Base $strategy
327
-     */
328
-    protected function _set_normalization_strategy(EE_Normalization_Strategy_Base $strategy)
329
-    {
330
-        $this->_normalization_strategy = $strategy;
331
-    }
332
-
333
-
334
-
335
-    /**
336
-     * Gets sensitive_data_removal_strategy
337
-     *
338
-     * @return EE_Sensitive_Data_Removal_Base
339
-     */
340
-    public function get_sensitive_data_removal_strategy()
341
-    {
342
-        return $this->_sensitive_data_removal_strategy;
343
-    }
344
-
345
-
346
-
347
-    /**
348
-     * Sets sensitive_data_removal_strategy
349
-     *
350
-     * @param EE_Sensitive_Data_Removal_Base $sensitive_data_removal_strategy
351
-     * @return void
352
-     */
353
-    public function set_sensitive_data_removal_strategy($sensitive_data_removal_strategy)
354
-    {
355
-        $this->_sensitive_data_removal_strategy = $sensitive_data_removal_strategy;
356
-    }
357
-
358
-
359
-
360
-    /**
361
-     * Gets the display strategy for this input
362
-     *
363
-     * @return EE_Display_Strategy_Base
364
-     */
365
-    public function get_display_strategy()
366
-    {
367
-        return $this->_display_strategy;
368
-    }
369
-
370
-
371
-
372
-    /**
373
-     * Overwrites the display strategy
374
-     *
375
-     * @param EE_Display_Strategy_Base $display_strategy
376
-     */
377
-    public function set_display_strategy($display_strategy)
378
-    {
379
-        $this->_display_strategy = $display_strategy;
380
-        $this->_display_strategy->_construct_finalize($this);
381
-    }
382
-
383
-
384
-
385
-    /**
386
-     * Gets the normalization strategy set on this input
387
-     *
388
-     * @return EE_Normalization_Strategy_Base
389
-     */
390
-    public function get_normalization_strategy()
391
-    {
392
-        return $this->_normalization_strategy;
393
-    }
394
-
395
-
396
-
397
-    /**
398
-     * Overwrites the normalization strategy
399
-     *
400
-     * @param EE_Normalization_Strategy_Base $normalization_strategy
401
-     */
402
-    public function set_normalization_strategy($normalization_strategy)
403
-    {
404
-        $this->_normalization_strategy = $normalization_strategy;
405
-        $this->_normalization_strategy->_construct_finalize($this);
406
-    }
407
-
408
-
409
-
410
-    /**
411
-     * Returns all teh validation strategies which apply to this field, numerically indexed
412
-     *
413
-     * @return EE_Validation_Strategy_Base[]
414
-     */
415
-    public function get_validation_strategies()
416
-    {
417
-        return $this->_validation_strategies;
418
-    }
419
-
420
-
421
-
422
-    /**
423
-     * Adds this strategy to the field so it will be used in both JS validation and server-side validation
424
-     *
425
-     * @param EE_Validation_Strategy_Base $validation_strategy
426
-     * @return void
427
-     */
428
-    protected function _add_validation_strategy(EE_Validation_Strategy_Base $validation_strategy)
429
-    {
430
-        $validation_strategy->_construct_finalize($this);
431
-        $this->_validation_strategies[] = $validation_strategy;
432
-    }
433
-
434
-
435
-
436
-    /**
437
-     * Adds a new validation strategy onto the form input
438
-     *
439
-     * @param EE_Validation_Strategy_Base $validation_strategy
440
-     * @return void
441
-     */
442
-    public function add_validation_strategy(EE_Validation_Strategy_Base $validation_strategy)
443
-    {
444
-        $this->_add_validation_strategy($validation_strategy);
445
-    }
446
-
447
-
448
-
449
-    /**
450
-     * The classname of the validation strategy to remove
451
-     *
452
-     * @param string $validation_strategy_classname
453
-     */
454
-    public function remove_validation_strategy($validation_strategy_classname)
455
-    {
456
-        foreach ($this->_validation_strategies as $key => $validation_strategy) {
457
-            if (
458
-                $validation_strategy instanceof $validation_strategy_classname
459
-                || is_subclass_of($validation_strategy, $validation_strategy_classname)
460
-            ) {
461
-                unset($this->_validation_strategies[ $key ]);
462
-            }
463
-        }
464
-    }
465
-
466
-
467
-
468
-    /**
469
-     * returns true if input employs any of the validation strategy defined by the supplied array of classnames
470
-     *
471
-     * @param array $validation_strategy_classnames
472
-     * @return bool
473
-     */
474
-    public function has_validation_strategy($validation_strategy_classnames)
475
-    {
476
-        $validation_strategy_classnames = is_array($validation_strategy_classnames)
477
-            ? $validation_strategy_classnames
478
-            : array($validation_strategy_classnames);
479
-        foreach ($this->_validation_strategies as $key => $validation_strategy) {
480
-            if (in_array($key, $validation_strategy_classnames)) {
481
-                return true;
482
-            }
483
-        }
484
-        return false;
485
-    }
486
-
487
-
488
-
489
-    /**
490
-     * Gets the HTML
491
-     *
492
-     * @return string
493
-     */
494
-    public function get_html()
495
-    {
496
-        return $this->_parent_section->get_html_for_input($this);
497
-    }
498
-
499
-
500
-
501
-    /**
502
-     * Gets the HTML for the input itself (no label or errors) according to the
503
-     * input's display strategy
504
-     * Makes sure the JS and CSS are enqueued for it
505
-     *
506
-     * @return string
507
-     * @throws EE_Error
508
-     */
509
-    public function get_html_for_input()
510
-    {
511
-        return $this->_form_html_filter
512
-            ? $this->_form_html_filter->filterHtml(
513
-                $this->_get_display_strategy()->display(),
514
-                $this
515
-            )
516
-            : $this->_get_display_strategy()->display();
517
-    }
518
-
519
-
520
-
521
-    /**
522
-     * @return string
523
-     */
524
-    public function html_other_attributes()
525
-    {
526
-        EE_Error::doing_it_wrong(
527
-            __METHOD__,
528
-            sprintf(
529
-                esc_html__(
530
-                    'This method is no longer in use. You should replace it by %s',
531
-                    'event_espresso'
532
-                ),
533
-                'EE_Form_Section_Base::other_html_attributes()'
534
-            ),
535
-            '4.10.2.p'
536
-        );
537
-
538
-        return $this->other_html_attributes();
539
-    }
540
-
541
-
542
-
543
-    /**
544
-     * @param string $html_other_attributes
545
-     */
546
-    public function set_html_other_attributes($html_other_attributes)
547
-    {
548
-        EE_Error::doing_it_wrong(
549
-            __METHOD__,
550
-            sprintf(
551
-                esc_html__(
552
-                    'This method is no longer in use. You should replace it by %s',
553
-                    'event_espresso'
554
-                ),
555
-                'EE_Form_Section_Base::set_other_html_attributes()'
556
-            ),
557
-            '4.10.2.p'
558
-        );
559
-
560
-        $this->set_other_html_attributes($html_other_attributes);
561
-    }
562
-
563
-
564
-
565
-    /**
566
-     * Gets the HTML for displaying the label for this form input
567
-     * according to the form section's layout strategy
568
-     *
569
-     * @return string
570
-     */
571
-    public function get_html_for_label()
572
-    {
573
-        return $this->_parent_section->get_layout_strategy()->display_label($this);
574
-    }
575
-
576
-
577
-
578
-    /**
579
-     * Gets the HTML for displaying the errors section for this form input
580
-     * according to the form section's layout strategy
581
-     *
582
-     * @return string
583
-     */
584
-    public function get_html_for_errors()
585
-    {
586
-        return $this->_parent_section->get_layout_strategy()->display_errors($this);
587
-    }
588
-
589
-
590
-
591
-    /**
592
-     * Gets the HTML for displaying the help text for this form input
593
-     * according to the form section's layout strategy
594
-     *
595
-     * @return string
596
-     */
597
-    public function get_html_for_help()
598
-    {
599
-        return $this->_parent_section->get_layout_strategy()->display_help_text($this);
600
-    }
601
-
602
-
603
-
604
-    /**
605
-     * Validates the input's sanitized value (assumes _sanitize() has already been called)
606
-     * and returns whether or not the form input's submitted value is value
607
-     *
608
-     * @return boolean
609
-     */
610
-    protected function _validate()
611
-    {
612
-        if ($this->isDisabled()) {
613
-            return true;
614
-        }
615
-        foreach ($this->_validation_strategies as $validation_strategy) {
616
-            if ($validation_strategy instanceof EE_Validation_Strategy_Base) {
617
-                try {
618
-                    $validation_strategy->validate($this->normalized_value());
619
-                } catch (EE_Validation_Error $e) {
620
-                    $this->add_validation_error($e);
621
-                }
622
-            }
623
-        }
624
-        if ($this->get_validation_errors()) {
625
-            return false;
626
-        } else {
627
-            return true;
628
-        }
629
-    }
630
-
631
-
632
-
633
-    /**
634
-     * Performs basic sanitization on this value. But what sanitization can be performed anyways?
635
-     * This value MIGHT be allowed to have tags, so we can't really remove them.
636
-     *
637
-     * @param string $value
638
-     * @return null|string
639
-     */
640
-    protected function _sanitize($value)
641
-    {
642
-        return $value !== null ? stripslashes(html_entity_decode(trim($value))) : null;
643
-    }
644
-
645
-
646
-
647
-    /**
648
-     * Picks out the form value that relates to this form input,
649
-     * and stores it as the sanitized value on the form input, and sets the normalized value.
650
-     * Returns whether or not any validation errors occurred
651
-     *
652
-     * @param array $req_data
653
-     * @return boolean whether or not there was an error
654
-     * @throws EE_Error
655
-     */
656
-    protected function _normalize($req_data)
657
-    {
658
-        // any existing validation errors don't apply so clear them
659
-        $this->_validation_errors = array();
660
-        // if the input is disabled, ignore whatever input was sent in
661
-        if ($this->isDisabled()) {
662
-            $this->_set_raw_value(null);
663
-            $this->_set_normalized_value($this->get_default());
664
-            return false;
665
-        }
666
-        try {
667
-            $raw_input = $this->find_form_data_for_this_section($req_data);
668
-            // super simple sanitization for now
669
-            if (is_array($raw_input)) {
670
-                $raw_value = array();
671
-                foreach ($raw_input as $key => $value) {
672
-                    $raw_value[ $key ] = $this->_sanitize($value);
673
-                }
674
-                $this->_set_raw_value($raw_value);
675
-            } else {
676
-                $this->_set_raw_value($this->_sanitize($raw_input));
677
-            }
678
-            // we want to mostly leave the input alone in case we need to re-display it to the user
679
-            $this->_set_normalized_value($this->_normalization_strategy->normalize($this->raw_value()));
680
-            return false;
681
-        } catch (EE_Validation_Error $e) {
682
-            $this->add_validation_error($e);
683
-            return true;
684
-        }
685
-    }
686
-
687
-
688
-    /**
689
-     * @return string
690
-     * @throws EE_Error
691
-     */
692
-    public function html_name()
693
-    {
694
-        $this->_set_default_html_name_if_empty();
695
-        return $this->_html_name;
696
-    }
697
-
698
-
699
-    /**
700
-     * @return string
701
-     * @throws EE_Error
702
-     */
703
-    public function html_label_id()
704
-    {
705
-        return ! empty($this->_html_label_id) ? $this->_html_label_id : $this->html_id() . '-lbl';
706
-    }
707
-
708
-
709
-
710
-    /**
711
-     * @return string
712
-     */
713
-    public function html_label_class()
714
-    {
715
-        return $this->_html_label_class;
716
-    }
717
-
718
-
719
-
720
-    /**
721
-     * @return string
722
-     */
723
-    public function html_label_style()
724
-    {
725
-        return $this->_html_label_style;
726
-    }
727
-
728
-
729
-
730
-    /**
731
-     * @return string
732
-     */
733
-    public function html_label_text()
734
-    {
735
-        return $this->_html_label_text;
736
-    }
737
-
738
-
739
-
740
-    /**
741
-     * @return string
742
-     */
743
-    public function html_help_text()
744
-    {
745
-        return $this->_html_help_text;
746
-    }
747
-
748
-
749
-
750
-    /**
751
-     * @return string
752
-     */
753
-    public function html_help_class()
754
-    {
755
-        return $this->_html_help_class;
756
-    }
757
-
758
-
759
-
760
-    /**
761
-     * @return string
762
-     */
763
-    public function html_help_style()
764
-    {
765
-        return $this->_html_style;
766
-    }
767
-
768
-
769
-
770
-    /**
771
-     * returns the raw, UNSAFE, input, almost exactly as the user submitted it.
772
-     * Please note that almost all client code should instead use the normalized_value;
773
-     * or possibly raw_value_in_form (which prepares the string for displaying in an HTML attribute on a tag,
774
-     * mostly by escaping quotes)
775
-     * Note, we do not store the exact original value sent in the user's request because
776
-     * it may have malicious content, and we MIGHT want to store the form input in a transient or something...
777
-     * in which case, we would have stored the malicious content to our database.
778
-     *
779
-     * @return string
780
-     */
781
-    public function raw_value()
782
-    {
783
-        return $this->_raw_value;
784
-    }
785
-
786
-
787
-
788
-    /**
789
-     * Returns a string safe to usage in form inputs when displaying, because
790
-     * it escapes all html entities
791
-     *
792
-     * @return string
793
-     */
794
-    public function raw_value_in_form()
795
-    {
796
-        return htmlentities($this->raw_value(), ENT_QUOTES, 'UTF-8');
797
-    }
798
-
799
-
800
-
801
-    /**
802
-     * returns the value after it's been sanitized, and then converted into it's proper type
803
-     * in PHP. Eg, a string, an int, an array,
804
-     *
805
-     * @return mixed
806
-     */
807
-    public function normalized_value()
808
-    {
809
-        return $this->_normalized_value;
810
-    }
811
-
812
-
813
-
814
-    /**
815
-     * Returns the normalized value is a presentable way. By default this is just
816
-     * the normalized value by itself, but it can be overridden for when that's not
817
-     * the best thing to display
818
-     *
819
-     * @return string
820
-     */
821
-    public function pretty_value()
822
-    {
823
-        return $this->_normalized_value;
824
-    }
825
-
826
-
827
-
828
-    /**
829
-     * When generating the JS for the jquery validation rules like<br>
830
-     * <code>$( "#myform" ).validate({
831
-     * rules: {
832
-     * password: "required",
833
-     * password_again: {
834
-     * equalTo: "#password"
835
-     * }
836
-     * }
837
-     * });</code>
838
-     * if this field had the name 'password_again', it should return
839
-     * <br><code>password_again: {
840
-     * equalTo: "#password"
841
-     * }</code>
842
-     *
843
-     * @return array
844
-     */
845
-    public function get_jquery_validation_rules()
846
-    {
847
-        $jquery_validation_js = array();
848
-        $jquery_validation_rules = array();
849
-        foreach ($this->get_validation_strategies() as $validation_strategy) {
850
-            $jquery_validation_rules = array_replace_recursive(
851
-                $jquery_validation_rules,
852
-                $validation_strategy->get_jquery_validation_rule_array()
853
-            );
854
-        }
855
-        if (! empty($jquery_validation_rules)) {
856
-            foreach ($this->get_display_strategy()->get_html_input_ids(true) as $html_id_with_pound_sign) {
857
-                $jquery_validation_js[ $html_id_with_pound_sign ] = $jquery_validation_rules;
858
-            }
859
-        }
860
-        return $jquery_validation_js;
861
-    }
862
-
863
-
864
-
865
-    /**
866
-     * Sets the input's default value for use in displaying in the form. Note: value should be
867
-     * normalized (Eg, if providing a default of ra Yes_NO_Input you would provide TRUE or FALSE, not '1' or '0')
868
-     *
869
-     * @param mixed $value
870
-     * @return void
871
-     */
872
-    public function set_default($value)
873
-    {
874
-        $this->_default = $value;
875
-        $this->_set_normalized_value($value);
876
-        $this->_set_raw_value($value);
877
-    }
878
-
879
-
880
-
881
-    /**
882
-     * Sets the normalized value on this input
883
-     *
884
-     * @param mixed $value
885
-     */
886
-    protected function _set_normalized_value($value)
887
-    {
888
-        $this->_normalized_value = $value;
889
-    }
890
-
891
-
892
-
893
-    /**
894
-     * Sets the raw value on this input (ie, exactly as the user submitted it)
895
-     *
896
-     * @param mixed $value
897
-     */
898
-    protected function _set_raw_value($value)
899
-    {
900
-        $this->_raw_value = $this->_normalization_strategy->unnormalize($value);
901
-    }
902
-
903
-
904
-
905
-    /**
906
-     * Sets the HTML label text after it has already been defined
907
-     *
908
-     * @param string $label
909
-     * @return void
910
-     */
911
-    public function set_html_label_text($label)
912
-    {
913
-        $this->_html_label_text = $label;
914
-    }
915
-
916
-
917
-
918
-    /**
919
-     * Sets whether or not this field is required, and adjusts the validation strategy.
920
-     * If you want to use the EE_Conditionally_Required_Validation_Strategy,
921
-     * please add it as a validation strategy using add_validation_strategy as normal
922
-     *
923
-     * @param boolean $required boolean
924
-     * @param null    $required_text
925
-     */
926
-    public function set_required($required = true, $required_text = null)
927
-    {
928
-        $required = filter_var($required, FILTER_VALIDATE_BOOLEAN);
929
-        // whether $required is a string or a boolean, we want to add a required validation strategy
930
-        if ($required) {
931
-            $this->_add_validation_strategy(new EE_Required_Validation_Strategy($required_text));
932
-        } else {
933
-            $this->remove_validation_strategy('EE_Required_Validation_Strategy');
934
-        }
935
-        $this->_required = $required;
936
-    }
937
-
938
-
939
-
940
-    /**
941
-     * Returns whether or not this field is required
942
-     *
943
-     * @return boolean
944
-     */
945
-    public function required()
946
-    {
947
-        return $this->_required;
948
-    }
949
-
950
-
951
-
952
-    /**
953
-     * @param string $required_css_class
954
-     */
955
-    public function set_required_css_class($required_css_class)
956
-    {
957
-        $this->_required_css_class = $required_css_class;
958
-    }
959
-
960
-
961
-
962
-    /**
963
-     * @return string
964
-     */
965
-    public function required_css_class()
966
-    {
967
-        return $this->_required_css_class;
968
-    }
969
-
970
-
971
-
972
-    /**
973
-     * @param bool $add_required
974
-     * @return string
975
-     */
976
-    public function html_class($add_required = false)
977
-    {
978
-        return $add_required && $this->required()
979
-            ? $this->required_css_class() . ' ' . $this->_html_class
980
-            : $this->_html_class;
981
-    }
982
-
983
-
984
-    /**
985
-     * Sets the help text, in case
986
-     *
987
-     * @param string $text
988
-     */
989
-    public function set_html_help_text($text)
990
-    {
991
-        $this->_html_help_text = $text;
992
-    }
993
-
994
-
995
-
996
-    /**
997
-     * Uses the sensitive data removal strategy to remove the sensitive data from this
998
-     * input. If there is any kind of sensitive data removal on this input, we clear
999
-     * out the raw value completely
1000
-     *
1001
-     * @return void
1002
-     */
1003
-    public function clean_sensitive_data()
1004
-    {
1005
-        // if we do ANY kind of sensitive data removal on this, then just clear out the raw value
1006
-        // if we need more logic than this we'll make a strategy for it
1007
-        if (
1008
-            $this->_sensitive_data_removal_strategy
1009
-            && ! $this->_sensitive_data_removal_strategy instanceof EE_No_Sensitive_Data_Removal
1010
-        ) {
1011
-            $this->_set_raw_value(null);
1012
-        }
1013
-        // and clean the normalized value according to the appropriate strategy
1014
-        $this->_set_normalized_value(
1015
-            $this->get_sensitive_data_removal_strategy()->remove_sensitive_data(
1016
-                $this->_normalized_value
1017
-            )
1018
-        );
1019
-    }
1020
-
1021
-
1022
-
1023
-    /**
1024
-     * @param bool   $primary
1025
-     * @param string $button_size
1026
-     * @param string $other_attributes
1027
-     */
1028
-    public function set_button_css_attributes($primary = true, $button_size = '', $other_attributes = '')
1029
-    {
1030
-        $button_css_attributes = 'button';
1031
-        $button_css_attributes .= $primary === true ? ' button-primary' : ' button-secondary';
1032
-        switch ($button_size) {
1033
-            case 'xs':
1034
-            case 'extra-small':
1035
-                $button_css_attributes .= ' button-xs';
1036
-                break;
1037
-            case 'sm':
1038
-            case 'small':
1039
-                $button_css_attributes .= ' button-sm';
1040
-                break;
1041
-            case 'lg':
1042
-            case 'large':
1043
-                $button_css_attributes .= ' button-lg';
1044
-                break;
1045
-            case 'block':
1046
-                $button_css_attributes .= ' button-block';
1047
-                break;
1048
-            case 'md':
1049
-            case 'medium':
1050
-            default:
1051
-                $button_css_attributes .= '';
1052
-        }
1053
-        $this->_button_css_attributes .= ! empty($other_attributes)
1054
-            ? $button_css_attributes . ' ' . $other_attributes
1055
-            : $button_css_attributes;
1056
-    }
1057
-
1058
-
1059
-
1060
-    /**
1061
-     * @return string
1062
-     */
1063
-    public function button_css_attributes()
1064
-    {
1065
-        if (empty($this->_button_css_attributes)) {
1066
-            $this->set_button_css_attributes();
1067
-        }
1068
-        return $this->_button_css_attributes;
1069
-    }
1070
-
1071
-
1072
-
1073
-    /**
1074
-     * find_form_data_for_this_section
1075
-     * using this section's name and its parents, finds the value of the form data that corresponds to it.
1076
-     * For example, if this form section's HTML name is my_form[subform][form_input_1],
1077
-     * then it's value should be in request at request['my_form']['subform']['form_input_1'].
1078
-     * (If that doesn't exist, we also check for this subsection's name
1079
-     * at the TOP LEVEL of the request data. Eg request['form_input_1'].)
1080
-     * This function finds its value in the form.
1081
-     *
1082
-     * @param array $req_data
1083
-     * @return mixed whatever the raw value of this form section is in the request data
1084
-     * @throws EE_Error
1085
-     */
1086
-    public function find_form_data_for_this_section($req_data)
1087
-    {
1088
-        $name_parts = $this->getInputNameParts();
1089
-        // now get the value for the input
1090
-        $value = $this->findRequestForSectionUsingNameParts($name_parts, $req_data);
1091
-        // check if this thing's name is at the TOP level of the request data
1092
-        if ($value === null && isset($req_data[ $this->name() ])) {
1093
-            $value = $req_data[ $this->name() ];
1094
-        }
1095
-        return $value;
1096
-    }
1097
-
1098
-
1099
-    /**
1100
-     * If this input's name is something like "foo[bar][baz]"
1101
-     * returns an array like `array('foo','bar',baz')`
1102
-     *
1103
-     * @return array
1104
-     * @throws EE_Error
1105
-     */
1106
-    protected function getInputNameParts()
1107
-    {
1108
-        // break up the html name by "[]"
1109
-        if (strpos($this->html_name(), '[') !== false) {
1110
-            $before_any_brackets = substr($this->html_name(), 0, strpos($this->html_name(), '['));
1111
-        } else {
1112
-            $before_any_brackets = $this->html_name();
1113
-        }
1114
-        // grab all of the segments
1115
-        preg_match_all('~\[([^]]*)\]~', $this->html_name(), $matches);
1116
-        if (isset($matches[1]) && is_array($matches[1])) {
1117
-            $name_parts = $matches[1];
1118
-            array_unshift($name_parts, $before_any_brackets);
1119
-        } else {
1120
-            $name_parts = array($before_any_brackets);
1121
-        }
1122
-        return $name_parts;
1123
-    }
1124
-
1125
-
1126
-
1127
-    /**
1128
-     * @param array $html_name_parts
1129
-     * @param array $req_data
1130
-     * @return array | NULL
1131
-     */
1132
-    public function findRequestForSectionUsingNameParts($html_name_parts, $req_data)
1133
-    {
1134
-        $first_part_to_consider = array_shift($html_name_parts);
1135
-        if (isset($req_data[ $first_part_to_consider ])) {
1136
-            if (empty($html_name_parts)) {
1137
-                return $req_data[ $first_part_to_consider ];
1138
-            } else {
1139
-                return $this->findRequestForSectionUsingNameParts(
1140
-                    $html_name_parts,
1141
-                    $req_data[ $first_part_to_consider ]
1142
-                );
1143
-            }
1144
-        } else {
1145
-            return null;
1146
-        }
1147
-    }
1148
-
1149
-
1150
-
1151
-    /**
1152
-     * Checks if this form input's data is in the request data
1153
-     *
1154
-     * @param array $req_data
1155
-     * @return boolean
1156
-     * @throws EE_Error
1157
-     */
1158
-    public function form_data_present_in($req_data = null)
1159
-    {
1160
-        if ($req_data === null) {
1161
-            /** @var RequestInterface $request */
1162
-            $request = LoaderFactory::getLoader()->getShared(RequestInterface::class);
1163
-            $req_data = $request->postParams();
1164
-        }
1165
-        $checked_value = $this->find_form_data_for_this_section($req_data);
1166
-        if ($checked_value !== null) {
1167
-            return true;
1168
-        } else {
1169
-            return false;
1170
-        }
1171
-    }
1172
-
1173
-
1174
-
1175
-    /**
1176
-     * Overrides parent to add js data from validation and display strategies
1177
-     *
1178
-     * @param array $form_other_js_data
1179
-     * @return array
1180
-     */
1181
-    public function get_other_js_data($form_other_js_data = array())
1182
-    {
1183
-        return $this->get_other_js_data_from_strategies($form_other_js_data);
1184
-    }
1185
-
1186
-
1187
-
1188
-    /**
1189
-     * Gets other JS data for localization from this input's strategies, like
1190
-     * the validation strategies and the display strategy
1191
-     *
1192
-     * @param array $form_other_js_data
1193
-     * @return array
1194
-     */
1195
-    public function get_other_js_data_from_strategies($form_other_js_data = array())
1196
-    {
1197
-        $form_other_js_data = $this->get_display_strategy()->get_other_js_data($form_other_js_data);
1198
-        foreach ($this->get_validation_strategies() as $validation_strategy) {
1199
-            $form_other_js_data = $validation_strategy->get_other_js_data($form_other_js_data);
1200
-        }
1201
-        return $form_other_js_data;
1202
-    }
1203
-
1204
-
1205
-
1206
-    /**
1207
-     * Override parent because we want to give our strategies an opportunity to enqueue some js and css
1208
-     *
1209
-     * @return void
1210
-     */
1211
-    public function enqueue_js()
1212
-    {
1213
-        // ask our display strategy and validation strategies if they have js to enqueue
1214
-        $this->enqueue_js_from_strategies();
1215
-    }
1216
-
1217
-
1218
-
1219
-    /**
1220
-     * Tells strategies when its ok to enqueue their js and css
1221
-     *
1222
-     * @return void
1223
-     */
1224
-    public function enqueue_js_from_strategies()
1225
-    {
1226
-        $this->get_display_strategy()->enqueue_js();
1227
-        foreach ($this->get_validation_strategies() as $validation_strategy) {
1228
-            $validation_strategy->enqueue_js();
1229
-        }
1230
-    }
1231
-
1232
-
1233
-
1234
-    /**
1235
-     * Gets the default value set on the input (not the current value, which may have been
1236
-     * changed because of a form submission). If no default was set, this us null.
1237
-     * @return mixed
1238
-     */
1239
-    public function get_default()
1240
-    {
1241
-        return $this->_default;
1242
-    }
1243
-
1244
-
1245
-
1246
-    /**
1247
-     * Makes this input disabled. That means it will have the HTML attribute 'disabled="disabled"',
1248
-     * and server-side if any input was received it will be ignored
1249
-     */
1250
-    public function disable($disable = true)
1251
-    {
1252
-        $disabled_attribute = ' disabled="disabled"';
1253
-        $this->disabled = filter_var($disable, FILTER_VALIDATE_BOOLEAN);
1254
-        if ($this->disabled) {
1255
-            if (strpos($this->_other_html_attributes, $disabled_attribute) === false) {
1256
-                $this->_other_html_attributes .= $disabled_attribute;
1257
-            }
1258
-            $this->_set_normalized_value($this->get_default());
1259
-        } else {
1260
-            $this->_other_html_attributes = str_replace($disabled_attribute, '', $this->_other_html_attributes);
1261
-        }
1262
-    }
1263
-
1264
-
1265
-
1266
-    /**
1267
-     * Returns whether or not this input is currently disabled.
1268
-     * @return bool
1269
-     */
1270
-    public function isDisabled()
1271
-    {
1272
-        return $this->disabled;
1273
-    }
17
+	/**
18
+	 * the input's name attribute
19
+	 *
20
+	 * @var string
21
+	 */
22
+	protected $_html_name;
23
+
24
+	/**
25
+	 * id for the html label tag
26
+	 *
27
+	 * @var string
28
+	 */
29
+	protected $_html_label_id;
30
+
31
+	/**
32
+	 * class for teh html label tag
33
+	 *
34
+	 * @var string
35
+	 */
36
+	protected $_html_label_class;
37
+
38
+	/**
39
+	 * style for teh html label tag
40
+	 *
41
+	 * @var string
42
+	 */
43
+	protected $_html_label_style;
44
+
45
+	/**
46
+	 * text to be placed in the html label
47
+	 *
48
+	 * @var string
49
+	 */
50
+	protected $_html_label_text;
51
+
52
+	/**
53
+	 * the full html label. If used, all other html_label_* properties are invalid
54
+	 *
55
+	 * @var string
56
+	 */
57
+	protected $_html_label;
58
+
59
+	/**
60
+	 * HTML to use for help text (normally placed below form input), in a span which normally
61
+	 * has a class of 'description'
62
+	 *
63
+	 * @var string
64
+	 */
65
+	protected $_html_help_text;
66
+
67
+	/**
68
+	 * CSS classes for displaying the help span
69
+	 *
70
+	 * @var string
71
+	 */
72
+	protected $_html_help_class = 'description';
73
+
74
+	/**
75
+	 * CSS to put in the style attribute on the help span
76
+	 *
77
+	 * @var string
78
+	 */
79
+	protected $_html_help_style;
80
+
81
+	/**
82
+	 * Stores whether or not this input's response is required.
83
+	 * Because certain styling elements may also want to know that this
84
+	 * input is required etc.
85
+	 *
86
+	 * @var boolean
87
+	 */
88
+	protected $_required;
89
+
90
+	/**
91
+	 * css class added to required inputs
92
+	 *
93
+	 * @var string
94
+	 */
95
+	protected $_required_css_class = 'ee-required';
96
+
97
+	/**
98
+	 * css styles applied to button type inputs
99
+	 *
100
+	 * @var string
101
+	 */
102
+	protected $_button_css_attributes;
103
+
104
+	/**
105
+	 * The raw post data submitted for this
106
+	 * Generally unsafe for usage in client code
107
+	 *
108
+	 * @var mixed string or array
109
+	 */
110
+	protected $_raw_value;
111
+
112
+	/**
113
+	 * Value normalized according to the input's normalization strategy.
114
+	 * The normalization strategy dictates whether this is a string, int, float,
115
+	 * boolean, or array of any of those.
116
+	 *
117
+	 * @var mixed
118
+	 */
119
+	protected $_normalized_value;
120
+
121
+
122
+	/**
123
+	 * Normalized default value either initially set on the input, or provided by calling
124
+	 * set_default().
125
+	 * @var mixed
126
+	 */
127
+	protected $_default;
128
+
129
+	/**
130
+	 * Strategy used for displaying this field.
131
+	 * Child classes must use _get_display_strategy to access it.
132
+	 *
133
+	 * @var EE_Display_Strategy_Base
134
+	 */
135
+	private $_display_strategy;
136
+
137
+	/**
138
+	 * Gets all the validation strategies used on this field
139
+	 *
140
+	 * @var EE_Validation_Strategy_Base[]
141
+	 */
142
+	private $_validation_strategies = array();
143
+
144
+	/**
145
+	 * The normalization strategy for this field
146
+	 *
147
+	 * @var EE_Normalization_Strategy_Base
148
+	 */
149
+	private $_normalization_strategy;
150
+
151
+	/**
152
+	 * Strategy for removing sensitive data after we're done with the form input
153
+	 *
154
+	 * @var EE_Sensitive_Data_Removal_Base
155
+	 */
156
+	protected $_sensitive_data_removal_strategy;
157
+
158
+	/**
159
+	 * Whether this input has been disabled or not.
160
+	 * If it's disabled while rendering, an extra hidden input is added that indicates it has been knowingly disabled.
161
+	 * (Client-side code that wants to dynamically disable it must also add this hidden input).
162
+	 * When the form is submitted, if the input is disabled in the PHP form section, then input is ignored.
163
+	 * If the input is missing from the request data but the hidden input indicating the input is disabled, then the input is again ignored.
164
+	 *
165
+	 * @var boolean
166
+	 */
167
+	protected $disabled = false;
168
+
169
+
170
+
171
+	/**
172
+	 * @param array                         $input_args       {
173
+	 * @type string                         $html_name        the html name for the input
174
+	 * @type string                         $html_label_id    the id attribute to give to the html label tag
175
+	 * @type string                         $html_label_class the class attribute to give to the html label tag
176
+	 * @type string                         $html_label_style the style attribute to give ot teh label tag
177
+	 * @type string                         $html_label_text  the text to put in the label tag
178
+	 * @type string                         $html_label       the full html label. If used,
179
+	 *                                                        all other html_label_* args are invalid
180
+	 * @type string                         $html_help_text   text to put in help element
181
+	 * @type string                         $html_help_style  style attribute to give to teh help element
182
+	 * @type string                         $html_help_class  class attribute to give to the help element
183
+	 * @type string                         $default          default value NORMALIZED (eg, if providing the default
184
+	 *       for a Yes_No_Input, you should provide TRUE or FALSE, not '1' or '0')
185
+	 * @type EE_Display_Strategy_Base       $display          strategy
186
+	 * @type EE_Normalization_Strategy_Base $normalization_strategy
187
+	 * @type EE_Validation_Strategy_Base[]  $validation_strategies
188
+	 * @type boolean                        $ignore_input special argument which can be used to avoid adding any validation strategies,
189
+	 *                                                    and sets the normalization strategy to the Null normalization. This is good
190
+	 *                                                    when you want the input to be totally ignored server-side (like when using
191
+	 *                                                    React.js form inputs)
192
+	 *                                                        }
193
+	 */
194
+	public function __construct($input_args = array())
195
+	{
196
+		$input_args = (array) apply_filters('FHEE__EE_Form_Input_Base___construct__input_args', $input_args, $this);
197
+		// the following properties must be cast as arrays
198
+		if (isset($input_args['validation_strategies'])) {
199
+			foreach ((array) $input_args['validation_strategies'] as $validation_strategy) {
200
+				if ($validation_strategy instanceof EE_Validation_Strategy_Base && empty($input_args['ignore_input'])) {
201
+					$this->_validation_strategies[ get_class($validation_strategy) ] = $validation_strategy;
202
+				}
203
+			}
204
+			unset($input_args['validation_strategies']);
205
+		}
206
+		if (isset($input_args['ignore_input'])) {
207
+			$this->_validation_strategies = array();
208
+		}
209
+		// loop thru incoming options
210
+		foreach ($input_args as $key => $value) {
211
+			// add underscore to $key to match property names
212
+			$_key = '_' . $key;
213
+			if (property_exists($this, $_key)) {
214
+				$this->{$_key} = $value;
215
+			}
216
+		}
217
+		// ensure that "required" is set correctly
218
+		$this->set_required(
219
+			$this->_required,
220
+			isset($input_args['required_validation_error_message'])
221
+			? $input_args['required_validation_error_message']
222
+			: null
223
+		);
224
+		// $this->_html_name_specified = isset( $input_args['html_name'] ) ? TRUE : FALSE;
225
+		$this->_display_strategy->_construct_finalize($this);
226
+		foreach ($this->_validation_strategies as $validation_strategy) {
227
+			$validation_strategy->_construct_finalize($this);
228
+		}
229
+		if (isset($input_args['ignore_input'])) {
230
+			$this->_normalization_strategy = new EE_Null_Normalization();
231
+		}
232
+		if (! $this->_normalization_strategy) {
233
+				$this->_normalization_strategy = new EE_Text_Normalization();
234
+		}
235
+		$this->_normalization_strategy->_construct_finalize($this);
236
+		// at least we can use the normalization strategy to populate the default
237
+		if (isset($input_args['default'])) {
238
+			$this->set_default($input_args['default']);
239
+			unset($input_args['default']);
240
+		}
241
+		if (! $this->_sensitive_data_removal_strategy) {
242
+			$this->_sensitive_data_removal_strategy = new EE_No_Sensitive_Data_Removal();
243
+		}
244
+		$this->_sensitive_data_removal_strategy->_construct_finalize($this);
245
+		parent::__construct($input_args);
246
+	}
247
+
248
+
249
+
250
+	/**
251
+	 * Sets the html_name to its default value, if none was specified in teh constructor.
252
+	 * Calculation involves using the name and the parent's html_name
253
+	 *
254
+	 * @throws EE_Error
255
+	 */
256
+	protected function _set_default_html_name_if_empty()
257
+	{
258
+		if (! $this->_html_name) {
259
+			$this->_html_name = $this->name();
260
+			if ($this->_parent_section && $this->_parent_section instanceof EE_Form_Section_Proper) {
261
+				$this->_html_name = $this->_parent_section->html_name_prefix() . "[{$this->name()}]";
262
+			}
263
+		}
264
+	}
265
+
266
+
267
+
268
+	/**
269
+	 * @param $parent_form_section
270
+	 * @param $name
271
+	 * @throws EE_Error
272
+	 */
273
+	public function _construct_finalize($parent_form_section, $name)
274
+	{
275
+		parent::_construct_finalize($parent_form_section, $name);
276
+		if ($this->_html_label === null && $this->_html_label_text === null) {
277
+			$this->_html_label_text = ucwords(str_replace("_", " ", $name));
278
+		}
279
+		do_action('AHEE__EE_Form_Input_Base___construct_finalize__end', $this, $parent_form_section, $name);
280
+	}
281
+
282
+
283
+
284
+	/**
285
+	 * Returns the strategy for displaying this form input. If none is set, throws an exception.
286
+	 *
287
+	 * @return EE_Display_Strategy_Base
288
+	 * @throws EE_Error
289
+	 */
290
+	protected function _get_display_strategy()
291
+	{
292
+		$this->ensure_construct_finalized_called();
293
+		if (! $this->_display_strategy || ! $this->_display_strategy instanceof EE_Display_Strategy_Base) {
294
+			throw new EE_Error(
295
+				sprintf(
296
+					esc_html__(
297
+						"Cannot get display strategy for form input with name %s and id %s, because it has not been set in the constructor",
298
+						"event_espresso"
299
+					),
300
+					$this->html_name(),
301
+					$this->html_id()
302
+				)
303
+			);
304
+		} else {
305
+			return $this->_display_strategy;
306
+		}
307
+	}
308
+
309
+
310
+
311
+	/**
312
+	 * Sets the display strategy.
313
+	 *
314
+	 * @param EE_Display_Strategy_Base $strategy
315
+	 */
316
+	protected function _set_display_strategy(EE_Display_Strategy_Base $strategy)
317
+	{
318
+		$this->_display_strategy = $strategy;
319
+	}
320
+
321
+
322
+
323
+	/**
324
+	 * Sets the sanitization strategy
325
+	 *
326
+	 * @param EE_Normalization_Strategy_Base $strategy
327
+	 */
328
+	protected function _set_normalization_strategy(EE_Normalization_Strategy_Base $strategy)
329
+	{
330
+		$this->_normalization_strategy = $strategy;
331
+	}
332
+
333
+
334
+
335
+	/**
336
+	 * Gets sensitive_data_removal_strategy
337
+	 *
338
+	 * @return EE_Sensitive_Data_Removal_Base
339
+	 */
340
+	public function get_sensitive_data_removal_strategy()
341
+	{
342
+		return $this->_sensitive_data_removal_strategy;
343
+	}
344
+
345
+
346
+
347
+	/**
348
+	 * Sets sensitive_data_removal_strategy
349
+	 *
350
+	 * @param EE_Sensitive_Data_Removal_Base $sensitive_data_removal_strategy
351
+	 * @return void
352
+	 */
353
+	public function set_sensitive_data_removal_strategy($sensitive_data_removal_strategy)
354
+	{
355
+		$this->_sensitive_data_removal_strategy = $sensitive_data_removal_strategy;
356
+	}
357
+
358
+
359
+
360
+	/**
361
+	 * Gets the display strategy for this input
362
+	 *
363
+	 * @return EE_Display_Strategy_Base
364
+	 */
365
+	public function get_display_strategy()
366
+	{
367
+		return $this->_display_strategy;
368
+	}
369
+
370
+
371
+
372
+	/**
373
+	 * Overwrites the display strategy
374
+	 *
375
+	 * @param EE_Display_Strategy_Base $display_strategy
376
+	 */
377
+	public function set_display_strategy($display_strategy)
378
+	{
379
+		$this->_display_strategy = $display_strategy;
380
+		$this->_display_strategy->_construct_finalize($this);
381
+	}
382
+
383
+
384
+
385
+	/**
386
+	 * Gets the normalization strategy set on this input
387
+	 *
388
+	 * @return EE_Normalization_Strategy_Base
389
+	 */
390
+	public function get_normalization_strategy()
391
+	{
392
+		return $this->_normalization_strategy;
393
+	}
394
+
395
+
396
+
397
+	/**
398
+	 * Overwrites the normalization strategy
399
+	 *
400
+	 * @param EE_Normalization_Strategy_Base $normalization_strategy
401
+	 */
402
+	public function set_normalization_strategy($normalization_strategy)
403
+	{
404
+		$this->_normalization_strategy = $normalization_strategy;
405
+		$this->_normalization_strategy->_construct_finalize($this);
406
+	}
407
+
408
+
409
+
410
+	/**
411
+	 * Returns all teh validation strategies which apply to this field, numerically indexed
412
+	 *
413
+	 * @return EE_Validation_Strategy_Base[]
414
+	 */
415
+	public function get_validation_strategies()
416
+	{
417
+		return $this->_validation_strategies;
418
+	}
419
+
420
+
421
+
422
+	/**
423
+	 * Adds this strategy to the field so it will be used in both JS validation and server-side validation
424
+	 *
425
+	 * @param EE_Validation_Strategy_Base $validation_strategy
426
+	 * @return void
427
+	 */
428
+	protected function _add_validation_strategy(EE_Validation_Strategy_Base $validation_strategy)
429
+	{
430
+		$validation_strategy->_construct_finalize($this);
431
+		$this->_validation_strategies[] = $validation_strategy;
432
+	}
433
+
434
+
435
+
436
+	/**
437
+	 * Adds a new validation strategy onto the form input
438
+	 *
439
+	 * @param EE_Validation_Strategy_Base $validation_strategy
440
+	 * @return void
441
+	 */
442
+	public function add_validation_strategy(EE_Validation_Strategy_Base $validation_strategy)
443
+	{
444
+		$this->_add_validation_strategy($validation_strategy);
445
+	}
446
+
447
+
448
+
449
+	/**
450
+	 * The classname of the validation strategy to remove
451
+	 *
452
+	 * @param string $validation_strategy_classname
453
+	 */
454
+	public function remove_validation_strategy($validation_strategy_classname)
455
+	{
456
+		foreach ($this->_validation_strategies as $key => $validation_strategy) {
457
+			if (
458
+				$validation_strategy instanceof $validation_strategy_classname
459
+				|| is_subclass_of($validation_strategy, $validation_strategy_classname)
460
+			) {
461
+				unset($this->_validation_strategies[ $key ]);
462
+			}
463
+		}
464
+	}
465
+
466
+
467
+
468
+	/**
469
+	 * returns true if input employs any of the validation strategy defined by the supplied array of classnames
470
+	 *
471
+	 * @param array $validation_strategy_classnames
472
+	 * @return bool
473
+	 */
474
+	public function has_validation_strategy($validation_strategy_classnames)
475
+	{
476
+		$validation_strategy_classnames = is_array($validation_strategy_classnames)
477
+			? $validation_strategy_classnames
478
+			: array($validation_strategy_classnames);
479
+		foreach ($this->_validation_strategies as $key => $validation_strategy) {
480
+			if (in_array($key, $validation_strategy_classnames)) {
481
+				return true;
482
+			}
483
+		}
484
+		return false;
485
+	}
486
+
487
+
488
+
489
+	/**
490
+	 * Gets the HTML
491
+	 *
492
+	 * @return string
493
+	 */
494
+	public function get_html()
495
+	{
496
+		return $this->_parent_section->get_html_for_input($this);
497
+	}
498
+
499
+
500
+
501
+	/**
502
+	 * Gets the HTML for the input itself (no label or errors) according to the
503
+	 * input's display strategy
504
+	 * Makes sure the JS and CSS are enqueued for it
505
+	 *
506
+	 * @return string
507
+	 * @throws EE_Error
508
+	 */
509
+	public function get_html_for_input()
510
+	{
511
+		return $this->_form_html_filter
512
+			? $this->_form_html_filter->filterHtml(
513
+				$this->_get_display_strategy()->display(),
514
+				$this
515
+			)
516
+			: $this->_get_display_strategy()->display();
517
+	}
518
+
519
+
520
+
521
+	/**
522
+	 * @return string
523
+	 */
524
+	public function html_other_attributes()
525
+	{
526
+		EE_Error::doing_it_wrong(
527
+			__METHOD__,
528
+			sprintf(
529
+				esc_html__(
530
+					'This method is no longer in use. You should replace it by %s',
531
+					'event_espresso'
532
+				),
533
+				'EE_Form_Section_Base::other_html_attributes()'
534
+			),
535
+			'4.10.2.p'
536
+		);
537
+
538
+		return $this->other_html_attributes();
539
+	}
540
+
541
+
542
+
543
+	/**
544
+	 * @param string $html_other_attributes
545
+	 */
546
+	public function set_html_other_attributes($html_other_attributes)
547
+	{
548
+		EE_Error::doing_it_wrong(
549
+			__METHOD__,
550
+			sprintf(
551
+				esc_html__(
552
+					'This method is no longer in use. You should replace it by %s',
553
+					'event_espresso'
554
+				),
555
+				'EE_Form_Section_Base::set_other_html_attributes()'
556
+			),
557
+			'4.10.2.p'
558
+		);
559
+
560
+		$this->set_other_html_attributes($html_other_attributes);
561
+	}
562
+
563
+
564
+
565
+	/**
566
+	 * Gets the HTML for displaying the label for this form input
567
+	 * according to the form section's layout strategy
568
+	 *
569
+	 * @return string
570
+	 */
571
+	public function get_html_for_label()
572
+	{
573
+		return $this->_parent_section->get_layout_strategy()->display_label($this);
574
+	}
575
+
576
+
577
+
578
+	/**
579
+	 * Gets the HTML for displaying the errors section for this form input
580
+	 * according to the form section's layout strategy
581
+	 *
582
+	 * @return string
583
+	 */
584
+	public function get_html_for_errors()
585
+	{
586
+		return $this->_parent_section->get_layout_strategy()->display_errors($this);
587
+	}
588
+
589
+
590
+
591
+	/**
592
+	 * Gets the HTML for displaying the help text for this form input
593
+	 * according to the form section's layout strategy
594
+	 *
595
+	 * @return string
596
+	 */
597
+	public function get_html_for_help()
598
+	{
599
+		return $this->_parent_section->get_layout_strategy()->display_help_text($this);
600
+	}
601
+
602
+
603
+
604
+	/**
605
+	 * Validates the input's sanitized value (assumes _sanitize() has already been called)
606
+	 * and returns whether or not the form input's submitted value is value
607
+	 *
608
+	 * @return boolean
609
+	 */
610
+	protected function _validate()
611
+	{
612
+		if ($this->isDisabled()) {
613
+			return true;
614
+		}
615
+		foreach ($this->_validation_strategies as $validation_strategy) {
616
+			if ($validation_strategy instanceof EE_Validation_Strategy_Base) {
617
+				try {
618
+					$validation_strategy->validate($this->normalized_value());
619
+				} catch (EE_Validation_Error $e) {
620
+					$this->add_validation_error($e);
621
+				}
622
+			}
623
+		}
624
+		if ($this->get_validation_errors()) {
625
+			return false;
626
+		} else {
627
+			return true;
628
+		}
629
+	}
630
+
631
+
632
+
633
+	/**
634
+	 * Performs basic sanitization on this value. But what sanitization can be performed anyways?
635
+	 * This value MIGHT be allowed to have tags, so we can't really remove them.
636
+	 *
637
+	 * @param string $value
638
+	 * @return null|string
639
+	 */
640
+	protected function _sanitize($value)
641
+	{
642
+		return $value !== null ? stripslashes(html_entity_decode(trim($value))) : null;
643
+	}
644
+
645
+
646
+
647
+	/**
648
+	 * Picks out the form value that relates to this form input,
649
+	 * and stores it as the sanitized value on the form input, and sets the normalized value.
650
+	 * Returns whether or not any validation errors occurred
651
+	 *
652
+	 * @param array $req_data
653
+	 * @return boolean whether or not there was an error
654
+	 * @throws EE_Error
655
+	 */
656
+	protected function _normalize($req_data)
657
+	{
658
+		// any existing validation errors don't apply so clear them
659
+		$this->_validation_errors = array();
660
+		// if the input is disabled, ignore whatever input was sent in
661
+		if ($this->isDisabled()) {
662
+			$this->_set_raw_value(null);
663
+			$this->_set_normalized_value($this->get_default());
664
+			return false;
665
+		}
666
+		try {
667
+			$raw_input = $this->find_form_data_for_this_section($req_data);
668
+			// super simple sanitization for now
669
+			if (is_array($raw_input)) {
670
+				$raw_value = array();
671
+				foreach ($raw_input as $key => $value) {
672
+					$raw_value[ $key ] = $this->_sanitize($value);
673
+				}
674
+				$this->_set_raw_value($raw_value);
675
+			} else {
676
+				$this->_set_raw_value($this->_sanitize($raw_input));
677
+			}
678
+			// we want to mostly leave the input alone in case we need to re-display it to the user
679
+			$this->_set_normalized_value($this->_normalization_strategy->normalize($this->raw_value()));
680
+			return false;
681
+		} catch (EE_Validation_Error $e) {
682
+			$this->add_validation_error($e);
683
+			return true;
684
+		}
685
+	}
686
+
687
+
688
+	/**
689
+	 * @return string
690
+	 * @throws EE_Error
691
+	 */
692
+	public function html_name()
693
+	{
694
+		$this->_set_default_html_name_if_empty();
695
+		return $this->_html_name;
696
+	}
697
+
698
+
699
+	/**
700
+	 * @return string
701
+	 * @throws EE_Error
702
+	 */
703
+	public function html_label_id()
704
+	{
705
+		return ! empty($this->_html_label_id) ? $this->_html_label_id : $this->html_id() . '-lbl';
706
+	}
707
+
708
+
709
+
710
+	/**
711
+	 * @return string
712
+	 */
713
+	public function html_label_class()
714
+	{
715
+		return $this->_html_label_class;
716
+	}
717
+
718
+
719
+
720
+	/**
721
+	 * @return string
722
+	 */
723
+	public function html_label_style()
724
+	{
725
+		return $this->_html_label_style;
726
+	}
727
+
728
+
729
+
730
+	/**
731
+	 * @return string
732
+	 */
733
+	public function html_label_text()
734
+	{
735
+		return $this->_html_label_text;
736
+	}
737
+
738
+
739
+
740
+	/**
741
+	 * @return string
742
+	 */
743
+	public function html_help_text()
744
+	{
745
+		return $this->_html_help_text;
746
+	}
747
+
748
+
749
+
750
+	/**
751
+	 * @return string
752
+	 */
753
+	public function html_help_class()
754
+	{
755
+		return $this->_html_help_class;
756
+	}
757
+
758
+
759
+
760
+	/**
761
+	 * @return string
762
+	 */
763
+	public function html_help_style()
764
+	{
765
+		return $this->_html_style;
766
+	}
767
+
768
+
769
+
770
+	/**
771
+	 * returns the raw, UNSAFE, input, almost exactly as the user submitted it.
772
+	 * Please note that almost all client code should instead use the normalized_value;
773
+	 * or possibly raw_value_in_form (which prepares the string for displaying in an HTML attribute on a tag,
774
+	 * mostly by escaping quotes)
775
+	 * Note, we do not store the exact original value sent in the user's request because
776
+	 * it may have malicious content, and we MIGHT want to store the form input in a transient or something...
777
+	 * in which case, we would have stored the malicious content to our database.
778
+	 *
779
+	 * @return string
780
+	 */
781
+	public function raw_value()
782
+	{
783
+		return $this->_raw_value;
784
+	}
785
+
786
+
787
+
788
+	/**
789
+	 * Returns a string safe to usage in form inputs when displaying, because
790
+	 * it escapes all html entities
791
+	 *
792
+	 * @return string
793
+	 */
794
+	public function raw_value_in_form()
795
+	{
796
+		return htmlentities($this->raw_value(), ENT_QUOTES, 'UTF-8');
797
+	}
798
+
799
+
800
+
801
+	/**
802
+	 * returns the value after it's been sanitized, and then converted into it's proper type
803
+	 * in PHP. Eg, a string, an int, an array,
804
+	 *
805
+	 * @return mixed
806
+	 */
807
+	public function normalized_value()
808
+	{
809
+		return $this->_normalized_value;
810
+	}
811
+
812
+
813
+
814
+	/**
815
+	 * Returns the normalized value is a presentable way. By default this is just
816
+	 * the normalized value by itself, but it can be overridden for when that's not
817
+	 * the best thing to display
818
+	 *
819
+	 * @return string
820
+	 */
821
+	public function pretty_value()
822
+	{
823
+		return $this->_normalized_value;
824
+	}
825
+
826
+
827
+
828
+	/**
829
+	 * When generating the JS for the jquery validation rules like<br>
830
+	 * <code>$( "#myform" ).validate({
831
+	 * rules: {
832
+	 * password: "required",
833
+	 * password_again: {
834
+	 * equalTo: "#password"
835
+	 * }
836
+	 * }
837
+	 * });</code>
838
+	 * if this field had the name 'password_again', it should return
839
+	 * <br><code>password_again: {
840
+	 * equalTo: "#password"
841
+	 * }</code>
842
+	 *
843
+	 * @return array
844
+	 */
845
+	public function get_jquery_validation_rules()
846
+	{
847
+		$jquery_validation_js = array();
848
+		$jquery_validation_rules = array();
849
+		foreach ($this->get_validation_strategies() as $validation_strategy) {
850
+			$jquery_validation_rules = array_replace_recursive(
851
+				$jquery_validation_rules,
852
+				$validation_strategy->get_jquery_validation_rule_array()
853
+			);
854
+		}
855
+		if (! empty($jquery_validation_rules)) {
856
+			foreach ($this->get_display_strategy()->get_html_input_ids(true) as $html_id_with_pound_sign) {
857
+				$jquery_validation_js[ $html_id_with_pound_sign ] = $jquery_validation_rules;
858
+			}
859
+		}
860
+		return $jquery_validation_js;
861
+	}
862
+
863
+
864
+
865
+	/**
866
+	 * Sets the input's default value for use in displaying in the form. Note: value should be
867
+	 * normalized (Eg, if providing a default of ra Yes_NO_Input you would provide TRUE or FALSE, not '1' or '0')
868
+	 *
869
+	 * @param mixed $value
870
+	 * @return void
871
+	 */
872
+	public function set_default($value)
873
+	{
874
+		$this->_default = $value;
875
+		$this->_set_normalized_value($value);
876
+		$this->_set_raw_value($value);
877
+	}
878
+
879
+
880
+
881
+	/**
882
+	 * Sets the normalized value on this input
883
+	 *
884
+	 * @param mixed $value
885
+	 */
886
+	protected function _set_normalized_value($value)
887
+	{
888
+		$this->_normalized_value = $value;
889
+	}
890
+
891
+
892
+
893
+	/**
894
+	 * Sets the raw value on this input (ie, exactly as the user submitted it)
895
+	 *
896
+	 * @param mixed $value
897
+	 */
898
+	protected function _set_raw_value($value)
899
+	{
900
+		$this->_raw_value = $this->_normalization_strategy->unnormalize($value);
901
+	}
902
+
903
+
904
+
905
+	/**
906
+	 * Sets the HTML label text after it has already been defined
907
+	 *
908
+	 * @param string $label
909
+	 * @return void
910
+	 */
911
+	public function set_html_label_text($label)
912
+	{
913
+		$this->_html_label_text = $label;
914
+	}
915
+
916
+
917
+
918
+	/**
919
+	 * Sets whether or not this field is required, and adjusts the validation strategy.
920
+	 * If you want to use the EE_Conditionally_Required_Validation_Strategy,
921
+	 * please add it as a validation strategy using add_validation_strategy as normal
922
+	 *
923
+	 * @param boolean $required boolean
924
+	 * @param null    $required_text
925
+	 */
926
+	public function set_required($required = true, $required_text = null)
927
+	{
928
+		$required = filter_var($required, FILTER_VALIDATE_BOOLEAN);
929
+		// whether $required is a string or a boolean, we want to add a required validation strategy
930
+		if ($required) {
931
+			$this->_add_validation_strategy(new EE_Required_Validation_Strategy($required_text));
932
+		} else {
933
+			$this->remove_validation_strategy('EE_Required_Validation_Strategy');
934
+		}
935
+		$this->_required = $required;
936
+	}
937
+
938
+
939
+
940
+	/**
941
+	 * Returns whether or not this field is required
942
+	 *
943
+	 * @return boolean
944
+	 */
945
+	public function required()
946
+	{
947
+		return $this->_required;
948
+	}
949
+
950
+
951
+
952
+	/**
953
+	 * @param string $required_css_class
954
+	 */
955
+	public function set_required_css_class($required_css_class)
956
+	{
957
+		$this->_required_css_class = $required_css_class;
958
+	}
959
+
960
+
961
+
962
+	/**
963
+	 * @return string
964
+	 */
965
+	public function required_css_class()
966
+	{
967
+		return $this->_required_css_class;
968
+	}
969
+
970
+
971
+
972
+	/**
973
+	 * @param bool $add_required
974
+	 * @return string
975
+	 */
976
+	public function html_class($add_required = false)
977
+	{
978
+		return $add_required && $this->required()
979
+			? $this->required_css_class() . ' ' . $this->_html_class
980
+			: $this->_html_class;
981
+	}
982
+
983
+
984
+	/**
985
+	 * Sets the help text, in case
986
+	 *
987
+	 * @param string $text
988
+	 */
989
+	public function set_html_help_text($text)
990
+	{
991
+		$this->_html_help_text = $text;
992
+	}
993
+
994
+
995
+
996
+	/**
997
+	 * Uses the sensitive data removal strategy to remove the sensitive data from this
998
+	 * input. If there is any kind of sensitive data removal on this input, we clear
999
+	 * out the raw value completely
1000
+	 *
1001
+	 * @return void
1002
+	 */
1003
+	public function clean_sensitive_data()
1004
+	{
1005
+		// if we do ANY kind of sensitive data removal on this, then just clear out the raw value
1006
+		// if we need more logic than this we'll make a strategy for it
1007
+		if (
1008
+			$this->_sensitive_data_removal_strategy
1009
+			&& ! $this->_sensitive_data_removal_strategy instanceof EE_No_Sensitive_Data_Removal
1010
+		) {
1011
+			$this->_set_raw_value(null);
1012
+		}
1013
+		// and clean the normalized value according to the appropriate strategy
1014
+		$this->_set_normalized_value(
1015
+			$this->get_sensitive_data_removal_strategy()->remove_sensitive_data(
1016
+				$this->_normalized_value
1017
+			)
1018
+		);
1019
+	}
1020
+
1021
+
1022
+
1023
+	/**
1024
+	 * @param bool   $primary
1025
+	 * @param string $button_size
1026
+	 * @param string $other_attributes
1027
+	 */
1028
+	public function set_button_css_attributes($primary = true, $button_size = '', $other_attributes = '')
1029
+	{
1030
+		$button_css_attributes = 'button';
1031
+		$button_css_attributes .= $primary === true ? ' button-primary' : ' button-secondary';
1032
+		switch ($button_size) {
1033
+			case 'xs':
1034
+			case 'extra-small':
1035
+				$button_css_attributes .= ' button-xs';
1036
+				break;
1037
+			case 'sm':
1038
+			case 'small':
1039
+				$button_css_attributes .= ' button-sm';
1040
+				break;
1041
+			case 'lg':
1042
+			case 'large':
1043
+				$button_css_attributes .= ' button-lg';
1044
+				break;
1045
+			case 'block':
1046
+				$button_css_attributes .= ' button-block';
1047
+				break;
1048
+			case 'md':
1049
+			case 'medium':
1050
+			default:
1051
+				$button_css_attributes .= '';
1052
+		}
1053
+		$this->_button_css_attributes .= ! empty($other_attributes)
1054
+			? $button_css_attributes . ' ' . $other_attributes
1055
+			: $button_css_attributes;
1056
+	}
1057
+
1058
+
1059
+
1060
+	/**
1061
+	 * @return string
1062
+	 */
1063
+	public function button_css_attributes()
1064
+	{
1065
+		if (empty($this->_button_css_attributes)) {
1066
+			$this->set_button_css_attributes();
1067
+		}
1068
+		return $this->_button_css_attributes;
1069
+	}
1070
+
1071
+
1072
+
1073
+	/**
1074
+	 * find_form_data_for_this_section
1075
+	 * using this section's name and its parents, finds the value of the form data that corresponds to it.
1076
+	 * For example, if this form section's HTML name is my_form[subform][form_input_1],
1077
+	 * then it's value should be in request at request['my_form']['subform']['form_input_1'].
1078
+	 * (If that doesn't exist, we also check for this subsection's name
1079
+	 * at the TOP LEVEL of the request data. Eg request['form_input_1'].)
1080
+	 * This function finds its value in the form.
1081
+	 *
1082
+	 * @param array $req_data
1083
+	 * @return mixed whatever the raw value of this form section is in the request data
1084
+	 * @throws EE_Error
1085
+	 */
1086
+	public function find_form_data_for_this_section($req_data)
1087
+	{
1088
+		$name_parts = $this->getInputNameParts();
1089
+		// now get the value for the input
1090
+		$value = $this->findRequestForSectionUsingNameParts($name_parts, $req_data);
1091
+		// check if this thing's name is at the TOP level of the request data
1092
+		if ($value === null && isset($req_data[ $this->name() ])) {
1093
+			$value = $req_data[ $this->name() ];
1094
+		}
1095
+		return $value;
1096
+	}
1097
+
1098
+
1099
+	/**
1100
+	 * If this input's name is something like "foo[bar][baz]"
1101
+	 * returns an array like `array('foo','bar',baz')`
1102
+	 *
1103
+	 * @return array
1104
+	 * @throws EE_Error
1105
+	 */
1106
+	protected function getInputNameParts()
1107
+	{
1108
+		// break up the html name by "[]"
1109
+		if (strpos($this->html_name(), '[') !== false) {
1110
+			$before_any_brackets = substr($this->html_name(), 0, strpos($this->html_name(), '['));
1111
+		} else {
1112
+			$before_any_brackets = $this->html_name();
1113
+		}
1114
+		// grab all of the segments
1115
+		preg_match_all('~\[([^]]*)\]~', $this->html_name(), $matches);
1116
+		if (isset($matches[1]) && is_array($matches[1])) {
1117
+			$name_parts = $matches[1];
1118
+			array_unshift($name_parts, $before_any_brackets);
1119
+		} else {
1120
+			$name_parts = array($before_any_brackets);
1121
+		}
1122
+		return $name_parts;
1123
+	}
1124
+
1125
+
1126
+
1127
+	/**
1128
+	 * @param array $html_name_parts
1129
+	 * @param array $req_data
1130
+	 * @return array | NULL
1131
+	 */
1132
+	public function findRequestForSectionUsingNameParts($html_name_parts, $req_data)
1133
+	{
1134
+		$first_part_to_consider = array_shift($html_name_parts);
1135
+		if (isset($req_data[ $first_part_to_consider ])) {
1136
+			if (empty($html_name_parts)) {
1137
+				return $req_data[ $first_part_to_consider ];
1138
+			} else {
1139
+				return $this->findRequestForSectionUsingNameParts(
1140
+					$html_name_parts,
1141
+					$req_data[ $first_part_to_consider ]
1142
+				);
1143
+			}
1144
+		} else {
1145
+			return null;
1146
+		}
1147
+	}
1148
+
1149
+
1150
+
1151
+	/**
1152
+	 * Checks if this form input's data is in the request data
1153
+	 *
1154
+	 * @param array $req_data
1155
+	 * @return boolean
1156
+	 * @throws EE_Error
1157
+	 */
1158
+	public function form_data_present_in($req_data = null)
1159
+	{
1160
+		if ($req_data === null) {
1161
+			/** @var RequestInterface $request */
1162
+			$request = LoaderFactory::getLoader()->getShared(RequestInterface::class);
1163
+			$req_data = $request->postParams();
1164
+		}
1165
+		$checked_value = $this->find_form_data_for_this_section($req_data);
1166
+		if ($checked_value !== null) {
1167
+			return true;
1168
+		} else {
1169
+			return false;
1170
+		}
1171
+	}
1172
+
1173
+
1174
+
1175
+	/**
1176
+	 * Overrides parent to add js data from validation and display strategies
1177
+	 *
1178
+	 * @param array $form_other_js_data
1179
+	 * @return array
1180
+	 */
1181
+	public function get_other_js_data($form_other_js_data = array())
1182
+	{
1183
+		return $this->get_other_js_data_from_strategies($form_other_js_data);
1184
+	}
1185
+
1186
+
1187
+
1188
+	/**
1189
+	 * Gets other JS data for localization from this input's strategies, like
1190
+	 * the validation strategies and the display strategy
1191
+	 *
1192
+	 * @param array $form_other_js_data
1193
+	 * @return array
1194
+	 */
1195
+	public function get_other_js_data_from_strategies($form_other_js_data = array())
1196
+	{
1197
+		$form_other_js_data = $this->get_display_strategy()->get_other_js_data($form_other_js_data);
1198
+		foreach ($this->get_validation_strategies() as $validation_strategy) {
1199
+			$form_other_js_data = $validation_strategy->get_other_js_data($form_other_js_data);
1200
+		}
1201
+		return $form_other_js_data;
1202
+	}
1203
+
1204
+
1205
+
1206
+	/**
1207
+	 * Override parent because we want to give our strategies an opportunity to enqueue some js and css
1208
+	 *
1209
+	 * @return void
1210
+	 */
1211
+	public function enqueue_js()
1212
+	{
1213
+		// ask our display strategy and validation strategies if they have js to enqueue
1214
+		$this->enqueue_js_from_strategies();
1215
+	}
1216
+
1217
+
1218
+
1219
+	/**
1220
+	 * Tells strategies when its ok to enqueue their js and css
1221
+	 *
1222
+	 * @return void
1223
+	 */
1224
+	public function enqueue_js_from_strategies()
1225
+	{
1226
+		$this->get_display_strategy()->enqueue_js();
1227
+		foreach ($this->get_validation_strategies() as $validation_strategy) {
1228
+			$validation_strategy->enqueue_js();
1229
+		}
1230
+	}
1231
+
1232
+
1233
+
1234
+	/**
1235
+	 * Gets the default value set on the input (not the current value, which may have been
1236
+	 * changed because of a form submission). If no default was set, this us null.
1237
+	 * @return mixed
1238
+	 */
1239
+	public function get_default()
1240
+	{
1241
+		return $this->_default;
1242
+	}
1243
+
1244
+
1245
+
1246
+	/**
1247
+	 * Makes this input disabled. That means it will have the HTML attribute 'disabled="disabled"',
1248
+	 * and server-side if any input was received it will be ignored
1249
+	 */
1250
+	public function disable($disable = true)
1251
+	{
1252
+		$disabled_attribute = ' disabled="disabled"';
1253
+		$this->disabled = filter_var($disable, FILTER_VALIDATE_BOOLEAN);
1254
+		if ($this->disabled) {
1255
+			if (strpos($this->_other_html_attributes, $disabled_attribute) === false) {
1256
+				$this->_other_html_attributes .= $disabled_attribute;
1257
+			}
1258
+			$this->_set_normalized_value($this->get_default());
1259
+		} else {
1260
+			$this->_other_html_attributes = str_replace($disabled_attribute, '', $this->_other_html_attributes);
1261
+		}
1262
+	}
1263
+
1264
+
1265
+
1266
+	/**
1267
+	 * Returns whether or not this input is currently disabled.
1268
+	 * @return bool
1269
+	 */
1270
+	public function isDisabled()
1271
+	{
1272
+		return $this->disabled;
1273
+	}
1274 1274
 }
Please login to merge, or discard this patch.
core/libraries/form_sections/inputs/EE_Yes_No_Input.input.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -15,7 +15,7 @@
 block discarded – undo
15 15
      */
16 16
     public function __construct($options = array())
17 17
     {
18
-        $select_options = array(true =>  esc_html__("Yes", "event_espresso"),false =>  esc_html__("No", "event_espresso"));
18
+        $select_options = array(true =>  esc_html__("Yes", "event_espresso"), false =>  esc_html__("No", "event_espresso"));
19 19
 
20 20
         parent::__construct($select_options, $options);
21 21
     }
Please login to merge, or discard this patch.
Indentation   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -9,13 +9,13 @@
 block discarded – undo
9 9
  */
10 10
 class EE_Yes_No_Input extends EE_Select_Input
11 11
 {
12
-    /**
13
-     * @param array $options
14
-     */
15
-    public function __construct($options = array())
16
-    {
17
-        $select_options = array(true =>  esc_html__("Yes", "event_espresso"),false =>  esc_html__("No", "event_espresso"));
12
+	/**
13
+	 * @param array $options
14
+	 */
15
+	public function __construct($options = array())
16
+	{
17
+		$select_options = array(true =>  esc_html__("Yes", "event_espresso"),false =>  esc_html__("No", "event_espresso"));
18 18
 
19
-        parent::__construct($select_options, $options);
20
-    }
19
+		parent::__construct($select_options, $options);
20
+	}
21 21
 }
Please login to merge, or discard this patch.
core/libraries/form_sections/inputs/EE_Phone_Input.input.php 1 patch
Indentation   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -14,17 +14,17 @@
 block discarded – undo
14 14
  */
15 15
 class EE_Phone_Input extends EE_Text_Input
16 16
 {
17
-    /**
18
-     * @param array $options
19
-     */
20
-    public function __construct($options = array())
21
-    {
22
-        $this->_add_validation_strategy(
23
-            new EE_Text_Validation_Strategy(
24
-                esc_html__('Please enter a valid phone number. Eg 123-456-7890 or 1234567890', 'event_espresso'),
25
-                '~^(([\d]{10})|(^[\d]{3}-[\d]{3}-[\d]{4}))$~'
26
-            )
27
-        );
28
-        parent::__construct($options);
29
-    }
17
+	/**
18
+	 * @param array $options
19
+	 */
20
+	public function __construct($options = array())
21
+	{
22
+		$this->_add_validation_strategy(
23
+			new EE_Text_Validation_Strategy(
24
+				esc_html__('Please enter a valid phone number. Eg 123-456-7890 or 1234567890', 'event_espresso'),
25
+				'~^(([\d]{10})|(^[\d]{3}-[\d]{3}-[\d]{4}))$~'
26
+			)
27
+		);
28
+		parent::__construct($options);
29
+	}
30 30
 }
Please login to merge, or discard this patch.
libraries/form_sections/inputs/EE_Select_Ajax_Model_Rest_Input.input.php 2 patches
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -74,7 +74,7 @@  discard block
 block discarded – undo
74 74
         );
75 75
         // make sure limit and caps are always set
76 76
         $query_params = array_merge(
77
-            array( 'limit' => 10, 'caps' => EEM_Base::caps_read_admin ),
77
+            array('limit' => 10, 'caps' => EEM_Base::caps_read_admin),
78 78
             $query_params
79 79
         );
80 80
         $this->_value_field_name = EEH_Array::is_set(
@@ -155,12 +155,12 @@  discard block
 block discarded – undo
155 155
         $values_for_options = (array) $value;
156 156
         $value_field = $this->_get_model()->field_settings_for($this->_value_field_name);
157 157
         $display_field = $this->_get_model()->field_settings_for($this->_display_field_name);
158
-        $this->_extra_select_columns[] = $value_field->get_qualified_column() . ' AS ' . $this->_value_field_name;
159
-        $this->_extra_select_columns[] = $display_field->get_qualified_column() . ' AS ' . $this->_display_field_name;
158
+        $this->_extra_select_columns[] = $value_field->get_qualified_column().' AS '.$this->_value_field_name;
159
+        $this->_extra_select_columns[] = $display_field->get_qualified_column().' AS '.$this->_display_field_name;
160 160
         $display_values = $this->_get_model()->get_all_wpdb_results(
161 161
             array(
162 162
                 array(
163
-                    $this->_value_field_name => array( 'IN', $values_for_options )
163
+                    $this->_value_field_name => array('IN', $values_for_options)
164 164
                 )
165 165
             ),
166 166
             ARRAY_A,
@@ -170,9 +170,9 @@  discard block
 block discarded – undo
170 170
         if (is_array($select_options)) {
171 171
             foreach ($display_values as $db_rows) {
172 172
                 $db_rows = (array) $db_rows;
173
-                $select_options[ $db_rows[ $this->_value_field_name ] ] = apply_filters(
173
+                $select_options[$db_rows[$this->_value_field_name]] = apply_filters(
174 174
                     'FHEE__EE_Select_Ajax_Model_Rest_Input___set_raw_value__select_option_value',
175
-                    $db_rows[ $this->_display_field_name ],
175
+                    $db_rows[$this->_display_field_name],
176 176
                     $db_rows
177 177
                 );
178 178
             }
@@ -188,7 +188,7 @@  discard block
 block discarded – undo
188 188
      */
189 189
     protected function _get_model()
190 190
     {
191
-        if (! EE_Registry::instance()->is_model_name($this->_model_name)) {
191
+        if ( ! EE_Registry::instance()->is_model_name($this->_model_name)) {
192 192
             throw new EE_Error(
193 193
                 sprintf(
194 194
                     esc_html__(
Please login to merge, or discard this patch.
Indentation   +176 added lines, -176 removed lines patch added patch discarded remove patch
@@ -16,189 +16,189 @@
 block discarded – undo
16 16
  */
17 17
 class EE_Select_Ajax_Model_Rest_Input extends EE_Form_Input_With_Options_Base
18 18
 {
19
-    /**
20
-     * @var string $_model_name
21
-     */
22
-    protected $_model_name;
19
+	/**
20
+	 * @var string $_model_name
21
+	 */
22
+	protected $_model_name;
23 23
 
24
-    /**
25
-     * @var string $_display_field_name
26
-     */
27
-    protected $_display_field_name;
24
+	/**
25
+	 * @var string $_display_field_name
26
+	 */
27
+	protected $_display_field_name;
28 28
 
29
-    /**
30
-     * @var string $_value_field_name
31
-     */
32
-    protected $_value_field_name;
29
+	/**
30
+	 * @var string $_value_field_name
31
+	 */
32
+	protected $_value_field_name;
33 33
 
34
-    /**
35
-     * @var array $_extra_select_columns
36
-     */
37
-    protected $_extra_select_columns = array();
34
+	/**
35
+	 * @var array $_extra_select_columns
36
+	 */
37
+	protected $_extra_select_columns = array();
38 38
 
39 39
 
40
-    /**
41
-     * @param array $input_settings     {
42
-     * @type string $model_name         the name of model to be used for searching, both via the REST API and server-side model queries
43
-     * @type array  $query_params       default query parameters which will apply to both REST API queries and server-side queries. This should be
44
-     *                                  in the exact format that will be used for server-side model usage (eg use index 0 for where conditions, not
45
-     *                                  the string "where")
46
-     * @type string $value_field_name   the name of the model field on this model to
47
-     *                                  be used for the HTML select's option's values
48
-     * @type string $display_field_name the name of the model field on this model
49
-     *                                  to be used for the HTML select's option's display text
50
-     * @type array  $select2_args       arguments to be passed directly into the select2's JS constructor
51
-     *                                  }
52
-     *                                  And the arguments accepted by EE_Form_Input_With_Options_Base
53
-     * }
54
-     * @throws EE_Error
55
-     * @throws InvalidArgumentException
56
-     * @throws InvalidDataTypeException
57
-     * @throws InvalidInterfaceException
58
-     */
59
-    public function __construct($input_settings = array())
60
-    {
61
-        // needed input settings:
62
-        // select2_args
63
-        $this->_model_name = EEH_Array::is_set(
64
-            $input_settings,
65
-            'model_name',
66
-            null
67
-        );
68
-        $model = $this->_get_model();
69
-        $query_params = EEH_Array::is_set(
70
-            $input_settings,
71
-            'query_params',
72
-            array()
73
-        );
74
-        // make sure limit and caps are always set
75
-        $query_params = array_merge(
76
-            array( 'limit' => 10, 'caps' => EEM_Base::caps_read_admin ),
77
-            $query_params
78
-        );
79
-        $this->_value_field_name = EEH_Array::is_set(
80
-            $input_settings,
81
-            'value_field_name',
82
-            $model->primary_key_name()
83
-        );
84
-        $this->_display_field_name = EEH_Array::is_set(
85
-            $input_settings,
86
-            'display_field_name',
87
-            $model->get_a_field_of_type('EE_Text_Field_Base')->get_name()
88
-        );
89
-        $this->_extra_select_columns = EEH_Array::is_set(
90
-            $input_settings,
91
-            'extra_select_columns',
92
-            array()
93
-        );
94
-        $this->_add_validation_strategy(
95
-            new EE_Model_Matching_Query_Validation_Strategy(
96
-                '',
97
-                $this->_model_name,
98
-                $query_params,
99
-                $this->_value_field_name
100
-            )
101
-        );
102
-        // get resource endpoint
103
-        $rest_controller = LoaderFactory::getLoader()->getNew(
104
-            'EventEspresso\core\libraries\rest_api\controllers\model\Read'
105
-        );
106
-        $rest_controller->setRequestedVersion(EED_Core_Rest_Api::latest_rest_api_version());
107
-        $default_select2_args = array(
108
-            'ajax' => array(
109
-                'url' => $rest_controller->getVersionedLinkTo(
110
-                    EEH_Inflector::pluralize_and_lower($this->_model_name)
111
-                ),
112
-                'dataType' => 'json',
113
-                'delay' => '250',
114
-                'data_interface' => 'EE_Select2_REST_API_Interface',
115
-                'data_interface_args' => array(
116
-                    'default_query_params' => (object) ModelDataTranslator::prepareQueryParamsForRestApi(
117
-                        $query_params,
118
-                        $model
119
-                    ),
120
-                    'display_field' => $this->_display_field_name,
121
-                    'value_field' => $this->_value_field_name,
122
-                    'nonce' => wp_create_nonce('wp_rest'),
123
-                    'locale' => str_replace('_', '-', strtolower(get_locale()))
124
-                ),
125
-            ),
126
-            'cache' => true,
127
-            'width' => 'resolve'
128
-        );
129
-        $select2_args = array_replace_recursive(
130
-            $default_select2_args,
131
-            (array) EEH_Array::is_set($input_settings, 'select2_args', array())
132
-        );
133
-        $this->set_display_strategy(new EE_Select2_Display_Strategy($select2_args));
134
-        parent::__construct(array(), $input_settings);
135
-    }
40
+	/**
41
+	 * @param array $input_settings     {
42
+	 * @type string $model_name         the name of model to be used for searching, both via the REST API and server-side model queries
43
+	 * @type array  $query_params       default query parameters which will apply to both REST API queries and server-side queries. This should be
44
+	 *                                  in the exact format that will be used for server-side model usage (eg use index 0 for where conditions, not
45
+	 *                                  the string "where")
46
+	 * @type string $value_field_name   the name of the model field on this model to
47
+	 *                                  be used for the HTML select's option's values
48
+	 * @type string $display_field_name the name of the model field on this model
49
+	 *                                  to be used for the HTML select's option's display text
50
+	 * @type array  $select2_args       arguments to be passed directly into the select2's JS constructor
51
+	 *                                  }
52
+	 *                                  And the arguments accepted by EE_Form_Input_With_Options_Base
53
+	 * }
54
+	 * @throws EE_Error
55
+	 * @throws InvalidArgumentException
56
+	 * @throws InvalidDataTypeException
57
+	 * @throws InvalidInterfaceException
58
+	 */
59
+	public function __construct($input_settings = array())
60
+	{
61
+		// needed input settings:
62
+		// select2_args
63
+		$this->_model_name = EEH_Array::is_set(
64
+			$input_settings,
65
+			'model_name',
66
+			null
67
+		);
68
+		$model = $this->_get_model();
69
+		$query_params = EEH_Array::is_set(
70
+			$input_settings,
71
+			'query_params',
72
+			array()
73
+		);
74
+		// make sure limit and caps are always set
75
+		$query_params = array_merge(
76
+			array( 'limit' => 10, 'caps' => EEM_Base::caps_read_admin ),
77
+			$query_params
78
+		);
79
+		$this->_value_field_name = EEH_Array::is_set(
80
+			$input_settings,
81
+			'value_field_name',
82
+			$model->primary_key_name()
83
+		);
84
+		$this->_display_field_name = EEH_Array::is_set(
85
+			$input_settings,
86
+			'display_field_name',
87
+			$model->get_a_field_of_type('EE_Text_Field_Base')->get_name()
88
+		);
89
+		$this->_extra_select_columns = EEH_Array::is_set(
90
+			$input_settings,
91
+			'extra_select_columns',
92
+			array()
93
+		);
94
+		$this->_add_validation_strategy(
95
+			new EE_Model_Matching_Query_Validation_Strategy(
96
+				'',
97
+				$this->_model_name,
98
+				$query_params,
99
+				$this->_value_field_name
100
+			)
101
+		);
102
+		// get resource endpoint
103
+		$rest_controller = LoaderFactory::getLoader()->getNew(
104
+			'EventEspresso\core\libraries\rest_api\controllers\model\Read'
105
+		);
106
+		$rest_controller->setRequestedVersion(EED_Core_Rest_Api::latest_rest_api_version());
107
+		$default_select2_args = array(
108
+			'ajax' => array(
109
+				'url' => $rest_controller->getVersionedLinkTo(
110
+					EEH_Inflector::pluralize_and_lower($this->_model_name)
111
+				),
112
+				'dataType' => 'json',
113
+				'delay' => '250',
114
+				'data_interface' => 'EE_Select2_REST_API_Interface',
115
+				'data_interface_args' => array(
116
+					'default_query_params' => (object) ModelDataTranslator::prepareQueryParamsForRestApi(
117
+						$query_params,
118
+						$model
119
+					),
120
+					'display_field' => $this->_display_field_name,
121
+					'value_field' => $this->_value_field_name,
122
+					'nonce' => wp_create_nonce('wp_rest'),
123
+					'locale' => str_replace('_', '-', strtolower(get_locale()))
124
+				),
125
+			),
126
+			'cache' => true,
127
+			'width' => 'resolve'
128
+		);
129
+		$select2_args = array_replace_recursive(
130
+			$default_select2_args,
131
+			(array) EEH_Array::is_set($input_settings, 'select2_args', array())
132
+		);
133
+		$this->set_display_strategy(new EE_Select2_Display_Strategy($select2_args));
134
+		parent::__construct(array(), $input_settings);
135
+	}
136 136
 
137 137
 
138 138
 
139
-    /**
140
-     * Before setting the raw value (usually because we're setting the default,
141
-     * or we've received a form submission and this might be re-displayed to the user),
142
-     * sets the options so that the current selections appear on initial display.
143
-     *
144
-     * Note: because this input uses EE_Model_Matching_Query_Validation_Strategy
145
-     * for validation, this input's options only affect DISPLAY and NOT validation,
146
-     * which is why its ok to just assume the provided $value to be in the list of acceptable values
147
-     *
148
-     * @param mixed $value
149
-     * @return void
150
-     * @throws \EE_Error
151
-     */
152
-    public function _set_raw_value($value)
153
-    {
154
-        $values_for_options = (array) $value;
155
-        $value_field = $this->_get_model()->field_settings_for($this->_value_field_name);
156
-        $display_field = $this->_get_model()->field_settings_for($this->_display_field_name);
157
-        $this->_extra_select_columns[] = $value_field->get_qualified_column() . ' AS ' . $this->_value_field_name;
158
-        $this->_extra_select_columns[] = $display_field->get_qualified_column() . ' AS ' . $this->_display_field_name;
159
-        $display_values = $this->_get_model()->get_all_wpdb_results(
160
-            array(
161
-                array(
162
-                    $this->_value_field_name => array( 'IN', $values_for_options )
163
-                )
164
-            ),
165
-            ARRAY_A,
166
-            implode(',', $this->_extra_select_columns)
167
-        );
168
-        $select_options = array();
169
-        if (is_array($select_options)) {
170
-            foreach ($display_values as $db_rows) {
171
-                $db_rows = (array) $db_rows;
172
-                $select_options[ $db_rows[ $this->_value_field_name ] ] = apply_filters(
173
-                    'FHEE__EE_Select_Ajax_Model_Rest_Input___set_raw_value__select_option_value',
174
-                    $db_rows[ $this->_display_field_name ],
175
-                    $db_rows
176
-                );
177
-            }
178
-        }
179
-        $this->set_select_options($select_options);
180
-        parent::_set_raw_value($value);
181
-    }
139
+	/**
140
+	 * Before setting the raw value (usually because we're setting the default,
141
+	 * or we've received a form submission and this might be re-displayed to the user),
142
+	 * sets the options so that the current selections appear on initial display.
143
+	 *
144
+	 * Note: because this input uses EE_Model_Matching_Query_Validation_Strategy
145
+	 * for validation, this input's options only affect DISPLAY and NOT validation,
146
+	 * which is why its ok to just assume the provided $value to be in the list of acceptable values
147
+	 *
148
+	 * @param mixed $value
149
+	 * @return void
150
+	 * @throws \EE_Error
151
+	 */
152
+	public function _set_raw_value($value)
153
+	{
154
+		$values_for_options = (array) $value;
155
+		$value_field = $this->_get_model()->field_settings_for($this->_value_field_name);
156
+		$display_field = $this->_get_model()->field_settings_for($this->_display_field_name);
157
+		$this->_extra_select_columns[] = $value_field->get_qualified_column() . ' AS ' . $this->_value_field_name;
158
+		$this->_extra_select_columns[] = $display_field->get_qualified_column() . ' AS ' . $this->_display_field_name;
159
+		$display_values = $this->_get_model()->get_all_wpdb_results(
160
+			array(
161
+				array(
162
+					$this->_value_field_name => array( 'IN', $values_for_options )
163
+				)
164
+			),
165
+			ARRAY_A,
166
+			implode(',', $this->_extra_select_columns)
167
+		);
168
+		$select_options = array();
169
+		if (is_array($select_options)) {
170
+			foreach ($display_values as $db_rows) {
171
+				$db_rows = (array) $db_rows;
172
+				$select_options[ $db_rows[ $this->_value_field_name ] ] = apply_filters(
173
+					'FHEE__EE_Select_Ajax_Model_Rest_Input___set_raw_value__select_option_value',
174
+					$db_rows[ $this->_display_field_name ],
175
+					$db_rows
176
+				);
177
+			}
178
+		}
179
+		$this->set_select_options($select_options);
180
+		parent::_set_raw_value($value);
181
+	}
182 182
 
183
-    /**
184
-     * Returns the model, or throws an exception if the model name provided in constructor doesn't exist
185
-     * @return EEM_Base
186
-     * @throws EE_Error
187
-     */
188
-    protected function _get_model()
189
-    {
190
-        if (! EE_Registry::instance()->is_model_name($this->_model_name)) {
191
-            throw new EE_Error(
192
-                sprintf(
193
-                    esc_html__(
194
-                        '%1$s is not a proper model name. Please provide a model name in the "model_name" form input argument',
195
-                        'event_espresso'
196
-                    ),
197
-                    $this->_model_name
198
-                )
199
-            );
200
-        } else {
201
-            return EE_Registry::instance()->load_model($this->_model_name);
202
-        }
203
-    }
183
+	/**
184
+	 * Returns the model, or throws an exception if the model name provided in constructor doesn't exist
185
+	 * @return EEM_Base
186
+	 * @throws EE_Error
187
+	 */
188
+	protected function _get_model()
189
+	{
190
+		if (! EE_Registry::instance()->is_model_name($this->_model_name)) {
191
+			throw new EE_Error(
192
+				sprintf(
193
+					esc_html__(
194
+						'%1$s is not a proper model name. Please provide a model name in the "model_name" form input argument',
195
+						'event_espresso'
196
+					),
197
+					$this->_model_name
198
+				)
199
+			);
200
+		} else {
201
+			return EE_Registry::instance()->load_model($this->_model_name);
202
+		}
203
+	}
204 204
 }
Please login to merge, or discard this patch.
core/EE_Configurable.core.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -120,7 +120,7 @@
 block discarded – undo
120 120
     public function _update_config(EE_Config_Base $config_obj = null)
121 121
     {
122 122
         $config_class = $this->config_class();
123
-        if (! $config_obj instanceof $config_class) {
123
+        if ( ! $config_obj instanceof $config_class) {
124 124
             throw new EE_Error(
125 125
                 sprintf(
126 126
                     esc_html__('The "%1$s" class is not an instance of %2$s.', 'event_espresso'),
Please login to merge, or discard this patch.
Indentation   +139 added lines, -139 removed lines patch added patch discarded remove patch
@@ -9,143 +9,143 @@
 block discarded – undo
9 9
  */
10 10
 abstract class EE_Configurable extends EE_Base
11 11
 {
12
-    /**
13
-     * @var $_config
14
-     * @type EE_Config_Base
15
-     */
16
-    protected $_config;
17
-
18
-    /**
19
-     * @var $_config_section
20
-     * @type string
21
-     */
22
-    protected $_config_section = '';
23
-
24
-    /**
25
-     * @var $_config_class
26
-     * @type string
27
-     */
28
-    protected $_config_class = '';
29
-
30
-    /**
31
-     * @var $_config_name
32
-     * @type string
33
-     */
34
-    protected $_config_name = '';
35
-
36
-
37
-    /**
38
-     * @param string $config_section
39
-     */
40
-    public function set_config_section($config_section = '')
41
-    {
42
-        $this->_config_section = ! empty($config_section) ? $config_section : 'modules';
43
-    }
44
-
45
-
46
-    /**
47
-     * @return mixed
48
-     */
49
-    public function config_section()
50
-    {
51
-        return $this->_config_section;
52
-    }
53
-
54
-
55
-    /**
56
-     * @param string $config_class
57
-     */
58
-    public function set_config_class($config_class = '')
59
-    {
60
-        $this->_config_class = $config_class;
61
-    }
62
-
63
-
64
-    /**
65
-     * @return mixed
66
-     */
67
-    public function config_class()
68
-    {
69
-        return $this->_config_class;
70
-    }
71
-
72
-
73
-    /**
74
-     * @param mixed $config_name
75
-     */
76
-    public function set_config_name($config_name)
77
-    {
78
-        $this->_config_name = ! empty($config_name) ? $config_name : get_called_class();
79
-    }
80
-
81
-
82
-    /**
83
-     * @return mixed
84
-     */
85
-    public function config_name()
86
-    {
87
-        return $this->_config_name;
88
-    }
89
-
90
-
91
-    /**
92
-     *    set_config
93
-     *    this method integrates directly with EE_Config to set up the config object for this class
94
-     *
95
-     * @access    protected
96
-     * @param    EE_Config_Base $config_obj
97
-     * @return    mixed    EE_Config_Base | NULL
98
-     */
99
-    protected function _set_config(EE_Config_Base $config_obj = null)
100
-    {
101
-        return EE_Config::instance()->set_config(
102
-            $this->config_section(),
103
-            $this->config_name(),
104
-            $this->config_class(),
105
-            $config_obj
106
-        );
107
-    }
108
-
109
-
110
-    /**
111
-     *    _update_config
112
-     *    this method integrates directly with EE_Config to update an existing config object for this class
113
-     *
114
-     * @access    protected
115
-     * @param    EE_Config_Base $config_obj
116
-     * @throws \EE_Error
117
-     * @return    mixed    EE_Config_Base | NULL
118
-     */
119
-    public function _update_config(EE_Config_Base $config_obj = null)
120
-    {
121
-        $config_class = $this->config_class();
122
-        if (! $config_obj instanceof $config_class) {
123
-            throw new EE_Error(
124
-                sprintf(
125
-                    esc_html__('The "%1$s" class is not an instance of %2$s.', 'event_espresso'),
126
-                    print_r($config_obj, true),
127
-                    $config_class
128
-                )
129
-            );
130
-        }
131
-        return EE_Config::instance()->update_config($this->config_section(), $this->config_name(), $config_obj);
132
-    }
133
-
134
-
135
-    /**
136
-     * gets the class's config object
137
-     *
138
-     * @return EE_Config_Base
139
-     */
140
-    public function config()
141
-    {
142
-        if (empty($this->_config)) {
143
-            $this->_config = EE_Config::instance()->get_config(
144
-                $this->config_section(),
145
-                $this->config_name(),
146
-                $this->config_class()
147
-            );
148
-        }
149
-        return $this->_config;
150
-    }
12
+	/**
13
+	 * @var $_config
14
+	 * @type EE_Config_Base
15
+	 */
16
+	protected $_config;
17
+
18
+	/**
19
+	 * @var $_config_section
20
+	 * @type string
21
+	 */
22
+	protected $_config_section = '';
23
+
24
+	/**
25
+	 * @var $_config_class
26
+	 * @type string
27
+	 */
28
+	protected $_config_class = '';
29
+
30
+	/**
31
+	 * @var $_config_name
32
+	 * @type string
33
+	 */
34
+	protected $_config_name = '';
35
+
36
+
37
+	/**
38
+	 * @param string $config_section
39
+	 */
40
+	public function set_config_section($config_section = '')
41
+	{
42
+		$this->_config_section = ! empty($config_section) ? $config_section : 'modules';
43
+	}
44
+
45
+
46
+	/**
47
+	 * @return mixed
48
+	 */
49
+	public function config_section()
50
+	{
51
+		return $this->_config_section;
52
+	}
53
+
54
+
55
+	/**
56
+	 * @param string $config_class
57
+	 */
58
+	public function set_config_class($config_class = '')
59
+	{
60
+		$this->_config_class = $config_class;
61
+	}
62
+
63
+
64
+	/**
65
+	 * @return mixed
66
+	 */
67
+	public function config_class()
68
+	{
69
+		return $this->_config_class;
70
+	}
71
+
72
+
73
+	/**
74
+	 * @param mixed $config_name
75
+	 */
76
+	public function set_config_name($config_name)
77
+	{
78
+		$this->_config_name = ! empty($config_name) ? $config_name : get_called_class();
79
+	}
80
+
81
+
82
+	/**
83
+	 * @return mixed
84
+	 */
85
+	public function config_name()
86
+	{
87
+		return $this->_config_name;
88
+	}
89
+
90
+
91
+	/**
92
+	 *    set_config
93
+	 *    this method integrates directly with EE_Config to set up the config object for this class
94
+	 *
95
+	 * @access    protected
96
+	 * @param    EE_Config_Base $config_obj
97
+	 * @return    mixed    EE_Config_Base | NULL
98
+	 */
99
+	protected function _set_config(EE_Config_Base $config_obj = null)
100
+	{
101
+		return EE_Config::instance()->set_config(
102
+			$this->config_section(),
103
+			$this->config_name(),
104
+			$this->config_class(),
105
+			$config_obj
106
+		);
107
+	}
108
+
109
+
110
+	/**
111
+	 *    _update_config
112
+	 *    this method integrates directly with EE_Config to update an existing config object for this class
113
+	 *
114
+	 * @access    protected
115
+	 * @param    EE_Config_Base $config_obj
116
+	 * @throws \EE_Error
117
+	 * @return    mixed    EE_Config_Base | NULL
118
+	 */
119
+	public function _update_config(EE_Config_Base $config_obj = null)
120
+	{
121
+		$config_class = $this->config_class();
122
+		if (! $config_obj instanceof $config_class) {
123
+			throw new EE_Error(
124
+				sprintf(
125
+					esc_html__('The "%1$s" class is not an instance of %2$s.', 'event_espresso'),
126
+					print_r($config_obj, true),
127
+					$config_class
128
+				)
129
+			);
130
+		}
131
+		return EE_Config::instance()->update_config($this->config_section(), $this->config_name(), $config_obj);
132
+	}
133
+
134
+
135
+	/**
136
+	 * gets the class's config object
137
+	 *
138
+	 * @return EE_Config_Base
139
+	 */
140
+	public function config()
141
+	{
142
+		if (empty($this->_config)) {
143
+			$this->_config = EE_Config::instance()->get_config(
144
+				$this->config_section(),
145
+				$this->config_name(),
146
+				$this->config_class()
147
+			);
148
+		}
149
+		return $this->_config;
150
+	}
151 151
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Price.model.php 2 patches
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -24,7 +24,7 @@  discard block
 block discarded – undo
24 24
      */
25 25
     protected function __construct($timezone)
26 26
     {
27
-        require_once(EE_MODELS . 'EEM_Price_Type.model.php');
27
+        require_once(EE_MODELS.'EEM_Price_Type.model.php');
28 28
         $this->singular_item = esc_html__('Price', 'event_espresso');
29 29
         $this->plural_item = esc_html__('Prices', 'event_espresso');
30 30
 
@@ -52,11 +52,11 @@  discard block
 block discarded – undo
52 52
             'WP_User' => new EE_Belongs_To_Relation(),
53 53
         );
54 54
         // this model is generally available for reading
55
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Default_Public('PRC_is_default', 'Ticket.Datetime.Event');
55
+        $this->_cap_restriction_generators[EEM_Base::caps_read] = new EE_Restriction_Generator_Default_Public('PRC_is_default', 'Ticket.Datetime.Event');
56 56
         // account for default tickets in the caps
57
-        $this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] = new EE_Restriction_Generator_Default_Protected('PRC_is_default', 'Ticket.Datetime.Event');
58
-        $this->_cap_restriction_generators[ EEM_Base::caps_edit ] = new EE_Restriction_Generator_Default_Protected('PRC_is_default', 'Ticket.Datetime.Event');
59
-        $this->_cap_restriction_generators[ EEM_Base::caps_delete ] = new EE_Restriction_Generator_Default_Protected('PRC_is_default', 'Ticket.Datetime.Event');
57
+        $this->_cap_restriction_generators[EEM_Base::caps_read_admin] = new EE_Restriction_Generator_Default_Protected('PRC_is_default', 'Ticket.Datetime.Event');
58
+        $this->_cap_restriction_generators[EEM_Base::caps_edit] = new EE_Restriction_Generator_Default_Protected('PRC_is_default', 'Ticket.Datetime.Event');
59
+        $this->_cap_restriction_generators[EEM_Base::caps_delete] = new EE_Restriction_Generator_Default_Protected('PRC_is_default', 'Ticket.Datetime.Event');
60 60
         parent::__construct($timezone);
61 61
     }
62 62
 
@@ -103,7 +103,7 @@  discard block
 block discarded – undo
103 103
         return $this->get_all(array(
104 104
             array(
105 105
                 'EVT_ID' => $EVT_ID,
106
-                'Price_Type.PBT_ID' => array('!=',  EEM_Price_Type::base_type_tax)
106
+                'Price_Type.PBT_ID' => array('!=', EEM_Price_Type::base_type_tax)
107 107
             ),
108 108
             'order_by' => $this->_order_by_array_for_get_all_method()
109 109
         ));
@@ -121,7 +121,7 @@  discard block
 block discarded – undo
121 121
     public function get_all_default_prices($count = false)
122 122
     {
123 123
         $_where = array(
124
-            'Price_Type.PBT_ID' => array('!=',4),
124
+            'Price_Type.PBT_ID' => array('!=', 4),
125 125
             'PRC_deleted' => 0,
126 126
             'PRC_is_default' => 1
127 127
         );
@@ -153,12 +153,12 @@  discard block
 block discarded – undo
153 153
     {
154 154
         $taxes = array();
155 155
         $all_taxes = $this->get_all(array(
156
-            array( 'Price_Type.PBT_ID' =>  EEM_Price_Type::base_type_tax ),
157
-            'order_by' => array( 'Price_Type.PRT_order' => 'ASC', 'PRC_order' => 'ASC' )
156
+            array('Price_Type.PBT_ID' =>  EEM_Price_Type::base_type_tax),
157
+            'order_by' => array('Price_Type.PRT_order' => 'ASC', 'PRC_order' => 'ASC')
158 158
         ));
159 159
         foreach ($all_taxes as $tax) {
160 160
             if ($tax instanceof EE_Price) {
161
-                $taxes[ $tax->order() ][ $tax->ID() ] = $tax;
161
+                $taxes[$tax->order()][$tax->ID()] = $tax;
162 162
             }
163 163
         }
164 164
         return $taxes;
@@ -186,7 +186,7 @@  discard block
 block discarded – undo
186 186
             if ($default_prices) {
187 187
                 foreach ($default_prices as $price) {
188 188
                     if ($price instanceof EE_Price) {
189
-                        $array_of_price_objects[ $price->type() ][] = $price;
189
+                        $array_of_price_objects[$price->type()][] = $price;
190 190
                     }
191 191
                 }
192 192
                 return $array_of_price_objects;
@@ -203,10 +203,10 @@  discard block
 block discarded – undo
203 203
             ));
204 204
         }
205 205
 
206
-        if (!empty($ticket_prices)) {
206
+        if ( ! empty($ticket_prices)) {
207 207
             foreach ($ticket_prices as $price) {
208 208
                 if ($price instanceof EE_Price) {
209
-                    $array_of_price_objects[ $price->type() ][] = $price;
209
+                    $array_of_price_objects[$price->type()][] = $price;
210 210
                 }
211 211
             }
212 212
             return $array_of_price_objects;
Please login to merge, or discard this patch.
Indentation   +275 added lines, -275 removed lines patch added patch discarded remove patch
@@ -9,279 +9,279 @@
 block discarded – undo
9 9
  */
10 10
 class EEM_Price extends EEM_Soft_Delete_Base
11 11
 {
12
-    // private instance of the EEM_Price object
13
-    protected static $_instance = null;
14
-
15
-
16
-
17
-    /**
18
-     *      private constructor to prevent direct creation
19
-     *      @Constructor
20
-     *      @access protected
21
-     *      @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any incoming timezone data that gets saved).  Note this just sends the timezone info to the date time model field objects.  Default is NULL (and will be assumed using the set timezone in the 'timezone_string' wp option)
22
-     *      @return EEM_Price
23
-     */
24
-    protected function __construct($timezone)
25
-    {
26
-        require_once(EE_MODELS . 'EEM_Price_Type.model.php');
27
-        $this->singular_item = esc_html__('Price', 'event_espresso');
28
-        $this->plural_item = esc_html__('Prices', 'event_espresso');
29
-
30
-        $this->_tables = array(
31
-            'Price' => new EE_Primary_Table('esp_price', 'PRC_ID')
32
-        );
33
-        $this->_fields = array(
34
-            'Price' => array(
35
-                'PRC_ID' => new EE_Primary_Key_Int_Field('PRC_ID', 'Price ID'),
36
-                'PRT_ID' => new EE_Foreign_Key_Int_Field('PRT_ID', 'Price type Id', false, null, 'Price_Type'),
37
-                'PRC_amount' => new EE_Money_Field('PRC_amount', 'Price Amount', false, 0),
38
-                'PRC_name' => new EE_Plain_Text_Field('PRC_name', 'Name of Price', false, ''),
39
-                'PRC_desc' => new EE_Post_Content_Field('PRC_desc', 'Price Description', false, ''),
40
-                'PRC_is_default' => new EE_Boolean_Field('PRC_is_default', 'Flag indicating whether price is a default price', false, false),
41
-                'PRC_overrides' => new EE_Integer_Field('PRC_overrides', 'Price ID for a global Price that will be overridden by this Price  ( for replacing default prices )', true, 0),
42
-                'PRC_order' => new EE_Integer_Field('PRC_order', 'Order of Application of Price (lower numbers apply first?)', false, 1),
43
-                'PRC_deleted' => new EE_Trashed_Flag_Field('PRC_deleted', 'Flag Indicating if this has been deleted or not', false, false),
44
-                'PRC_parent' => new EE_Integer_Field('PRC_parent', esc_html__('Indicates what PRC_ID is the parent of this PRC_ID', 'event_espresso'), true, 0),
45
-                'PRC_wp_user' => new EE_WP_User_Field('PRC_wp_user', esc_html__('Price Creator ID', 'event_espresso'), false),
46
-            )
47
-        );
48
-        $this->_model_relations = array(
49
-            'Ticket' => new EE_HABTM_Relation('Ticket_Price'),
50
-            'Price_Type' => new EE_Belongs_To_Relation(),
51
-            'WP_User' => new EE_Belongs_To_Relation(),
52
-        );
53
-        // this model is generally available for reading
54
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Default_Public('PRC_is_default', 'Ticket.Datetime.Event');
55
-        // account for default tickets in the caps
56
-        $this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] = new EE_Restriction_Generator_Default_Protected('PRC_is_default', 'Ticket.Datetime.Event');
57
-        $this->_cap_restriction_generators[ EEM_Base::caps_edit ] = new EE_Restriction_Generator_Default_Protected('PRC_is_default', 'Ticket.Datetime.Event');
58
-        $this->_cap_restriction_generators[ EEM_Base::caps_delete ] = new EE_Restriction_Generator_Default_Protected('PRC_is_default', 'Ticket.Datetime.Event');
59
-        parent::__construct($timezone);
60
-    }
61
-
62
-
63
-
64
-    /**
65
-     *      instantiate a new price object with blank/empty properties
66
-     *
67
-     *      @access     public
68
-     *      @return     mixed       array on success, FALSE on fail
69
-     */
70
-    public function get_new_price()
71
-    {
72
-        return $this->create_default_object();
73
-    }
74
-
75
-
76
-
77
-
78
-
79
-    /**
80
-     *      retrieve  ALL prices from db
81
-     *
82
-     *      @access     public
83
-     *      @return     EE_PRice[]
84
-     */
85
-    public function get_all_prices()
86
-    {
87
-        // retrieve all prices
88
-        return $this->get_all(array('order_by' => array('PRC_amount' => 'ASC')));
89
-    }
90
-
91
-
92
-
93
-    /**
94
-     *        retrieve all active prices for a particular event
95
-     *
96
-     * @access        public
97
-     * @param int $EVT_ID
98
-     * @return array on success
99
-     */
100
-    public function get_all_event_prices($EVT_ID = 0)
101
-    {
102
-        return $this->get_all(array(
103
-            array(
104
-                'EVT_ID' => $EVT_ID,
105
-                'Price_Type.PBT_ID' => array('!=',  EEM_Price_Type::base_type_tax)
106
-            ),
107
-            'order_by' => $this->_order_by_array_for_get_all_method()
108
-        ));
109
-    }
110
-
111
-
112
-    /**
113
-     *      retrieve all active global prices (that are not taxes (PBT_ID=4)) for a particular event
114
-     *
115
-     *      @access     public
116
-     *      @param      boolean         $count  return count
117
-     *      @return         array           on success
118
-     *      @return         boolean     false on fail
119
-     */
120
-    public function get_all_default_prices($count = false)
121
-    {
122
-        $_where = array(
123
-            'Price_Type.PBT_ID' => array('!=',4),
124
-            'PRC_deleted' => 0,
125
-            'PRC_is_default' => 1
126
-        );
127
-        $_query_params = array(
128
-            $_where,
129
-            'order_by' => $this->_order_by_array_for_get_all_method()
130
-        );
131
-        return $count ? $this->count(array($_where)) : $this->get_all($_query_params);
132
-    }
133
-
134
-
135
-
136
-
137
-
138
-
139
-
140
-
141
-
142
-
143
-    /**
144
-     *      retrieve all prices that are taxes
145
-     *
146
-     *      @access     public
147
-     *      @return         array               on success
148
-     *      @return         array top-level keys are the price's order and their values are an array,
149
-     *                      next-level keys are the price's ID, and their values are EE_Price objects
150
-     */
151
-    public function get_all_prices_that_are_taxes()
152
-    {
153
-        $taxes = array();
154
-        $all_taxes = $this->get_all(array(
155
-            array( 'Price_Type.PBT_ID' =>  EEM_Price_Type::base_type_tax ),
156
-            'order_by' => array( 'Price_Type.PRT_order' => 'ASC', 'PRC_order' => 'ASC' )
157
-        ));
158
-        foreach ($all_taxes as $tax) {
159
-            if ($tax instanceof EE_Price) {
160
-                $taxes[ $tax->order() ][ $tax->ID() ] = $tax;
161
-            }
162
-        }
163
-        return $taxes;
164
-    }
165
-
166
-
167
-
168
-
169
-
170
-    /**
171
-     *      retrieve all prices for an ticket plus default global prices, but not taxes
172
-     *
173
-     *      @access     public
174
-     *      @param int $TKT_ID          the id of the event.  If not included then we assume that this is a new ticket.
175
-     *      @return         boolean         false on fail
176
-     */
177
-    public function get_all_ticket_prices_for_admin($TKT_ID = 0)
178
-    {
179
-        $array_of_price_objects = array();
180
-        if (empty($TKT_ID)) {
181
-            // if there is no tkt, get prices with no tkt ID, are global, are not a tax, and are active
182
-            // return that list
183
-            $default_prices = $this->get_all_default_prices();
184
-
185
-            if ($default_prices) {
186
-                foreach ($default_prices as $price) {
187
-                    if ($price instanceof EE_Price) {
188
-                        $array_of_price_objects[ $price->type() ][] = $price;
189
-                    }
190
-                }
191
-                return $array_of_price_objects;
192
-            } else {
193
-                return array();
194
-            }
195
-        } else {
196
-            $ticket_prices = $this->get_all(array(
197
-                array(
198
-                    'TKT_ID' => $TKT_ID,
199
-                    'PRC_deleted' => 0
200
-                    ),
201
-                'order_by' => array('PRC_order' => 'ASC')
202
-            ));
203
-        }
204
-
205
-        if (!empty($ticket_prices)) {
206
-            foreach ($ticket_prices as $price) {
207
-                if ($price instanceof EE_Price) {
208
-                    $array_of_price_objects[ $price->type() ][] = $price;
209
-                }
210
-            }
211
-            return $array_of_price_objects;
212
-        } else {
213
-            return false;
214
-        }
215
-    }
216
-
217
-
218
-
219
-    /**
220
-     *        _sort_event_prices_by_type
221
-     *
222
-     * @access public
223
-     * @param \EE_Price $price_a
224
-     * @param \EE_Price $price_b
225
-     * @return bool false on fail
226
-     */
227
-    public function _sort_event_prices_by_type(EE_Price $price_a, EE_Price $price_b)
228
-    {
229
-        if ($price_a->type_obj()->order() == $price_b->type_obj()->order()) {
230
-            return $this->_sort_event_prices_by_order($price_a, $price_b);
231
-        }
232
-        return $price_a->type_obj()->order() < $price_b->type_obj()->order() ? -1 : 1;
233
-    }
234
-
235
-
236
-
237
-    /**
238
-     *        _sort_event_prices_by_order
239
-     *
240
-     * @access public
241
-     * @param \EE_Price $price_a
242
-     * @param \EE_Price $price_b
243
-     * @return bool false on fail
244
-     */
245
-    public function _sort_event_prices_by_order(EE_Price $price_a, EE_Price $price_b)
246
-    {
247
-        if ($price_a->order() == $price_b->order()) {
248
-            return 0;
249
-        }
250
-        return $price_a->order() < $price_b->order() ? -1 : 1;
251
-    }
252
-
253
-
254
-
255
-    /**
256
-     *      get all prices of a specific type
257
-     *
258
-     *      @access     public
259
-     *      @param      int                 $type - PRT_ID
260
-     *      @return         boolean     false on fail
261
-     */
262
-    public function get_all_prices_that_are_type($type = 0)
263
-    {
264
-        return $this->get_all(array(
265
-            array(
266
-                'PRT_ID' => $type
267
-            ),
268
-            'order_by' => $this->_order_by_array_for_get_all_method()
269
-        ));
270
-    }
271
-
272
-
273
-
274
-    /**
275
-     * Returns an array of the normal 'order_by' query parameter provided to the get_all query.
276
-     * Of course you don't have to use it, but this is the order we usually want to sort prices by
277
-     * @return array which can be used like so: $this->get_all(array(array(...where stuff...),'order_by'=>$this->_order_by_array_for_get_all_method()));
278
-     */
279
-    public function _order_by_array_for_get_all_method()
280
-    {
281
-        return array(
282
-                'PRC_order' => 'ASC',
283
-                'Price_Type.PRT_order' => 'ASC',
284
-                'PRC_ID' => 'ASC'
285
-        );
286
-    }
12
+	// private instance of the EEM_Price object
13
+	protected static $_instance = null;
14
+
15
+
16
+
17
+	/**
18
+	 *      private constructor to prevent direct creation
19
+	 *      @Constructor
20
+	 *      @access protected
21
+	 *      @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any incoming timezone data that gets saved).  Note this just sends the timezone info to the date time model field objects.  Default is NULL (and will be assumed using the set timezone in the 'timezone_string' wp option)
22
+	 *      @return EEM_Price
23
+	 */
24
+	protected function __construct($timezone)
25
+	{
26
+		require_once(EE_MODELS . 'EEM_Price_Type.model.php');
27
+		$this->singular_item = esc_html__('Price', 'event_espresso');
28
+		$this->plural_item = esc_html__('Prices', 'event_espresso');
29
+
30
+		$this->_tables = array(
31
+			'Price' => new EE_Primary_Table('esp_price', 'PRC_ID')
32
+		);
33
+		$this->_fields = array(
34
+			'Price' => array(
35
+				'PRC_ID' => new EE_Primary_Key_Int_Field('PRC_ID', 'Price ID'),
36
+				'PRT_ID' => new EE_Foreign_Key_Int_Field('PRT_ID', 'Price type Id', false, null, 'Price_Type'),
37
+				'PRC_amount' => new EE_Money_Field('PRC_amount', 'Price Amount', false, 0),
38
+				'PRC_name' => new EE_Plain_Text_Field('PRC_name', 'Name of Price', false, ''),
39
+				'PRC_desc' => new EE_Post_Content_Field('PRC_desc', 'Price Description', false, ''),
40
+				'PRC_is_default' => new EE_Boolean_Field('PRC_is_default', 'Flag indicating whether price is a default price', false, false),
41
+				'PRC_overrides' => new EE_Integer_Field('PRC_overrides', 'Price ID for a global Price that will be overridden by this Price  ( for replacing default prices )', true, 0),
42
+				'PRC_order' => new EE_Integer_Field('PRC_order', 'Order of Application of Price (lower numbers apply first?)', false, 1),
43
+				'PRC_deleted' => new EE_Trashed_Flag_Field('PRC_deleted', 'Flag Indicating if this has been deleted or not', false, false),
44
+				'PRC_parent' => new EE_Integer_Field('PRC_parent', esc_html__('Indicates what PRC_ID is the parent of this PRC_ID', 'event_espresso'), true, 0),
45
+				'PRC_wp_user' => new EE_WP_User_Field('PRC_wp_user', esc_html__('Price Creator ID', 'event_espresso'), false),
46
+			)
47
+		);
48
+		$this->_model_relations = array(
49
+			'Ticket' => new EE_HABTM_Relation('Ticket_Price'),
50
+			'Price_Type' => new EE_Belongs_To_Relation(),
51
+			'WP_User' => new EE_Belongs_To_Relation(),
52
+		);
53
+		// this model is generally available for reading
54
+		$this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Default_Public('PRC_is_default', 'Ticket.Datetime.Event');
55
+		// account for default tickets in the caps
56
+		$this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] = new EE_Restriction_Generator_Default_Protected('PRC_is_default', 'Ticket.Datetime.Event');
57
+		$this->_cap_restriction_generators[ EEM_Base::caps_edit ] = new EE_Restriction_Generator_Default_Protected('PRC_is_default', 'Ticket.Datetime.Event');
58
+		$this->_cap_restriction_generators[ EEM_Base::caps_delete ] = new EE_Restriction_Generator_Default_Protected('PRC_is_default', 'Ticket.Datetime.Event');
59
+		parent::__construct($timezone);
60
+	}
61
+
62
+
63
+
64
+	/**
65
+	 *      instantiate a new price object with blank/empty properties
66
+	 *
67
+	 *      @access     public
68
+	 *      @return     mixed       array on success, FALSE on fail
69
+	 */
70
+	public function get_new_price()
71
+	{
72
+		return $this->create_default_object();
73
+	}
74
+
75
+
76
+
77
+
78
+
79
+	/**
80
+	 *      retrieve  ALL prices from db
81
+	 *
82
+	 *      @access     public
83
+	 *      @return     EE_PRice[]
84
+	 */
85
+	public function get_all_prices()
86
+	{
87
+		// retrieve all prices
88
+		return $this->get_all(array('order_by' => array('PRC_amount' => 'ASC')));
89
+	}
90
+
91
+
92
+
93
+	/**
94
+	 *        retrieve all active prices for a particular event
95
+	 *
96
+	 * @access        public
97
+	 * @param int $EVT_ID
98
+	 * @return array on success
99
+	 */
100
+	public function get_all_event_prices($EVT_ID = 0)
101
+	{
102
+		return $this->get_all(array(
103
+			array(
104
+				'EVT_ID' => $EVT_ID,
105
+				'Price_Type.PBT_ID' => array('!=',  EEM_Price_Type::base_type_tax)
106
+			),
107
+			'order_by' => $this->_order_by_array_for_get_all_method()
108
+		));
109
+	}
110
+
111
+
112
+	/**
113
+	 *      retrieve all active global prices (that are not taxes (PBT_ID=4)) for a particular event
114
+	 *
115
+	 *      @access     public
116
+	 *      @param      boolean         $count  return count
117
+	 *      @return         array           on success
118
+	 *      @return         boolean     false on fail
119
+	 */
120
+	public function get_all_default_prices($count = false)
121
+	{
122
+		$_where = array(
123
+			'Price_Type.PBT_ID' => array('!=',4),
124
+			'PRC_deleted' => 0,
125
+			'PRC_is_default' => 1
126
+		);
127
+		$_query_params = array(
128
+			$_where,
129
+			'order_by' => $this->_order_by_array_for_get_all_method()
130
+		);
131
+		return $count ? $this->count(array($_where)) : $this->get_all($_query_params);
132
+	}
133
+
134
+
135
+
136
+
137
+
138
+
139
+
140
+
141
+
142
+
143
+	/**
144
+	 *      retrieve all prices that are taxes
145
+	 *
146
+	 *      @access     public
147
+	 *      @return         array               on success
148
+	 *      @return         array top-level keys are the price's order and their values are an array,
149
+	 *                      next-level keys are the price's ID, and their values are EE_Price objects
150
+	 */
151
+	public function get_all_prices_that_are_taxes()
152
+	{
153
+		$taxes = array();
154
+		$all_taxes = $this->get_all(array(
155
+			array( 'Price_Type.PBT_ID' =>  EEM_Price_Type::base_type_tax ),
156
+			'order_by' => array( 'Price_Type.PRT_order' => 'ASC', 'PRC_order' => 'ASC' )
157
+		));
158
+		foreach ($all_taxes as $tax) {
159
+			if ($tax instanceof EE_Price) {
160
+				$taxes[ $tax->order() ][ $tax->ID() ] = $tax;
161
+			}
162
+		}
163
+		return $taxes;
164
+	}
165
+
166
+
167
+
168
+
169
+
170
+	/**
171
+	 *      retrieve all prices for an ticket plus default global prices, but not taxes
172
+	 *
173
+	 *      @access     public
174
+	 *      @param int $TKT_ID          the id of the event.  If not included then we assume that this is a new ticket.
175
+	 *      @return         boolean         false on fail
176
+	 */
177
+	public function get_all_ticket_prices_for_admin($TKT_ID = 0)
178
+	{
179
+		$array_of_price_objects = array();
180
+		if (empty($TKT_ID)) {
181
+			// if there is no tkt, get prices with no tkt ID, are global, are not a tax, and are active
182
+			// return that list
183
+			$default_prices = $this->get_all_default_prices();
184
+
185
+			if ($default_prices) {
186
+				foreach ($default_prices as $price) {
187
+					if ($price instanceof EE_Price) {
188
+						$array_of_price_objects[ $price->type() ][] = $price;
189
+					}
190
+				}
191
+				return $array_of_price_objects;
192
+			} else {
193
+				return array();
194
+			}
195
+		} else {
196
+			$ticket_prices = $this->get_all(array(
197
+				array(
198
+					'TKT_ID' => $TKT_ID,
199
+					'PRC_deleted' => 0
200
+					),
201
+				'order_by' => array('PRC_order' => 'ASC')
202
+			));
203
+		}
204
+
205
+		if (!empty($ticket_prices)) {
206
+			foreach ($ticket_prices as $price) {
207
+				if ($price instanceof EE_Price) {
208
+					$array_of_price_objects[ $price->type() ][] = $price;
209
+				}
210
+			}
211
+			return $array_of_price_objects;
212
+		} else {
213
+			return false;
214
+		}
215
+	}
216
+
217
+
218
+
219
+	/**
220
+	 *        _sort_event_prices_by_type
221
+	 *
222
+	 * @access public
223
+	 * @param \EE_Price $price_a
224
+	 * @param \EE_Price $price_b
225
+	 * @return bool false on fail
226
+	 */
227
+	public function _sort_event_prices_by_type(EE_Price $price_a, EE_Price $price_b)
228
+	{
229
+		if ($price_a->type_obj()->order() == $price_b->type_obj()->order()) {
230
+			return $this->_sort_event_prices_by_order($price_a, $price_b);
231
+		}
232
+		return $price_a->type_obj()->order() < $price_b->type_obj()->order() ? -1 : 1;
233
+	}
234
+
235
+
236
+
237
+	/**
238
+	 *        _sort_event_prices_by_order
239
+	 *
240
+	 * @access public
241
+	 * @param \EE_Price $price_a
242
+	 * @param \EE_Price $price_b
243
+	 * @return bool false on fail
244
+	 */
245
+	public function _sort_event_prices_by_order(EE_Price $price_a, EE_Price $price_b)
246
+	{
247
+		if ($price_a->order() == $price_b->order()) {
248
+			return 0;
249
+		}
250
+		return $price_a->order() < $price_b->order() ? -1 : 1;
251
+	}
252
+
253
+
254
+
255
+	/**
256
+	 *      get all prices of a specific type
257
+	 *
258
+	 *      @access     public
259
+	 *      @param      int                 $type - PRT_ID
260
+	 *      @return         boolean     false on fail
261
+	 */
262
+	public function get_all_prices_that_are_type($type = 0)
263
+	{
264
+		return $this->get_all(array(
265
+			array(
266
+				'PRT_ID' => $type
267
+			),
268
+			'order_by' => $this->_order_by_array_for_get_all_method()
269
+		));
270
+	}
271
+
272
+
273
+
274
+	/**
275
+	 * Returns an array of the normal 'order_by' query parameter provided to the get_all query.
276
+	 * Of course you don't have to use it, but this is the order we usually want to sort prices by
277
+	 * @return array which can be used like so: $this->get_all(array(array(...where stuff...),'order_by'=>$this->_order_by_array_for_get_all_method()));
278
+	 */
279
+	public function _order_by_array_for_get_all_method()
280
+	{
281
+		return array(
282
+				'PRC_order' => 'ASC',
283
+				'Price_Type.PRT_order' => 'ASC',
284
+				'PRC_ID' => 'ASC'
285
+		);
286
+	}
287 287
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Base.model.php 2 patches
Spacing   +227 added lines, -227 removed lines patch added patch discarded remove patch
@@ -555,7 +555,7 @@  discard block
 block discarded – undo
555 555
     protected function __construct($timezone = null)
556 556
     {
557 557
         // check that the model has not been loaded too soon
558
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
558
+        if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
559 559
             throw new EE_Error(
560 560
                 sprintf(
561 561
                     esc_html__(
@@ -578,7 +578,7 @@  discard block
 block discarded – undo
578 578
          *
579 579
          * @var EE_Table_Base[] $_tables
580 580
          */
581
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
581
+        $this->_tables = (array) apply_filters('FHEE__'.get_class($this).'__construct__tables', $this->_tables);
582 582
         foreach ($this->_tables as $table_alias => $table_obj) {
583 583
             /** @var $table_obj EE_Table_Base */
584 584
             $table_obj->_construct_finalize_with_alias($table_alias);
@@ -593,10 +593,10 @@  discard block
 block discarded – undo
593 593
          *
594 594
          * @param EE_Model_Field_Base[] $_fields
595 595
          */
596
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
596
+        $this->_fields = (array) apply_filters('FHEE__'.get_class($this).'__construct__fields', $this->_fields);
597 597
         $this->_invalidate_field_caches();
598 598
         foreach ($this->_fields as $table_alias => $fields_for_table) {
599
-            if (! array_key_exists($table_alias, $this->_tables)) {
599
+            if ( ! array_key_exists($table_alias, $this->_tables)) {
600 600
                 throw new EE_Error(sprintf(esc_html__(
601 601
                     "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
602 602
                     'event_espresso'
@@ -627,7 +627,7 @@  discard block
 block discarded – undo
627 627
          * @param EE_Model_Relation_Base[] $_model_relations
628 628
          */
629 629
         $this->_model_relations = (array) apply_filters(
630
-            'FHEE__' . get_class($this) . '__construct__model_relations',
630
+            'FHEE__'.get_class($this).'__construct__model_relations',
631 631
             $this->_model_relations
632 632
         );
633 633
         foreach ($this->_model_relations as $model_name => $relation_obj) {
@@ -640,12 +640,12 @@  discard block
 block discarded – undo
640 640
         }
641 641
         $this->set_timezone($timezone);
642 642
         // finalize default where condition strategy, or set default
643
-        if (! $this->_default_where_conditions_strategy) {
643
+        if ( ! $this->_default_where_conditions_strategy) {
644 644
             // nothing was set during child constructor, so set default
645 645
             $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
646 646
         }
647 647
         $this->_default_where_conditions_strategy->_finalize_construct($this);
648
-        if (! $this->_minimum_where_conditions_strategy) {
648
+        if ( ! $this->_minimum_where_conditions_strategy) {
649 649
             // nothing was set during child constructor, so set default
650 650
             $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
651 651
         }
@@ -658,8 +658,8 @@  discard block
 block discarded – undo
658 658
         // initialize the standard cap restriction generators if none were specified by the child constructor
659 659
         if ($this->_cap_restriction_generators !== false) {
660 660
             foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
661
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
662
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
661
+                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
662
+                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
663 663
                         'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
664 664
                         new EE_Restriction_Generator_Protected(),
665 665
                         $cap_context,
@@ -671,10 +671,10 @@  discard block
 block discarded – undo
671 671
         // if there are cap restriction generators, use them to make the default cap restrictions
672 672
         if ($this->_cap_restriction_generators !== false) {
673 673
             foreach ($this->_cap_restriction_generators as $context => $generator_object) {
674
-                if (! $generator_object) {
674
+                if ( ! $generator_object) {
675 675
                     continue;
676 676
                 }
677
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
677
+                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
678 678
                     throw new EE_Error(
679 679
                         sprintf(
680 680
                             esc_html__(
@@ -687,12 +687,12 @@  discard block
 block discarded – undo
687 687
                     );
688 688
                 }
689 689
                 $action = $this->cap_action_for_context($context);
690
-                if (! $generator_object->construction_finalized()) {
690
+                if ( ! $generator_object->construction_finalized()) {
691 691
                     $generator_object->_construct_finalize($this, $action);
692 692
                 }
693 693
             }
694 694
         }
695
-        do_action('AHEE__' . get_class($this) . '__construct__end');
695
+        do_action('AHEE__'.get_class($this).'__construct__end');
696 696
     }
697 697
 
698 698
 
@@ -739,7 +739,7 @@  discard block
 block discarded – undo
739 739
     public static function instance($timezone = null)
740 740
     {
741 741
         // check if instance of Espresso_model already exists
742
-        if (! static::$_instance instanceof static) {
742
+        if ( ! static::$_instance instanceof static) {
743 743
             // instantiate Espresso_model
744 744
             static::$_instance = new static(
745 745
                 $timezone,
@@ -778,7 +778,7 @@  discard block
 block discarded – undo
778 778
             foreach ($r->getDefaultProperties() as $property => $value) {
779 779
                 // don't set instance to null like it was originally,
780 780
                 // but it's static anyways, and we're ignoring static properties (for now at least)
781
-                if (! isset($static_properties[ $property ])) {
781
+                if ( ! isset($static_properties[$property])) {
782 782
                     static::$_instance->{$property} = $value;
783 783
                 }
784 784
             }
@@ -802,7 +802,7 @@  discard block
 block discarded – undo
802 802
      */
803 803
     private static function getLoader()
804 804
     {
805
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
805
+        if ( ! EEM_Base::$loader instanceof LoaderInterface) {
806 806
             EEM_Base::$loader = LoaderFactory::getLoader();
807 807
         }
808 808
         return EEM_Base::$loader;
@@ -822,7 +822,7 @@  discard block
 block discarded – undo
822 822
      */
823 823
     public function status_array($translated = false)
824 824
     {
825
-        if (! array_key_exists('Status', $this->_model_relations)) {
825
+        if ( ! array_key_exists('Status', $this->_model_relations)) {
826 826
             return array();
827 827
         }
828 828
         $model_name = $this->get_this_model_name();
@@ -830,7 +830,7 @@  discard block
 block discarded – undo
830 830
         $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
831 831
         $status_array = array();
832 832
         foreach ($stati as $status) {
833
-            $status_array[ $status->ID() ] = $status->get('STS_code');
833
+            $status_array[$status->ID()] = $status->get('STS_code');
834 834
         }
835 835
         return $translated
836 836
             ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
@@ -891,7 +891,7 @@  discard block
 block discarded – undo
891 891
     {
892 892
         $wp_user_field_name = $this->wp_user_field_name();
893 893
         if ($wp_user_field_name) {
894
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
894
+            $query_params[0][$wp_user_field_name] = get_current_user_id();
895 895
         }
896 896
         return $query_params;
897 897
     }
@@ -909,17 +909,17 @@  discard block
 block discarded – undo
909 909
     public function wp_user_field_name()
910 910
     {
911 911
         try {
912
-            if (! empty($this->_model_chain_to_wp_user)) {
912
+            if ( ! empty($this->_model_chain_to_wp_user)) {
913 913
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
914 914
                 $last_model_name = end($models_to_follow_to_wp_users);
915 915
                 $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
916
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
916
+                $model_chain_to_wp_user = $this->_model_chain_to_wp_user.'.';
917 917
             } else {
918 918
                 $model_with_fk_to_wp_users = $this;
919 919
                 $model_chain_to_wp_user = '';
920 920
             }
921 921
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
922
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
922
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
923 923
         } catch (EE_Error $e) {
924 924
             return false;
925 925
         }
@@ -996,11 +996,11 @@  discard block
 block discarded – undo
996 996
         if ($this->_custom_selections instanceof CustomSelects) {
997 997
             $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
998 998
             $select_expressions .= $select_expressions
999
-                ? ', ' . $custom_expressions
999
+                ? ', '.$custom_expressions
1000 1000
                 : $custom_expressions;
1001 1001
         }
1002 1002
 
1003
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1003
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1004 1004
         return $this->_do_wpdb_query('get_results', array($SQL, $output));
1005 1005
     }
1006 1006
 
@@ -1017,7 +1017,7 @@  discard block
 block discarded – undo
1017 1017
      */
1018 1018
     protected function getCustomSelection(array $query_params, $columns_to_select = null)
1019 1019
     {
1020
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1020
+        if ( ! isset($query_params['extra_selects']) && $columns_to_select === null) {
1021 1021
             return null;
1022 1022
         }
1023 1023
         $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
@@ -1066,7 +1066,7 @@  discard block
 block discarded – undo
1066 1066
         if (is_array($columns_to_select)) {
1067 1067
             $select_sql_array = array();
1068 1068
             foreach ($columns_to_select as $alias => $selection_and_datatype) {
1069
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1069
+                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1070 1070
                     throw new EE_Error(
1071 1071
                         sprintf(
1072 1072
                             esc_html__(
@@ -1078,7 +1078,7 @@  discard block
 block discarded – undo
1078 1078
                         )
1079 1079
                     );
1080 1080
                 }
1081
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1081
+                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1082 1082
                     throw new EE_Error(
1083 1083
                         sprintf(
1084 1084
                             esc_html__(
@@ -1157,12 +1157,12 @@  discard block
 block discarded – undo
1157 1157
      */
1158 1158
     public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1159 1159
     {
1160
-        if (! isset($query_params[0])) {
1160
+        if ( ! isset($query_params[0])) {
1161 1161
             $query_params[0] = array();
1162 1162
         }
1163 1163
         $conditions_from_id = $this->parse_index_primary_key_string($id);
1164 1164
         if ($conditions_from_id === null) {
1165
-            $query_params[0][ $this->primary_key_name() ] = $id;
1165
+            $query_params[0][$this->primary_key_name()] = $id;
1166 1166
         } else {
1167 1167
             // no primary key, so the $id must be from the get_index_primary_key_string()
1168 1168
             $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
@@ -1182,7 +1182,7 @@  discard block
 block discarded – undo
1182 1182
      */
1183 1183
     public function get_one($query_params = array())
1184 1184
     {
1185
-        if (! is_array($query_params)) {
1185
+        if ( ! is_array($query_params)) {
1186 1186
             EE_Error::doing_it_wrong(
1187 1187
                 'EEM_Base::get_one',
1188 1188
                 sprintf(
@@ -1380,7 +1380,7 @@  discard block
 block discarded – undo
1380 1380
                 return array();
1381 1381
             }
1382 1382
         }
1383
-        if (! is_array($query_params)) {
1383
+        if ( ! is_array($query_params)) {
1384 1384
             EE_Error::doing_it_wrong(
1385 1385
                 'EEM_Base::_get_consecutive',
1386 1386
                 sprintf(
@@ -1392,7 +1392,7 @@  discard block
 block discarded – undo
1392 1392
             $query_params = array();
1393 1393
         }
1394 1394
         // let's add the where query param for consecutive look up.
1395
-        $query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1395
+        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1396 1396
         $query_params['limit'] = $limit;
1397 1397
         // set direction
1398 1398
         $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
@@ -1473,7 +1473,7 @@  discard block
 block discarded – undo
1473 1473
     {
1474 1474
         $field_settings = $this->field_settings_for($field_name);
1475 1475
         // if not a valid EE_Datetime_Field then throw error
1476
-        if (! $field_settings instanceof EE_Datetime_Field) {
1476
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1477 1477
             throw new EE_Error(sprintf(esc_html__(
1478 1478
                 '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.',
1479 1479
                 'event_espresso'
@@ -1622,7 +1622,7 @@  discard block
 block discarded – undo
1622 1622
      */
1623 1623
     public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1624 1624
     {
1625
-        if (! is_array($query_params)) {
1625
+        if ( ! is_array($query_params)) {
1626 1626
             EE_Error::doing_it_wrong(
1627 1627
                 'EEM_Base::update',
1628 1628
                 sprintf(
@@ -1670,7 +1670,7 @@  discard block
 block discarded – undo
1670 1670
             $wpdb_result = (array) $wpdb_result;
1671 1671
             // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1672 1672
             if ($this->has_primary_key_field()) {
1673
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1673
+                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1674 1674
             } else {
1675 1675
                 // 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)
1676 1676
                 $main_table_pk_value = null;
@@ -1686,7 +1686,7 @@  discard block
 block discarded – undo
1686 1686
                     // in this table, right? so insert a row in the current table, using any fields available
1687 1687
                     if (
1688 1688
                         ! (array_key_exists($this_table_pk_column, $wpdb_result)
1689
-                           && $wpdb_result[ $this_table_pk_column ])
1689
+                           && $wpdb_result[$this_table_pk_column])
1690 1690
                     ) {
1691 1691
                         $success = $this->_insert_into_specific_table(
1692 1692
                             $table_obj,
@@ -1694,7 +1694,7 @@  discard block
 block discarded – undo
1694 1694
                             $main_table_pk_value
1695 1695
                         );
1696 1696
                         // if we died here, report the error
1697
-                        if (! $success) {
1697
+                        if ( ! $success) {
1698 1698
                             return false;
1699 1699
                         }
1700 1700
                     }
@@ -1722,10 +1722,10 @@  discard block
 block discarded – undo
1722 1722
                 $model_objs_affected_ids = array();
1723 1723
                 foreach ($models_affected_key_columns as $row) {
1724 1724
                     $combined_index_key = $this->get_index_primary_key_string($row);
1725
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1725
+                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1726 1726
                 }
1727 1727
             }
1728
-            if (! $model_objs_affected_ids) {
1728
+            if ( ! $model_objs_affected_ids) {
1729 1729
                 // wait wait wait- if nothing was affected let's stop here
1730 1730
                 return 0;
1731 1731
             }
@@ -1752,7 +1752,7 @@  discard block
 block discarded – undo
1752 1752
                . $model_query_info->get_full_join_sql()
1753 1753
                . " SET "
1754 1754
                . $this->_construct_update_sql($fields_n_values)
1755
-               . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1755
+               . $model_query_info->get_where_sql(); // note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1756 1756
         $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1757 1757
         /**
1758 1758
          * Action called after a model update call has been made.
@@ -1763,7 +1763,7 @@  discard block
 block discarded – undo
1763 1763
          * @param int      $rows_affected
1764 1764
          */
1765 1765
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1766
-        return $rows_affected;// how many supposedly got updated
1766
+        return $rows_affected; // how many supposedly got updated
1767 1767
     }
1768 1768
 
1769 1769
 
@@ -1791,7 +1791,7 @@  discard block
 block discarded – undo
1791 1791
         }
1792 1792
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1793 1793
         $select_expressions = $field->get_qualified_column();
1794
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1794
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1795 1795
         return $this->_do_wpdb_query('get_col', array($SQL));
1796 1796
     }
1797 1797
 
@@ -1809,7 +1809,7 @@  discard block
 block discarded – undo
1809 1809
     {
1810 1810
         $query_params['limit'] = 1;
1811 1811
         $col = $this->get_col($query_params, $field_to_select);
1812
-        if (! empty($col)) {
1812
+        if ( ! empty($col)) {
1813 1813
             return reset($col);
1814 1814
         }
1815 1815
         return null;
@@ -1840,7 +1840,7 @@  discard block
 block discarded – undo
1840 1840
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1841 1841
             $value_sql = $prepared_value === null ? 'NULL'
1842 1842
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1843
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1843
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1844 1844
         }
1845 1845
         return implode(",", $cols_n_values);
1846 1846
     }
@@ -1984,12 +1984,12 @@  discard block
 block discarded – undo
1984 1984
         if (
1985 1985
             $this->has_primary_key_field()
1986 1986
             && $rows_deleted !== false
1987
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
1987
+            && isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
1988 1988
         ) {
1989
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
1989
+            $ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
1990 1990
             foreach ($ids_for_removal as $id) {
1991
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
1992
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
1991
+                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
1992
+                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
1993 1993
                 }
1994 1994
             }
1995 1995
 
@@ -2026,7 +2026,7 @@  discard block
 block discarded – undo
2026 2026
          * @param int      $rows_deleted
2027 2027
          */
2028 2028
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2029
-        return $rows_deleted;// how many supposedly got deleted
2029
+        return $rows_deleted; // how many supposedly got deleted
2030 2030
     }
2031 2031
 
2032 2032
 
@@ -2120,15 +2120,15 @@  discard block
 block discarded – undo
2120 2120
                 if (
2121 2121
                     $allow_blocking
2122 2122
                     && $this->delete_is_blocked_by_related_models(
2123
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2123
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2124 2124
                     )
2125 2125
                 ) {
2126 2126
                     continue;
2127 2127
                 }
2128 2128
                 // primary table deletes
2129
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2130
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2131
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2129
+                if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2130
+                    $ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2131
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2132 2132
                 }
2133 2133
             }
2134 2134
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2137,8 +2137,8 @@  discard block
 block discarded – undo
2137 2137
                 $ids_to_delete_indexed_by_column_for_row = array();
2138 2138
                 foreach ($fields as $cpk_field) {
2139 2139
                     if ($cpk_field instanceof EE_Model_Field_Base) {
2140
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2141
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2140
+                        $ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2141
+                            $item_to_delete[$cpk_field->get_qualified_column()];
2142 2142
                     }
2143 2143
                 }
2144 2144
                 $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
@@ -2176,7 +2176,7 @@  discard block
 block discarded – undo
2176 2176
         } elseif ($this->has_primary_key_field()) {
2177 2177
             $query = array();
2178 2178
             foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2179
-                $query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2179
+                $query[] = $column.' IN'.$this->_construct_in_value($ids, $this->_primary_key_field);
2180 2180
             }
2181 2181
             $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2182 2182
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2184,7 +2184,7 @@  discard block
 block discarded – undo
2184 2184
             foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2185 2185
                 $values_for_each_combined_primary_key_for_a_row = array();
2186 2186
                 foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2187
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2187
+                    $values_for_each_combined_primary_key_for_a_row[] = $column.'='.$id;
2188 2188
                 }
2189 2189
                 $ways_to_identify_a_row[] = '('
2190 2190
                                             . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
@@ -2256,8 +2256,8 @@  discard block
 block discarded – undo
2256 2256
                 $column_to_count = '*';
2257 2257
             }
2258 2258
         }
2259
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2260
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2259
+        $column_to_count = $distinct ? "DISTINCT ".$column_to_count : $column_to_count;
2260
+        $SQL = "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2261 2261
         return (int) $this->_do_wpdb_query('get_var', array($SQL));
2262 2262
     }
2263 2263
 
@@ -2280,7 +2280,7 @@  discard block
 block discarded – undo
2280 2280
             $field_obj = $this->get_primary_key_field();
2281 2281
         }
2282 2282
         $column_to_count = $field_obj->get_qualified_column();
2283
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2283
+        $SQL = "SELECT SUM(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2284 2284
         $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2285 2285
         $data_type = $field_obj->get_wpdb_data_type();
2286 2286
         if ($data_type === '%d' || $data_type === '%s') {
@@ -2307,7 +2307,7 @@  discard block
 block discarded – undo
2307 2307
         // if we're in maintenance mode level 2, DON'T run any queries
2308 2308
         // because level 2 indicates the database needs updating and
2309 2309
         // is probably out of sync with the code
2310
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2310
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2311 2311
             throw new EE_Error(sprintf(esc_html__(
2312 2312
                 "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.",
2313 2313
                 "event_espresso"
@@ -2315,7 +2315,7 @@  discard block
 block discarded – undo
2315 2315
         }
2316 2316
         /** @type WPDB $wpdb */
2317 2317
         global $wpdb;
2318
-        if (! method_exists($wpdb, $wpdb_method)) {
2318
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2319 2319
             throw new EE_Error(sprintf(esc_html__(
2320 2320
                 'There is no method named "%s" on Wordpress\' $wpdb object',
2321 2321
                 'event_espresso'
@@ -2329,7 +2329,7 @@  discard block
 block discarded – undo
2329 2329
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2330 2330
         if (WP_DEBUG) {
2331 2331
             $wpdb->show_errors($old_show_errors_value);
2332
-            if (! empty($wpdb->last_error)) {
2332
+            if ( ! empty($wpdb->last_error)) {
2333 2333
                 throw new EE_Error(sprintf(esc_html__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2334 2334
             }
2335 2335
             if ($result === false) {
@@ -2395,7 +2395,7 @@  discard block
 block discarded – undo
2395 2395
                     return $result;
2396 2396
                     break;
2397 2397
             }
2398
-            if (! empty($error_message)) {
2398
+            if ( ! empty($error_message)) {
2399 2399
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2400 2400
                 trigger_error($error_message);
2401 2401
             }
@@ -2475,11 +2475,11 @@  discard block
 block discarded – undo
2475 2475
      */
2476 2476
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2477 2477
     {
2478
-        return " FROM " . $model_query_info->get_full_join_sql() .
2479
-               $model_query_info->get_where_sql() .
2480
-               $model_query_info->get_group_by_sql() .
2481
-               $model_query_info->get_having_sql() .
2482
-               $model_query_info->get_order_by_sql() .
2478
+        return " FROM ".$model_query_info->get_full_join_sql().
2479
+               $model_query_info->get_where_sql().
2480
+               $model_query_info->get_group_by_sql().
2481
+               $model_query_info->get_having_sql().
2482
+               $model_query_info->get_order_by_sql().
2483 2483
                $model_query_info->get_limit_sql();
2484 2484
     }
2485 2485
 
@@ -2675,12 +2675,12 @@  discard block
 block discarded – undo
2675 2675
         $related_model = $this->get_related_model_obj($model_name);
2676 2676
         // we're just going to use the query params on the related model's normal get_all query,
2677 2677
         // except add a condition to say to match the current mod
2678
-        if (! isset($query_params['default_where_conditions'])) {
2678
+        if ( ! isset($query_params['default_where_conditions'])) {
2679 2679
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2680 2680
         }
2681 2681
         $this_model_name = $this->get_this_model_name();
2682 2682
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2683
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2683
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2684 2684
         return $related_model->count($query_params, $field_to_count, $distinct);
2685 2685
     }
2686 2686
 
@@ -2700,7 +2700,7 @@  discard block
 block discarded – undo
2700 2700
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2701 2701
     {
2702 2702
         $related_model = $this->get_related_model_obj($model_name);
2703
-        if (! is_array($query_params)) {
2703
+        if ( ! is_array($query_params)) {
2704 2704
             EE_Error::doing_it_wrong(
2705 2705
                 'EEM_Base::sum_related',
2706 2706
                 sprintf(
@@ -2713,12 +2713,12 @@  discard block
 block discarded – undo
2713 2713
         }
2714 2714
         // we're just going to use the query params on the related model's normal get_all query,
2715 2715
         // except add a condition to say to match the current mod
2716
-        if (! isset($query_params['default_where_conditions'])) {
2716
+        if ( ! isset($query_params['default_where_conditions'])) {
2717 2717
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2718 2718
         }
2719 2719
         $this_model_name = $this->get_this_model_name();
2720 2720
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2721
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2721
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2722 2722
         return $related_model->sum($query_params, $field_to_sum);
2723 2723
     }
2724 2724
 
@@ -2771,7 +2771,7 @@  discard block
 block discarded – undo
2771 2771
                 $field_with_model_name = $field;
2772 2772
             }
2773 2773
         }
2774
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2774
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2775 2775
             throw new EE_Error(sprintf(
2776 2776
                 esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2777 2777
                 $this->get_this_model_name()
@@ -2908,13 +2908,13 @@  discard block
 block discarded – undo
2908 2908
                 || $this->get_primary_key_field()
2909 2909
                    instanceof
2910 2910
                    EE_Primary_Key_String_Field)
2911
-            && isset($fields_n_values[ $this->primary_key_name() ])
2911
+            && isset($fields_n_values[$this->primary_key_name()])
2912 2912
         ) {
2913
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2913
+            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2914 2914
         }
2915 2915
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2916 2916
             $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2917
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2917
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2918 2918
         }
2919 2919
         // if there is nothing to base this search on, then we shouldn't find anything
2920 2920
         if (empty($query_params)) {
@@ -2992,15 +2992,15 @@  discard block
 block discarded – undo
2992 2992
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2993 2993
             // if the value we want to assign it to is NULL, just don't mention it for the insertion
2994 2994
             if ($prepared_value !== null) {
2995
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
2995
+                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2996 2996
                 $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2997 2997
             }
2998 2998
         }
2999 2999
         if ($table instanceof EE_Secondary_Table && $new_id) {
3000 3000
             // its not the main table, so we should have already saved the main table's PK which we just inserted
3001 3001
             // so add the fk to the main table as a column
3002
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3003
-            $format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
3002
+            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
3003
+            $format_for_insertion[] = '%d'; // yes right now we're only allowing these foreign keys to be INTs
3004 3004
         }
3005 3005
         // insert the new entry
3006 3006
         $result = $this->_do_wpdb_query(
@@ -3017,7 +3017,7 @@  discard block
 block discarded – undo
3017 3017
             }
3018 3018
             // it's not an auto-increment primary key, so
3019 3019
             // it must have been supplied
3020
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3020
+            return $fields_n_values[$this->get_primary_key_field()->get_name()];
3021 3021
         }
3022 3022
         // we can't return a  primary key because there is none. instead return
3023 3023
         // a unique string indicating this model
@@ -3042,14 +3042,14 @@  discard block
 block discarded – undo
3042 3042
         if (
3043 3043
             ! $field_obj->is_nullable()
3044 3044
             && (
3045
-                ! isset($fields_n_values[ $field_obj->get_name() ])
3046
-                || $fields_n_values[ $field_obj->get_name() ] === null
3045
+                ! isset($fields_n_values[$field_obj->get_name()])
3046
+                || $fields_n_values[$field_obj->get_name()] === null
3047 3047
             )
3048 3048
         ) {
3049
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3049
+            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
3050 3050
         }
3051
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3052
-            ? $fields_n_values[ $field_obj->get_name() ]
3051
+        $unprepared_value = isset($fields_n_values[$field_obj->get_name()])
3052
+            ? $fields_n_values[$field_obj->get_name()]
3053 3053
             : null;
3054 3054
         return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3055 3055
     }
@@ -3150,7 +3150,7 @@  discard block
 block discarded – undo
3150 3150
      */
3151 3151
     public function get_table_obj_by_alias($table_alias = '')
3152 3152
     {
3153
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3153
+        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3154 3154
     }
3155 3155
 
3156 3156
 
@@ -3165,7 +3165,7 @@  discard block
 block discarded – undo
3165 3165
         $other_tables = array();
3166 3166
         foreach ($this->_tables as $table_alias => $table) {
3167 3167
             if ($table instanceof EE_Secondary_Table) {
3168
-                $other_tables[ $table_alias ] = $table;
3168
+                $other_tables[$table_alias] = $table;
3169 3169
             }
3170 3170
         }
3171 3171
         return $other_tables;
@@ -3181,7 +3181,7 @@  discard block
 block discarded – undo
3181 3181
      */
3182 3182
     public function _get_fields_for_table($table_alias)
3183 3183
     {
3184
-        return $this->_fields[ $table_alias ];
3184
+        return $this->_fields[$table_alias];
3185 3185
     }
3186 3186
 
3187 3187
 
@@ -3210,7 +3210,7 @@  discard block
 block discarded – undo
3210 3210
                     $query_info_carrier,
3211 3211
                     'group_by'
3212 3212
                 );
3213
-            } elseif (! empty($query_params['group_by'])) {
3213
+            } elseif ( ! empty($query_params['group_by'])) {
3214 3214
                 $this->_extract_related_model_info_from_query_param(
3215 3215
                     $query_params['group_by'],
3216 3216
                     $query_info_carrier,
@@ -3232,7 +3232,7 @@  discard block
 block discarded – undo
3232 3232
                     $query_info_carrier,
3233 3233
                     'order_by'
3234 3234
                 );
3235
-            } elseif (! empty($query_params['order_by'])) {
3235
+            } elseif ( ! empty($query_params['order_by'])) {
3236 3236
                 $this->_extract_related_model_info_from_query_param(
3237 3237
                     $query_params['order_by'],
3238 3238
                     $query_info_carrier,
@@ -3267,7 +3267,7 @@  discard block
 block discarded – undo
3267 3267
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3268 3268
         $query_param_type
3269 3269
     ) {
3270
-        if (! empty($sub_query_params)) {
3270
+        if ( ! empty($sub_query_params)) {
3271 3271
             $sub_query_params = (array) $sub_query_params;
3272 3272
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3273 3273
                 // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
@@ -3282,7 +3282,7 @@  discard block
 block discarded – undo
3282 3282
                 // of array('Registration.TXN_ID'=>23)
3283 3283
                 $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3284 3284
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3285
-                    if (! is_array($possibly_array_of_params)) {
3285
+                    if ( ! is_array($possibly_array_of_params)) {
3286 3286
                         throw new EE_Error(sprintf(
3287 3287
                             esc_html__(
3288 3288
                                 "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'))",
@@ -3306,7 +3306,7 @@  discard block
 block discarded – undo
3306 3306
                     // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3307 3307
                     // indicating that $possible_array_of_params[1] is actually a field name,
3308 3308
                     // from which we should extract query parameters!
3309
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3309
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3310 3310
                         throw new EE_Error(sprintf(esc_html__(
3311 3311
                             "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3312 3312
                             "event_espresso"
@@ -3340,8 +3340,8 @@  discard block
 block discarded – undo
3340 3340
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3341 3341
         $query_param_type
3342 3342
     ) {
3343
-        if (! empty($sub_query_params)) {
3344
-            if (! is_array($sub_query_params)) {
3343
+        if ( ! empty($sub_query_params)) {
3344
+            if ( ! is_array($sub_query_params)) {
3345 3345
                 throw new EE_Error(sprintf(
3346 3346
                     esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3347 3347
                     $sub_query_params
@@ -3375,7 +3375,7 @@  discard block
 block discarded – undo
3375 3375
      */
3376 3376
     public function _create_model_query_info_carrier($query_params)
3377 3377
     {
3378
-        if (! is_array($query_params)) {
3378
+        if ( ! is_array($query_params)) {
3379 3379
             EE_Error::doing_it_wrong(
3380 3380
                 'EEM_Base::_create_model_query_info_carrier',
3381 3381
                 sprintf(
@@ -3408,7 +3408,7 @@  discard block
 block discarded – undo
3408 3408
             // only include if related to a cpt where no password has been set
3409 3409
             $query_params[0]['OR*nopassword'] = array(
3410 3410
                 $where_param_key_for_password => '',
3411
-                $where_param_key_for_password . '*' => array('IS_NULL')
3411
+                $where_param_key_for_password.'*' => array('IS_NULL')
3412 3412
             );
3413 3413
         }
3414 3414
         $query_object = $this->_extract_related_models_from_query($query_params);
@@ -3462,7 +3462,7 @@  discard block
 block discarded – undo
3462 3462
         // set limit
3463 3463
         if (array_key_exists('limit', $query_params)) {
3464 3464
             if (is_array($query_params['limit'])) {
3465
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3465
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3466 3466
                     $e = sprintf(
3467 3467
                         esc_html__(
3468 3468
                             "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)",
@@ -3470,12 +3470,12 @@  discard block
 block discarded – undo
3470 3470
                         ),
3471 3471
                         http_build_query($query_params['limit'])
3472 3472
                     );
3473
-                    throw new EE_Error($e . "|" . $e);
3473
+                    throw new EE_Error($e."|".$e);
3474 3474
                 }
3475 3475
                 // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3476
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3477
-            } elseif (! empty($query_params['limit'])) {
3478
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3476
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3477
+            } elseif ( ! empty($query_params['limit'])) {
3478
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3479 3479
             }
3480 3480
         }
3481 3481
         // set order by
@@ -3507,10 +3507,10 @@  discard block
 block discarded – undo
3507 3507
                 $order_array = array();
3508 3508
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3509 3509
                     $order = $this->_extract_order($order);
3510
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3510
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3511 3511
                 }
3512
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3513
-            } elseif (! empty($query_params['order_by'])) {
3512
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3513
+            } elseif ( ! empty($query_params['order_by'])) {
3514 3514
                 $this->_extract_related_model_info_from_query_param(
3515 3515
                     $query_params['order_by'],
3516 3516
                     $query_object,
@@ -3521,7 +3521,7 @@  discard block
 block discarded – undo
3521 3521
                     ? $this->_extract_order($query_params['order'])
3522 3522
                     : 'DESC';
3523 3523
                 $query_object->set_order_by_sql(
3524
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3524
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3525 3525
                 );
3526 3526
             }
3527 3527
         }
@@ -3533,7 +3533,7 @@  discard block
 block discarded – undo
3533 3533
         ) {
3534 3534
             $pk_field = $this->get_primary_key_field();
3535 3535
             $order = $this->_extract_order($query_params['order']);
3536
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3536
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3537 3537
         }
3538 3538
         // set group by
3539 3539
         if (array_key_exists('group_by', $query_params)) {
@@ -3543,10 +3543,10 @@  discard block
 block discarded – undo
3543 3543
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3544 3544
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3545 3545
                 }
3546
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3547
-            } elseif (! empty($query_params['group_by'])) {
3546
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3547
+            } elseif ( ! empty($query_params['group_by'])) {
3548 3548
                 $query_object->set_group_by_sql(
3549
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3549
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3550 3550
                 );
3551 3551
             }
3552 3552
         }
@@ -3556,7 +3556,7 @@  discard block
 block discarded – undo
3556 3556
         }
3557 3557
         // now, just verify they didn't pass anything wack
3558 3558
         foreach ($query_params as $query_key => $query_value) {
3559
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3559
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3560 3560
                 throw new EE_Error(
3561 3561
                     sprintf(
3562 3562
                         esc_html__(
@@ -3664,7 +3664,7 @@  discard block
 block discarded – undo
3664 3664
         $where_query_params = array()
3665 3665
     ) {
3666 3666
         $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3667
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3667
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3668 3668
             throw new EE_Error(sprintf(
3669 3669
                 esc_html__(
3670 3670
                     "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
@@ -3796,19 +3796,19 @@  discard block
 block discarded – undo
3796 3796
     ) {
3797 3797
         $null_friendly_where_conditions = array();
3798 3798
         $none_overridden = true;
3799
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3799
+        $or_condition_key_for_defaults = 'OR*'.get_class($model);
3800 3800
         foreach ($default_where_conditions as $key => $val) {
3801
-            if (isset($provided_where_conditions[ $key ])) {
3801
+            if (isset($provided_where_conditions[$key])) {
3802 3802
                 $none_overridden = false;
3803 3803
             } else {
3804
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3804
+                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3805 3805
             }
3806 3806
         }
3807 3807
         if ($none_overridden && $default_where_conditions) {
3808 3808
             if ($model->has_primary_key_field()) {
3809
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3809
+                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3810 3810
                                                                                 . "."
3811
-                                                                                . $model->primary_key_name() ] = array('IS NULL');
3811
+                                                                                . $model->primary_key_name()] = array('IS NULL');
3812 3812
             }/*else{
3813 3813
                 //@todo NO PK, use other defaults
3814 3814
             }*/
@@ -3915,7 +3915,7 @@  discard block
 block discarded – undo
3915 3915
             foreach ($tables as $table_obj) {
3916 3916
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3917 3917
                                        . $table_obj->get_fully_qualified_pk_column();
3918
-                if (! in_array($qualified_pk_column, $selects)) {
3918
+                if ( ! in_array($qualified_pk_column, $selects)) {
3919 3919
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3920 3920
                 }
3921 3921
             }
@@ -4067,9 +4067,9 @@  discard block
 block discarded – undo
4067 4067
         $query_parameter_type
4068 4068
     ) {
4069 4069
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4070
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4070
+            if (strpos($possible_join_string, $valid_related_model_name.".") === 0) {
4071 4071
                 $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4072
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4072
+                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name."."));
4073 4073
                 if ($possible_join_string === '') {
4074 4074
                     // nothing left to $query_param
4075 4075
                     // we should actually end in a field name, not a model like this!
@@ -4200,7 +4200,7 @@  discard block
 block discarded – undo
4200 4200
     {
4201 4201
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4202 4202
         if ($SQL) {
4203
-            return " WHERE " . $SQL;
4203
+            return " WHERE ".$SQL;
4204 4204
         }
4205 4205
         return '';
4206 4206
     }
@@ -4219,7 +4219,7 @@  discard block
 block discarded – undo
4219 4219
     {
4220 4220
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4221 4221
         if ($SQL) {
4222
-            return " HAVING " . $SQL;
4222
+            return " HAVING ".$SQL;
4223 4223
         }
4224 4224
         return '';
4225 4225
     }
@@ -4238,7 +4238,7 @@  discard block
 block discarded – undo
4238 4238
     {
4239 4239
         $where_clauses = array();
4240 4240
         foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4241
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4241
+            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param); // str_replace("*",'',$query_param);
4242 4242
             if (in_array($query_param, $this->_logic_query_param_keys)) {
4243 4243
                 switch ($query_param) {
4244 4244
                     case 'not':
@@ -4272,7 +4272,7 @@  discard block
 block discarded – undo
4272 4272
             } else {
4273 4273
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
4274 4274
                 // if it's not a normal field, maybe it's a custom selection?
4275
-                if (! $field_obj) {
4275
+                if ( ! $field_obj) {
4276 4276
                     if ($this->_custom_selections instanceof CustomSelects) {
4277 4277
                         $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4278 4278
                     } else {
@@ -4283,7 +4283,7 @@  discard block
 block discarded – undo
4283 4283
                     }
4284 4284
                 }
4285 4285
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4286
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4286
+                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
4287 4287
             }
4288 4288
         }
4289 4289
         return $where_clauses ? implode($glue, $where_clauses) : '';
@@ -4306,7 +4306,7 @@  discard block
 block discarded – undo
4306 4306
                 $field->get_model_name(),
4307 4307
                 $query_param
4308 4308
             );
4309
-            return $table_alias_prefix . $field->get_qualified_column();
4309
+            return $table_alias_prefix.$field->get_qualified_column();
4310 4310
         }
4311 4311
         if (
4312 4312
             $this->_custom_selections instanceof CustomSelects
@@ -4366,7 +4366,7 @@  discard block
 block discarded – undo
4366 4366
     {
4367 4367
         if (is_array($op_and_value)) {
4368 4368
             $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4369
-            if (! $operator) {
4369
+            if ( ! $operator) {
4370 4370
                 $php_array_like_string = array();
4371 4371
                 foreach ($op_and_value as $key => $value) {
4372 4372
                     $php_array_like_string[] = "$key=>$value";
@@ -4388,14 +4388,14 @@  discard block
 block discarded – undo
4388 4388
         }
4389 4389
         // check to see if the value is actually another field
4390 4390
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4391
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4391
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4392 4392
         }
4393 4393
         if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4394 4394
             // in this case, the value should be an array, or at least a comma-separated list
4395 4395
             // it will need to handle a little differently
4396 4396
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4397 4397
             // note: $cleaned_value has already been run through $wpdb->prepare()
4398
-            return $operator . SP . $cleaned_value;
4398
+            return $operator.SP.$cleaned_value;
4399 4399
         }
4400 4400
         if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4401 4401
             // the value should be an array with count of two.
@@ -4411,7 +4411,7 @@  discard block
 block discarded – undo
4411 4411
                 );
4412 4412
             }
4413 4413
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4414
-            return $operator . SP . $cleaned_value;
4414
+            return $operator.SP.$cleaned_value;
4415 4415
         }
4416 4416
         if (in_array($operator, $this->valid_null_style_operators())) {
4417 4417
             if ($value !== null) {
@@ -4431,10 +4431,10 @@  discard block
 block discarded – undo
4431 4431
         if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4432 4432
             // if the operator is 'LIKE', we want to allow percent signs (%) and not
4433 4433
             // remove other junk. So just treat it as a string.
4434
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4434
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4435 4435
         }
4436
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4437
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4436
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4437
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4438 4438
         }
4439 4439
         if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4440 4440
             throw new EE_Error(
@@ -4448,7 +4448,7 @@  discard block
 block discarded – undo
4448 4448
                 )
4449 4449
             );
4450 4450
         }
4451
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4451
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4452 4452
             throw new EE_Error(
4453 4453
                 sprintf(
4454 4454
                     esc_html__(
@@ -4488,7 +4488,7 @@  discard block
 block discarded – undo
4488 4488
         foreach ($values as $value) {
4489 4489
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4490 4490
         }
4491
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4491
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4492 4492
     }
4493 4493
 
4494 4494
 
@@ -4522,11 +4522,11 @@  discard block
 block discarded – undo
4522 4522
         // which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4523 4523
         if (empty($prepped)) {
4524 4524
             $all_fields = $this->field_settings();
4525
-            $first_field    = reset($all_fields);
4525
+            $first_field = reset($all_fields);
4526 4526
             $main_table = $this->_get_main_table();
4527 4527
             $prepped[]  = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4528 4528
         }
4529
-        return '(' . implode(',', $prepped) . ')';
4529
+        return '('.implode(',', $prepped).')';
4530 4530
     }
4531 4531
 
4532 4532
 
@@ -4547,7 +4547,7 @@  discard block
 block discarded – undo
4547 4547
                 $this->_prepare_value_for_use_in_db($value, $field_obj)
4548 4548
             );
4549 4549
         } //$field_obj should really just be a data type
4550
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4550
+        if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4551 4551
             throw new EE_Error(
4552 4552
                 sprintf(
4553 4553
                     esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
@@ -4580,14 +4580,14 @@  discard block
 block discarded – undo
4580 4580
             ), $query_param_name));
4581 4581
         }
4582 4582
         $number_of_parts = count($query_param_parts);
4583
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4583
+        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4584 4584
         if ($number_of_parts === 1) {
4585 4585
             $field_name = $last_query_param_part;
4586 4586
             $model_obj = $this;
4587 4587
         } else {// $number_of_parts >= 2
4588 4588
             // the last part is the column name, and there are only 2parts. therefore...
4589 4589
             $field_name = $last_query_param_part;
4590
-            $model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4590
+            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4591 4591
         }
4592 4592
         try {
4593 4593
             return $model_obj->field_settings_for($field_name);
@@ -4609,7 +4609,7 @@  discard block
 block discarded – undo
4609 4609
     public function _get_qualified_column_for_field($field_name)
4610 4610
     {
4611 4611
         $all_fields = $this->field_settings();
4612
-        $field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4612
+        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4613 4613
         if ($field) {
4614 4614
             return $field->get_qualified_column();
4615 4615
         }
@@ -4680,10 +4680,10 @@  discard block
 block discarded – undo
4680 4680
      */
4681 4681
     public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4682 4682
     {
4683
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4683
+        $table_prefix = str_replace('.', '__', $model_relation_chain).(empty($model_relation_chain) ? '' : '__');
4684 4684
         $qualified_columns = array();
4685 4685
         foreach ($this->field_settings() as $field_name => $field) {
4686
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4686
+            $qualified_columns[] = $table_prefix.$field->get_qualified_column();
4687 4687
         }
4688 4688
         return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4689 4689
     }
@@ -4707,11 +4707,11 @@  discard block
 block discarded – undo
4707 4707
             if ($table_obj instanceof EE_Primary_Table) {
4708 4708
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4709 4709
                     ? $table_obj->get_select_join_limit($limit)
4710
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4710
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4711 4711
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4712 4712
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4713 4713
                     ? $table_obj->get_select_join_limit_join($limit)
4714
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4714
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4715 4715
             }
4716 4716
         }
4717 4717
         return $SQL;
@@ -4783,7 +4783,7 @@  discard block
 block discarded – undo
4783 4783
         foreach ($this->field_settings() as $field_obj) {
4784 4784
             // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4785 4785
             /** @var $field_obj EE_Model_Field_Base */
4786
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4786
+            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4787 4787
         }
4788 4788
         return $data_types;
4789 4789
     }
@@ -4799,14 +4799,14 @@  discard block
 block discarded – undo
4799 4799
      */
4800 4800
     public function get_related_model_obj($model_name)
4801 4801
     {
4802
-        $model_classname = "EEM_" . $model_name;
4803
-        if (! class_exists($model_classname)) {
4802
+        $model_classname = "EEM_".$model_name;
4803
+        if ( ! class_exists($model_classname)) {
4804 4804
             throw new EE_Error(sprintf(esc_html__(
4805 4805
                 "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4806 4806
                 'event_espresso'
4807 4807
             ), $model_name, $model_classname));
4808 4808
         }
4809
-        return call_user_func($model_classname . "::instance");
4809
+        return call_user_func($model_classname."::instance");
4810 4810
     }
4811 4811
 
4812 4812
 
@@ -4835,7 +4835,7 @@  discard block
 block discarded – undo
4835 4835
         $belongs_to_relations = array();
4836 4836
         foreach ($this->relation_settings() as $model_name => $relation_obj) {
4837 4837
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
4838
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4838
+                $belongs_to_relations[$model_name] = $relation_obj;
4839 4839
             }
4840 4840
         }
4841 4841
         return $belongs_to_relations;
@@ -4853,7 +4853,7 @@  discard block
 block discarded – undo
4853 4853
     public function related_settings_for($relation_name)
4854 4854
     {
4855 4855
         $relatedModels = $this->relation_settings();
4856
-        if (! array_key_exists($relation_name, $relatedModels)) {
4856
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
4857 4857
             throw new EE_Error(
4858 4858
                 sprintf(
4859 4859
                     esc_html__(
@@ -4866,7 +4866,7 @@  discard block
 block discarded – undo
4866 4866
                 )
4867 4867
             );
4868 4868
         }
4869
-        return $relatedModels[ $relation_name ];
4869
+        return $relatedModels[$relation_name];
4870 4870
     }
4871 4871
 
4872 4872
 
@@ -4883,14 +4883,14 @@  discard block
 block discarded – undo
4883 4883
     public function field_settings_for($fieldName, $include_db_only_fields = true)
4884 4884
     {
4885 4885
         $fieldSettings = $this->field_settings($include_db_only_fields);
4886
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4886
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4887 4887
             throw new EE_Error(sprintf(
4888 4888
                 esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
4889 4889
                 $fieldName,
4890 4890
                 get_class($this)
4891 4891
             ));
4892 4892
         }
4893
-        return $fieldSettings[ $fieldName ];
4893
+        return $fieldSettings[$fieldName];
4894 4894
     }
4895 4895
 
4896 4896
 
@@ -4904,7 +4904,7 @@  discard block
 block discarded – undo
4904 4904
     public function has_field($fieldName)
4905 4905
     {
4906 4906
         $fieldSettings = $this->field_settings(true);
4907
-        if (isset($fieldSettings[ $fieldName ])) {
4907
+        if (isset($fieldSettings[$fieldName])) {
4908 4908
             return true;
4909 4909
         }
4910 4910
         return false;
@@ -4921,7 +4921,7 @@  discard block
 block discarded – undo
4921 4921
     public function has_relation($relation_name)
4922 4922
     {
4923 4923
         $relations = $this->relation_settings();
4924
-        if (isset($relations[ $relation_name ])) {
4924
+        if (isset($relations[$relation_name])) {
4925 4925
             return true;
4926 4926
         }
4927 4927
         return false;
@@ -4959,7 +4959,7 @@  discard block
 block discarded – undo
4959 4959
                     break;
4960 4960
                 }
4961 4961
             }
4962
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4962
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4963 4963
                 throw new EE_Error(sprintf(
4964 4964
                     esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
4965 4965
                     get_class($this)
@@ -5020,24 +5020,24 @@  discard block
 block discarded – undo
5020 5020
      */
5021 5021
     public function get_foreign_key_to($model_name)
5022 5022
     {
5023
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5023
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5024 5024
             foreach ($this->field_settings() as $field) {
5025 5025
                 if (
5026 5026
                     $field instanceof EE_Foreign_Key_Field_Base
5027 5027
                     && in_array($model_name, $field->get_model_names_pointed_to())
5028 5028
                 ) {
5029
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5029
+                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
5030 5030
                     break;
5031 5031
                 }
5032 5032
             }
5033
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5033
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5034 5034
                 throw new EE_Error(sprintf(esc_html__(
5035 5035
                     "There is no foreign key field pointing to model %s on model %s",
5036 5036
                     'event_espresso'
5037 5037
                 ), $model_name, get_class($this)));
5038 5038
             }
5039 5039
         }
5040
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5040
+        return $this->_cache_foreign_key_to_fields[$model_name];
5041 5041
     }
5042 5042
 
5043 5043
 
@@ -5053,7 +5053,7 @@  discard block
 block discarded – undo
5053 5053
     public function get_table_for_alias($table_alias)
5054 5054
     {
5055 5055
         $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5056
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5056
+        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
5057 5057
     }
5058 5058
 
5059 5059
 
@@ -5072,7 +5072,7 @@  discard block
 block discarded – undo
5072 5072
                 $this->_cached_fields = array();
5073 5073
                 foreach ($this->_fields as $fields_corresponding_to_table) {
5074 5074
                     foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5075
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5075
+                        $this->_cached_fields[$field_name] = $field_obj;
5076 5076
                     }
5077 5077
                 }
5078 5078
             }
@@ -5083,8 +5083,8 @@  discard block
 block discarded – undo
5083 5083
             foreach ($this->_fields as $fields_corresponding_to_table) {
5084 5084
                 foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5085 5085
                     /** @var $field_obj EE_Model_Field_Base */
5086
-                    if (! $field_obj->is_db_only_field()) {
5087
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5086
+                    if ( ! $field_obj->is_db_only_field()) {
5087
+                        $this->_cached_fields_non_db_only[$field_name] = $field_obj;
5088 5088
                     }
5089 5089
                 }
5090 5090
             }
@@ -5125,12 +5125,12 @@  discard block
 block discarded – undo
5125 5125
                     $primary_key_field->get_qualified_column(),
5126 5126
                     $primary_key_field->get_table_column()
5127 5127
                 );
5128
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5128
+                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
5129 5129
                     continue;
5130 5130
                 }
5131 5131
             }
5132 5132
             $classInstance = $this->instantiate_class_from_array_or_object($row);
5133
-            if (! $classInstance) {
5133
+            if ( ! $classInstance) {
5134 5134
                 throw new EE_Error(
5135 5135
                     sprintf(
5136 5136
                         esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -5143,7 +5143,7 @@  discard block
 block discarded – undo
5143 5143
             $classInstance->set_timezone($this->_timezone);
5144 5144
             // make sure if there is any timezone setting present that we set the timezone for the object
5145 5145
             $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5146
-            $array_of_objects[ $key ] = $classInstance;
5146
+            $array_of_objects[$key] = $classInstance;
5147 5147
             // also, for all the relations of type BelongsTo, see if we can cache
5148 5148
             // those related models
5149 5149
             // (we could do this for other relations too, but if there are conditions
@@ -5187,9 +5187,9 @@  discard block
 block discarded – undo
5187 5187
         $results = array();
5188 5188
         if ($this->_custom_selections instanceof CustomSelects) {
5189 5189
             foreach ($this->_custom_selections->columnAliases() as $alias) {
5190
-                if (isset($db_results_row[ $alias ])) {
5191
-                    $results[ $alias ] = $this->convertValueToDataType(
5192
-                        $db_results_row[ $alias ],
5190
+                if (isset($db_results_row[$alias])) {
5191
+                    $results[$alias] = $this->convertValueToDataType(
5192
+                        $db_results_row[$alias],
5193 5193
                         $this->_custom_selections->getDataTypeForAlias($alias)
5194 5194
                     );
5195 5195
                 }
@@ -5231,7 +5231,7 @@  discard block
 block discarded – undo
5231 5231
         $this_model_fields_and_values = array();
5232 5232
         // setup the row using default values;
5233 5233
         foreach ($this->field_settings() as $field_name => $field_obj) {
5234
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5234
+            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
5235 5235
         }
5236 5236
         $className = $this->_get_class_name();
5237 5237
         $classInstance = EE_Registry::instance()
@@ -5249,20 +5249,20 @@  discard block
 block discarded – undo
5249 5249
      */
5250 5250
     public function instantiate_class_from_array_or_object($cols_n_values)
5251 5251
     {
5252
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5252
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
5253 5253
             $cols_n_values = get_object_vars($cols_n_values);
5254 5254
         }
5255 5255
         $primary_key = null;
5256 5256
         // make sure the array only has keys that are fields/columns on this model
5257 5257
         $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5258
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5259
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5258
+        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5259
+            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5260 5260
         }
5261 5261
         $className = $this->_get_class_name();
5262 5262
         // check we actually found results that we can use to build our model object
5263 5263
         // if not, return null
5264 5264
         if ($this->has_primary_key_field()) {
5265
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5265
+            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5266 5266
                 return null;
5267 5267
             }
5268 5268
         } elseif ($this->unique_indexes()) {
@@ -5274,7 +5274,7 @@  discard block
 block discarded – undo
5274 5274
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5275 5275
         if ($primary_key) {
5276 5276
             $classInstance = $this->get_from_entity_map($primary_key);
5277
-            if (! $classInstance) {
5277
+            if ( ! $classInstance) {
5278 5278
                 $classInstance = EE_Registry::instance()
5279 5279
                                             ->load_class(
5280 5280
                                                 $className,
@@ -5307,8 +5307,8 @@  discard block
 block discarded – undo
5307 5307
      */
5308 5308
     public function get_from_entity_map($id)
5309 5309
     {
5310
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5311
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5310
+        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
5311
+            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
5312 5312
     }
5313 5313
 
5314 5314
 
@@ -5331,7 +5331,7 @@  discard block
 block discarded – undo
5331 5331
     public function add_to_entity_map(EE_Base_Class $object)
5332 5332
     {
5333 5333
         $className = $this->_get_class_name();
5334
-        if (! $object instanceof $className) {
5334
+        if ( ! $object instanceof $className) {
5335 5335
             throw new EE_Error(sprintf(
5336 5336
                 esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5337 5337
                 is_object($object) ? get_class($object) : $object,
@@ -5339,7 +5339,7 @@  discard block
 block discarded – undo
5339 5339
             ));
5340 5340
         }
5341 5341
         /** @var $object EE_Base_Class */
5342
-        if (! $object->ID()) {
5342
+        if ( ! $object->ID()) {
5343 5343
             throw new EE_Error(sprintf(esc_html__(
5344 5344
                 "You tried storing a model object with NO ID in the %s entity mapper.",
5345 5345
                 "event_espresso"
@@ -5350,7 +5350,7 @@  discard block
 block discarded – undo
5350 5350
         if ($classInstance) {
5351 5351
             return $classInstance;
5352 5352
         }
5353
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5353
+        $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5354 5354
         return $object;
5355 5355
     }
5356 5356
 
@@ -5366,11 +5366,11 @@  discard block
 block discarded – undo
5366 5366
     public function clear_entity_map($id = null)
5367 5367
     {
5368 5368
         if (empty($id)) {
5369
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5369
+            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
5370 5370
             return true;
5371 5371
         }
5372
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5373
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5372
+        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5373
+            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5374 5374
             return true;
5375 5375
         }
5376 5376
         return false;
@@ -5413,17 +5413,17 @@  discard block
 block discarded – undo
5413 5413
             // there is a primary key on this table and its not set. Use defaults for all its columns
5414 5414
             if ($table_pk_value === null && $table_obj->get_pk_column()) {
5415 5415
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5416
-                    if (! $field_obj->is_db_only_field()) {
5416
+                    if ( ! $field_obj->is_db_only_field()) {
5417 5417
                         // prepare field as if its coming from db
5418 5418
                         $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5419
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5419
+                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5420 5420
                     }
5421 5421
                 }
5422 5422
             } else {
5423 5423
                 // the table's rows existed. Use their values
5424 5424
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5425
-                    if (! $field_obj->is_db_only_field()) {
5426
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5425
+                    if ( ! $field_obj->is_db_only_field()) {
5426
+                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5427 5427
                             $cols_n_values,
5428 5428
                             $field_obj->get_qualified_column(),
5429 5429
                             $field_obj->get_table_column()
@@ -5450,17 +5450,17 @@  discard block
 block discarded – undo
5450 5450
         // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5451 5451
         // does the field on the model relate to this column retrieved from the db?
5452 5452
         // or is it a db-only field? (not relating to the model)
5453
-        if (isset($cols_n_values[ $qualified_column ])) {
5454
-            $value = $cols_n_values[ $qualified_column ];
5455
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5456
-            $value = $cols_n_values[ $regular_column ];
5457
-        } elseif (! empty($this->foreign_key_aliases)) {
5453
+        if (isset($cols_n_values[$qualified_column])) {
5454
+            $value = $cols_n_values[$qualified_column];
5455
+        } elseif (isset($cols_n_values[$regular_column])) {
5456
+            $value = $cols_n_values[$regular_column];
5457
+        } elseif ( ! empty($this->foreign_key_aliases)) {
5458 5458
             // no PK?  ok check if there is a foreign key alias set for this table
5459 5459
             // then check if that alias exists in the incoming data
5460 5460
             // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5461 5461
             foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5462
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5463
-                    $value = $cols_n_values[ $FK_alias ];
5462
+                if ($PK_column === $qualified_column && isset($cols_n_values[$FK_alias])) {
5463
+                    $value = $cols_n_values[$FK_alias];
5464 5464
                     list($pk_class) = explode('.', $PK_column);
5465 5465
                     $pk_model_name = "EEM_{$pk_class}";
5466 5466
                     /** @var EEM_Base $pk_model */
@@ -5504,7 +5504,7 @@  discard block
 block discarded – undo
5504 5504
                     $obj_in_map->clear_cache($relation_name, null, true);
5505 5505
                 }
5506 5506
             }
5507
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5507
+            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5508 5508
             return $obj_in_map;
5509 5509
         }
5510 5510
         return $this->get_one_by_ID($id);
@@ -5557,7 +5557,7 @@  discard block
 block discarded – undo
5557 5557
      */
5558 5558
     private function _get_class_name()
5559 5559
     {
5560
-        return "EE_" . $this->get_this_model_name();
5560
+        return "EE_".$this->get_this_model_name();
5561 5561
     }
5562 5562
 
5563 5563
 
@@ -5605,7 +5605,7 @@  discard block
 block discarded – undo
5605 5605
     {
5606 5606
         $className = get_class($this);
5607 5607
         $tagName = "FHEE__{$className}__{$methodName}";
5608
-        if (! has_filter($tagName)) {
5608
+        if ( ! has_filter($tagName)) {
5609 5609
             throw new EE_Error(
5610 5610
                 sprintf(
5611 5611
                     esc_html__(
@@ -5778,7 +5778,7 @@  discard block
 block discarded – undo
5778 5778
         $unique_indexes = array();
5779 5779
         foreach ($this->_indexes as $name => $index) {
5780 5780
             if ($index instanceof EE_Unique_Index) {
5781
-                $unique_indexes [ $name ] = $index;
5781
+                $unique_indexes [$name] = $index;
5782 5782
             }
5783 5783
         }
5784 5784
         return $unique_indexes;
@@ -5845,7 +5845,7 @@  discard block
 block discarded – undo
5845 5845
         $key_vals_in_combined_pk = array();
5846 5846
         parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5847 5847
         foreach ($key_fields as $key_field_name => $field_obj) {
5848
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5848
+            if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
5849 5849
                 return null;
5850 5850
             }
5851 5851
         }
@@ -5866,7 +5866,7 @@  discard block
 block discarded – undo
5866 5866
     {
5867 5867
         $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5868 5868
         foreach ($keys_it_should_have as $key) {
5869
-            if (! isset($key_vals[ $key ])) {
5869
+            if ( ! isset($key_vals[$key])) {
5870 5870
                 return false;
5871 5871
             }
5872 5872
         }
@@ -5899,8 +5899,8 @@  discard block
 block discarded – undo
5899 5899
         }
5900 5900
         // even copies obviously won't have the same ID, so remove the primary key
5901 5901
         // from the WHERE conditions for finding copies (if there is a primary key, of course)
5902
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5903
-            unset($attributes_array[ $this->primary_key_name() ]);
5902
+        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5903
+            unset($attributes_array[$this->primary_key_name()]);
5904 5904
         }
5905 5905
         if (isset($query_params[0])) {
5906 5906
             $query_params[0] = array_merge($attributes_array, $query_params);
@@ -5922,7 +5922,7 @@  discard block
 block discarded – undo
5922 5922
      */
5923 5923
     public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5924 5924
     {
5925
-        if (! is_array($query_params)) {
5925
+        if ( ! is_array($query_params)) {
5926 5926
             EE_Error::doing_it_wrong(
5927 5927
                 'EEM_Base::get_one_copy',
5928 5928
                 sprintf(
@@ -5972,7 +5972,7 @@  discard block
 block discarded – undo
5972 5972
      */
5973 5973
     private function _prepare_operator_for_sql($operator_supplied)
5974 5974
     {
5975
-        $sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5975
+        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5976 5976
             : null;
5977 5977
         if ($sql_operator) {
5978 5978
             return $sql_operator;
@@ -6063,7 +6063,7 @@  discard block
 block discarded – undo
6063 6063
         $objs = $this->get_all($query_params);
6064 6064
         $names = array();
6065 6065
         foreach ($objs as $obj) {
6066
-            $names[ $obj->ID() ] = $obj->name();
6066
+            $names[$obj->ID()] = $obj->name();
6067 6067
         }
6068 6068
         return $names;
6069 6069
     }
@@ -6084,7 +6084,7 @@  discard block
 block discarded – undo
6084 6084
      */
6085 6085
     public function get_IDs($model_objects, $filter_out_empty_ids = false)
6086 6086
     {
6087
-        if (! $this->has_primary_key_field()) {
6087
+        if ( ! $this->has_primary_key_field()) {
6088 6088
             if (WP_DEBUG) {
6089 6089
                 EE_Error::add_error(
6090 6090
                     esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
@@ -6097,7 +6097,7 @@  discard block
 block discarded – undo
6097 6097
         $IDs = array();
6098 6098
         foreach ($model_objects as $model_object) {
6099 6099
             $id = $model_object->ID();
6100
-            if (! $id) {
6100
+            if ( ! $id) {
6101 6101
                 if ($filter_out_empty_ids) {
6102 6102
                     continue;
6103 6103
                 }
@@ -6148,22 +6148,22 @@  discard block
 block discarded – undo
6148 6148
         EEM_Base::verify_is_valid_cap_context($context);
6149 6149
         // check if we ought to run the restriction generator first
6150 6150
         if (
6151
-            isset($this->_cap_restriction_generators[ $context ])
6152
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6153
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6151
+            isset($this->_cap_restriction_generators[$context])
6152
+            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
6153
+            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
6154 6154
         ) {
6155
-            $this->_cap_restrictions[ $context ] = array_merge(
6156
-                $this->_cap_restrictions[ $context ],
6157
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6155
+            $this->_cap_restrictions[$context] = array_merge(
6156
+                $this->_cap_restrictions[$context],
6157
+                $this->_cap_restriction_generators[$context]->generate_restrictions()
6158 6158
             );
6159 6159
         }
6160 6160
         // and make sure we've finalized the construction of each restriction
6161
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6161
+        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
6162 6162
             if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6163 6163
                 $where_conditions_obj->_finalize_construct($this);
6164 6164
             }
6165 6165
         }
6166
-        return $this->_cap_restrictions[ $context ];
6166
+        return $this->_cap_restrictions[$context];
6167 6167
     }
6168 6168
 
6169 6169
 
@@ -6195,9 +6195,9 @@  discard block
 block discarded – undo
6195 6195
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6196 6196
             if (
6197 6197
                 ! EE_Capabilities::instance()
6198
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6198
+                                 ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
6199 6199
             ) {
6200
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6200
+                $missing_caps[$cap] = $restriction_if_no_cap;
6201 6201
             }
6202 6202
         }
6203 6203
         return $missing_caps;
@@ -6232,8 +6232,8 @@  discard block
 block discarded – undo
6232 6232
     public function cap_action_for_context($context)
6233 6233
     {
6234 6234
         $mapping = $this->cap_contexts_to_cap_action_map();
6235
-        if (isset($mapping[ $context ])) {
6236
-            return $mapping[ $context ];
6235
+        if (isset($mapping[$context])) {
6236
+            return $mapping[$context];
6237 6237
         }
6238 6238
         if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6239 6239
             return $action;
@@ -6351,7 +6351,7 @@  discard block
 block discarded – undo
6351 6351
         foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6352 6352
             if (
6353 6353
                 $query_param_key === $logic_query_param_key
6354
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6354
+                || strpos($query_param_key, $logic_query_param_key.'*') === 0
6355 6355
             ) {
6356 6356
                 return true;
6357 6357
             }
@@ -6404,7 +6404,7 @@  discard block
 block discarded – undo
6404 6404
         if ($password_field instanceof EE_Password_Field) {
6405 6405
             $field_names = $password_field->protectedFields();
6406 6406
             foreach ($field_names as $field_name) {
6407
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6407
+                $fields[$field_name] = $this->field_settings_for($field_name);
6408 6408
             }
6409 6409
         }
6410 6410
         return $fields;
@@ -6429,7 +6429,7 @@  discard block
 block discarded – undo
6429 6429
         if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6430 6430
             $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6431 6431
         }
6432
-        if (!is_array($model_obj_or_fields_n_values)) {
6432
+        if ( ! is_array($model_obj_or_fields_n_values)) {
6433 6433
             throw new UnexpectedEntityException(
6434 6434
                 $model_obj_or_fields_n_values,
6435 6435
                 'EE_Base_Class',
@@ -6504,7 +6504,7 @@  discard block
 block discarded – undo
6504 6504
                 )
6505 6505
             );
6506 6506
         }
6507
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6507
+        return ($this->model_chain_to_password ? $this->model_chain_to_password.'.' : '').$password_field_name;
6508 6508
     }
6509 6509
 
6510 6510
     /**
Please login to merge, or discard this patch.
Indentation   +6479 added lines, -6479 removed lines patch added patch discarded remove patch
@@ -35,6485 +35,6485 @@
 block discarded – undo
35 35
  */
36 36
 abstract class EEM_Base extends EE_Base implements ResettableInterface
37 37
 {
38
-    /**
39
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
40
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
41
-     * They almost always WILL NOT, but it's not necessarily a requirement.
42
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
43
-     *
44
-     * @var boolean
45
-     */
46
-    private $_values_already_prepared_by_model_object = 0;
47
-
48
-    /**
49
-     * when $_values_already_prepared_by_model_object equals this, we assume
50
-     * the data is just like form input that needs to have the model fields'
51
-     * prepare_for_set and prepare_for_use_in_db called on it
52
-     */
53
-    const not_prepared_by_model_object = 0;
54
-
55
-    /**
56
-     * when $_values_already_prepared_by_model_object equals this, we
57
-     * assume this value is coming from a model object and doesn't need to have
58
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
59
-     */
60
-    const prepared_by_model_object = 1;
61
-
62
-    /**
63
-     * when $_values_already_prepared_by_model_object equals this, we assume
64
-     * the values are already to be used in the database (ie no processing is done
65
-     * on them by the model's fields)
66
-     */
67
-    const prepared_for_use_in_db = 2;
68
-
69
-
70
-    protected $singular_item = 'Item';
71
-
72
-    protected $plural_item   = 'Items';
73
-
74
-    /**
75
-     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
76
-     */
77
-    protected $_tables;
78
-
79
-    /**
80
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
81
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
82
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
83
-     *
84
-     * @var \EE_Model_Field_Base[][] $_fields
85
-     */
86
-    protected $_fields;
87
-
88
-    /**
89
-     * array of different kinds of relations
90
-     *
91
-     * @var \EE_Model_Relation_Base[] $_model_relations
92
-     */
93
-    protected $_model_relations;
94
-
95
-    /**
96
-     * @var \EE_Index[] $_indexes
97
-     */
98
-    protected $_indexes = array();
99
-
100
-    /**
101
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
102
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
103
-     * by setting the same columns as used in these queries in the query yourself.
104
-     *
105
-     * @var EE_Default_Where_Conditions
106
-     */
107
-    protected $_default_where_conditions_strategy;
108
-
109
-    /**
110
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
111
-     * This is particularly useful when you want something between 'none' and 'default'
112
-     *
113
-     * @var EE_Default_Where_Conditions
114
-     */
115
-    protected $_minimum_where_conditions_strategy;
116
-
117
-    /**
118
-     * String describing how to find the "owner" of this model's objects.
119
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
120
-     * But when there isn't, this indicates which related model, or transiently-related model,
121
-     * has the foreign key to the wp_users table.
122
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
123
-     * related to events, and events have a foreign key to wp_users.
124
-     * On EEM_Transaction, this would be 'Transaction.Event'
125
-     *
126
-     * @var string
127
-     */
128
-    protected $_model_chain_to_wp_user = '';
129
-
130
-    /**
131
-     * String describing how to find the model with a password controlling access to this model. This property has the
132
-     * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
133
-     * This value is the path of models to follow to arrive at the model with the password field.
134
-     * If it is an empty string, it means this model has the password field. If it is null, it means there is no
135
-     * model with a password that should affect reading this on the front-end.
136
-     * Eg this is an empty string for the Event model because it has a password.
137
-     * This is null for the Registration model, because its event's password has no bearing on whether
138
-     * you can read the registration or not on the front-end (it just depends on your capabilities.)
139
-     * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
140
-     * should hide tickets for datetimes for events that have a password set.
141
-     * @var string |null
142
-     */
143
-    protected $model_chain_to_password = null;
144
-
145
-    /**
146
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
147
-     * don't need it (particularly CPT models)
148
-     *
149
-     * @var bool
150
-     */
151
-    protected $_ignore_where_strategy = false;
152
-
153
-    /**
154
-     * String used in caps relating to this model. Eg, if the caps relating to this
155
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
156
-     *
157
-     * @var string. If null it hasn't been initialized yet. If false then we
158
-     * have indicated capabilities don't apply to this
159
-     */
160
-    protected $_caps_slug = null;
161
-
162
-    /**
163
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
164
-     * and next-level keys are capability names, and each's value is a
165
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
166
-     * they specify which context to use (ie, frontend, backend, edit or delete)
167
-     * and then each capability in the corresponding sub-array that they're missing
168
-     * adds the where conditions onto the query.
169
-     *
170
-     * @var array
171
-     */
172
-    protected $_cap_restrictions = array(
173
-        self::caps_read       => array(),
174
-        self::caps_read_admin => array(),
175
-        self::caps_edit       => array(),
176
-        self::caps_delete     => array(),
177
-    );
178
-
179
-    /**
180
-     * Array defining which cap restriction generators to use to create default
181
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
182
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
183
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
184
-     * automatically set this to false (not just null).
185
-     *
186
-     * @var EE_Restriction_Generator_Base[]
187
-     */
188
-    protected $_cap_restriction_generators = array();
189
-
190
-    /**
191
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
192
-     */
193
-    const caps_read       = 'read';
194
-
195
-    const caps_read_admin = 'read_admin';
196
-
197
-    const caps_edit       = 'edit';
198
-
199
-    const caps_delete     = 'delete';
200
-
201
-    /**
202
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
203
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
204
-     * maps to 'read' because when looking for relevant permissions we're going to use
205
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
206
-     *
207
-     * @var array
208
-     */
209
-    protected $_cap_contexts_to_cap_action_map = array(
210
-        self::caps_read       => 'read',
211
-        self::caps_read_admin => 'read',
212
-        self::caps_edit       => 'edit',
213
-        self::caps_delete     => 'delete',
214
-    );
215
-
216
-    /**
217
-     * Timezone
218
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
219
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
220
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
221
-     * EE_Datetime_Field data type will have access to it.
222
-     *
223
-     * @var string
224
-     */
225
-    protected $_timezone;
226
-
227
-
228
-    /**
229
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
230
-     * multisite.
231
-     *
232
-     * @var int
233
-     */
234
-    protected static $_model_query_blog_id;
235
-
236
-    /**
237
-     * A copy of _fields, except the array keys are the model names pointed to by
238
-     * the field
239
-     *
240
-     * @var EE_Model_Field_Base[]
241
-     */
242
-    private $_cache_foreign_key_to_fields = array();
243
-
244
-    /**
245
-     * Cached list of all the fields on the model, indexed by their name
246
-     *
247
-     * @var EE_Model_Field_Base[]
248
-     */
249
-    private $_cached_fields = null;
250
-
251
-    /**
252
-     * Cached list of all the fields on the model, except those that are
253
-     * marked as only pertinent to the database
254
-     *
255
-     * @var EE_Model_Field_Base[]
256
-     */
257
-    private $_cached_fields_non_db_only = null;
258
-
259
-    /**
260
-     * A cached reference to the primary key for quick lookup
261
-     *
262
-     * @var EE_Model_Field_Base
263
-     */
264
-    private $_primary_key_field = null;
265
-
266
-    /**
267
-     * Flag indicating whether this model has a primary key or not
268
-     *
269
-     * @var boolean
270
-     */
271
-    protected $_has_primary_key_field = null;
272
-
273
-    /**
274
-     * array in the format:  [ FK alias => full PK ]
275
-     * where keys are local column name aliases for foreign keys
276
-     * and values are the fully qualified column name for the primary key they represent
277
-     *  ex:
278
-     *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
279
-     *
280
-     * @var array $foreign_key_aliases
281
-     */
282
-    protected $foreign_key_aliases = [];
283
-
284
-    /**
285
-     * Whether or not this model is based off a table in WP core only (CPTs should set
286
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
287
-     * This should be true for models that deal with data that should exist independent of EE.
288
-     * For example, if the model can read and insert data that isn't used by EE, this should be true.
289
-     * It would be false, however, if you could guarantee the model would only interact with EE data,
290
-     * even if it uses a WP core table (eg event and venue models set this to false for that reason:
291
-     * they can only read and insert events and venues custom post types, not arbitrary post types)
292
-     * @var boolean
293
-     */
294
-    protected $_wp_core_model = false;
295
-
296
-    /**
297
-     * @var bool stores whether this model has a password field or not.
298
-     * null until initialized by hasPasswordField()
299
-     */
300
-    protected $has_password_field;
301
-
302
-    /**
303
-     * @var EE_Password_Field|null Automatically set when calling getPasswordField()
304
-     */
305
-    protected $password_field;
306
-
307
-    /**
308
-     *    List of valid operators that can be used for querying.
309
-     * The keys are all operators we'll accept, the values are the real SQL
310
-     * operators used
311
-     *
312
-     * @var array
313
-     */
314
-    protected $_valid_operators = array(
315
-        '='           => '=',
316
-        '<='          => '<=',
317
-        '<'           => '<',
318
-        '>='          => '>=',
319
-        '>'           => '>',
320
-        '!='          => '!=',
321
-        'LIKE'        => 'LIKE',
322
-        'like'        => 'LIKE',
323
-        'NOT_LIKE'    => 'NOT LIKE',
324
-        'not_like'    => 'NOT LIKE',
325
-        'NOT LIKE'    => 'NOT LIKE',
326
-        'not like'    => 'NOT LIKE',
327
-        'IN'          => 'IN',
328
-        'in'          => 'IN',
329
-        'NOT_IN'      => 'NOT IN',
330
-        'not_in'      => 'NOT IN',
331
-        'NOT IN'      => 'NOT IN',
332
-        'not in'      => 'NOT IN',
333
-        'between'     => 'BETWEEN',
334
-        'BETWEEN'     => 'BETWEEN',
335
-        'IS_NOT_NULL' => 'IS NOT NULL',
336
-        'is_not_null' => 'IS NOT NULL',
337
-        'IS NOT NULL' => 'IS NOT NULL',
338
-        'is not null' => 'IS NOT NULL',
339
-        'IS_NULL'     => 'IS NULL',
340
-        'is_null'     => 'IS NULL',
341
-        'IS NULL'     => 'IS NULL',
342
-        'is null'     => 'IS NULL',
343
-        'REGEXP'      => 'REGEXP',
344
-        'regexp'      => 'REGEXP',
345
-        'NOT_REGEXP'  => 'NOT REGEXP',
346
-        'not_regexp'  => 'NOT REGEXP',
347
-        'NOT REGEXP'  => 'NOT REGEXP',
348
-        'not regexp'  => 'NOT REGEXP',
349
-    );
350
-
351
-    /**
352
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
353
-     *
354
-     * @var array
355
-     */
356
-    protected $_in_style_operators = array('IN', 'NOT IN');
357
-
358
-    /**
359
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
360
-     * '12-31-2012'"
361
-     *
362
-     * @var array
363
-     */
364
-    protected $_between_style_operators = array('BETWEEN');
365
-
366
-    /**
367
-     * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
368
-     * @var array
369
-     */
370
-    protected $_like_style_operators = array('LIKE', 'NOT LIKE');
371
-    /**
372
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
373
-     * on a join table.
374
-     *
375
-     * @var array
376
-     */
377
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
378
-
379
-    /**
380
-     * Allowed values for $query_params['order'] for ordering in queries
381
-     *
382
-     * @var array
383
-     */
384
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
385
-
386
-    /**
387
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
388
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
389
-     *
390
-     * @var array
391
-     */
392
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
393
-
394
-    /**
395
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
396
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
397
-     *
398
-     * @var array
399
-     */
400
-    private $_allowed_query_params = array(
401
-        0,
402
-        'limit',
403
-        'order_by',
404
-        'group_by',
405
-        'having',
406
-        'force_join',
407
-        'order',
408
-        'on_join_limit',
409
-        'default_where_conditions',
410
-        'caps',
411
-        'extra_selects',
412
-        'exclude_protected',
413
-    );
414
-
415
-    /**
416
-     * All the data types that can be used in $wpdb->prepare statements.
417
-     *
418
-     * @var array
419
-     */
420
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
421
-
422
-    /**
423
-     * @var EE_Registry $EE
424
-     */
425
-    protected $EE = null;
426
-
427
-
428
-    /**
429
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
430
-     *
431
-     * @var int
432
-     */
433
-    protected $_show_next_x_db_queries = 0;
434
-
435
-    /**
436
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
437
-     * it gets saved on this property as an instance of CustomSelects so those selections can be used in
438
-     * WHERE, GROUP_BY, etc.
439
-     *
440
-     * @var CustomSelects
441
-     */
442
-    protected $_custom_selections = array();
443
-
444
-    /**
445
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
446
-     * caches every model object we've fetched from the DB on this request
447
-     *
448
-     * @var array
449
-     */
450
-    protected $_entity_map;
451
-
452
-    /**
453
-     * @var LoaderInterface $loader
454
-     */
455
-    protected static $loader;
456
-
457
-
458
-    /**
459
-     * constant used to show EEM_Base has not yet verified the db on this http request
460
-     */
461
-    const db_verified_none = 0;
462
-
463
-    /**
464
-     * constant used to show EEM_Base has verified the EE core db on this http request,
465
-     * but not the addons' dbs
466
-     */
467
-    const db_verified_core = 1;
468
-
469
-    /**
470
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
471
-     * the EE core db too)
472
-     */
473
-    const db_verified_addons = 2;
474
-
475
-    /**
476
-     * indicates whether an EEM_Base child has already re-verified the DB
477
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
478
-     * looking like EEM_Base::db_verified_*
479
-     *
480
-     * @var int - 0 = none, 1 = core, 2 = addons
481
-     */
482
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
483
-
484
-    /**
485
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
486
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
487
-     *        registrations for non-trashed tickets for non-trashed datetimes)
488
-     */
489
-    const default_where_conditions_all = 'all';
490
-
491
-    /**
492
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
493
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
494
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
495
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
496
-     *        models which share tables with other models, this can return data for the wrong model.
497
-     */
498
-    const default_where_conditions_this_only = 'this_model_only';
499
-
500
-    /**
501
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
502
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
503
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
504
-     */
505
-    const default_where_conditions_others_only = 'other_models_only';
506
-
507
-    /**
508
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
509
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
510
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
511
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
512
-     *        (regardless of whether those events and venues are trashed)
513
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
514
-     *        events.
515
-     */
516
-    const default_where_conditions_minimum_all = 'minimum';
517
-
518
-    /**
519
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
520
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
521
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
522
-     *        not)
523
-     */
524
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
525
-
526
-    /**
527
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
528
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
529
-     *        it's possible it will return table entries for other models. You should use
530
-     *        EEM_Base::default_where_conditions_minimum_all instead.
531
-     */
532
-    const default_where_conditions_none = 'none';
533
-
534
-
535
-
536
-    /**
537
-     * About all child constructors:
538
-     * they should define the _tables, _fields and _model_relations arrays.
539
-     * Should ALWAYS be called after child constructor.
540
-     * In order to make the child constructors to be as simple as possible, this parent constructor
541
-     * finalizes constructing all the object's attributes.
542
-     * Generally, rather than requiring a child to code
543
-     * $this->_tables = array(
544
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
545
-     *        ...);
546
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
547
-     * each EE_Table has a function to set the table's alias after the constructor, using
548
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
549
-     * do something similar.
550
-     *
551
-     * @param null $timezone
552
-     * @throws EE_Error
553
-     */
554
-    protected function __construct($timezone = null)
555
-    {
556
-        // check that the model has not been loaded too soon
557
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
558
-            throw new EE_Error(
559
-                sprintf(
560
-                    esc_html__(
561
-                        '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.',
562
-                        'event_espresso'
563
-                    ),
564
-                    get_class($this)
565
-                )
566
-            );
567
-        }
568
-        /**
569
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
570
-         */
571
-        if (empty(EEM_Base::$_model_query_blog_id)) {
572
-            EEM_Base::set_model_query_blog_id();
573
-        }
574
-        /**
575
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
576
-         * just use EE_Register_Model_Extension
577
-         *
578
-         * @var EE_Table_Base[] $_tables
579
-         */
580
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
581
-        foreach ($this->_tables as $table_alias => $table_obj) {
582
-            /** @var $table_obj EE_Table_Base */
583
-            $table_obj->_construct_finalize_with_alias($table_alias);
584
-            if ($table_obj instanceof EE_Secondary_Table) {
585
-                /** @var $table_obj EE_Secondary_Table */
586
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
587
-            }
588
-        }
589
-        /**
590
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
591
-         * EE_Register_Model_Extension
592
-         *
593
-         * @param EE_Model_Field_Base[] $_fields
594
-         */
595
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
596
-        $this->_invalidate_field_caches();
597
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
598
-            if (! array_key_exists($table_alias, $this->_tables)) {
599
-                throw new EE_Error(sprintf(esc_html__(
600
-                    "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
601
-                    'event_espresso'
602
-                ), $table_alias, implode(",", $this->_fields)));
603
-            }
604
-            foreach ($fields_for_table as $field_name => $field_obj) {
605
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
606
-                // primary key field base has a slightly different _construct_finalize
607
-                /** @var $field_obj EE_Model_Field_Base */
608
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
609
-            }
610
-        }
611
-        // everything is related to Extra_Meta
612
-        if (get_class($this) !== 'EEM_Extra_Meta') {
613
-            // make extra meta related to everything, but don't block deleting things just
614
-            // because they have related extra meta info. For now just orphan those extra meta
615
-            // in the future we should automatically delete them
616
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
617
-        }
618
-        // and change logs
619
-        if (get_class($this) !== 'EEM_Change_Log') {
620
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
621
-        }
622
-        /**
623
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
624
-         * EE_Register_Model_Extension
625
-         *
626
-         * @param EE_Model_Relation_Base[] $_model_relations
627
-         */
628
-        $this->_model_relations = (array) apply_filters(
629
-            'FHEE__' . get_class($this) . '__construct__model_relations',
630
-            $this->_model_relations
631
-        );
632
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
633
-            /** @var $relation_obj EE_Model_Relation_Base */
634
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
635
-        }
636
-        foreach ($this->_indexes as $index_name => $index_obj) {
637
-            /** @var $index_obj EE_Index */
638
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
639
-        }
640
-        $this->set_timezone($timezone);
641
-        // finalize default where condition strategy, or set default
642
-        if (! $this->_default_where_conditions_strategy) {
643
-            // nothing was set during child constructor, so set default
644
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
645
-        }
646
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
647
-        if (! $this->_minimum_where_conditions_strategy) {
648
-            // nothing was set during child constructor, so set default
649
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
650
-        }
651
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
652
-        // if the cap slug hasn't been set, and we haven't set it to false on purpose
653
-        // to indicate to NOT set it, set it to the logical default
654
-        if ($this->_caps_slug === null) {
655
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
656
-        }
657
-        // initialize the standard cap restriction generators if none were specified by the child constructor
658
-        if ($this->_cap_restriction_generators !== false) {
659
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
660
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
661
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
662
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
663
-                        new EE_Restriction_Generator_Protected(),
664
-                        $cap_context,
665
-                        $this
666
-                    );
667
-                }
668
-            }
669
-        }
670
-        // if there are cap restriction generators, use them to make the default cap restrictions
671
-        if ($this->_cap_restriction_generators !== false) {
672
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
673
-                if (! $generator_object) {
674
-                    continue;
675
-                }
676
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
677
-                    throw new EE_Error(
678
-                        sprintf(
679
-                            esc_html__(
680
-                                '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.',
681
-                                'event_espresso'
682
-                            ),
683
-                            $context,
684
-                            $this->get_this_model_name()
685
-                        )
686
-                    );
687
-                }
688
-                $action = $this->cap_action_for_context($context);
689
-                if (! $generator_object->construction_finalized()) {
690
-                    $generator_object->_construct_finalize($this, $action);
691
-                }
692
-            }
693
-        }
694
-        do_action('AHEE__' . get_class($this) . '__construct__end');
695
-    }
696
-
697
-
698
-
699
-    /**
700
-     * Used to set the $_model_query_blog_id static property.
701
-     *
702
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
703
-     *                      value for get_current_blog_id() will be used.
704
-     */
705
-    public static function set_model_query_blog_id($blog_id = 0)
706
-    {
707
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
708
-    }
709
-
710
-
711
-
712
-    /**
713
-     * Returns whatever is set as the internal $model_query_blog_id.
714
-     *
715
-     * @return int
716
-     */
717
-    public static function get_model_query_blog_id()
718
-    {
719
-        return EEM_Base::$_model_query_blog_id;
720
-    }
721
-
722
-
723
-
724
-    /**
725
-     * This function is a singleton method used to instantiate the Espresso_model object
726
-     *
727
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
728
-     *                                (and any incoming timezone data that gets saved).
729
-     *                                Note this just sends the timezone info to the date time model field objects.
730
-     *                                Default is NULL
731
-     *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
732
-     * @return static (as in the concrete child class)
733
-     * @throws EE_Error
734
-     * @throws InvalidArgumentException
735
-     * @throws InvalidDataTypeException
736
-     * @throws InvalidInterfaceException
737
-     */
738
-    public static function instance($timezone = null)
739
-    {
740
-        // check if instance of Espresso_model already exists
741
-        if (! static::$_instance instanceof static) {
742
-            // instantiate Espresso_model
743
-            static::$_instance = new static(
744
-                $timezone,
745
-                EEM_Base::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
746
-            );
747
-        }
748
-        // we might have a timezone set, let set_timezone decide what to do with it
749
-        static::$_instance->set_timezone($timezone);
750
-        // Espresso_model object
751
-        return static::$_instance;
752
-    }
753
-
754
-
755
-
756
-    /**
757
-     * resets the model and returns it
758
-     *
759
-     * @param null | string $timezone
760
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
761
-     * all its properties reset; if it wasn't instantiated, returns null)
762
-     * @throws EE_Error
763
-     * @throws ReflectionException
764
-     * @throws InvalidArgumentException
765
-     * @throws InvalidDataTypeException
766
-     * @throws InvalidInterfaceException
767
-     */
768
-    public static function reset($timezone = null)
769
-    {
770
-        if (static::$_instance instanceof EEM_Base) {
771
-            // let's try to NOT swap out the current instance for a new one
772
-            // because if someone has a reference to it, we can't remove their reference
773
-            // so it's best to keep using the same reference, but change the original object
774
-            // reset all its properties to their original values as defined in the class
775
-            $r = new ReflectionClass(get_class(static::$_instance));
776
-            $static_properties = $r->getStaticProperties();
777
-            foreach ($r->getDefaultProperties() as $property => $value) {
778
-                // don't set instance to null like it was originally,
779
-                // but it's static anyways, and we're ignoring static properties (for now at least)
780
-                if (! isset($static_properties[ $property ])) {
781
-                    static::$_instance->{$property} = $value;
782
-                }
783
-            }
784
-            // and then directly call its constructor again, like we would if we were creating a new one
785
-            static::$_instance->__construct(
786
-                $timezone,
787
-                EEM_Base::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
788
-            );
789
-            return self::instance();
790
-        }
791
-        return null;
792
-    }
793
-
794
-
795
-
796
-    /**
797
-     * @return LoaderInterface
798
-     * @throws InvalidArgumentException
799
-     * @throws InvalidDataTypeException
800
-     * @throws InvalidInterfaceException
801
-     */
802
-    private static function getLoader()
803
-    {
804
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
805
-            EEM_Base::$loader = LoaderFactory::getLoader();
806
-        }
807
-        return EEM_Base::$loader;
808
-    }
809
-
810
-
811
-
812
-    /**
813
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
814
-     *
815
-     * @param  boolean $translated return localized strings or JUST the array.
816
-     * @return array
817
-     * @throws EE_Error
818
-     * @throws InvalidArgumentException
819
-     * @throws InvalidDataTypeException
820
-     * @throws InvalidInterfaceException
821
-     */
822
-    public function status_array($translated = false)
823
-    {
824
-        if (! array_key_exists('Status', $this->_model_relations)) {
825
-            return array();
826
-        }
827
-        $model_name = $this->get_this_model_name();
828
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
829
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
830
-        $status_array = array();
831
-        foreach ($stati as $status) {
832
-            $status_array[ $status->ID() ] = $status->get('STS_code');
833
-        }
834
-        return $translated
835
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
836
-            : $status_array;
837
-    }
838
-
839
-
840
-
841
-    /**
842
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
843
-     *
844
-     * @param array $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
845
-     *                             or if you have the development copy of EE you can view this at the path:
846
-     *                             /docs/G--Model-System/model-query-params.md
847
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
848
-     *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object IDs (if there is a primary key on the model.
849
-     *                                        if not, numerically indexed) Some full examples: get 10 transactions
850
-     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
851
-     *                                        array( array(
852
-     *                                        'OR'=>array(
853
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
854
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
855
-     *                                        )
856
-     *                                        ),
857
-     *                                        'limit'=>10,
858
-     *                                        'group_by'=>'TXN_ID'
859
-     *                                        ));
860
-     *                                        get all the answers to the question titled "shirt size" for event with id
861
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
862
-     *                                        'Question.QST_display_text'=>'shirt size',
863
-     *                                        'Registration.Event.EVT_ID'=>12
864
-     *                                        ),
865
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
866
-     *                                        ));
867
-     * @throws EE_Error
868
-     */
869
-    public function get_all($query_params = array())
870
-    {
871
-        if (
872
-            isset($query_params['limit'])
873
-            && ! isset($query_params['group_by'])
874
-        ) {
875
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
876
-        }
877
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
878
-    }
879
-
880
-
881
-
882
-    /**
883
-     * Modifies the query parameters so we only get back model objects
884
-     * that "belong" to the current user
885
-     *
886
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
887
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
888
-     */
889
-    public function alter_query_params_to_only_include_mine($query_params = array())
890
-    {
891
-        $wp_user_field_name = $this->wp_user_field_name();
892
-        if ($wp_user_field_name) {
893
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
894
-        }
895
-        return $query_params;
896
-    }
897
-
898
-
899
-
900
-    /**
901
-     * Returns the name of the field's name that points to the WP_User table
902
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
903
-     * foreign key to the WP_User table)
904
-     *
905
-     * @return string|boolean string on success, boolean false when there is no
906
-     * foreign key to the WP_User table
907
-     */
908
-    public function wp_user_field_name()
909
-    {
910
-        try {
911
-            if (! empty($this->_model_chain_to_wp_user)) {
912
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
913
-                $last_model_name = end($models_to_follow_to_wp_users);
914
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
915
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
916
-            } else {
917
-                $model_with_fk_to_wp_users = $this;
918
-                $model_chain_to_wp_user = '';
919
-            }
920
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
921
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
922
-        } catch (EE_Error $e) {
923
-            return false;
924
-        }
925
-    }
926
-
927
-
928
-
929
-    /**
930
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
931
-     * (or transiently-related model) has a foreign key to the wp_users table;
932
-     * useful for finding if model objects of this type are 'owned' by the current user.
933
-     * This is an empty string when the foreign key is on this model and when it isn't,
934
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
935
-     * (or transiently-related model)
936
-     *
937
-     * @return string
938
-     */
939
-    public function model_chain_to_wp_user()
940
-    {
941
-        return $this->_model_chain_to_wp_user;
942
-    }
943
-
944
-
945
-
946
-    /**
947
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
948
-     * like how registrations don't have a foreign key to wp_users, but the
949
-     * events they are for are), or is unrelated to wp users.
950
-     * generally available
951
-     *
952
-     * @return boolean
953
-     */
954
-    public function is_owned()
955
-    {
956
-        if ($this->model_chain_to_wp_user()) {
957
-            return true;
958
-        }
959
-        try {
960
-            $this->get_foreign_key_to('WP_User');
961
-            return true;
962
-        } catch (EE_Error $e) {
963
-            return false;
964
-        }
965
-    }
966
-
967
-
968
-    /**
969
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
970
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
971
-     * the model)
972
-     *
973
-     * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
974
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
975
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
976
-     *                                  fields on the model, and the models we joined to in the query. However, you can
977
-     *                                  override this and set the select to "*", or a specific column name, like
978
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
979
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
980
-     *                                  the aliases used to refer to this selection, and values are to be
981
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
982
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
983
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
984
-     * @throws EE_Error
985
-     * @throws InvalidArgumentException
986
-     */
987
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
988
-    {
989
-        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
990
-        ;
991
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
992
-        $select_expressions = $columns_to_select === null
993
-            ? $this->_construct_default_select_sql($model_query_info)
994
-            : '';
995
-        if ($this->_custom_selections instanceof CustomSelects) {
996
-            $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
997
-            $select_expressions .= $select_expressions
998
-                ? ', ' . $custom_expressions
999
-                : $custom_expressions;
1000
-        }
1001
-
1002
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1003
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
1004
-    }
1005
-
1006
-
1007
-    /**
1008
-     * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1009
-     * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1010
-     * method of including extra select information.
1011
-     *
1012
-     * @param array             $query_params
1013
-     * @param null|array|string $columns_to_select
1014
-     * @return null|CustomSelects
1015
-     * @throws InvalidArgumentException
1016
-     */
1017
-    protected function getCustomSelection(array $query_params, $columns_to_select = null)
1018
-    {
1019
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1020
-            return null;
1021
-        }
1022
-        $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1023
-        $selects = is_string($selects) ? explode(',', $selects) : $selects;
1024
-        return new CustomSelects($selects);
1025
-    }
1026
-
1027
-
1028
-
1029
-    /**
1030
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1031
-     * but you can use the model query params to more easily
1032
-     * take care of joins, field preparation etc.
1033
-     *
1034
-     * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1035
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1036
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1037
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1038
-     *                                  override this and set the select to "*", or a specific column name, like
1039
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1040
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1041
-     *                                  the aliases used to refer to this selection, and values are to be
1042
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1043
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1044
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1045
-     * @throws EE_Error
1046
-     */
1047
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1048
-    {
1049
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1050
-    }
1051
-
1052
-
1053
-
1054
-    /**
1055
-     * For creating a custom select statement
1056
-     *
1057
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1058
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1059
-     *                                 SQL, and 1=>is the datatype
1060
-     * @throws EE_Error
1061
-     * @return string
1062
-     */
1063
-    private function _construct_select_from_input($columns_to_select)
1064
-    {
1065
-        if (is_array($columns_to_select)) {
1066
-            $select_sql_array = array();
1067
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1068
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1069
-                    throw new EE_Error(
1070
-                        sprintf(
1071
-                            esc_html__(
1072
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1073
-                                'event_espresso'
1074
-                            ),
1075
-                            $selection_and_datatype,
1076
-                            $alias
1077
-                        )
1078
-                    );
1079
-                }
1080
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1081
-                    throw new EE_Error(
1082
-                        sprintf(
1083
-                            esc_html__(
1084
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1085
-                                'event_espresso'
1086
-                            ),
1087
-                            $selection_and_datatype[1],
1088
-                            $selection_and_datatype[0],
1089
-                            $alias,
1090
-                            implode(', ', $this->_valid_wpdb_data_types)
1091
-                        )
1092
-                    );
1093
-                }
1094
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1095
-            }
1096
-            $columns_to_select_string = implode(', ', $select_sql_array);
1097
-        } else {
1098
-            $columns_to_select_string = $columns_to_select;
1099
-        }
1100
-        return $columns_to_select_string;
1101
-    }
1102
-
1103
-
1104
-
1105
-    /**
1106
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1107
-     *
1108
-     * @return string
1109
-     * @throws EE_Error
1110
-     */
1111
-    public function primary_key_name()
1112
-    {
1113
-        return $this->get_primary_key_field()->get_name();
1114
-    }
1115
-
1116
-
1117
-    /**
1118
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1119
-     * If there is no primary key on this model, $id is treated as primary key string
1120
-     *
1121
-     * @param mixed $id int or string, depending on the type of the model's primary key
1122
-     * @return EE_Base_Class
1123
-     * @throws EE_Error
1124
-     */
1125
-    public function get_one_by_ID($id)
1126
-    {
1127
-        if ($this->get_from_entity_map($id)) {
1128
-            return $this->get_from_entity_map($id);
1129
-        }
1130
-        $model_object = $this->get_one(
1131
-            $this->alter_query_params_to_restrict_by_ID(
1132
-                $id,
1133
-                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1134
-            )
1135
-        );
1136
-        $className = $this->_get_class_name();
1137
-        if ($model_object instanceof $className) {
1138
-            // make sure valid objects get added to the entity map
1139
-            // so that the next call to this method doesn't trigger another trip to the db
1140
-            $this->add_to_entity_map($model_object);
1141
-        }
1142
-        return $model_object;
1143
-    }
1144
-
1145
-
1146
-
1147
-    /**
1148
-     * Alters query parameters to only get items with this ID are returned.
1149
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1150
-     * or could just be a simple primary key ID
1151
-     *
1152
-     * @param int   $id
1153
-     * @param array $query_params
1154
-     * @return array of normal query params, @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1155
-     * @throws EE_Error
1156
-     */
1157
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1158
-    {
1159
-        if (! isset($query_params[0])) {
1160
-            $query_params[0] = array();
1161
-        }
1162
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1163
-        if ($conditions_from_id === null) {
1164
-            $query_params[0][ $this->primary_key_name() ] = $id;
1165
-        } else {
1166
-            // no primary key, so the $id must be from the get_index_primary_key_string()
1167
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1168
-        }
1169
-        return $query_params;
1170
-    }
1171
-
1172
-
1173
-
1174
-    /**
1175
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1176
-     * array. If no item is found, null is returned.
1177
-     *
1178
-     * @param array $query_params like EEM_Base's $query_params variable.
1179
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1180
-     * @throws EE_Error
1181
-     */
1182
-    public function get_one($query_params = array())
1183
-    {
1184
-        if (! is_array($query_params)) {
1185
-            EE_Error::doing_it_wrong(
1186
-                'EEM_Base::get_one',
1187
-                sprintf(
1188
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1189
-                    gettype($query_params)
1190
-                ),
1191
-                '4.6.0'
1192
-            );
1193
-            $query_params = array();
1194
-        }
1195
-        $query_params['limit'] = 1;
1196
-        $items = $this->get_all($query_params);
1197
-        if (empty($items)) {
1198
-            return null;
1199
-        }
1200
-        return array_shift($items);
1201
-    }
1202
-
1203
-
1204
-
1205
-    /**
1206
-     * Returns the next x number of items in sequence from the given value as
1207
-     * found in the database matching the given query conditions.
1208
-     *
1209
-     * @param mixed $current_field_value    Value used for the reference point.
1210
-     * @param null  $field_to_order_by      What field is used for the
1211
-     *                                      reference point.
1212
-     * @param int   $limit                  How many to return.
1213
-     * @param array $query_params           Extra conditions on the query.
1214
-     * @param null  $columns_to_select      If left null, then an array of
1215
-     *                                      EE_Base_Class objects is returned,
1216
-     *                                      otherwise you can indicate just the
1217
-     *                                      columns you want returned.
1218
-     * @return EE_Base_Class[]|array
1219
-     * @throws EE_Error
1220
-     */
1221
-    public function next_x(
1222
-        $current_field_value,
1223
-        $field_to_order_by = null,
1224
-        $limit = 1,
1225
-        $query_params = array(),
1226
-        $columns_to_select = null
1227
-    ) {
1228
-        return $this->_get_consecutive(
1229
-            $current_field_value,
1230
-            '>',
1231
-            $field_to_order_by,
1232
-            $limit,
1233
-            $query_params,
1234
-            $columns_to_select
1235
-        );
1236
-    }
1237
-
1238
-
1239
-
1240
-    /**
1241
-     * Returns the previous x number of items in sequence from the given value
1242
-     * as found in the database matching the given query conditions.
1243
-     *
1244
-     * @param mixed $current_field_value    Value used for the reference point.
1245
-     * @param null  $field_to_order_by      What field is used for the
1246
-     *                                      reference point.
1247
-     * @param int   $limit                  How many to return.
1248
-     * @param array $query_params           Extra conditions on the query.
1249
-     * @param null  $columns_to_select      If left null, then an array of
1250
-     *                                      EE_Base_Class objects is returned,
1251
-     *                                      otherwise you can indicate just the
1252
-     *                                      columns you want returned.
1253
-     * @return EE_Base_Class[]|array
1254
-     * @throws EE_Error
1255
-     */
1256
-    public function previous_x(
1257
-        $current_field_value,
1258
-        $field_to_order_by = null,
1259
-        $limit = 1,
1260
-        $query_params = array(),
1261
-        $columns_to_select = null
1262
-    ) {
1263
-        return $this->_get_consecutive(
1264
-            $current_field_value,
1265
-            '<',
1266
-            $field_to_order_by,
1267
-            $limit,
1268
-            $query_params,
1269
-            $columns_to_select
1270
-        );
1271
-    }
1272
-
1273
-
1274
-
1275
-    /**
1276
-     * Returns the next item in sequence from the given value as found in the
1277
-     * database matching the given query conditions.
1278
-     *
1279
-     * @param mixed $current_field_value    Value used for the reference point.
1280
-     * @param null  $field_to_order_by      What field is used for the
1281
-     *                                      reference point.
1282
-     * @param array $query_params           Extra conditions on the query.
1283
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1284
-     *                                      object is returned, otherwise you
1285
-     *                                      can indicate just the columns you
1286
-     *                                      want and a single array indexed by
1287
-     *                                      the columns will be returned.
1288
-     * @return EE_Base_Class|null|array()
1289
-     * @throws EE_Error
1290
-     */
1291
-    public function next(
1292
-        $current_field_value,
1293
-        $field_to_order_by = null,
1294
-        $query_params = array(),
1295
-        $columns_to_select = null
1296
-    ) {
1297
-        $results = $this->_get_consecutive(
1298
-            $current_field_value,
1299
-            '>',
1300
-            $field_to_order_by,
1301
-            1,
1302
-            $query_params,
1303
-            $columns_to_select
1304
-        );
1305
-        return empty($results) ? null : reset($results);
1306
-    }
1307
-
1308
-
1309
-
1310
-    /**
1311
-     * Returns the previous item in sequence from the given value as found in
1312
-     * the database matching the given query conditions.
1313
-     *
1314
-     * @param mixed $current_field_value    Value used for the reference point.
1315
-     * @param null  $field_to_order_by      What field is used for the
1316
-     *                                      reference point.
1317
-     * @param array $query_params           Extra conditions on the query.
1318
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1319
-     *                                      object is returned, otherwise you
1320
-     *                                      can indicate just the columns you
1321
-     *                                      want and a single array indexed by
1322
-     *                                      the columns will be returned.
1323
-     * @return EE_Base_Class|null|array()
1324
-     * @throws EE_Error
1325
-     */
1326
-    public function previous(
1327
-        $current_field_value,
1328
-        $field_to_order_by = null,
1329
-        $query_params = array(),
1330
-        $columns_to_select = null
1331
-    ) {
1332
-        $results = $this->_get_consecutive(
1333
-            $current_field_value,
1334
-            '<',
1335
-            $field_to_order_by,
1336
-            1,
1337
-            $query_params,
1338
-            $columns_to_select
1339
-        );
1340
-        return empty($results) ? null : reset($results);
1341
-    }
1342
-
1343
-
1344
-
1345
-    /**
1346
-     * Returns the a consecutive number of items in sequence from the given
1347
-     * value as found in the database matching the given query conditions.
1348
-     *
1349
-     * @param mixed  $current_field_value   Value used for the reference point.
1350
-     * @param string $operand               What operand is used for the sequence.
1351
-     * @param string $field_to_order_by     What field is used for the reference point.
1352
-     * @param int    $limit                 How many to return.
1353
-     * @param array  $query_params          Extra conditions on the query.
1354
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1355
-     *                                      otherwise you can indicate just the columns you want returned.
1356
-     * @return EE_Base_Class[]|array
1357
-     * @throws EE_Error
1358
-     */
1359
-    protected function _get_consecutive(
1360
-        $current_field_value,
1361
-        $operand = '>',
1362
-        $field_to_order_by = null,
1363
-        $limit = 1,
1364
-        $query_params = array(),
1365
-        $columns_to_select = null
1366
-    ) {
1367
-        // if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1368
-        if (empty($field_to_order_by)) {
1369
-            if ($this->has_primary_key_field()) {
1370
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1371
-            } else {
1372
-                if (WP_DEBUG) {
1373
-                    throw new EE_Error(esc_html__(
1374
-                        '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).',
1375
-                        'event_espresso'
1376
-                    ));
1377
-                }
1378
-                EE_Error::add_error(esc_html__('There was an error with the query.', 'event_espresso'));
1379
-                return array();
1380
-            }
1381
-        }
1382
-        if (! is_array($query_params)) {
1383
-            EE_Error::doing_it_wrong(
1384
-                'EEM_Base::_get_consecutive',
1385
-                sprintf(
1386
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1387
-                    gettype($query_params)
1388
-                ),
1389
-                '4.6.0'
1390
-            );
1391
-            $query_params = array();
1392
-        }
1393
-        // let's add the where query param for consecutive look up.
1394
-        $query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1395
-        $query_params['limit'] = $limit;
1396
-        // set direction
1397
-        $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1398
-        $query_params['order_by'] = $operand === '>'
1399
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1400
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1401
-        // if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1402
-        if (empty($columns_to_select)) {
1403
-            return $this->get_all($query_params);
1404
-        }
1405
-        // getting just the fields
1406
-        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1407
-    }
1408
-
1409
-
1410
-
1411
-    /**
1412
-     * This sets the _timezone property after model object has been instantiated.
1413
-     *
1414
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1415
-     */
1416
-    public function set_timezone($timezone)
1417
-    {
1418
-        if ($timezone !== null) {
1419
-            $this->_timezone = $timezone;
1420
-        }
1421
-        // note we need to loop through relations and set the timezone on those objects as well.
1422
-        foreach ($this->_model_relations as $relation) {
1423
-            $relation->set_timezone($timezone);
1424
-        }
1425
-        // and finally we do the same for any datetime fields
1426
-        foreach ($this->_fields as $field) {
1427
-            if ($field instanceof EE_Datetime_Field) {
1428
-                $field->set_timezone($timezone);
1429
-            }
1430
-        }
1431
-    }
1432
-
1433
-
1434
-
1435
-    /**
1436
-     * This just returns whatever is set for the current timezone.
1437
-     *
1438
-     * @access public
1439
-     * @return string
1440
-     */
1441
-    public function get_timezone()
1442
-    {
1443
-        // first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1444
-        if (empty($this->_timezone)) {
1445
-            foreach ($this->_fields as $field) {
1446
-                if ($field instanceof EE_Datetime_Field) {
1447
-                    $this->set_timezone($field->get_timezone());
1448
-                    break;
1449
-                }
1450
-            }
1451
-        }
1452
-        // if timezone STILL empty then return the default timezone for the site.
1453
-        if (empty($this->_timezone)) {
1454
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1455
-        }
1456
-        return $this->_timezone;
1457
-    }
1458
-
1459
-
1460
-
1461
-    /**
1462
-     * This returns the date formats set for the given field name and also ensures that
1463
-     * $this->_timezone property is set correctly.
1464
-     *
1465
-     * @since 4.6.x
1466
-     * @param string $field_name The name of the field the formats are being retrieved for.
1467
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1468
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1469
-     * @return array formats in an array with the date format first, and the time format last.
1470
-     */
1471
-    public function get_formats_for($field_name, $pretty = false)
1472
-    {
1473
-        $field_settings = $this->field_settings_for($field_name);
1474
-        // if not a valid EE_Datetime_Field then throw error
1475
-        if (! $field_settings instanceof EE_Datetime_Field) {
1476
-            throw new EE_Error(sprintf(esc_html__(
1477
-                '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.',
1478
-                'event_espresso'
1479
-            ), $field_name));
1480
-        }
1481
-        // while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1482
-        // the field.
1483
-        $this->_timezone = $field_settings->get_timezone();
1484
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1485
-    }
1486
-
1487
-
1488
-
1489
-    /**
1490
-     * This returns the current time in a format setup for a query on this model.
1491
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1492
-     * it will return:
1493
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1494
-     *  NOW
1495
-     *  - or a unix timestamp (equivalent to time())
1496
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1497
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1498
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1499
-     * @since 4.6.x
1500
-     * @param string $field_name       The field the current time is needed for.
1501
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1502
-     *                                 formatted string matching the set format for the field in the set timezone will
1503
-     *                                 be returned.
1504
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1505
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1506
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1507
-     *                                 exception is triggered.
1508
-     */
1509
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1510
-    {
1511
-        $formats = $this->get_formats_for($field_name);
1512
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1513
-        if ($timestamp) {
1514
-            return $DateTime->format('U');
1515
-        }
1516
-        // not returning timestamp, so return formatted string in timezone.
1517
-        switch ($what) {
1518
-            case 'time':
1519
-                return $DateTime->format($formats[1]);
1520
-                break;
1521
-            case 'date':
1522
-                return $DateTime->format($formats[0]);
1523
-                break;
1524
-            default:
1525
-                return $DateTime->format(implode(' ', $formats));
1526
-                break;
1527
-        }
1528
-    }
1529
-
1530
-
1531
-
1532
-    /**
1533
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1534
-     * for the model are.  Returns a DateTime object.
1535
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1536
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1537
-     * ignored.
1538
-     *
1539
-     * @param string $field_name      The field being setup.
1540
-     * @param string $timestring      The date time string being used.
1541
-     * @param string $incoming_format The format for the time string.
1542
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1543
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1544
-     *                                format is
1545
-     *                                'U', this is ignored.
1546
-     * @return DateTime
1547
-     * @throws EE_Error
1548
-     */
1549
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1550
-    {
1551
-        // just using this to ensure the timezone is set correctly internally
1552
-        $this->get_formats_for($field_name);
1553
-        // load EEH_DTT_Helper
1554
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1555
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1556
-        EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1557
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1558
-    }
1559
-
1560
-
1561
-
1562
-    /**
1563
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1564
-     *
1565
-     * @return EE_Table_Base[]
1566
-     */
1567
-    public function get_tables()
1568
-    {
1569
-        return $this->_tables;
1570
-    }
1571
-
1572
-
1573
-
1574
-    /**
1575
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1576
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1577
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1578
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1579
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1580
-     * model object with EVT_ID = 1
1581
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1582
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1583
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1584
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1585
-     * are not specified)
1586
-     *
1587
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1588
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1589
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1590
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1591
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1592
-     *                                         ID=34, we'd use this method as follows:
1593
-     *                                         EEM_Transaction::instance()->update(
1594
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1595
-     *                                         array(array('TXN_ID'=>34)));
1596
-     * @param array   $query_params            @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1597
-     *                                         Eg, consider updating Question's QST_admin_label field is of type
1598
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1599
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1600
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1601
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1602
-     *                                         TRUE, it is assumed that you've already called
1603
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1604
-     *                                         malicious javascript. However, if
1605
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1606
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1607
-     *                                         and every other field, before insertion. We provide this parameter
1608
-     *                                         because model objects perform their prepare_for_set function on all
1609
-     *                                         their values, and so don't need to be called again (and in many cases,
1610
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1611
-     *                                         prepare_for_set method...)
1612
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1613
-     *                                         in this model's entity map according to $fields_n_values that match
1614
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1615
-     *                                         by setting this to FALSE, but be aware that model objects being used
1616
-     *                                         could get out-of-sync with the database
1617
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1618
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1619
-     *                                         bad)
1620
-     * @throws EE_Error
1621
-     */
1622
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1623
-    {
1624
-        if (! is_array($query_params)) {
1625
-            EE_Error::doing_it_wrong(
1626
-                'EEM_Base::update',
1627
-                sprintf(
1628
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1629
-                    gettype($query_params)
1630
-                ),
1631
-                '4.6.0'
1632
-            );
1633
-            $query_params = array();
1634
-        }
1635
-        /**
1636
-         * Action called before a model update call has been made.
1637
-         *
1638
-         * @param EEM_Base $model
1639
-         * @param array    $fields_n_values the updated fields and their new values
1640
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1641
-         */
1642
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1643
-        /**
1644
-         * Filters the fields about to be updated given the query parameters. You can provide the
1645
-         * $query_params to $this->get_all() to find exactly which records will be updated
1646
-         *
1647
-         * @param array    $fields_n_values fields and their new values
1648
-         * @param EEM_Base $model           the model being queried
1649
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1650
-         */
1651
-        $fields_n_values = (array) apply_filters(
1652
-            'FHEE__EEM_Base__update__fields_n_values',
1653
-            $fields_n_values,
1654
-            $this,
1655
-            $query_params
1656
-        );
1657
-        // need to verify that, for any entry we want to update, there are entries in each secondary table.
1658
-        // to do that, for each table, verify that it's PK isn't null.
1659
-        $tables = $this->get_tables();
1660
-        // 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
1661
-        // NOTE: we should make this code more efficient by NOT querying twice
1662
-        // before the real update, but that needs to first go through ALPHA testing
1663
-        // as it's dangerous. says Mike August 8 2014
1664
-        // we want to make sure the default_where strategy is ignored
1665
-        $this->_ignore_where_strategy = true;
1666
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1667
-        foreach ($wpdb_select_results as $wpdb_result) {
1668
-            // type cast stdClass as array
1669
-            $wpdb_result = (array) $wpdb_result;
1670
-            // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1671
-            if ($this->has_primary_key_field()) {
1672
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1673
-            } else {
1674
-                // 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)
1675
-                $main_table_pk_value = null;
1676
-            }
1677
-            // 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
1678
-            // 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
1679
-            if (count($tables) > 1) {
1680
-                // foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1681
-                // in that table, and so we'll want to insert one
1682
-                foreach ($tables as $table_obj) {
1683
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1684
-                    // if there is no private key for this table on the results, it means there's no entry
1685
-                    // in this table, right? so insert a row in the current table, using any fields available
1686
-                    if (
1687
-                        ! (array_key_exists($this_table_pk_column, $wpdb_result)
1688
-                           && $wpdb_result[ $this_table_pk_column ])
1689
-                    ) {
1690
-                        $success = $this->_insert_into_specific_table(
1691
-                            $table_obj,
1692
-                            $fields_n_values,
1693
-                            $main_table_pk_value
1694
-                        );
1695
-                        // if we died here, report the error
1696
-                        if (! $success) {
1697
-                            return false;
1698
-                        }
1699
-                    }
1700
-                }
1701
-            }
1702
-            //              //and now check that if we have cached any models by that ID on the model, that
1703
-            //              //they also get updated properly
1704
-            //              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1705
-            //              if( $model_object ){
1706
-            //                  foreach( $fields_n_values as $field => $value ){
1707
-            //                      $model_object->set($field, $value);
1708
-            // let's make sure default_where strategy is followed now
1709
-            $this->_ignore_where_strategy = false;
1710
-        }
1711
-        // if we want to keep model objects in sync, AND
1712
-        // if this wasn't called from a model object (to update itself)
1713
-        // then we want to make sure we keep all the existing
1714
-        // model objects in sync with the db
1715
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1716
-            if ($this->has_primary_key_field()) {
1717
-                $model_objs_affected_ids = $this->get_col($query_params);
1718
-            } else {
1719
-                // we need to select a bunch of columns and then combine them into the the "index primary key string"s
1720
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1721
-                $model_objs_affected_ids = array();
1722
-                foreach ($models_affected_key_columns as $row) {
1723
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1724
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1725
-                }
1726
-            }
1727
-            if (! $model_objs_affected_ids) {
1728
-                // wait wait wait- if nothing was affected let's stop here
1729
-                return 0;
1730
-            }
1731
-            foreach ($model_objs_affected_ids as $id) {
1732
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1733
-                if ($model_obj_in_entity_map) {
1734
-                    foreach ($fields_n_values as $field => $new_value) {
1735
-                        $model_obj_in_entity_map->set($field, $new_value);
1736
-                    }
1737
-                }
1738
-            }
1739
-            // if there is a primary key on this model, we can now do a slight optimization
1740
-            if ($this->has_primary_key_field()) {
1741
-                // we already know what we want to update. So let's make the query simpler so it's a little more efficient
1742
-                $query_params = array(
1743
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1744
-                    'limit'                    => count($model_objs_affected_ids),
1745
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1746
-                );
1747
-            }
1748
-        }
1749
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1750
-        $SQL = "UPDATE "
1751
-               . $model_query_info->get_full_join_sql()
1752
-               . " SET "
1753
-               . $this->_construct_update_sql($fields_n_values)
1754
-               . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1755
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1756
-        /**
1757
-         * Action called after a model update call has been made.
1758
-         *
1759
-         * @param EEM_Base $model
1760
-         * @param array    $fields_n_values the updated fields and their new values
1761
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1762
-         * @param int      $rows_affected
1763
-         */
1764
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1765
-        return $rows_affected;// how many supposedly got updated
1766
-    }
1767
-
1768
-
1769
-
1770
-    /**
1771
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1772
-     * are teh values of the field specified (or by default the primary key field)
1773
-     * that matched the query params. Note that you should pass the name of the
1774
-     * model FIELD, not the database table's column name.
1775
-     *
1776
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1777
-     * @param string $field_to_select
1778
-     * @return array just like $wpdb->get_col()
1779
-     * @throws EE_Error
1780
-     */
1781
-    public function get_col($query_params = array(), $field_to_select = null)
1782
-    {
1783
-        if ($field_to_select) {
1784
-            $field = $this->field_settings_for($field_to_select);
1785
-        } elseif ($this->has_primary_key_field()) {
1786
-            $field = $this->get_primary_key_field();
1787
-        } else {
1788
-            // no primary key, just grab the first column
1789
-            $field = reset($this->field_settings());
1790
-        }
1791
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1792
-        $select_expressions = $field->get_qualified_column();
1793
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1794
-        return $this->_do_wpdb_query('get_col', array($SQL));
1795
-    }
1796
-
1797
-
1798
-
1799
-    /**
1800
-     * Returns a single column value for a single row from the database
1801
-     *
1802
-     * @param array  $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1803
-     * @param string $field_to_select @see EEM_Base::get_col()
1804
-     * @return string
1805
-     * @throws EE_Error
1806
-     */
1807
-    public function get_var($query_params = array(), $field_to_select = null)
1808
-    {
1809
-        $query_params['limit'] = 1;
1810
-        $col = $this->get_col($query_params, $field_to_select);
1811
-        if (! empty($col)) {
1812
-            return reset($col);
1813
-        }
1814
-        return null;
1815
-    }
1816
-
1817
-
1818
-
1819
-    /**
1820
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1821
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1822
-     * injection, but currently no further filtering is done
1823
-     *
1824
-     * @global      $wpdb
1825
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1826
-     *                               be updated to in the DB
1827
-     * @return string of SQL
1828
-     * @throws EE_Error
1829
-     */
1830
-    public function _construct_update_sql($fields_n_values)
1831
-    {
1832
-        /** @type WPDB $wpdb */
1833
-        global $wpdb;
1834
-        $cols_n_values = array();
1835
-        foreach ($fields_n_values as $field_name => $value) {
1836
-            $field_obj = $this->field_settings_for($field_name);
1837
-            // if the value is NULL, we want to assign the value to that.
1838
-            // wpdb->prepare doesn't really handle that properly
1839
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1840
-            $value_sql = $prepared_value === null ? 'NULL'
1841
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1842
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1843
-        }
1844
-        return implode(",", $cols_n_values);
1845
-    }
1846
-
1847
-
1848
-
1849
-    /**
1850
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1851
-     * Performs a HARD delete, meaning the database row should always be removed,
1852
-     * not just have a flag field on it switched
1853
-     * Wrapper for EEM_Base::delete_permanently()
1854
-     *
1855
-     * @param mixed $id
1856
-     * @param boolean $allow_blocking
1857
-     * @return int the number of rows deleted
1858
-     * @throws EE_Error
1859
-     */
1860
-    public function delete_permanently_by_ID($id, $allow_blocking = true)
1861
-    {
1862
-        return $this->delete_permanently(
1863
-            array(
1864
-                array($this->get_primary_key_field()->get_name() => $id),
1865
-                'limit' => 1,
1866
-            ),
1867
-            $allow_blocking
1868
-        );
1869
-    }
1870
-
1871
-
1872
-
1873
-    /**
1874
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1875
-     * Wrapper for EEM_Base::delete()
1876
-     *
1877
-     * @param mixed $id
1878
-     * @param boolean $allow_blocking
1879
-     * @return int the number of rows deleted
1880
-     * @throws EE_Error
1881
-     */
1882
-    public function delete_by_ID($id, $allow_blocking = true)
1883
-    {
1884
-        return $this->delete(
1885
-            array(
1886
-                array($this->get_primary_key_field()->get_name() => $id),
1887
-                'limit' => 1,
1888
-            ),
1889
-            $allow_blocking
1890
-        );
1891
-    }
1892
-
1893
-
1894
-
1895
-    /**
1896
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1897
-     * meaning if the model has a field that indicates its been "trashed" or
1898
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1899
-     *
1900
-     * @see EEM_Base::delete_permanently
1901
-     * @param array   $query_params
1902
-     * @param boolean $allow_blocking
1903
-     * @return int how many rows got deleted
1904
-     * @throws EE_Error
1905
-     */
1906
-    public function delete($query_params, $allow_blocking = true)
1907
-    {
1908
-        return $this->delete_permanently($query_params, $allow_blocking);
1909
-    }
1910
-
1911
-
1912
-
1913
-    /**
1914
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1915
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1916
-     * as archived, not actually deleted
1917
-     *
1918
-     * @param array   $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1919
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1920
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1921
-     *                                deletes regardless of other objects which may depend on it. Its generally
1922
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1923
-     *                                DB
1924
-     * @return int how many rows got deleted
1925
-     * @throws EE_Error
1926
-     */
1927
-    public function delete_permanently($query_params, $allow_blocking = true)
1928
-    {
1929
-        /**
1930
-         * Action called just before performing a real deletion query. You can use the
1931
-         * model and its $query_params to find exactly which items will be deleted
1932
-         *
1933
-         * @param EEM_Base $model
1934
-         * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1935
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1936
-         *                                 to block (prevent) this deletion
1937
-         */
1938
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1939
-        // some MySQL databases may be running safe mode, which may restrict
1940
-        // deletion if there is no KEY column used in the WHERE statement of a deletion.
1941
-        // to get around this, we first do a SELECT, get all the IDs, and then run another query
1942
-        // to delete them
1943
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1944
-        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1945
-        $deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1946
-            $columns_and_ids_for_deleting
1947
-        );
1948
-        /**
1949
-         * Allows client code to act on the items being deleted before the query is actually executed.
1950
-         *
1951
-         * @param EEM_Base $this  The model instance being acted on.
1952
-         * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1953
-         * @param bool     $allow_blocking @see param description in method phpdoc block.
1954
-         * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1955
-         *                                                  derived from the incoming query parameters.
1956
-         *                                                  @see details on the structure of this array in the phpdocs
1957
-         *                                                  for the `_get_ids_for_delete_method`
1958
-         *
1959
-         */
1960
-        do_action(
1961
-            'AHEE__EEM_Base__delete__before_query',
1962
-            $this,
1963
-            $query_params,
1964
-            $allow_blocking,
1965
-            $columns_and_ids_for_deleting
1966
-        );
1967
-        if ($deletion_where_query_part) {
1968
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
1969
-            $table_aliases = array_keys($this->_tables);
1970
-            $SQL = "DELETE "
1971
-                   . implode(", ", $table_aliases)
1972
-                   . " FROM "
1973
-                   . $model_query_info->get_full_join_sql()
1974
-                   . " WHERE "
1975
-                   . $deletion_where_query_part;
1976
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1977
-        } else {
1978
-            $rows_deleted = 0;
1979
-        }
1980
-
1981
-        // Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
1982
-        // there was no error with the delete query.
1983
-        if (
1984
-            $this->has_primary_key_field()
1985
-            && $rows_deleted !== false
1986
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
1987
-        ) {
1988
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
1989
-            foreach ($ids_for_removal as $id) {
1990
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
1991
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
1992
-                }
1993
-            }
1994
-
1995
-            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
1996
-            // `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
1997
-            // unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
1998
-            // (although it is possible).
1999
-            // Note this can be skipped by using the provided filter and returning false.
2000
-            if (
2001
-                apply_filters(
2002
-                    'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2003
-                    ! $this instanceof EEM_Extra_Meta,
2004
-                    $this
2005
-                )
2006
-            ) {
2007
-                EEM_Extra_Meta::instance()->delete_permanently(array(
2008
-                    0 => array(
2009
-                        'EXM_type' => $this->get_this_model_name(),
2010
-                        'OBJ_ID'   => array(
2011
-                            'IN',
2012
-                            $ids_for_removal
2013
-                        )
2014
-                    )
2015
-                ));
2016
-            }
2017
-        }
2018
-
2019
-        /**
2020
-         * Action called just after performing a real deletion query. Although at this point the
2021
-         * items should have been deleted
2022
-         *
2023
-         * @param EEM_Base $model
2024
-         * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2025
-         * @param int      $rows_deleted
2026
-         */
2027
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2028
-        return $rows_deleted;// how many supposedly got deleted
2029
-    }
2030
-
2031
-
2032
-
2033
-    /**
2034
-     * Checks all the relations that throw error messages when there are blocking related objects
2035
-     * for related model objects. If there are any related model objects on those relations,
2036
-     * adds an EE_Error, and return true
2037
-     *
2038
-     * @param EE_Base_Class|int $this_model_obj_or_id
2039
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2040
-     *                                                 should be ignored when determining whether there are related
2041
-     *                                                 model objects which block this model object's deletion. Useful
2042
-     *                                                 if you know A is related to B and are considering deleting A,
2043
-     *                                                 but want to see if A has any other objects blocking its deletion
2044
-     *                                                 before removing the relation between A and B
2045
-     * @return boolean
2046
-     * @throws EE_Error
2047
-     */
2048
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2049
-    {
2050
-        // first, if $ignore_this_model_obj was supplied, get its model
2051
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2052
-            $ignored_model = $ignore_this_model_obj->get_model();
2053
-        } else {
2054
-            $ignored_model = null;
2055
-        }
2056
-        // now check all the relations of $this_model_obj_or_id and see if there
2057
-        // are any related model objects blocking it?
2058
-        $is_blocked = false;
2059
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2060
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2061
-                // if $ignore_this_model_obj was supplied, then for the query
2062
-                // on that model needs to be told to ignore $ignore_this_model_obj
2063
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2064
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2065
-                        array(
2066
-                            $ignored_model->get_primary_key_field()->get_name() => array(
2067
-                                '!=',
2068
-                                $ignore_this_model_obj->ID(),
2069
-                            ),
2070
-                        ),
2071
-                    ));
2072
-                } else {
2073
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2074
-                }
2075
-                if ($related_model_objects) {
2076
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2077
-                    $is_blocked = true;
2078
-                }
2079
-            }
2080
-        }
2081
-        return $is_blocked;
2082
-    }
2083
-
2084
-
2085
-    /**
2086
-     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2087
-     * @param array $row_results_for_deleting
2088
-     * @param bool  $allow_blocking
2089
-     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2090
-     *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2091
-     *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2092
-     *                 deleted. Example:
2093
-     *                      array('Event.EVT_ID' => array( 1,2,3))
2094
-     *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2095
-     *                 where each element is a group of columns and values that get deleted. Example:
2096
-     *                      array(
2097
-     *                          0 => array(
2098
-     *                              'Term_Relationship.object_id' => 1
2099
-     *                              'Term_Relationship.term_taxonomy_id' => 5
2100
-     *                          ),
2101
-     *                          1 => array(
2102
-     *                              'Term_Relationship.object_id' => 1
2103
-     *                              'Term_Relationship.term_taxonomy_id' => 6
2104
-     *                          )
2105
-     *                      )
2106
-     * @throws EE_Error
2107
-     */
2108
-    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2109
-    {
2110
-        $ids_to_delete_indexed_by_column = array();
2111
-        if ($this->has_primary_key_field()) {
2112
-            $primary_table = $this->_get_main_table();
2113
-            $primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2114
-            $other_tables = $this->_get_other_tables();
2115
-            $ids_to_delete_indexed_by_column = $query = array();
2116
-            foreach ($row_results_for_deleting as $item_to_delete) {
2117
-                // before we mark this item for deletion,
2118
-                // make sure there's no related entities blocking its deletion (if we're checking)
2119
-                if (
2120
-                    $allow_blocking
2121
-                    && $this->delete_is_blocked_by_related_models(
2122
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2123
-                    )
2124
-                ) {
2125
-                    continue;
2126
-                }
2127
-                // primary table deletes
2128
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2129
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2130
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2131
-                }
2132
-            }
2133
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2134
-            $fields = $this->get_combined_primary_key_fields();
2135
-            foreach ($row_results_for_deleting as $item_to_delete) {
2136
-                $ids_to_delete_indexed_by_column_for_row = array();
2137
-                foreach ($fields as $cpk_field) {
2138
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2139
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2140
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2141
-                    }
2142
-                }
2143
-                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2144
-            }
2145
-        } else {
2146
-            // so there's no primary key and no combined key...
2147
-            // sorry, can't help you
2148
-            throw new EE_Error(
2149
-                sprintf(
2150
-                    esc_html__(
2151
-                        "Cannot delete objects of type %s because there is no primary key NOR combined key",
2152
-                        "event_espresso"
2153
-                    ),
2154
-                    get_class($this)
2155
-                )
2156
-            );
2157
-        }
2158
-        return $ids_to_delete_indexed_by_column;
2159
-    }
2160
-
2161
-
2162
-    /**
2163
-     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2164
-     * the corresponding query_part for the query performing the delete.
2165
-     *
2166
-     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2167
-     * @return string
2168
-     * @throws EE_Error
2169
-     */
2170
-    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2171
-    {
2172
-        $query_part = '';
2173
-        if (empty($ids_to_delete_indexed_by_column)) {
2174
-            return $query_part;
2175
-        } elseif ($this->has_primary_key_field()) {
2176
-            $query = array();
2177
-            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2178
-                $query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2179
-            }
2180
-            $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2181
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2182
-            $ways_to_identify_a_row = array();
2183
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2184
-                $values_for_each_combined_primary_key_for_a_row = array();
2185
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2186
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2187
-                }
2188
-                $ways_to_identify_a_row[] = '('
2189
-                                            . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2190
-                                            . ')';
2191
-            }
2192
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2193
-        }
2194
-        return $query_part;
2195
-    }
2196
-
2197
-
2198
-
2199
-    /**
2200
-     * Gets the model field by the fully qualified name
2201
-     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2202
-     * @return EE_Model_Field_Base
2203
-     */
2204
-    public function get_field_by_column($qualified_column_name)
2205
-    {
2206
-        foreach ($this->field_settings(true) as $field_name => $field_obj) {
2207
-            if ($field_obj->get_qualified_column() === $qualified_column_name) {
2208
-                return $field_obj;
2209
-            }
2210
-        }
2211
-        throw new EE_Error(
2212
-            sprintf(
2213
-                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2214
-                $this->get_this_model_name(),
2215
-                $qualified_column_name
2216
-            )
2217
-        );
2218
-    }
2219
-
2220
-
2221
-
2222
-    /**
2223
-     * Count all the rows that match criteria the model query params.
2224
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2225
-     * column
2226
-     *
2227
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2228
-     * @param string $field_to_count field on model to count by (not column name)
2229
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2230
-     *                               that by the setting $distinct to TRUE;
2231
-     * @return int
2232
-     * @throws EE_Error
2233
-     */
2234
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2235
-    {
2236
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2237
-        if ($field_to_count) {
2238
-            $field_obj = $this->field_settings_for($field_to_count);
2239
-            $column_to_count = $field_obj->get_qualified_column();
2240
-        } elseif ($this->has_primary_key_field()) {
2241
-            $pk_field_obj = $this->get_primary_key_field();
2242
-            $column_to_count = $pk_field_obj->get_qualified_column();
2243
-        } else {
2244
-            // there's no primary key
2245
-            // if we're counting distinct items, and there's no primary key,
2246
-            // we need to list out the columns for distinction;
2247
-            // otherwise we can just use star
2248
-            if ($distinct) {
2249
-                $columns_to_use = array();
2250
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2251
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2252
-                }
2253
-                $column_to_count = implode(',', $columns_to_use);
2254
-            } else {
2255
-                $column_to_count = '*';
2256
-            }
2257
-        }
2258
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2259
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2260
-        return (int) $this->_do_wpdb_query('get_var', array($SQL));
2261
-    }
2262
-
2263
-
2264
-
2265
-    /**
2266
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2267
-     *
2268
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2269
-     * @param string $field_to_sum name of field (array key in $_fields array)
2270
-     * @return float
2271
-     * @throws EE_Error
2272
-     */
2273
-    public function sum($query_params, $field_to_sum = null)
2274
-    {
2275
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2276
-        if ($field_to_sum) {
2277
-            $field_obj = $this->field_settings_for($field_to_sum);
2278
-        } else {
2279
-            $field_obj = $this->get_primary_key_field();
2280
-        }
2281
-        $column_to_count = $field_obj->get_qualified_column();
2282
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2283
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2284
-        $data_type = $field_obj->get_wpdb_data_type();
2285
-        if ($data_type === '%d' || $data_type === '%s') {
2286
-            return (float) $return_value;
2287
-        }
2288
-        // must be %f
2289
-        return (float) $return_value;
2290
-    }
2291
-
2292
-
2293
-
2294
-    /**
2295
-     * Just calls the specified method on $wpdb with the given arguments
2296
-     * Consolidates a little extra error handling code
2297
-     *
2298
-     * @param string $wpdb_method
2299
-     * @param array  $arguments_to_provide
2300
-     * @throws EE_Error
2301
-     * @global wpdb  $wpdb
2302
-     * @return mixed
2303
-     */
2304
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2305
-    {
2306
-        // if we're in maintenance mode level 2, DON'T run any queries
2307
-        // because level 2 indicates the database needs updating and
2308
-        // is probably out of sync with the code
2309
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2310
-            throw new EE_Error(sprintf(esc_html__(
2311
-                "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.",
2312
-                "event_espresso"
2313
-            )));
2314
-        }
2315
-        /** @type WPDB $wpdb */
2316
-        global $wpdb;
2317
-        if (! method_exists($wpdb, $wpdb_method)) {
2318
-            throw new EE_Error(sprintf(esc_html__(
2319
-                'There is no method named "%s" on Wordpress\' $wpdb object',
2320
-                'event_espresso'
2321
-            ), $wpdb_method));
2322
-        }
2323
-        if (WP_DEBUG) {
2324
-            $old_show_errors_value = $wpdb->show_errors;
2325
-            $wpdb->show_errors(false);
2326
-        }
2327
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2328
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2329
-        if (WP_DEBUG) {
2330
-            $wpdb->show_errors($old_show_errors_value);
2331
-            if (! empty($wpdb->last_error)) {
2332
-                throw new EE_Error(sprintf(esc_html__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2333
-            }
2334
-            if ($result === false) {
2335
-                throw new EE_Error(sprintf(esc_html__(
2336
-                    'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2337
-                    'event_espresso'
2338
-                ), $wpdb_method, var_export($arguments_to_provide, true)));
2339
-            }
2340
-        } elseif ($result === false) {
2341
-            EE_Error::add_error(
2342
-                sprintf(
2343
-                    esc_html__(
2344
-                        '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"',
2345
-                        'event_espresso'
2346
-                    ),
2347
-                    $wpdb_method,
2348
-                    var_export($arguments_to_provide, true),
2349
-                    $wpdb->last_error
2350
-                ),
2351
-                __FILE__,
2352
-                __FUNCTION__,
2353
-                __LINE__
2354
-            );
2355
-        }
2356
-        return $result;
2357
-    }
2358
-
2359
-
2360
-
2361
-    /**
2362
-     * Attempts to run the indicated WPDB method with the provided arguments,
2363
-     * and if there's an error tries to verify the DB is correct. Uses
2364
-     * the static property EEM_Base::$_db_verification_level to determine whether
2365
-     * we should try to fix the EE core db, the addons, or just give up
2366
-     *
2367
-     * @param string $wpdb_method
2368
-     * @param array  $arguments_to_provide
2369
-     * @return mixed
2370
-     */
2371
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2372
-    {
2373
-        /** @type WPDB $wpdb */
2374
-        global $wpdb;
2375
-        $wpdb->last_error = null;
2376
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2377
-        // was there an error running the query? but we don't care on new activations
2378
-        // (we're going to setup the DB anyway on new activations)
2379
-        if (
2380
-            ($result === false || ! empty($wpdb->last_error))
2381
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2382
-        ) {
2383
-            switch (EEM_Base::$_db_verification_level) {
2384
-                case EEM_Base::db_verified_none:
2385
-                    // let's double-check core's DB
2386
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2387
-                    break;
2388
-                case EEM_Base::db_verified_core:
2389
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2390
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2391
-                    break;
2392
-                case EEM_Base::db_verified_addons:
2393
-                    // ummmm... you in trouble
2394
-                    return $result;
2395
-                    break;
2396
-            }
2397
-            if (! empty($error_message)) {
2398
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2399
-                trigger_error($error_message);
2400
-            }
2401
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2402
-        }
2403
-        return $result;
2404
-    }
2405
-
2406
-
2407
-
2408
-    /**
2409
-     * Verifies the EE core database is up-to-date and records that we've done it on
2410
-     * EEM_Base::$_db_verification_level
2411
-     *
2412
-     * @param string $wpdb_method
2413
-     * @param array  $arguments_to_provide
2414
-     * @return string
2415
-     */
2416
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2417
-    {
2418
-        /** @type WPDB $wpdb */
2419
-        global $wpdb;
2420
-        // ok remember that we've already attempted fixing the core db, in case the problem persists
2421
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2422
-        $error_message = sprintf(
2423
-            esc_html__(
2424
-                'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2425
-                'event_espresso'
2426
-            ),
2427
-            $wpdb->last_error,
2428
-            $wpdb_method,
2429
-            wp_json_encode($arguments_to_provide)
2430
-        );
2431
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2432
-        return $error_message;
2433
-    }
2434
-
2435
-
2436
-
2437
-    /**
2438
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2439
-     * EEM_Base::$_db_verification_level
2440
-     *
2441
-     * @param $wpdb_method
2442
-     * @param $arguments_to_provide
2443
-     * @return string
2444
-     */
2445
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2446
-    {
2447
-        /** @type WPDB $wpdb */
2448
-        global $wpdb;
2449
-        // ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2450
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2451
-        $error_message = sprintf(
2452
-            esc_html__(
2453
-                'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2454
-                'event_espresso'
2455
-            ),
2456
-            $wpdb->last_error,
2457
-            $wpdb_method,
2458
-            wp_json_encode($arguments_to_provide)
2459
-        );
2460
-        EE_System::instance()->initialize_addons();
2461
-        return $error_message;
2462
-    }
2463
-
2464
-
2465
-
2466
-    /**
2467
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2468
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2469
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2470
-     * ..."
2471
-     *
2472
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2473
-     * @return string
2474
-     */
2475
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2476
-    {
2477
-        return " FROM " . $model_query_info->get_full_join_sql() .
2478
-               $model_query_info->get_where_sql() .
2479
-               $model_query_info->get_group_by_sql() .
2480
-               $model_query_info->get_having_sql() .
2481
-               $model_query_info->get_order_by_sql() .
2482
-               $model_query_info->get_limit_sql();
2483
-    }
2484
-
2485
-
2486
-
2487
-    /**
2488
-     * Set to easily debug the next X queries ran from this model.
2489
-     *
2490
-     * @param int $count
2491
-     */
2492
-    public function show_next_x_db_queries($count = 1)
2493
-    {
2494
-        $this->_show_next_x_db_queries = $count;
2495
-    }
2496
-
2497
-
2498
-
2499
-    /**
2500
-     * @param $sql_query
2501
-     */
2502
-    public function show_db_query_if_previously_requested($sql_query)
2503
-    {
2504
-        if ($this->_show_next_x_db_queries > 0) {
2505
-            echo esc_html($sql_query);
2506
-            $this->_show_next_x_db_queries--;
2507
-        }
2508
-    }
2509
-
2510
-
2511
-
2512
-    /**
2513
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2514
-     * There are the 3 cases:
2515
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2516
-     * $otherModelObject has no ID, it is first saved.
2517
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2518
-     * has no ID, it is first saved.
2519
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2520
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2521
-     * join table
2522
-     *
2523
-     * @param        EE_Base_Class                     /int $thisModelObject
2524
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2525
-     * @param string $relationName                     , key in EEM_Base::_relations
2526
-     *                                                 an attendee to a group, you also want to specify which role they
2527
-     *                                                 will have in that group. So you would use this parameter to
2528
-     *                                                 specify array('role-column-name'=>'role-id')
2529
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2530
-     *                                                 to for relation to methods that allow you to further specify
2531
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2532
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2533
-     *                                                 because these will be inserted in any new rows created as well.
2534
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2535
-     * @throws EE_Error
2536
-     */
2537
-    public function add_relationship_to(
2538
-        $id_or_obj,
2539
-        $other_model_id_or_obj,
2540
-        $relationName,
2541
-        $extra_join_model_fields_n_values = array()
2542
-    ) {
2543
-        $relation_obj = $this->related_settings_for($relationName);
2544
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2545
-    }
2546
-
2547
-
2548
-
2549
-    /**
2550
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2551
-     * There are the 3 cases:
2552
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2553
-     * error
2554
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2555
-     * an error
2556
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2557
-     *
2558
-     * @param        EE_Base_Class /int $id_or_obj
2559
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2560
-     * @param string $relationName key in EEM_Base::_relations
2561
-     * @return boolean of success
2562
-     * @throws EE_Error
2563
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2564
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2565
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2566
-     *                             because these will be inserted in any new rows created as well.
2567
-     */
2568
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2569
-    {
2570
-        $relation_obj = $this->related_settings_for($relationName);
2571
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2572
-    }
2573
-
2574
-
2575
-
2576
-    /**
2577
-     * @param mixed           $id_or_obj
2578
-     * @param string          $relationName
2579
-     * @param array           $where_query_params
2580
-     * @param EE_Base_Class[] objects to which relations were removed
2581
-     * @return \EE_Base_Class[]
2582
-     * @throws EE_Error
2583
-     */
2584
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2585
-    {
2586
-        $relation_obj = $this->related_settings_for($relationName);
2587
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2588
-    }
2589
-
2590
-
2591
-
2592
-    /**
2593
-     * Gets all the related items of the specified $model_name, using $query_params.
2594
-     * Note: by default, we remove the "default query params"
2595
-     * because we want to get even deleted items etc.
2596
-     *
2597
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2598
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2599
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2600
-     * @return EE_Base_Class[]
2601
-     * @throws EE_Error
2602
-     */
2603
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2604
-    {
2605
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2606
-        $relation_settings = $this->related_settings_for($model_name);
2607
-        return $relation_settings->get_all_related($model_obj, $query_params);
2608
-    }
2609
-
2610
-
2611
-
2612
-    /**
2613
-     * Deletes all the model objects across the relation indicated by $model_name
2614
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2615
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2616
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2617
-     *
2618
-     * @param EE_Base_Class|int|string $id_or_obj
2619
-     * @param string                   $model_name
2620
-     * @param array                    $query_params
2621
-     * @return int how many deleted
2622
-     * @throws EE_Error
2623
-     */
2624
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2625
-    {
2626
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2627
-        $relation_settings = $this->related_settings_for($model_name);
2628
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2629
-    }
2630
-
2631
-
2632
-
2633
-    /**
2634
-     * Hard deletes all the model objects across the relation indicated by $model_name
2635
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2636
-     * the model objects can't be hard deleted because of blocking related model objects,
2637
-     * just does a soft-delete on them instead.
2638
-     *
2639
-     * @param EE_Base_Class|int|string $id_or_obj
2640
-     * @param string                   $model_name
2641
-     * @param array                    $query_params
2642
-     * @return int how many deleted
2643
-     * @throws EE_Error
2644
-     */
2645
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2646
-    {
2647
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2648
-        $relation_settings = $this->related_settings_for($model_name);
2649
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2650
-    }
2651
-
2652
-
2653
-
2654
-    /**
2655
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2656
-     * unless otherwise specified in the $query_params
2657
-     *
2658
-     * @param        int             /EE_Base_Class $id_or_obj
2659
-     * @param string $model_name     like 'Event', or 'Registration'
2660
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2661
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2662
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2663
-     *                               that by the setting $distinct to TRUE;
2664
-     * @return int
2665
-     * @throws EE_Error
2666
-     */
2667
-    public function count_related(
2668
-        $id_or_obj,
2669
-        $model_name,
2670
-        $query_params = array(),
2671
-        $field_to_count = null,
2672
-        $distinct = false
2673
-    ) {
2674
-        $related_model = $this->get_related_model_obj($model_name);
2675
-        // we're just going to use the query params on the related model's normal get_all query,
2676
-        // except add a condition to say to match the current mod
2677
-        if (! isset($query_params['default_where_conditions'])) {
2678
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2679
-        }
2680
-        $this_model_name = $this->get_this_model_name();
2681
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2682
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2683
-        return $related_model->count($query_params, $field_to_count, $distinct);
2684
-    }
2685
-
2686
-
2687
-
2688
-    /**
2689
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2690
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2691
-     *
2692
-     * @param        int           /EE_Base_Class $id_or_obj
2693
-     * @param string $model_name   like 'Event', or 'Registration'
2694
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2695
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2696
-     * @return float
2697
-     * @throws EE_Error
2698
-     */
2699
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2700
-    {
2701
-        $related_model = $this->get_related_model_obj($model_name);
2702
-        if (! is_array($query_params)) {
2703
-            EE_Error::doing_it_wrong(
2704
-                'EEM_Base::sum_related',
2705
-                sprintf(
2706
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2707
-                    gettype($query_params)
2708
-                ),
2709
-                '4.6.0'
2710
-            );
2711
-            $query_params = array();
2712
-        }
2713
-        // we're just going to use the query params on the related model's normal get_all query,
2714
-        // except add a condition to say to match the current mod
2715
-        if (! isset($query_params['default_where_conditions'])) {
2716
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2717
-        }
2718
-        $this_model_name = $this->get_this_model_name();
2719
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2720
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2721
-        return $related_model->sum($query_params, $field_to_sum);
2722
-    }
2723
-
2724
-
2725
-
2726
-    /**
2727
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2728
-     * $modelObject
2729
-     *
2730
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2731
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2732
-     * @param array               $query_params     @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2733
-     * @return EE_Base_Class
2734
-     * @throws EE_Error
2735
-     */
2736
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2737
-    {
2738
-        $query_params['limit'] = 1;
2739
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2740
-        if ($results) {
2741
-            return array_shift($results);
2742
-        }
2743
-        return null;
2744
-    }
2745
-
2746
-
2747
-
2748
-    /**
2749
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2750
-     *
2751
-     * @return string
2752
-     */
2753
-    public function get_this_model_name()
2754
-    {
2755
-        return str_replace("EEM_", "", get_class($this));
2756
-    }
2757
-
2758
-
2759
-
2760
-    /**
2761
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2762
-     *
2763
-     * @return EE_Any_Foreign_Model_Name_Field
2764
-     * @throws EE_Error
2765
-     */
2766
-    public function get_field_containing_related_model_name()
2767
-    {
2768
-        foreach ($this->field_settings(true) as $field) {
2769
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2770
-                $field_with_model_name = $field;
2771
-            }
2772
-        }
2773
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2774
-            throw new EE_Error(sprintf(
2775
-                esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2776
-                $this->get_this_model_name()
2777
-            ));
2778
-        }
2779
-        return $field_with_model_name;
2780
-    }
2781
-
2782
-
2783
-
2784
-    /**
2785
-     * Inserts a new entry into the database, for each table.
2786
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2787
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2788
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2789
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2790
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2791
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2792
-     *
2793
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2794
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2795
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2796
-     *                              of EEM_Base)
2797
-     * @return int|string new primary key on main table that got inserted
2798
-     * @throws EE_Error
2799
-     */
2800
-    public function insert($field_n_values)
2801
-    {
2802
-        /**
2803
-         * Filters the fields and their values before inserting an item using the models
2804
-         *
2805
-         * @param array    $fields_n_values keys are the fields and values are their new values
2806
-         * @param EEM_Base $model           the model used
2807
-         */
2808
-        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2809
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2810
-            $main_table = $this->_get_main_table();
2811
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2812
-            if ($new_id !== false) {
2813
-                foreach ($this->_get_other_tables() as $other_table) {
2814
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2815
-                }
2816
-            }
2817
-            /**
2818
-             * Done just after attempting to insert a new model object
2819
-             *
2820
-             * @param EEM_Base   $model           used
2821
-             * @param array      $fields_n_values fields and their values
2822
-             * @param int|string the              ID of the newly-inserted model object
2823
-             */
2824
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2825
-            return $new_id;
2826
-        }
2827
-        return false;
2828
-    }
2829
-
2830
-
2831
-
2832
-    /**
2833
-     * Checks that the result would satisfy the unique indexes on this model
2834
-     *
2835
-     * @param array  $field_n_values
2836
-     * @param string $action
2837
-     * @return boolean
2838
-     * @throws EE_Error
2839
-     */
2840
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2841
-    {
2842
-        foreach ($this->unique_indexes() as $index_name => $index) {
2843
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2844
-            if ($this->exists(array($uniqueness_where_params))) {
2845
-                EE_Error::add_error(
2846
-                    sprintf(
2847
-                        esc_html__(
2848
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2849
-                            "event_espresso"
2850
-                        ),
2851
-                        $action,
2852
-                        $this->_get_class_name(),
2853
-                        $index_name,
2854
-                        implode(",", $index->field_names()),
2855
-                        http_build_query($uniqueness_where_params)
2856
-                    ),
2857
-                    __FILE__,
2858
-                    __FUNCTION__,
2859
-                    __LINE__
2860
-                );
2861
-                return false;
2862
-            }
2863
-        }
2864
-        return true;
2865
-    }
2866
-
2867
-
2868
-
2869
-    /**
2870
-     * Checks the database for an item that conflicts (ie, if this item were
2871
-     * saved to the DB would break some uniqueness requirement, like a primary key
2872
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2873
-     * can be either an EE_Base_Class or an array of fields n values
2874
-     *
2875
-     * @param EE_Base_Class|array $obj_or_fields_array
2876
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2877
-     *                                                 when looking for conflicts
2878
-     *                                                 (ie, if false, we ignore the model object's primary key
2879
-     *                                                 when finding "conflicts". If true, it's also considered).
2880
-     *                                                 Only works for INT primary key,
2881
-     *                                                 STRING primary keys cannot be ignored
2882
-     * @throws EE_Error
2883
-     * @return EE_Base_Class|array
2884
-     */
2885
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2886
-    {
2887
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2888
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2889
-        } elseif (is_array($obj_or_fields_array)) {
2890
-            $fields_n_values = $obj_or_fields_array;
2891
-        } else {
2892
-            throw new EE_Error(
2893
-                sprintf(
2894
-                    esc_html__(
2895
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2896
-                        "event_espresso"
2897
-                    ),
2898
-                    get_class($this),
2899
-                    $obj_or_fields_array
2900
-                )
2901
-            );
2902
-        }
2903
-        $query_params = array();
2904
-        if (
2905
-            $this->has_primary_key_field()
2906
-            && ($include_primary_key
2907
-                || $this->get_primary_key_field()
2908
-                   instanceof
2909
-                   EE_Primary_Key_String_Field)
2910
-            && isset($fields_n_values[ $this->primary_key_name() ])
2911
-        ) {
2912
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2913
-        }
2914
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2915
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2916
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2917
-        }
2918
-        // if there is nothing to base this search on, then we shouldn't find anything
2919
-        if (empty($query_params)) {
2920
-            return array();
2921
-        }
2922
-        return $this->get_one($query_params);
2923
-    }
2924
-
2925
-
2926
-
2927
-    /**
2928
-     * Like count, but is optimized and returns a boolean instead of an int
2929
-     *
2930
-     * @param array $query_params
2931
-     * @return boolean
2932
-     * @throws EE_Error
2933
-     */
2934
-    public function exists($query_params)
2935
-    {
2936
-        $query_params['limit'] = 1;
2937
-        return $this->count($query_params) > 0;
2938
-    }
2939
-
2940
-
2941
-
2942
-    /**
2943
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2944
-     *
2945
-     * @param int|string $id
2946
-     * @return boolean
2947
-     * @throws EE_Error
2948
-     */
2949
-    public function exists_by_ID($id)
2950
-    {
2951
-        return $this->exists(
2952
-            array(
2953
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2954
-                array(
2955
-                    $this->primary_key_name() => $id,
2956
-                ),
2957
-            )
2958
-        );
2959
-    }
2960
-
2961
-
2962
-
2963
-    /**
2964
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2965
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2966
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2967
-     * on the main table)
2968
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2969
-     * cases where we want to call it directly rather than via insert().
2970
-     *
2971
-     * @access   protected
2972
-     * @param EE_Table_Base $table
2973
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2974
-     *                                       float
2975
-     * @param int           $new_id          for now we assume only int keys
2976
-     * @throws EE_Error
2977
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2978
-     * @return int ID of new row inserted, or FALSE on failure
2979
-     */
2980
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2981
-    {
2982
-        global $wpdb;
2983
-        $insertion_col_n_values = array();
2984
-        $format_for_insertion = array();
2985
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2986
-        foreach ($fields_on_table as $field_name => $field_obj) {
2987
-            // check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2988
-            if ($field_obj->is_auto_increment()) {
2989
-                continue;
2990
-            }
2991
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2992
-            // if the value we want to assign it to is NULL, just don't mention it for the insertion
2993
-            if ($prepared_value !== null) {
2994
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
2995
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2996
-            }
2997
-        }
2998
-        if ($table instanceof EE_Secondary_Table && $new_id) {
2999
-            // its not the main table, so we should have already saved the main table's PK which we just inserted
3000
-            // so add the fk to the main table as a column
3001
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3002
-            $format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
3003
-        }
3004
-        // insert the new entry
3005
-        $result = $this->_do_wpdb_query(
3006
-            'insert',
3007
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion)
3008
-        );
3009
-        if ($result === false) {
3010
-            return false;
3011
-        }
3012
-        // ok, now what do we return for the ID of the newly-inserted thing?
3013
-        if ($this->has_primary_key_field()) {
3014
-            if ($this->get_primary_key_field()->is_auto_increment()) {
3015
-                return $wpdb->insert_id;
3016
-            }
3017
-            // it's not an auto-increment primary key, so
3018
-            // it must have been supplied
3019
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3020
-        }
3021
-        // we can't return a  primary key because there is none. instead return
3022
-        // a unique string indicating this model
3023
-        return $this->get_index_primary_key_string($fields_n_values);
3024
-    }
3025
-
3026
-
3027
-
3028
-    /**
3029
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3030
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3031
-     * and there is no default, we pass it along. WPDB will take care of it)
3032
-     *
3033
-     * @param EE_Model_Field_Base $field_obj
3034
-     * @param array               $fields_n_values
3035
-     * @return mixed string|int|float depending on what the table column will be expecting
3036
-     * @throws EE_Error
3037
-     */
3038
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3039
-    {
3040
-        // if this field doesn't allow nullable, don't allow it
3041
-        if (
3042
-            ! $field_obj->is_nullable()
3043
-            && (
3044
-                ! isset($fields_n_values[ $field_obj->get_name() ])
3045
-                || $fields_n_values[ $field_obj->get_name() ] === null
3046
-            )
3047
-        ) {
3048
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3049
-        }
3050
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3051
-            ? $fields_n_values[ $field_obj->get_name() ]
3052
-            : null;
3053
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3054
-    }
3055
-
3056
-
3057
-
3058
-    /**
3059
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3060
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3061
-     * the field's prepare_for_set() method.
3062
-     *
3063
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3064
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3065
-     *                                   top of file)
3066
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3067
-     *                                   $value is a custom selection
3068
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3069
-     */
3070
-    private function _prepare_value_for_use_in_db($value, $field)
3071
-    {
3072
-        if ($field && $field instanceof EE_Model_Field_Base) {
3073
-            // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3074
-            switch ($this->_values_already_prepared_by_model_object) {
3075
-                /** @noinspection PhpMissingBreakStatementInspection */
3076
-                case self::not_prepared_by_model_object:
3077
-                    $value = $field->prepare_for_set($value);
3078
-                // purposefully left out "return"
3079
-                case self::prepared_by_model_object:
3080
-                    /** @noinspection SuspiciousAssignmentsInspection */
3081
-                    $value = $field->prepare_for_use_in_db($value);
3082
-                case self::prepared_for_use_in_db:
3083
-                    // leave the value alone
3084
-            }
3085
-            return $value;
3086
-            // phpcs:enable
3087
-        }
3088
-        return $value;
3089
-    }
3090
-
3091
-
3092
-
3093
-    /**
3094
-     * Returns the main table on this model
3095
-     *
3096
-     * @return EE_Primary_Table
3097
-     * @throws EE_Error
3098
-     */
3099
-    protected function _get_main_table()
3100
-    {
3101
-        foreach ($this->_tables as $table) {
3102
-            if ($table instanceof EE_Primary_Table) {
3103
-                return $table;
3104
-            }
3105
-        }
3106
-        throw new EE_Error(sprintf(esc_html__(
3107
-            'There are no main tables on %s. They should be added to _tables array in the constructor',
3108
-            'event_espresso'
3109
-        ), get_class($this)));
3110
-    }
3111
-
3112
-
3113
-
3114
-    /**
3115
-     * table
3116
-     * returns EE_Primary_Table table name
3117
-     *
3118
-     * @return string
3119
-     * @throws EE_Error
3120
-     */
3121
-    public function table()
3122
-    {
3123
-        return $this->_get_main_table()->get_table_name();
3124
-    }
3125
-
3126
-
3127
-
3128
-    /**
3129
-     * table
3130
-     * returns first EE_Secondary_Table table name
3131
-     *
3132
-     * @return string
3133
-     */
3134
-    public function second_table()
3135
-    {
3136
-        // grab second table from tables array
3137
-        $second_table = end($this->_tables);
3138
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3139
-    }
3140
-
3141
-
3142
-
3143
-    /**
3144
-     * get_table_obj_by_alias
3145
-     * returns table name given it's alias
3146
-     *
3147
-     * @param string $table_alias
3148
-     * @return EE_Primary_Table | EE_Secondary_Table
3149
-     */
3150
-    public function get_table_obj_by_alias($table_alias = '')
3151
-    {
3152
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3153
-    }
3154
-
3155
-
3156
-
3157
-    /**
3158
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3159
-     *
3160
-     * @return EE_Secondary_Table[]
3161
-     */
3162
-    protected function _get_other_tables()
3163
-    {
3164
-        $other_tables = array();
3165
-        foreach ($this->_tables as $table_alias => $table) {
3166
-            if ($table instanceof EE_Secondary_Table) {
3167
-                $other_tables[ $table_alias ] = $table;
3168
-            }
3169
-        }
3170
-        return $other_tables;
3171
-    }
3172
-
3173
-
3174
-
3175
-    /**
3176
-     * Finds all the fields that correspond to the given table
3177
-     *
3178
-     * @param string $table_alias , array key in EEM_Base::_tables
3179
-     * @return EE_Model_Field_Base[]
3180
-     */
3181
-    public function _get_fields_for_table($table_alias)
3182
-    {
3183
-        return $this->_fields[ $table_alias ];
3184
-    }
3185
-
3186
-
3187
-
3188
-    /**
3189
-     * Recurses through all the where parameters, and finds all the related models we'll need
3190
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3191
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3192
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3193
-     * related Registration, Transaction, and Payment models.
3194
-     *
3195
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3196
-     * @return EE_Model_Query_Info_Carrier
3197
-     * @throws EE_Error
3198
-     */
3199
-    public function _extract_related_models_from_query($query_params)
3200
-    {
3201
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3202
-        if (array_key_exists(0, $query_params)) {
3203
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3204
-        }
3205
-        if (array_key_exists('group_by', $query_params)) {
3206
-            if (is_array($query_params['group_by'])) {
3207
-                $this->_extract_related_models_from_sub_params_array_values(
3208
-                    $query_params['group_by'],
3209
-                    $query_info_carrier,
3210
-                    'group_by'
3211
-                );
3212
-            } elseif (! empty($query_params['group_by'])) {
3213
-                $this->_extract_related_model_info_from_query_param(
3214
-                    $query_params['group_by'],
3215
-                    $query_info_carrier,
3216
-                    'group_by'
3217
-                );
3218
-            }
3219
-        }
3220
-        if (array_key_exists('having', $query_params)) {
3221
-            $this->_extract_related_models_from_sub_params_array_keys(
3222
-                $query_params[0],
3223
-                $query_info_carrier,
3224
-                'having'
3225
-            );
3226
-        }
3227
-        if (array_key_exists('order_by', $query_params)) {
3228
-            if (is_array($query_params['order_by'])) {
3229
-                $this->_extract_related_models_from_sub_params_array_keys(
3230
-                    $query_params['order_by'],
3231
-                    $query_info_carrier,
3232
-                    'order_by'
3233
-                );
3234
-            } elseif (! empty($query_params['order_by'])) {
3235
-                $this->_extract_related_model_info_from_query_param(
3236
-                    $query_params['order_by'],
3237
-                    $query_info_carrier,
3238
-                    'order_by'
3239
-                );
3240
-            }
3241
-        }
3242
-        if (array_key_exists('force_join', $query_params)) {
3243
-            $this->_extract_related_models_from_sub_params_array_values(
3244
-                $query_params['force_join'],
3245
-                $query_info_carrier,
3246
-                'force_join'
3247
-            );
3248
-        }
3249
-        $this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3250
-        return $query_info_carrier;
3251
-    }
3252
-
3253
-
3254
-
3255
-    /**
3256
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3257
-     *
3258
-     * @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
3259
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3260
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3261
-     * @throws EE_Error
3262
-     * @return \EE_Model_Query_Info_Carrier
3263
-     */
3264
-    private function _extract_related_models_from_sub_params_array_keys(
3265
-        $sub_query_params,
3266
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3267
-        $query_param_type
3268
-    ) {
3269
-        if (! empty($sub_query_params)) {
3270
-            $sub_query_params = (array) $sub_query_params;
3271
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3272
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3273
-                $this->_extract_related_model_info_from_query_param(
3274
-                    $param,
3275
-                    $model_query_info_carrier,
3276
-                    $query_param_type
3277
-                );
3278
-                // if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3279
-                // indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3280
-                // extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3281
-                // of array('Registration.TXN_ID'=>23)
3282
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3283
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3284
-                    if (! is_array($possibly_array_of_params)) {
3285
-                        throw new EE_Error(sprintf(
3286
-                            esc_html__(
3287
-                                "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'))",
3288
-                                "event_espresso"
3289
-                            ),
3290
-                            $param,
3291
-                            $possibly_array_of_params
3292
-                        ));
3293
-                    }
3294
-                    $this->_extract_related_models_from_sub_params_array_keys(
3295
-                        $possibly_array_of_params,
3296
-                        $model_query_info_carrier,
3297
-                        $query_param_type
3298
-                    );
3299
-                } elseif (
3300
-                    $query_param_type === 0 // ie WHERE
3301
-                          && is_array($possibly_array_of_params)
3302
-                          && isset($possibly_array_of_params[2])
3303
-                          && $possibly_array_of_params[2] == true
3304
-                ) {
3305
-                    // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3306
-                    // indicating that $possible_array_of_params[1] is actually a field name,
3307
-                    // from which we should extract query parameters!
3308
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3309
-                        throw new EE_Error(sprintf(esc_html__(
3310
-                            "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3311
-                            "event_espresso"
3312
-                        ), $query_param_type, implode(",", $possibly_array_of_params)));
3313
-                    }
3314
-                    $this->_extract_related_model_info_from_query_param(
3315
-                        $possibly_array_of_params[1],
3316
-                        $model_query_info_carrier,
3317
-                        $query_param_type
3318
-                    );
3319
-                }
3320
-            }
3321
-        }
3322
-        return $model_query_info_carrier;
3323
-    }
3324
-
3325
-
3326
-
3327
-    /**
3328
-     * For extracting related models from forced_joins, where the array values contain the info about what
3329
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3330
-     *
3331
-     * @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
3332
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3333
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3334
-     * @throws EE_Error
3335
-     * @return \EE_Model_Query_Info_Carrier
3336
-     */
3337
-    private function _extract_related_models_from_sub_params_array_values(
3338
-        $sub_query_params,
3339
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3340
-        $query_param_type
3341
-    ) {
3342
-        if (! empty($sub_query_params)) {
3343
-            if (! is_array($sub_query_params)) {
3344
-                throw new EE_Error(sprintf(
3345
-                    esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3346
-                    $sub_query_params
3347
-                ));
3348
-            }
3349
-            foreach ($sub_query_params as $param) {
3350
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3351
-                $this->_extract_related_model_info_from_query_param(
3352
-                    $param,
3353
-                    $model_query_info_carrier,
3354
-                    $query_param_type
3355
-                );
3356
-            }
3357
-        }
3358
-        return $model_query_info_carrier;
3359
-    }
3360
-
3361
-
3362
-    /**
3363
-     * Extract all the query parts from  model query params
3364
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3365
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3366
-     * but use them in a different order. Eg, we need to know what models we are querying
3367
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3368
-     * other models before we can finalize the where clause SQL.
3369
-     *
3370
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3371
-     * @throws EE_Error
3372
-     * @return EE_Model_Query_Info_Carrier
3373
-     * @throws ModelConfigurationException
3374
-     */
3375
-    public function _create_model_query_info_carrier($query_params)
3376
-    {
3377
-        if (! is_array($query_params)) {
3378
-            EE_Error::doing_it_wrong(
3379
-                'EEM_Base::_create_model_query_info_carrier',
3380
-                sprintf(
3381
-                    esc_html__(
3382
-                        '$query_params should be an array, you passed a variable of type %s',
3383
-                        'event_espresso'
3384
-                    ),
3385
-                    gettype($query_params)
3386
-                ),
3387
-                '4.6.0'
3388
-            );
3389
-            $query_params = array();
3390
-        }
3391
-        $query_params[0] = isset($query_params[0]) ? $query_params[0] : array();
3392
-        // first check if we should alter the query to account for caps or not
3393
-        // because the caps might require us to do extra joins
3394
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3395
-            $query_params[0] = array_replace_recursive(
3396
-                $query_params[0],
3397
-                $this->caps_where_conditions(
3398
-                    $query_params['caps']
3399
-                )
3400
-            );
3401
-        }
3402
-
3403
-        // check if we should alter the query to remove data related to protected
3404
-        // custom post types
3405
-        if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3406
-            $where_param_key_for_password = $this->modelChainAndPassword();
3407
-            // only include if related to a cpt where no password has been set
3408
-            $query_params[0]['OR*nopassword'] = array(
3409
-                $where_param_key_for_password => '',
3410
-                $where_param_key_for_password . '*' => array('IS_NULL')
3411
-            );
3412
-        }
3413
-        $query_object = $this->_extract_related_models_from_query($query_params);
3414
-        // verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3415
-        foreach ($query_params[0] as $key => $value) {
3416
-            if (is_int($key)) {
3417
-                throw new EE_Error(
3418
-                    sprintf(
3419
-                        esc_html__(
3420
-                            "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.",
3421
-                            "event_espresso"
3422
-                        ),
3423
-                        $key,
3424
-                        var_export($value, true),
3425
-                        var_export($query_params, true),
3426
-                        get_class($this)
3427
-                    )
3428
-                );
3429
-            }
3430
-        }
3431
-        if (
3432
-            array_key_exists('default_where_conditions', $query_params)
3433
-            && ! empty($query_params['default_where_conditions'])
3434
-        ) {
3435
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3436
-        } else {
3437
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3438
-        }
3439
-        $query_params[0] = array_merge(
3440
-            $this->_get_default_where_conditions_for_models_in_query(
3441
-                $query_object,
3442
-                $use_default_where_conditions,
3443
-                $query_params[0]
3444
-            ),
3445
-            $query_params[0]
3446
-        );
3447
-        $query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3448
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3449
-        // So we need to setup a subquery and use that for the main join.
3450
-        // Note for now this only works on the primary table for the model.
3451
-        // So for instance, you could set the limit array like this:
3452
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3453
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3454
-            $query_object->set_main_model_join_sql(
3455
-                $this->_construct_limit_join_select(
3456
-                    $query_params['on_join_limit'][0],
3457
-                    $query_params['on_join_limit'][1]
3458
-                )
3459
-            );
3460
-        }
3461
-        // set limit
3462
-        if (array_key_exists('limit', $query_params)) {
3463
-            if (is_array($query_params['limit'])) {
3464
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3465
-                    $e = sprintf(
3466
-                        esc_html__(
3467
-                            "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)",
3468
-                            "event_espresso"
3469
-                        ),
3470
-                        http_build_query($query_params['limit'])
3471
-                    );
3472
-                    throw new EE_Error($e . "|" . $e);
3473
-                }
3474
-                // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3475
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3476
-            } elseif (! empty($query_params['limit'])) {
3477
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3478
-            }
3479
-        }
3480
-        // set order by
3481
-        if (array_key_exists('order_by', $query_params)) {
3482
-            if (is_array($query_params['order_by'])) {
3483
-                // if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3484
-                // specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3485
-                // including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3486
-                if (array_key_exists('order', $query_params)) {
3487
-                    throw new EE_Error(
3488
-                        sprintf(
3489
-                            esc_html__(
3490
-                                "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 ",
3491
-                                "event_espresso"
3492
-                            ),
3493
-                            get_class($this),
3494
-                            implode(", ", array_keys($query_params['order_by'])),
3495
-                            implode(", ", $query_params['order_by']),
3496
-                            $query_params['order']
3497
-                        )
3498
-                    );
3499
-                }
3500
-                $this->_extract_related_models_from_sub_params_array_keys(
3501
-                    $query_params['order_by'],
3502
-                    $query_object,
3503
-                    'order_by'
3504
-                );
3505
-                // assume it's an array of fields to order by
3506
-                $order_array = array();
3507
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3508
-                    $order = $this->_extract_order($order);
3509
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3510
-                }
3511
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3512
-            } elseif (! empty($query_params['order_by'])) {
3513
-                $this->_extract_related_model_info_from_query_param(
3514
-                    $query_params['order_by'],
3515
-                    $query_object,
3516
-                    'order',
3517
-                    $query_params['order_by']
3518
-                );
3519
-                $order = isset($query_params['order'])
3520
-                    ? $this->_extract_order($query_params['order'])
3521
-                    : 'DESC';
3522
-                $query_object->set_order_by_sql(
3523
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3524
-                );
3525
-            }
3526
-        }
3527
-        // if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3528
-        if (
3529
-            ! array_key_exists('order_by', $query_params)
3530
-            && array_key_exists('order', $query_params)
3531
-            && ! empty($query_params['order'])
3532
-        ) {
3533
-            $pk_field = $this->get_primary_key_field();
3534
-            $order = $this->_extract_order($query_params['order']);
3535
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3536
-        }
3537
-        // set group by
3538
-        if (array_key_exists('group_by', $query_params)) {
3539
-            if (is_array($query_params['group_by'])) {
3540
-                // it's an array, so assume we'll be grouping by a bunch of stuff
3541
-                $group_by_array = array();
3542
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3543
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3544
-                }
3545
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3546
-            } elseif (! empty($query_params['group_by'])) {
3547
-                $query_object->set_group_by_sql(
3548
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3549
-                );
3550
-            }
3551
-        }
3552
-        // set having
3553
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3554
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3555
-        }
3556
-        // now, just verify they didn't pass anything wack
3557
-        foreach ($query_params as $query_key => $query_value) {
3558
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3559
-                throw new EE_Error(
3560
-                    sprintf(
3561
-                        esc_html__(
3562
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3563
-                            'event_espresso'
3564
-                        ),
3565
-                        $query_key,
3566
-                        get_class($this),
3567
-                        //                      print_r( $this->_allowed_query_params, TRUE )
3568
-                        implode(',', $this->_allowed_query_params)
3569
-                    )
3570
-                );
3571
-            }
3572
-        }
3573
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3574
-        if (empty($main_model_join_sql)) {
3575
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3576
-        }
3577
-        return $query_object;
3578
-    }
3579
-
3580
-
3581
-
3582
-    /**
3583
-     * Gets the where conditions that should be imposed on the query based on the
3584
-     * context (eg reading frontend, backend, edit or delete).
3585
-     *
3586
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3587
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3588
-     * @throws EE_Error
3589
-     */
3590
-    public function caps_where_conditions($context = self::caps_read)
3591
-    {
3592
-        EEM_Base::verify_is_valid_cap_context($context);
3593
-        $cap_where_conditions = array();
3594
-        $cap_restrictions = $this->caps_missing($context);
3595
-        /**
3596
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3597
-         */
3598
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3599
-            $cap_where_conditions = array_replace_recursive(
3600
-                $cap_where_conditions,
3601
-                $restriction_if_no_cap->get_default_where_conditions()
3602
-            );
3603
-        }
3604
-        return apply_filters(
3605
-            'FHEE__EEM_Base__caps_where_conditions__return',
3606
-            $cap_where_conditions,
3607
-            $this,
3608
-            $context,
3609
-            $cap_restrictions
3610
-        );
3611
-    }
3612
-
3613
-
3614
-
3615
-    /**
3616
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3617
-     * otherwise throws an exception
3618
-     *
3619
-     * @param string $should_be_order_string
3620
-     * @return string either ASC, asc, DESC or desc
3621
-     * @throws EE_Error
3622
-     */
3623
-    private function _extract_order($should_be_order_string)
3624
-    {
3625
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3626
-            return $should_be_order_string;
3627
-        }
3628
-        throw new EE_Error(
3629
-            sprintf(
3630
-                esc_html__(
3631
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3632
-                    "event_espresso"
3633
-                ),
3634
-                get_class($this),
3635
-                $should_be_order_string
3636
-            )
3637
-        );
3638
-    }
3639
-
3640
-
3641
-
3642
-    /**
3643
-     * Looks at all the models which are included in this query, and asks each
3644
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3645
-     * so they can be merged
3646
-     *
3647
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3648
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3649
-     *                                                                  'none' means NO default where conditions will
3650
-     *                                                                  be used AT ALL during this query.
3651
-     *                                                                  'other_models_only' means default where
3652
-     *                                                                  conditions from other models will be used, but
3653
-     *                                                                  not for this primary model. 'all', the default,
3654
-     *                                                                  means default where conditions will apply as
3655
-     *                                                                  normal
3656
-     * @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
3657
-     * @throws EE_Error
3658
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3659
-     */
3660
-    private function _get_default_where_conditions_for_models_in_query(
3661
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3662
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3663
-        $where_query_params = array()
3664
-    ) {
3665
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3666
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3667
-            throw new EE_Error(sprintf(
3668
-                esc_html__(
3669
-                    "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3670
-                    "event_espresso"
3671
-                ),
3672
-                $use_default_where_conditions,
3673
-                implode(", ", $allowed_used_default_where_conditions_values)
3674
-            ));
3675
-        }
3676
-        $universal_query_params = array();
3677
-        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3678
-            $universal_query_params = $this->_get_default_where_conditions();
3679
-        } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3680
-            $universal_query_params = $this->_get_minimum_where_conditions();
3681
-        }
3682
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3683
-            $related_model = $this->get_related_model_obj($model_name);
3684
-            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3685
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3686
-            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3687
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3688
-            } else {
3689
-                // we don't want to add full or even minimum default where conditions from this model, so just continue
3690
-                continue;
3691
-            }
3692
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3693
-                $related_model_universal_where_params,
3694
-                $where_query_params,
3695
-                $related_model,
3696
-                $model_relation_path
3697
-            );
3698
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3699
-                $universal_query_params,
3700
-                $overrides
3701
-            );
3702
-        }
3703
-        return $universal_query_params;
3704
-    }
3705
-
3706
-
3707
-
3708
-    /**
3709
-     * Determines whether or not we should use default where conditions for the model in question
3710
-     * (this model, or other related models).
3711
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3712
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3713
-     * We should use default where conditions on related models when they requested to use default where conditions
3714
-     * on all models, or specifically just on other related models
3715
-     * @param      $default_where_conditions_value
3716
-     * @param bool $for_this_model false means this is for OTHER related models
3717
-     * @return bool
3718
-     */
3719
-    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3720
-    {
3721
-        return (
3722
-                   $for_this_model
3723
-                   && in_array(
3724
-                       $default_where_conditions_value,
3725
-                       array(
3726
-                           EEM_Base::default_where_conditions_all,
3727
-                           EEM_Base::default_where_conditions_this_only,
3728
-                           EEM_Base::default_where_conditions_minimum_others,
3729
-                       ),
3730
-                       true
3731
-                   )
3732
-               )
3733
-               || (
3734
-                   ! $for_this_model
3735
-                   && in_array(
3736
-                       $default_where_conditions_value,
3737
-                       array(
3738
-                           EEM_Base::default_where_conditions_all,
3739
-                           EEM_Base::default_where_conditions_others_only,
3740
-                       ),
3741
-                       true
3742
-                   )
3743
-               );
3744
-    }
3745
-
3746
-    /**
3747
-     * Determines whether or not we should use default minimum conditions for the model in question
3748
-     * (this model, or other related models).
3749
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3750
-     * where conditions.
3751
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3752
-     * on this model or others
3753
-     * @param      $default_where_conditions_value
3754
-     * @param bool $for_this_model false means this is for OTHER related models
3755
-     * @return bool
3756
-     */
3757
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3758
-    {
3759
-        return (
3760
-                   $for_this_model
3761
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3762
-               )
3763
-               || (
3764
-                   ! $for_this_model
3765
-                   && in_array(
3766
-                       $default_where_conditions_value,
3767
-                       array(
3768
-                           EEM_Base::default_where_conditions_minimum_others,
3769
-                           EEM_Base::default_where_conditions_minimum_all,
3770
-                       ),
3771
-                       true
3772
-                   )
3773
-               );
3774
-    }
3775
-
3776
-
3777
-    /**
3778
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3779
-     * then we also add a special where condition which allows for that model's primary key
3780
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3781
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3782
-     *
3783
-     * @param array    $default_where_conditions
3784
-     * @param array    $provided_where_conditions
3785
-     * @param EEM_Base $model
3786
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3787
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3788
-     * @throws EE_Error
3789
-     */
3790
-    private function _override_defaults_or_make_null_friendly(
3791
-        $default_where_conditions,
3792
-        $provided_where_conditions,
3793
-        $model,
3794
-        $model_relation_path
3795
-    ) {
3796
-        $null_friendly_where_conditions = array();
3797
-        $none_overridden = true;
3798
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3799
-        foreach ($default_where_conditions as $key => $val) {
3800
-            if (isset($provided_where_conditions[ $key ])) {
3801
-                $none_overridden = false;
3802
-            } else {
3803
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3804
-            }
3805
-        }
3806
-        if ($none_overridden && $default_where_conditions) {
3807
-            if ($model->has_primary_key_field()) {
3808
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3809
-                                                                                . "."
3810
-                                                                                . $model->primary_key_name() ] = array('IS NULL');
3811
-            }/*else{
38
+	/**
39
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
40
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
41
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
42
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
43
+	 *
44
+	 * @var boolean
45
+	 */
46
+	private $_values_already_prepared_by_model_object = 0;
47
+
48
+	/**
49
+	 * when $_values_already_prepared_by_model_object equals this, we assume
50
+	 * the data is just like form input that needs to have the model fields'
51
+	 * prepare_for_set and prepare_for_use_in_db called on it
52
+	 */
53
+	const not_prepared_by_model_object = 0;
54
+
55
+	/**
56
+	 * when $_values_already_prepared_by_model_object equals this, we
57
+	 * assume this value is coming from a model object and doesn't need to have
58
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
59
+	 */
60
+	const prepared_by_model_object = 1;
61
+
62
+	/**
63
+	 * when $_values_already_prepared_by_model_object equals this, we assume
64
+	 * the values are already to be used in the database (ie no processing is done
65
+	 * on them by the model's fields)
66
+	 */
67
+	const prepared_for_use_in_db = 2;
68
+
69
+
70
+	protected $singular_item = 'Item';
71
+
72
+	protected $plural_item   = 'Items';
73
+
74
+	/**
75
+	 * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
76
+	 */
77
+	protected $_tables;
78
+
79
+	/**
80
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
81
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
82
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
83
+	 *
84
+	 * @var \EE_Model_Field_Base[][] $_fields
85
+	 */
86
+	protected $_fields;
87
+
88
+	/**
89
+	 * array of different kinds of relations
90
+	 *
91
+	 * @var \EE_Model_Relation_Base[] $_model_relations
92
+	 */
93
+	protected $_model_relations;
94
+
95
+	/**
96
+	 * @var \EE_Index[] $_indexes
97
+	 */
98
+	protected $_indexes = array();
99
+
100
+	/**
101
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
102
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
103
+	 * by setting the same columns as used in these queries in the query yourself.
104
+	 *
105
+	 * @var EE_Default_Where_Conditions
106
+	 */
107
+	protected $_default_where_conditions_strategy;
108
+
109
+	/**
110
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
111
+	 * This is particularly useful when you want something between 'none' and 'default'
112
+	 *
113
+	 * @var EE_Default_Where_Conditions
114
+	 */
115
+	protected $_minimum_where_conditions_strategy;
116
+
117
+	/**
118
+	 * String describing how to find the "owner" of this model's objects.
119
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
120
+	 * But when there isn't, this indicates which related model, or transiently-related model,
121
+	 * has the foreign key to the wp_users table.
122
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
123
+	 * related to events, and events have a foreign key to wp_users.
124
+	 * On EEM_Transaction, this would be 'Transaction.Event'
125
+	 *
126
+	 * @var string
127
+	 */
128
+	protected $_model_chain_to_wp_user = '';
129
+
130
+	/**
131
+	 * String describing how to find the model with a password controlling access to this model. This property has the
132
+	 * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
133
+	 * This value is the path of models to follow to arrive at the model with the password field.
134
+	 * If it is an empty string, it means this model has the password field. If it is null, it means there is no
135
+	 * model with a password that should affect reading this on the front-end.
136
+	 * Eg this is an empty string for the Event model because it has a password.
137
+	 * This is null for the Registration model, because its event's password has no bearing on whether
138
+	 * you can read the registration or not on the front-end (it just depends on your capabilities.)
139
+	 * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
140
+	 * should hide tickets for datetimes for events that have a password set.
141
+	 * @var string |null
142
+	 */
143
+	protected $model_chain_to_password = null;
144
+
145
+	/**
146
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
147
+	 * don't need it (particularly CPT models)
148
+	 *
149
+	 * @var bool
150
+	 */
151
+	protected $_ignore_where_strategy = false;
152
+
153
+	/**
154
+	 * String used in caps relating to this model. Eg, if the caps relating to this
155
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
156
+	 *
157
+	 * @var string. If null it hasn't been initialized yet. If false then we
158
+	 * have indicated capabilities don't apply to this
159
+	 */
160
+	protected $_caps_slug = null;
161
+
162
+	/**
163
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
164
+	 * and next-level keys are capability names, and each's value is a
165
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
166
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
167
+	 * and then each capability in the corresponding sub-array that they're missing
168
+	 * adds the where conditions onto the query.
169
+	 *
170
+	 * @var array
171
+	 */
172
+	protected $_cap_restrictions = array(
173
+		self::caps_read       => array(),
174
+		self::caps_read_admin => array(),
175
+		self::caps_edit       => array(),
176
+		self::caps_delete     => array(),
177
+	);
178
+
179
+	/**
180
+	 * Array defining which cap restriction generators to use to create default
181
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
182
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
183
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
184
+	 * automatically set this to false (not just null).
185
+	 *
186
+	 * @var EE_Restriction_Generator_Base[]
187
+	 */
188
+	protected $_cap_restriction_generators = array();
189
+
190
+	/**
191
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
192
+	 */
193
+	const caps_read       = 'read';
194
+
195
+	const caps_read_admin = 'read_admin';
196
+
197
+	const caps_edit       = 'edit';
198
+
199
+	const caps_delete     = 'delete';
200
+
201
+	/**
202
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
203
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
204
+	 * maps to 'read' because when looking for relevant permissions we're going to use
205
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
206
+	 *
207
+	 * @var array
208
+	 */
209
+	protected $_cap_contexts_to_cap_action_map = array(
210
+		self::caps_read       => 'read',
211
+		self::caps_read_admin => 'read',
212
+		self::caps_edit       => 'edit',
213
+		self::caps_delete     => 'delete',
214
+	);
215
+
216
+	/**
217
+	 * Timezone
218
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
219
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
220
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
221
+	 * EE_Datetime_Field data type will have access to it.
222
+	 *
223
+	 * @var string
224
+	 */
225
+	protected $_timezone;
226
+
227
+
228
+	/**
229
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
230
+	 * multisite.
231
+	 *
232
+	 * @var int
233
+	 */
234
+	protected static $_model_query_blog_id;
235
+
236
+	/**
237
+	 * A copy of _fields, except the array keys are the model names pointed to by
238
+	 * the field
239
+	 *
240
+	 * @var EE_Model_Field_Base[]
241
+	 */
242
+	private $_cache_foreign_key_to_fields = array();
243
+
244
+	/**
245
+	 * Cached list of all the fields on the model, indexed by their name
246
+	 *
247
+	 * @var EE_Model_Field_Base[]
248
+	 */
249
+	private $_cached_fields = null;
250
+
251
+	/**
252
+	 * Cached list of all the fields on the model, except those that are
253
+	 * marked as only pertinent to the database
254
+	 *
255
+	 * @var EE_Model_Field_Base[]
256
+	 */
257
+	private $_cached_fields_non_db_only = null;
258
+
259
+	/**
260
+	 * A cached reference to the primary key for quick lookup
261
+	 *
262
+	 * @var EE_Model_Field_Base
263
+	 */
264
+	private $_primary_key_field = null;
265
+
266
+	/**
267
+	 * Flag indicating whether this model has a primary key or not
268
+	 *
269
+	 * @var boolean
270
+	 */
271
+	protected $_has_primary_key_field = null;
272
+
273
+	/**
274
+	 * array in the format:  [ FK alias => full PK ]
275
+	 * where keys are local column name aliases for foreign keys
276
+	 * and values are the fully qualified column name for the primary key they represent
277
+	 *  ex:
278
+	 *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
279
+	 *
280
+	 * @var array $foreign_key_aliases
281
+	 */
282
+	protected $foreign_key_aliases = [];
283
+
284
+	/**
285
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
286
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
287
+	 * This should be true for models that deal with data that should exist independent of EE.
288
+	 * For example, if the model can read and insert data that isn't used by EE, this should be true.
289
+	 * It would be false, however, if you could guarantee the model would only interact with EE data,
290
+	 * even if it uses a WP core table (eg event and venue models set this to false for that reason:
291
+	 * they can only read and insert events and venues custom post types, not arbitrary post types)
292
+	 * @var boolean
293
+	 */
294
+	protected $_wp_core_model = false;
295
+
296
+	/**
297
+	 * @var bool stores whether this model has a password field or not.
298
+	 * null until initialized by hasPasswordField()
299
+	 */
300
+	protected $has_password_field;
301
+
302
+	/**
303
+	 * @var EE_Password_Field|null Automatically set when calling getPasswordField()
304
+	 */
305
+	protected $password_field;
306
+
307
+	/**
308
+	 *    List of valid operators that can be used for querying.
309
+	 * The keys are all operators we'll accept, the values are the real SQL
310
+	 * operators used
311
+	 *
312
+	 * @var array
313
+	 */
314
+	protected $_valid_operators = array(
315
+		'='           => '=',
316
+		'<='          => '<=',
317
+		'<'           => '<',
318
+		'>='          => '>=',
319
+		'>'           => '>',
320
+		'!='          => '!=',
321
+		'LIKE'        => 'LIKE',
322
+		'like'        => 'LIKE',
323
+		'NOT_LIKE'    => 'NOT LIKE',
324
+		'not_like'    => 'NOT LIKE',
325
+		'NOT LIKE'    => 'NOT LIKE',
326
+		'not like'    => 'NOT LIKE',
327
+		'IN'          => 'IN',
328
+		'in'          => 'IN',
329
+		'NOT_IN'      => 'NOT IN',
330
+		'not_in'      => 'NOT IN',
331
+		'NOT IN'      => 'NOT IN',
332
+		'not in'      => 'NOT IN',
333
+		'between'     => 'BETWEEN',
334
+		'BETWEEN'     => 'BETWEEN',
335
+		'IS_NOT_NULL' => 'IS NOT NULL',
336
+		'is_not_null' => 'IS NOT NULL',
337
+		'IS NOT NULL' => 'IS NOT NULL',
338
+		'is not null' => 'IS NOT NULL',
339
+		'IS_NULL'     => 'IS NULL',
340
+		'is_null'     => 'IS NULL',
341
+		'IS NULL'     => 'IS NULL',
342
+		'is null'     => 'IS NULL',
343
+		'REGEXP'      => 'REGEXP',
344
+		'regexp'      => 'REGEXP',
345
+		'NOT_REGEXP'  => 'NOT REGEXP',
346
+		'not_regexp'  => 'NOT REGEXP',
347
+		'NOT REGEXP'  => 'NOT REGEXP',
348
+		'not regexp'  => 'NOT REGEXP',
349
+	);
350
+
351
+	/**
352
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
353
+	 *
354
+	 * @var array
355
+	 */
356
+	protected $_in_style_operators = array('IN', 'NOT IN');
357
+
358
+	/**
359
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
360
+	 * '12-31-2012'"
361
+	 *
362
+	 * @var array
363
+	 */
364
+	protected $_between_style_operators = array('BETWEEN');
365
+
366
+	/**
367
+	 * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
368
+	 * @var array
369
+	 */
370
+	protected $_like_style_operators = array('LIKE', 'NOT LIKE');
371
+	/**
372
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
373
+	 * on a join table.
374
+	 *
375
+	 * @var array
376
+	 */
377
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
378
+
379
+	/**
380
+	 * Allowed values for $query_params['order'] for ordering in queries
381
+	 *
382
+	 * @var array
383
+	 */
384
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
385
+
386
+	/**
387
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
388
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
389
+	 *
390
+	 * @var array
391
+	 */
392
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
393
+
394
+	/**
395
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
396
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
397
+	 *
398
+	 * @var array
399
+	 */
400
+	private $_allowed_query_params = array(
401
+		0,
402
+		'limit',
403
+		'order_by',
404
+		'group_by',
405
+		'having',
406
+		'force_join',
407
+		'order',
408
+		'on_join_limit',
409
+		'default_where_conditions',
410
+		'caps',
411
+		'extra_selects',
412
+		'exclude_protected',
413
+	);
414
+
415
+	/**
416
+	 * All the data types that can be used in $wpdb->prepare statements.
417
+	 *
418
+	 * @var array
419
+	 */
420
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
421
+
422
+	/**
423
+	 * @var EE_Registry $EE
424
+	 */
425
+	protected $EE = null;
426
+
427
+
428
+	/**
429
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
430
+	 *
431
+	 * @var int
432
+	 */
433
+	protected $_show_next_x_db_queries = 0;
434
+
435
+	/**
436
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
437
+	 * it gets saved on this property as an instance of CustomSelects so those selections can be used in
438
+	 * WHERE, GROUP_BY, etc.
439
+	 *
440
+	 * @var CustomSelects
441
+	 */
442
+	protected $_custom_selections = array();
443
+
444
+	/**
445
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
446
+	 * caches every model object we've fetched from the DB on this request
447
+	 *
448
+	 * @var array
449
+	 */
450
+	protected $_entity_map;
451
+
452
+	/**
453
+	 * @var LoaderInterface $loader
454
+	 */
455
+	protected static $loader;
456
+
457
+
458
+	/**
459
+	 * constant used to show EEM_Base has not yet verified the db on this http request
460
+	 */
461
+	const db_verified_none = 0;
462
+
463
+	/**
464
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
465
+	 * but not the addons' dbs
466
+	 */
467
+	const db_verified_core = 1;
468
+
469
+	/**
470
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
471
+	 * the EE core db too)
472
+	 */
473
+	const db_verified_addons = 2;
474
+
475
+	/**
476
+	 * indicates whether an EEM_Base child has already re-verified the DB
477
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
478
+	 * looking like EEM_Base::db_verified_*
479
+	 *
480
+	 * @var int - 0 = none, 1 = core, 2 = addons
481
+	 */
482
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
483
+
484
+	/**
485
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
486
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
487
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
488
+	 */
489
+	const default_where_conditions_all = 'all';
490
+
491
+	/**
492
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
493
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
494
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
495
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
496
+	 *        models which share tables with other models, this can return data for the wrong model.
497
+	 */
498
+	const default_where_conditions_this_only = 'this_model_only';
499
+
500
+	/**
501
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
502
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
503
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
504
+	 */
505
+	const default_where_conditions_others_only = 'other_models_only';
506
+
507
+	/**
508
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
509
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
510
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
511
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
512
+	 *        (regardless of whether those events and venues are trashed)
513
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
514
+	 *        events.
515
+	 */
516
+	const default_where_conditions_minimum_all = 'minimum';
517
+
518
+	/**
519
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
520
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
521
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
522
+	 *        not)
523
+	 */
524
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
525
+
526
+	/**
527
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
528
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
529
+	 *        it's possible it will return table entries for other models. You should use
530
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
531
+	 */
532
+	const default_where_conditions_none = 'none';
533
+
534
+
535
+
536
+	/**
537
+	 * About all child constructors:
538
+	 * they should define the _tables, _fields and _model_relations arrays.
539
+	 * Should ALWAYS be called after child constructor.
540
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
541
+	 * finalizes constructing all the object's attributes.
542
+	 * Generally, rather than requiring a child to code
543
+	 * $this->_tables = array(
544
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
545
+	 *        ...);
546
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
547
+	 * each EE_Table has a function to set the table's alias after the constructor, using
548
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
549
+	 * do something similar.
550
+	 *
551
+	 * @param null $timezone
552
+	 * @throws EE_Error
553
+	 */
554
+	protected function __construct($timezone = null)
555
+	{
556
+		// check that the model has not been loaded too soon
557
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
558
+			throw new EE_Error(
559
+				sprintf(
560
+					esc_html__(
561
+						'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.',
562
+						'event_espresso'
563
+					),
564
+					get_class($this)
565
+				)
566
+			);
567
+		}
568
+		/**
569
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
570
+		 */
571
+		if (empty(EEM_Base::$_model_query_blog_id)) {
572
+			EEM_Base::set_model_query_blog_id();
573
+		}
574
+		/**
575
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
576
+		 * just use EE_Register_Model_Extension
577
+		 *
578
+		 * @var EE_Table_Base[] $_tables
579
+		 */
580
+		$this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
581
+		foreach ($this->_tables as $table_alias => $table_obj) {
582
+			/** @var $table_obj EE_Table_Base */
583
+			$table_obj->_construct_finalize_with_alias($table_alias);
584
+			if ($table_obj instanceof EE_Secondary_Table) {
585
+				/** @var $table_obj EE_Secondary_Table */
586
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
587
+			}
588
+		}
589
+		/**
590
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
591
+		 * EE_Register_Model_Extension
592
+		 *
593
+		 * @param EE_Model_Field_Base[] $_fields
594
+		 */
595
+		$this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
596
+		$this->_invalidate_field_caches();
597
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
598
+			if (! array_key_exists($table_alias, $this->_tables)) {
599
+				throw new EE_Error(sprintf(esc_html__(
600
+					"Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
601
+					'event_espresso'
602
+				), $table_alias, implode(",", $this->_fields)));
603
+			}
604
+			foreach ($fields_for_table as $field_name => $field_obj) {
605
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
606
+				// primary key field base has a slightly different _construct_finalize
607
+				/** @var $field_obj EE_Model_Field_Base */
608
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
609
+			}
610
+		}
611
+		// everything is related to Extra_Meta
612
+		if (get_class($this) !== 'EEM_Extra_Meta') {
613
+			// make extra meta related to everything, but don't block deleting things just
614
+			// because they have related extra meta info. For now just orphan those extra meta
615
+			// in the future we should automatically delete them
616
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
617
+		}
618
+		// and change logs
619
+		if (get_class($this) !== 'EEM_Change_Log') {
620
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
621
+		}
622
+		/**
623
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
624
+		 * EE_Register_Model_Extension
625
+		 *
626
+		 * @param EE_Model_Relation_Base[] $_model_relations
627
+		 */
628
+		$this->_model_relations = (array) apply_filters(
629
+			'FHEE__' . get_class($this) . '__construct__model_relations',
630
+			$this->_model_relations
631
+		);
632
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
633
+			/** @var $relation_obj EE_Model_Relation_Base */
634
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
635
+		}
636
+		foreach ($this->_indexes as $index_name => $index_obj) {
637
+			/** @var $index_obj EE_Index */
638
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
639
+		}
640
+		$this->set_timezone($timezone);
641
+		// finalize default where condition strategy, or set default
642
+		if (! $this->_default_where_conditions_strategy) {
643
+			// nothing was set during child constructor, so set default
644
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
645
+		}
646
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
647
+		if (! $this->_minimum_where_conditions_strategy) {
648
+			// nothing was set during child constructor, so set default
649
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
650
+		}
651
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
652
+		// if the cap slug hasn't been set, and we haven't set it to false on purpose
653
+		// to indicate to NOT set it, set it to the logical default
654
+		if ($this->_caps_slug === null) {
655
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
656
+		}
657
+		// initialize the standard cap restriction generators if none were specified by the child constructor
658
+		if ($this->_cap_restriction_generators !== false) {
659
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
660
+				if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
661
+					$this->_cap_restriction_generators[ $cap_context ] = apply_filters(
662
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
663
+						new EE_Restriction_Generator_Protected(),
664
+						$cap_context,
665
+						$this
666
+					);
667
+				}
668
+			}
669
+		}
670
+		// if there are cap restriction generators, use them to make the default cap restrictions
671
+		if ($this->_cap_restriction_generators !== false) {
672
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
673
+				if (! $generator_object) {
674
+					continue;
675
+				}
676
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
677
+					throw new EE_Error(
678
+						sprintf(
679
+							esc_html__(
680
+								'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.',
681
+								'event_espresso'
682
+							),
683
+							$context,
684
+							$this->get_this_model_name()
685
+						)
686
+					);
687
+				}
688
+				$action = $this->cap_action_for_context($context);
689
+				if (! $generator_object->construction_finalized()) {
690
+					$generator_object->_construct_finalize($this, $action);
691
+				}
692
+			}
693
+		}
694
+		do_action('AHEE__' . get_class($this) . '__construct__end');
695
+	}
696
+
697
+
698
+
699
+	/**
700
+	 * Used to set the $_model_query_blog_id static property.
701
+	 *
702
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
703
+	 *                      value for get_current_blog_id() will be used.
704
+	 */
705
+	public static function set_model_query_blog_id($blog_id = 0)
706
+	{
707
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
708
+	}
709
+
710
+
711
+
712
+	/**
713
+	 * Returns whatever is set as the internal $model_query_blog_id.
714
+	 *
715
+	 * @return int
716
+	 */
717
+	public static function get_model_query_blog_id()
718
+	{
719
+		return EEM_Base::$_model_query_blog_id;
720
+	}
721
+
722
+
723
+
724
+	/**
725
+	 * This function is a singleton method used to instantiate the Espresso_model object
726
+	 *
727
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
728
+	 *                                (and any incoming timezone data that gets saved).
729
+	 *                                Note this just sends the timezone info to the date time model field objects.
730
+	 *                                Default is NULL
731
+	 *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
732
+	 * @return static (as in the concrete child class)
733
+	 * @throws EE_Error
734
+	 * @throws InvalidArgumentException
735
+	 * @throws InvalidDataTypeException
736
+	 * @throws InvalidInterfaceException
737
+	 */
738
+	public static function instance($timezone = null)
739
+	{
740
+		// check if instance of Espresso_model already exists
741
+		if (! static::$_instance instanceof static) {
742
+			// instantiate Espresso_model
743
+			static::$_instance = new static(
744
+				$timezone,
745
+				EEM_Base::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
746
+			);
747
+		}
748
+		// we might have a timezone set, let set_timezone decide what to do with it
749
+		static::$_instance->set_timezone($timezone);
750
+		// Espresso_model object
751
+		return static::$_instance;
752
+	}
753
+
754
+
755
+
756
+	/**
757
+	 * resets the model and returns it
758
+	 *
759
+	 * @param null | string $timezone
760
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
761
+	 * all its properties reset; if it wasn't instantiated, returns null)
762
+	 * @throws EE_Error
763
+	 * @throws ReflectionException
764
+	 * @throws InvalidArgumentException
765
+	 * @throws InvalidDataTypeException
766
+	 * @throws InvalidInterfaceException
767
+	 */
768
+	public static function reset($timezone = null)
769
+	{
770
+		if (static::$_instance instanceof EEM_Base) {
771
+			// let's try to NOT swap out the current instance for a new one
772
+			// because if someone has a reference to it, we can't remove their reference
773
+			// so it's best to keep using the same reference, but change the original object
774
+			// reset all its properties to their original values as defined in the class
775
+			$r = new ReflectionClass(get_class(static::$_instance));
776
+			$static_properties = $r->getStaticProperties();
777
+			foreach ($r->getDefaultProperties() as $property => $value) {
778
+				// don't set instance to null like it was originally,
779
+				// but it's static anyways, and we're ignoring static properties (for now at least)
780
+				if (! isset($static_properties[ $property ])) {
781
+					static::$_instance->{$property} = $value;
782
+				}
783
+			}
784
+			// and then directly call its constructor again, like we would if we were creating a new one
785
+			static::$_instance->__construct(
786
+				$timezone,
787
+				EEM_Base::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
788
+			);
789
+			return self::instance();
790
+		}
791
+		return null;
792
+	}
793
+
794
+
795
+
796
+	/**
797
+	 * @return LoaderInterface
798
+	 * @throws InvalidArgumentException
799
+	 * @throws InvalidDataTypeException
800
+	 * @throws InvalidInterfaceException
801
+	 */
802
+	private static function getLoader()
803
+	{
804
+		if (! EEM_Base::$loader instanceof LoaderInterface) {
805
+			EEM_Base::$loader = LoaderFactory::getLoader();
806
+		}
807
+		return EEM_Base::$loader;
808
+	}
809
+
810
+
811
+
812
+	/**
813
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
814
+	 *
815
+	 * @param  boolean $translated return localized strings or JUST the array.
816
+	 * @return array
817
+	 * @throws EE_Error
818
+	 * @throws InvalidArgumentException
819
+	 * @throws InvalidDataTypeException
820
+	 * @throws InvalidInterfaceException
821
+	 */
822
+	public function status_array($translated = false)
823
+	{
824
+		if (! array_key_exists('Status', $this->_model_relations)) {
825
+			return array();
826
+		}
827
+		$model_name = $this->get_this_model_name();
828
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
829
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
830
+		$status_array = array();
831
+		foreach ($stati as $status) {
832
+			$status_array[ $status->ID() ] = $status->get('STS_code');
833
+		}
834
+		return $translated
835
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
836
+			: $status_array;
837
+	}
838
+
839
+
840
+
841
+	/**
842
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
843
+	 *
844
+	 * @param array $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
845
+	 *                             or if you have the development copy of EE you can view this at the path:
846
+	 *                             /docs/G--Model-System/model-query-params.md
847
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
848
+	 *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object IDs (if there is a primary key on the model.
849
+	 *                                        if not, numerically indexed) Some full examples: get 10 transactions
850
+	 *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
851
+	 *                                        array( array(
852
+	 *                                        'OR'=>array(
853
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
854
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
855
+	 *                                        )
856
+	 *                                        ),
857
+	 *                                        'limit'=>10,
858
+	 *                                        'group_by'=>'TXN_ID'
859
+	 *                                        ));
860
+	 *                                        get all the answers to the question titled "shirt size" for event with id
861
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
862
+	 *                                        'Question.QST_display_text'=>'shirt size',
863
+	 *                                        'Registration.Event.EVT_ID'=>12
864
+	 *                                        ),
865
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
866
+	 *                                        ));
867
+	 * @throws EE_Error
868
+	 */
869
+	public function get_all($query_params = array())
870
+	{
871
+		if (
872
+			isset($query_params['limit'])
873
+			&& ! isset($query_params['group_by'])
874
+		) {
875
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
876
+		}
877
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
878
+	}
879
+
880
+
881
+
882
+	/**
883
+	 * Modifies the query parameters so we only get back model objects
884
+	 * that "belong" to the current user
885
+	 *
886
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
887
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
888
+	 */
889
+	public function alter_query_params_to_only_include_mine($query_params = array())
890
+	{
891
+		$wp_user_field_name = $this->wp_user_field_name();
892
+		if ($wp_user_field_name) {
893
+			$query_params[0][ $wp_user_field_name ] = get_current_user_id();
894
+		}
895
+		return $query_params;
896
+	}
897
+
898
+
899
+
900
+	/**
901
+	 * Returns the name of the field's name that points to the WP_User table
902
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
903
+	 * foreign key to the WP_User table)
904
+	 *
905
+	 * @return string|boolean string on success, boolean false when there is no
906
+	 * foreign key to the WP_User table
907
+	 */
908
+	public function wp_user_field_name()
909
+	{
910
+		try {
911
+			if (! empty($this->_model_chain_to_wp_user)) {
912
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
913
+				$last_model_name = end($models_to_follow_to_wp_users);
914
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
915
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
916
+			} else {
917
+				$model_with_fk_to_wp_users = $this;
918
+				$model_chain_to_wp_user = '';
919
+			}
920
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
921
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
922
+		} catch (EE_Error $e) {
923
+			return false;
924
+		}
925
+	}
926
+
927
+
928
+
929
+	/**
930
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
931
+	 * (or transiently-related model) has a foreign key to the wp_users table;
932
+	 * useful for finding if model objects of this type are 'owned' by the current user.
933
+	 * This is an empty string when the foreign key is on this model and when it isn't,
934
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
935
+	 * (or transiently-related model)
936
+	 *
937
+	 * @return string
938
+	 */
939
+	public function model_chain_to_wp_user()
940
+	{
941
+		return $this->_model_chain_to_wp_user;
942
+	}
943
+
944
+
945
+
946
+	/**
947
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
948
+	 * like how registrations don't have a foreign key to wp_users, but the
949
+	 * events they are for are), or is unrelated to wp users.
950
+	 * generally available
951
+	 *
952
+	 * @return boolean
953
+	 */
954
+	public function is_owned()
955
+	{
956
+		if ($this->model_chain_to_wp_user()) {
957
+			return true;
958
+		}
959
+		try {
960
+			$this->get_foreign_key_to('WP_User');
961
+			return true;
962
+		} catch (EE_Error $e) {
963
+			return false;
964
+		}
965
+	}
966
+
967
+
968
+	/**
969
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
970
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
971
+	 * the model)
972
+	 *
973
+	 * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
974
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
975
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
976
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
977
+	 *                                  override this and set the select to "*", or a specific column name, like
978
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
979
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
980
+	 *                                  the aliases used to refer to this selection, and values are to be
981
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
982
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
983
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
984
+	 * @throws EE_Error
985
+	 * @throws InvalidArgumentException
986
+	 */
987
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
988
+	{
989
+		$this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
990
+		;
991
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
992
+		$select_expressions = $columns_to_select === null
993
+			? $this->_construct_default_select_sql($model_query_info)
994
+			: '';
995
+		if ($this->_custom_selections instanceof CustomSelects) {
996
+			$custom_expressions = $this->_custom_selections->columnsToSelectExpression();
997
+			$select_expressions .= $select_expressions
998
+				? ', ' . $custom_expressions
999
+				: $custom_expressions;
1000
+		}
1001
+
1002
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1003
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
1004
+	}
1005
+
1006
+
1007
+	/**
1008
+	 * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1009
+	 * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1010
+	 * method of including extra select information.
1011
+	 *
1012
+	 * @param array             $query_params
1013
+	 * @param null|array|string $columns_to_select
1014
+	 * @return null|CustomSelects
1015
+	 * @throws InvalidArgumentException
1016
+	 */
1017
+	protected function getCustomSelection(array $query_params, $columns_to_select = null)
1018
+	{
1019
+		if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1020
+			return null;
1021
+		}
1022
+		$selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1023
+		$selects = is_string($selects) ? explode(',', $selects) : $selects;
1024
+		return new CustomSelects($selects);
1025
+	}
1026
+
1027
+
1028
+
1029
+	/**
1030
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1031
+	 * but you can use the model query params to more easily
1032
+	 * take care of joins, field preparation etc.
1033
+	 *
1034
+	 * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1035
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1036
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1037
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1038
+	 *                                  override this and set the select to "*", or a specific column name, like
1039
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1040
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1041
+	 *                                  the aliases used to refer to this selection, and values are to be
1042
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1043
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1044
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1045
+	 * @throws EE_Error
1046
+	 */
1047
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1048
+	{
1049
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1050
+	}
1051
+
1052
+
1053
+
1054
+	/**
1055
+	 * For creating a custom select statement
1056
+	 *
1057
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1058
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1059
+	 *                                 SQL, and 1=>is the datatype
1060
+	 * @throws EE_Error
1061
+	 * @return string
1062
+	 */
1063
+	private function _construct_select_from_input($columns_to_select)
1064
+	{
1065
+		if (is_array($columns_to_select)) {
1066
+			$select_sql_array = array();
1067
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1068
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1069
+					throw new EE_Error(
1070
+						sprintf(
1071
+							esc_html__(
1072
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1073
+								'event_espresso'
1074
+							),
1075
+							$selection_and_datatype,
1076
+							$alias
1077
+						)
1078
+					);
1079
+				}
1080
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1081
+					throw new EE_Error(
1082
+						sprintf(
1083
+							esc_html__(
1084
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1085
+								'event_espresso'
1086
+							),
1087
+							$selection_and_datatype[1],
1088
+							$selection_and_datatype[0],
1089
+							$alias,
1090
+							implode(', ', $this->_valid_wpdb_data_types)
1091
+						)
1092
+					);
1093
+				}
1094
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1095
+			}
1096
+			$columns_to_select_string = implode(', ', $select_sql_array);
1097
+		} else {
1098
+			$columns_to_select_string = $columns_to_select;
1099
+		}
1100
+		return $columns_to_select_string;
1101
+	}
1102
+
1103
+
1104
+
1105
+	/**
1106
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1107
+	 *
1108
+	 * @return string
1109
+	 * @throws EE_Error
1110
+	 */
1111
+	public function primary_key_name()
1112
+	{
1113
+		return $this->get_primary_key_field()->get_name();
1114
+	}
1115
+
1116
+
1117
+	/**
1118
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1119
+	 * If there is no primary key on this model, $id is treated as primary key string
1120
+	 *
1121
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1122
+	 * @return EE_Base_Class
1123
+	 * @throws EE_Error
1124
+	 */
1125
+	public function get_one_by_ID($id)
1126
+	{
1127
+		if ($this->get_from_entity_map($id)) {
1128
+			return $this->get_from_entity_map($id);
1129
+		}
1130
+		$model_object = $this->get_one(
1131
+			$this->alter_query_params_to_restrict_by_ID(
1132
+				$id,
1133
+				array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1134
+			)
1135
+		);
1136
+		$className = $this->_get_class_name();
1137
+		if ($model_object instanceof $className) {
1138
+			// make sure valid objects get added to the entity map
1139
+			// so that the next call to this method doesn't trigger another trip to the db
1140
+			$this->add_to_entity_map($model_object);
1141
+		}
1142
+		return $model_object;
1143
+	}
1144
+
1145
+
1146
+
1147
+	/**
1148
+	 * Alters query parameters to only get items with this ID are returned.
1149
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1150
+	 * or could just be a simple primary key ID
1151
+	 *
1152
+	 * @param int   $id
1153
+	 * @param array $query_params
1154
+	 * @return array of normal query params, @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1155
+	 * @throws EE_Error
1156
+	 */
1157
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1158
+	{
1159
+		if (! isset($query_params[0])) {
1160
+			$query_params[0] = array();
1161
+		}
1162
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1163
+		if ($conditions_from_id === null) {
1164
+			$query_params[0][ $this->primary_key_name() ] = $id;
1165
+		} else {
1166
+			// no primary key, so the $id must be from the get_index_primary_key_string()
1167
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1168
+		}
1169
+		return $query_params;
1170
+	}
1171
+
1172
+
1173
+
1174
+	/**
1175
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1176
+	 * array. If no item is found, null is returned.
1177
+	 *
1178
+	 * @param array $query_params like EEM_Base's $query_params variable.
1179
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1180
+	 * @throws EE_Error
1181
+	 */
1182
+	public function get_one($query_params = array())
1183
+	{
1184
+		if (! is_array($query_params)) {
1185
+			EE_Error::doing_it_wrong(
1186
+				'EEM_Base::get_one',
1187
+				sprintf(
1188
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1189
+					gettype($query_params)
1190
+				),
1191
+				'4.6.0'
1192
+			);
1193
+			$query_params = array();
1194
+		}
1195
+		$query_params['limit'] = 1;
1196
+		$items = $this->get_all($query_params);
1197
+		if (empty($items)) {
1198
+			return null;
1199
+		}
1200
+		return array_shift($items);
1201
+	}
1202
+
1203
+
1204
+
1205
+	/**
1206
+	 * Returns the next x number of items in sequence from the given value as
1207
+	 * found in the database matching the given query conditions.
1208
+	 *
1209
+	 * @param mixed $current_field_value    Value used for the reference point.
1210
+	 * @param null  $field_to_order_by      What field is used for the
1211
+	 *                                      reference point.
1212
+	 * @param int   $limit                  How many to return.
1213
+	 * @param array $query_params           Extra conditions on the query.
1214
+	 * @param null  $columns_to_select      If left null, then an array of
1215
+	 *                                      EE_Base_Class objects is returned,
1216
+	 *                                      otherwise you can indicate just the
1217
+	 *                                      columns you want returned.
1218
+	 * @return EE_Base_Class[]|array
1219
+	 * @throws EE_Error
1220
+	 */
1221
+	public function next_x(
1222
+		$current_field_value,
1223
+		$field_to_order_by = null,
1224
+		$limit = 1,
1225
+		$query_params = array(),
1226
+		$columns_to_select = null
1227
+	) {
1228
+		return $this->_get_consecutive(
1229
+			$current_field_value,
1230
+			'>',
1231
+			$field_to_order_by,
1232
+			$limit,
1233
+			$query_params,
1234
+			$columns_to_select
1235
+		);
1236
+	}
1237
+
1238
+
1239
+
1240
+	/**
1241
+	 * Returns the previous x number of items in sequence from the given value
1242
+	 * as found in the database matching the given query conditions.
1243
+	 *
1244
+	 * @param mixed $current_field_value    Value used for the reference point.
1245
+	 * @param null  $field_to_order_by      What field is used for the
1246
+	 *                                      reference point.
1247
+	 * @param int   $limit                  How many to return.
1248
+	 * @param array $query_params           Extra conditions on the query.
1249
+	 * @param null  $columns_to_select      If left null, then an array of
1250
+	 *                                      EE_Base_Class objects is returned,
1251
+	 *                                      otherwise you can indicate just the
1252
+	 *                                      columns you want returned.
1253
+	 * @return EE_Base_Class[]|array
1254
+	 * @throws EE_Error
1255
+	 */
1256
+	public function previous_x(
1257
+		$current_field_value,
1258
+		$field_to_order_by = null,
1259
+		$limit = 1,
1260
+		$query_params = array(),
1261
+		$columns_to_select = null
1262
+	) {
1263
+		return $this->_get_consecutive(
1264
+			$current_field_value,
1265
+			'<',
1266
+			$field_to_order_by,
1267
+			$limit,
1268
+			$query_params,
1269
+			$columns_to_select
1270
+		);
1271
+	}
1272
+
1273
+
1274
+
1275
+	/**
1276
+	 * Returns the next item in sequence from the given value as found in the
1277
+	 * database matching the given query conditions.
1278
+	 *
1279
+	 * @param mixed $current_field_value    Value used for the reference point.
1280
+	 * @param null  $field_to_order_by      What field is used for the
1281
+	 *                                      reference point.
1282
+	 * @param array $query_params           Extra conditions on the query.
1283
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1284
+	 *                                      object is returned, otherwise you
1285
+	 *                                      can indicate just the columns you
1286
+	 *                                      want and a single array indexed by
1287
+	 *                                      the columns will be returned.
1288
+	 * @return EE_Base_Class|null|array()
1289
+	 * @throws EE_Error
1290
+	 */
1291
+	public function next(
1292
+		$current_field_value,
1293
+		$field_to_order_by = null,
1294
+		$query_params = array(),
1295
+		$columns_to_select = null
1296
+	) {
1297
+		$results = $this->_get_consecutive(
1298
+			$current_field_value,
1299
+			'>',
1300
+			$field_to_order_by,
1301
+			1,
1302
+			$query_params,
1303
+			$columns_to_select
1304
+		);
1305
+		return empty($results) ? null : reset($results);
1306
+	}
1307
+
1308
+
1309
+
1310
+	/**
1311
+	 * Returns the previous item in sequence from the given value as found in
1312
+	 * the database matching the given query conditions.
1313
+	 *
1314
+	 * @param mixed $current_field_value    Value used for the reference point.
1315
+	 * @param null  $field_to_order_by      What field is used for the
1316
+	 *                                      reference point.
1317
+	 * @param array $query_params           Extra conditions on the query.
1318
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1319
+	 *                                      object is returned, otherwise you
1320
+	 *                                      can indicate just the columns you
1321
+	 *                                      want and a single array indexed by
1322
+	 *                                      the columns will be returned.
1323
+	 * @return EE_Base_Class|null|array()
1324
+	 * @throws EE_Error
1325
+	 */
1326
+	public function previous(
1327
+		$current_field_value,
1328
+		$field_to_order_by = null,
1329
+		$query_params = array(),
1330
+		$columns_to_select = null
1331
+	) {
1332
+		$results = $this->_get_consecutive(
1333
+			$current_field_value,
1334
+			'<',
1335
+			$field_to_order_by,
1336
+			1,
1337
+			$query_params,
1338
+			$columns_to_select
1339
+		);
1340
+		return empty($results) ? null : reset($results);
1341
+	}
1342
+
1343
+
1344
+
1345
+	/**
1346
+	 * Returns the a consecutive number of items in sequence from the given
1347
+	 * value as found in the database matching the given query conditions.
1348
+	 *
1349
+	 * @param mixed  $current_field_value   Value used for the reference point.
1350
+	 * @param string $operand               What operand is used for the sequence.
1351
+	 * @param string $field_to_order_by     What field is used for the reference point.
1352
+	 * @param int    $limit                 How many to return.
1353
+	 * @param array  $query_params          Extra conditions on the query.
1354
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1355
+	 *                                      otherwise you can indicate just the columns you want returned.
1356
+	 * @return EE_Base_Class[]|array
1357
+	 * @throws EE_Error
1358
+	 */
1359
+	protected function _get_consecutive(
1360
+		$current_field_value,
1361
+		$operand = '>',
1362
+		$field_to_order_by = null,
1363
+		$limit = 1,
1364
+		$query_params = array(),
1365
+		$columns_to_select = null
1366
+	) {
1367
+		// if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1368
+		if (empty($field_to_order_by)) {
1369
+			if ($this->has_primary_key_field()) {
1370
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1371
+			} else {
1372
+				if (WP_DEBUG) {
1373
+					throw new EE_Error(esc_html__(
1374
+						'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).',
1375
+						'event_espresso'
1376
+					));
1377
+				}
1378
+				EE_Error::add_error(esc_html__('There was an error with the query.', 'event_espresso'));
1379
+				return array();
1380
+			}
1381
+		}
1382
+		if (! is_array($query_params)) {
1383
+			EE_Error::doing_it_wrong(
1384
+				'EEM_Base::_get_consecutive',
1385
+				sprintf(
1386
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1387
+					gettype($query_params)
1388
+				),
1389
+				'4.6.0'
1390
+			);
1391
+			$query_params = array();
1392
+		}
1393
+		// let's add the where query param for consecutive look up.
1394
+		$query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1395
+		$query_params['limit'] = $limit;
1396
+		// set direction
1397
+		$incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1398
+		$query_params['order_by'] = $operand === '>'
1399
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1400
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1401
+		// if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1402
+		if (empty($columns_to_select)) {
1403
+			return $this->get_all($query_params);
1404
+		}
1405
+		// getting just the fields
1406
+		return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1407
+	}
1408
+
1409
+
1410
+
1411
+	/**
1412
+	 * This sets the _timezone property after model object has been instantiated.
1413
+	 *
1414
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1415
+	 */
1416
+	public function set_timezone($timezone)
1417
+	{
1418
+		if ($timezone !== null) {
1419
+			$this->_timezone = $timezone;
1420
+		}
1421
+		// note we need to loop through relations and set the timezone on those objects as well.
1422
+		foreach ($this->_model_relations as $relation) {
1423
+			$relation->set_timezone($timezone);
1424
+		}
1425
+		// and finally we do the same for any datetime fields
1426
+		foreach ($this->_fields as $field) {
1427
+			if ($field instanceof EE_Datetime_Field) {
1428
+				$field->set_timezone($timezone);
1429
+			}
1430
+		}
1431
+	}
1432
+
1433
+
1434
+
1435
+	/**
1436
+	 * This just returns whatever is set for the current timezone.
1437
+	 *
1438
+	 * @access public
1439
+	 * @return string
1440
+	 */
1441
+	public function get_timezone()
1442
+	{
1443
+		// first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1444
+		if (empty($this->_timezone)) {
1445
+			foreach ($this->_fields as $field) {
1446
+				if ($field instanceof EE_Datetime_Field) {
1447
+					$this->set_timezone($field->get_timezone());
1448
+					break;
1449
+				}
1450
+			}
1451
+		}
1452
+		// if timezone STILL empty then return the default timezone for the site.
1453
+		if (empty($this->_timezone)) {
1454
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1455
+		}
1456
+		return $this->_timezone;
1457
+	}
1458
+
1459
+
1460
+
1461
+	/**
1462
+	 * This returns the date formats set for the given field name and also ensures that
1463
+	 * $this->_timezone property is set correctly.
1464
+	 *
1465
+	 * @since 4.6.x
1466
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1467
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1468
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1469
+	 * @return array formats in an array with the date format first, and the time format last.
1470
+	 */
1471
+	public function get_formats_for($field_name, $pretty = false)
1472
+	{
1473
+		$field_settings = $this->field_settings_for($field_name);
1474
+		// if not a valid EE_Datetime_Field then throw error
1475
+		if (! $field_settings instanceof EE_Datetime_Field) {
1476
+			throw new EE_Error(sprintf(esc_html__(
1477
+				'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.',
1478
+				'event_espresso'
1479
+			), $field_name));
1480
+		}
1481
+		// while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1482
+		// the field.
1483
+		$this->_timezone = $field_settings->get_timezone();
1484
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1485
+	}
1486
+
1487
+
1488
+
1489
+	/**
1490
+	 * This returns the current time in a format setup for a query on this model.
1491
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1492
+	 * it will return:
1493
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1494
+	 *  NOW
1495
+	 *  - or a unix timestamp (equivalent to time())
1496
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1497
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1498
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1499
+	 * @since 4.6.x
1500
+	 * @param string $field_name       The field the current time is needed for.
1501
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1502
+	 *                                 formatted string matching the set format for the field in the set timezone will
1503
+	 *                                 be returned.
1504
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1505
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1506
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1507
+	 *                                 exception is triggered.
1508
+	 */
1509
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1510
+	{
1511
+		$formats = $this->get_formats_for($field_name);
1512
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1513
+		if ($timestamp) {
1514
+			return $DateTime->format('U');
1515
+		}
1516
+		// not returning timestamp, so return formatted string in timezone.
1517
+		switch ($what) {
1518
+			case 'time':
1519
+				return $DateTime->format($formats[1]);
1520
+				break;
1521
+			case 'date':
1522
+				return $DateTime->format($formats[0]);
1523
+				break;
1524
+			default:
1525
+				return $DateTime->format(implode(' ', $formats));
1526
+				break;
1527
+		}
1528
+	}
1529
+
1530
+
1531
+
1532
+	/**
1533
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1534
+	 * for the model are.  Returns a DateTime object.
1535
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1536
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1537
+	 * ignored.
1538
+	 *
1539
+	 * @param string $field_name      The field being setup.
1540
+	 * @param string $timestring      The date time string being used.
1541
+	 * @param string $incoming_format The format for the time string.
1542
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1543
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1544
+	 *                                format is
1545
+	 *                                'U', this is ignored.
1546
+	 * @return DateTime
1547
+	 * @throws EE_Error
1548
+	 */
1549
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1550
+	{
1551
+		// just using this to ensure the timezone is set correctly internally
1552
+		$this->get_formats_for($field_name);
1553
+		// load EEH_DTT_Helper
1554
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1555
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1556
+		EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1557
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1558
+	}
1559
+
1560
+
1561
+
1562
+	/**
1563
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1564
+	 *
1565
+	 * @return EE_Table_Base[]
1566
+	 */
1567
+	public function get_tables()
1568
+	{
1569
+		return $this->_tables;
1570
+	}
1571
+
1572
+
1573
+
1574
+	/**
1575
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1576
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1577
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1578
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1579
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1580
+	 * model object with EVT_ID = 1
1581
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1582
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1583
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1584
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1585
+	 * are not specified)
1586
+	 *
1587
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1588
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1589
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1590
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1591
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1592
+	 *                                         ID=34, we'd use this method as follows:
1593
+	 *                                         EEM_Transaction::instance()->update(
1594
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1595
+	 *                                         array(array('TXN_ID'=>34)));
1596
+	 * @param array   $query_params            @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1597
+	 *                                         Eg, consider updating Question's QST_admin_label field is of type
1598
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1599
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1600
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1601
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1602
+	 *                                         TRUE, it is assumed that you've already called
1603
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1604
+	 *                                         malicious javascript. However, if
1605
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1606
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1607
+	 *                                         and every other field, before insertion. We provide this parameter
1608
+	 *                                         because model objects perform their prepare_for_set function on all
1609
+	 *                                         their values, and so don't need to be called again (and in many cases,
1610
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1611
+	 *                                         prepare_for_set method...)
1612
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1613
+	 *                                         in this model's entity map according to $fields_n_values that match
1614
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1615
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1616
+	 *                                         could get out-of-sync with the database
1617
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1618
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1619
+	 *                                         bad)
1620
+	 * @throws EE_Error
1621
+	 */
1622
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1623
+	{
1624
+		if (! is_array($query_params)) {
1625
+			EE_Error::doing_it_wrong(
1626
+				'EEM_Base::update',
1627
+				sprintf(
1628
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1629
+					gettype($query_params)
1630
+				),
1631
+				'4.6.0'
1632
+			);
1633
+			$query_params = array();
1634
+		}
1635
+		/**
1636
+		 * Action called before a model update call has been made.
1637
+		 *
1638
+		 * @param EEM_Base $model
1639
+		 * @param array    $fields_n_values the updated fields and their new values
1640
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1641
+		 */
1642
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1643
+		/**
1644
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1645
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1646
+		 *
1647
+		 * @param array    $fields_n_values fields and their new values
1648
+		 * @param EEM_Base $model           the model being queried
1649
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1650
+		 */
1651
+		$fields_n_values = (array) apply_filters(
1652
+			'FHEE__EEM_Base__update__fields_n_values',
1653
+			$fields_n_values,
1654
+			$this,
1655
+			$query_params
1656
+		);
1657
+		// need to verify that, for any entry we want to update, there are entries in each secondary table.
1658
+		// to do that, for each table, verify that it's PK isn't null.
1659
+		$tables = $this->get_tables();
1660
+		// 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
1661
+		// NOTE: we should make this code more efficient by NOT querying twice
1662
+		// before the real update, but that needs to first go through ALPHA testing
1663
+		// as it's dangerous. says Mike August 8 2014
1664
+		// we want to make sure the default_where strategy is ignored
1665
+		$this->_ignore_where_strategy = true;
1666
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1667
+		foreach ($wpdb_select_results as $wpdb_result) {
1668
+			// type cast stdClass as array
1669
+			$wpdb_result = (array) $wpdb_result;
1670
+			// get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1671
+			if ($this->has_primary_key_field()) {
1672
+				$main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1673
+			} else {
1674
+				// 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)
1675
+				$main_table_pk_value = null;
1676
+			}
1677
+			// 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
1678
+			// 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
1679
+			if (count($tables) > 1) {
1680
+				// foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1681
+				// in that table, and so we'll want to insert one
1682
+				foreach ($tables as $table_obj) {
1683
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1684
+					// if there is no private key for this table on the results, it means there's no entry
1685
+					// in this table, right? so insert a row in the current table, using any fields available
1686
+					if (
1687
+						! (array_key_exists($this_table_pk_column, $wpdb_result)
1688
+						   && $wpdb_result[ $this_table_pk_column ])
1689
+					) {
1690
+						$success = $this->_insert_into_specific_table(
1691
+							$table_obj,
1692
+							$fields_n_values,
1693
+							$main_table_pk_value
1694
+						);
1695
+						// if we died here, report the error
1696
+						if (! $success) {
1697
+							return false;
1698
+						}
1699
+					}
1700
+				}
1701
+			}
1702
+			//              //and now check that if we have cached any models by that ID on the model, that
1703
+			//              //they also get updated properly
1704
+			//              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1705
+			//              if( $model_object ){
1706
+			//                  foreach( $fields_n_values as $field => $value ){
1707
+			//                      $model_object->set($field, $value);
1708
+			// let's make sure default_where strategy is followed now
1709
+			$this->_ignore_where_strategy = false;
1710
+		}
1711
+		// if we want to keep model objects in sync, AND
1712
+		// if this wasn't called from a model object (to update itself)
1713
+		// then we want to make sure we keep all the existing
1714
+		// model objects in sync with the db
1715
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1716
+			if ($this->has_primary_key_field()) {
1717
+				$model_objs_affected_ids = $this->get_col($query_params);
1718
+			} else {
1719
+				// we need to select a bunch of columns and then combine them into the the "index primary key string"s
1720
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1721
+				$model_objs_affected_ids = array();
1722
+				foreach ($models_affected_key_columns as $row) {
1723
+					$combined_index_key = $this->get_index_primary_key_string($row);
1724
+					$model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1725
+				}
1726
+			}
1727
+			if (! $model_objs_affected_ids) {
1728
+				// wait wait wait- if nothing was affected let's stop here
1729
+				return 0;
1730
+			}
1731
+			foreach ($model_objs_affected_ids as $id) {
1732
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1733
+				if ($model_obj_in_entity_map) {
1734
+					foreach ($fields_n_values as $field => $new_value) {
1735
+						$model_obj_in_entity_map->set($field, $new_value);
1736
+					}
1737
+				}
1738
+			}
1739
+			// if there is a primary key on this model, we can now do a slight optimization
1740
+			if ($this->has_primary_key_field()) {
1741
+				// we already know what we want to update. So let's make the query simpler so it's a little more efficient
1742
+				$query_params = array(
1743
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1744
+					'limit'                    => count($model_objs_affected_ids),
1745
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1746
+				);
1747
+			}
1748
+		}
1749
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1750
+		$SQL = "UPDATE "
1751
+			   . $model_query_info->get_full_join_sql()
1752
+			   . " SET "
1753
+			   . $this->_construct_update_sql($fields_n_values)
1754
+			   . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1755
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1756
+		/**
1757
+		 * Action called after a model update call has been made.
1758
+		 *
1759
+		 * @param EEM_Base $model
1760
+		 * @param array    $fields_n_values the updated fields and their new values
1761
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1762
+		 * @param int      $rows_affected
1763
+		 */
1764
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1765
+		return $rows_affected;// how many supposedly got updated
1766
+	}
1767
+
1768
+
1769
+
1770
+	/**
1771
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1772
+	 * are teh values of the field specified (or by default the primary key field)
1773
+	 * that matched the query params. Note that you should pass the name of the
1774
+	 * model FIELD, not the database table's column name.
1775
+	 *
1776
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1777
+	 * @param string $field_to_select
1778
+	 * @return array just like $wpdb->get_col()
1779
+	 * @throws EE_Error
1780
+	 */
1781
+	public function get_col($query_params = array(), $field_to_select = null)
1782
+	{
1783
+		if ($field_to_select) {
1784
+			$field = $this->field_settings_for($field_to_select);
1785
+		} elseif ($this->has_primary_key_field()) {
1786
+			$field = $this->get_primary_key_field();
1787
+		} else {
1788
+			// no primary key, just grab the first column
1789
+			$field = reset($this->field_settings());
1790
+		}
1791
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1792
+		$select_expressions = $field->get_qualified_column();
1793
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1794
+		return $this->_do_wpdb_query('get_col', array($SQL));
1795
+	}
1796
+
1797
+
1798
+
1799
+	/**
1800
+	 * Returns a single column value for a single row from the database
1801
+	 *
1802
+	 * @param array  $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1803
+	 * @param string $field_to_select @see EEM_Base::get_col()
1804
+	 * @return string
1805
+	 * @throws EE_Error
1806
+	 */
1807
+	public function get_var($query_params = array(), $field_to_select = null)
1808
+	{
1809
+		$query_params['limit'] = 1;
1810
+		$col = $this->get_col($query_params, $field_to_select);
1811
+		if (! empty($col)) {
1812
+			return reset($col);
1813
+		}
1814
+		return null;
1815
+	}
1816
+
1817
+
1818
+
1819
+	/**
1820
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1821
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1822
+	 * injection, but currently no further filtering is done
1823
+	 *
1824
+	 * @global      $wpdb
1825
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1826
+	 *                               be updated to in the DB
1827
+	 * @return string of SQL
1828
+	 * @throws EE_Error
1829
+	 */
1830
+	public function _construct_update_sql($fields_n_values)
1831
+	{
1832
+		/** @type WPDB $wpdb */
1833
+		global $wpdb;
1834
+		$cols_n_values = array();
1835
+		foreach ($fields_n_values as $field_name => $value) {
1836
+			$field_obj = $this->field_settings_for($field_name);
1837
+			// if the value is NULL, we want to assign the value to that.
1838
+			// wpdb->prepare doesn't really handle that properly
1839
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1840
+			$value_sql = $prepared_value === null ? 'NULL'
1841
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1842
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1843
+		}
1844
+		return implode(",", $cols_n_values);
1845
+	}
1846
+
1847
+
1848
+
1849
+	/**
1850
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1851
+	 * Performs a HARD delete, meaning the database row should always be removed,
1852
+	 * not just have a flag field on it switched
1853
+	 * Wrapper for EEM_Base::delete_permanently()
1854
+	 *
1855
+	 * @param mixed $id
1856
+	 * @param boolean $allow_blocking
1857
+	 * @return int the number of rows deleted
1858
+	 * @throws EE_Error
1859
+	 */
1860
+	public function delete_permanently_by_ID($id, $allow_blocking = true)
1861
+	{
1862
+		return $this->delete_permanently(
1863
+			array(
1864
+				array($this->get_primary_key_field()->get_name() => $id),
1865
+				'limit' => 1,
1866
+			),
1867
+			$allow_blocking
1868
+		);
1869
+	}
1870
+
1871
+
1872
+
1873
+	/**
1874
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1875
+	 * Wrapper for EEM_Base::delete()
1876
+	 *
1877
+	 * @param mixed $id
1878
+	 * @param boolean $allow_blocking
1879
+	 * @return int the number of rows deleted
1880
+	 * @throws EE_Error
1881
+	 */
1882
+	public function delete_by_ID($id, $allow_blocking = true)
1883
+	{
1884
+		return $this->delete(
1885
+			array(
1886
+				array($this->get_primary_key_field()->get_name() => $id),
1887
+				'limit' => 1,
1888
+			),
1889
+			$allow_blocking
1890
+		);
1891
+	}
1892
+
1893
+
1894
+
1895
+	/**
1896
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1897
+	 * meaning if the model has a field that indicates its been "trashed" or
1898
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1899
+	 *
1900
+	 * @see EEM_Base::delete_permanently
1901
+	 * @param array   $query_params
1902
+	 * @param boolean $allow_blocking
1903
+	 * @return int how many rows got deleted
1904
+	 * @throws EE_Error
1905
+	 */
1906
+	public function delete($query_params, $allow_blocking = true)
1907
+	{
1908
+		return $this->delete_permanently($query_params, $allow_blocking);
1909
+	}
1910
+
1911
+
1912
+
1913
+	/**
1914
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1915
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1916
+	 * as archived, not actually deleted
1917
+	 *
1918
+	 * @param array   $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1919
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1920
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1921
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1922
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1923
+	 *                                DB
1924
+	 * @return int how many rows got deleted
1925
+	 * @throws EE_Error
1926
+	 */
1927
+	public function delete_permanently($query_params, $allow_blocking = true)
1928
+	{
1929
+		/**
1930
+		 * Action called just before performing a real deletion query. You can use the
1931
+		 * model and its $query_params to find exactly which items will be deleted
1932
+		 *
1933
+		 * @param EEM_Base $model
1934
+		 * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1935
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1936
+		 *                                 to block (prevent) this deletion
1937
+		 */
1938
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1939
+		// some MySQL databases may be running safe mode, which may restrict
1940
+		// deletion if there is no KEY column used in the WHERE statement of a deletion.
1941
+		// to get around this, we first do a SELECT, get all the IDs, and then run another query
1942
+		// to delete them
1943
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1944
+		$columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1945
+		$deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1946
+			$columns_and_ids_for_deleting
1947
+		);
1948
+		/**
1949
+		 * Allows client code to act on the items being deleted before the query is actually executed.
1950
+		 *
1951
+		 * @param EEM_Base $this  The model instance being acted on.
1952
+		 * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1953
+		 * @param bool     $allow_blocking @see param description in method phpdoc block.
1954
+		 * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1955
+		 *                                                  derived from the incoming query parameters.
1956
+		 *                                                  @see details on the structure of this array in the phpdocs
1957
+		 *                                                  for the `_get_ids_for_delete_method`
1958
+		 *
1959
+		 */
1960
+		do_action(
1961
+			'AHEE__EEM_Base__delete__before_query',
1962
+			$this,
1963
+			$query_params,
1964
+			$allow_blocking,
1965
+			$columns_and_ids_for_deleting
1966
+		);
1967
+		if ($deletion_where_query_part) {
1968
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1969
+			$table_aliases = array_keys($this->_tables);
1970
+			$SQL = "DELETE "
1971
+				   . implode(", ", $table_aliases)
1972
+				   . " FROM "
1973
+				   . $model_query_info->get_full_join_sql()
1974
+				   . " WHERE "
1975
+				   . $deletion_where_query_part;
1976
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1977
+		} else {
1978
+			$rows_deleted = 0;
1979
+		}
1980
+
1981
+		// Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
1982
+		// there was no error with the delete query.
1983
+		if (
1984
+			$this->has_primary_key_field()
1985
+			&& $rows_deleted !== false
1986
+			&& isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
1987
+		) {
1988
+			$ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
1989
+			foreach ($ids_for_removal as $id) {
1990
+				if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
1991
+					unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
1992
+				}
1993
+			}
1994
+
1995
+			// delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
1996
+			// `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
1997
+			// unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
1998
+			// (although it is possible).
1999
+			// Note this can be skipped by using the provided filter and returning false.
2000
+			if (
2001
+				apply_filters(
2002
+					'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2003
+					! $this instanceof EEM_Extra_Meta,
2004
+					$this
2005
+				)
2006
+			) {
2007
+				EEM_Extra_Meta::instance()->delete_permanently(array(
2008
+					0 => array(
2009
+						'EXM_type' => $this->get_this_model_name(),
2010
+						'OBJ_ID'   => array(
2011
+							'IN',
2012
+							$ids_for_removal
2013
+						)
2014
+					)
2015
+				));
2016
+			}
2017
+		}
2018
+
2019
+		/**
2020
+		 * Action called just after performing a real deletion query. Although at this point the
2021
+		 * items should have been deleted
2022
+		 *
2023
+		 * @param EEM_Base $model
2024
+		 * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2025
+		 * @param int      $rows_deleted
2026
+		 */
2027
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2028
+		return $rows_deleted;// how many supposedly got deleted
2029
+	}
2030
+
2031
+
2032
+
2033
+	/**
2034
+	 * Checks all the relations that throw error messages when there are blocking related objects
2035
+	 * for related model objects. If there are any related model objects on those relations,
2036
+	 * adds an EE_Error, and return true
2037
+	 *
2038
+	 * @param EE_Base_Class|int $this_model_obj_or_id
2039
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2040
+	 *                                                 should be ignored when determining whether there are related
2041
+	 *                                                 model objects which block this model object's deletion. Useful
2042
+	 *                                                 if you know A is related to B and are considering deleting A,
2043
+	 *                                                 but want to see if A has any other objects blocking its deletion
2044
+	 *                                                 before removing the relation between A and B
2045
+	 * @return boolean
2046
+	 * @throws EE_Error
2047
+	 */
2048
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2049
+	{
2050
+		// first, if $ignore_this_model_obj was supplied, get its model
2051
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2052
+			$ignored_model = $ignore_this_model_obj->get_model();
2053
+		} else {
2054
+			$ignored_model = null;
2055
+		}
2056
+		// now check all the relations of $this_model_obj_or_id and see if there
2057
+		// are any related model objects blocking it?
2058
+		$is_blocked = false;
2059
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2060
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2061
+				// if $ignore_this_model_obj was supplied, then for the query
2062
+				// on that model needs to be told to ignore $ignore_this_model_obj
2063
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2064
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2065
+						array(
2066
+							$ignored_model->get_primary_key_field()->get_name() => array(
2067
+								'!=',
2068
+								$ignore_this_model_obj->ID(),
2069
+							),
2070
+						),
2071
+					));
2072
+				} else {
2073
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2074
+				}
2075
+				if ($related_model_objects) {
2076
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2077
+					$is_blocked = true;
2078
+				}
2079
+			}
2080
+		}
2081
+		return $is_blocked;
2082
+	}
2083
+
2084
+
2085
+	/**
2086
+	 * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2087
+	 * @param array $row_results_for_deleting
2088
+	 * @param bool  $allow_blocking
2089
+	 * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2090
+	 *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2091
+	 *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2092
+	 *                 deleted. Example:
2093
+	 *                      array('Event.EVT_ID' => array( 1,2,3))
2094
+	 *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2095
+	 *                 where each element is a group of columns and values that get deleted. Example:
2096
+	 *                      array(
2097
+	 *                          0 => array(
2098
+	 *                              'Term_Relationship.object_id' => 1
2099
+	 *                              'Term_Relationship.term_taxonomy_id' => 5
2100
+	 *                          ),
2101
+	 *                          1 => array(
2102
+	 *                              'Term_Relationship.object_id' => 1
2103
+	 *                              'Term_Relationship.term_taxonomy_id' => 6
2104
+	 *                          )
2105
+	 *                      )
2106
+	 * @throws EE_Error
2107
+	 */
2108
+	protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2109
+	{
2110
+		$ids_to_delete_indexed_by_column = array();
2111
+		if ($this->has_primary_key_field()) {
2112
+			$primary_table = $this->_get_main_table();
2113
+			$primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2114
+			$other_tables = $this->_get_other_tables();
2115
+			$ids_to_delete_indexed_by_column = $query = array();
2116
+			foreach ($row_results_for_deleting as $item_to_delete) {
2117
+				// before we mark this item for deletion,
2118
+				// make sure there's no related entities blocking its deletion (if we're checking)
2119
+				if (
2120
+					$allow_blocking
2121
+					&& $this->delete_is_blocked_by_related_models(
2122
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2123
+					)
2124
+				) {
2125
+					continue;
2126
+				}
2127
+				// primary table deletes
2128
+				if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2129
+					$ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2130
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2131
+				}
2132
+			}
2133
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2134
+			$fields = $this->get_combined_primary_key_fields();
2135
+			foreach ($row_results_for_deleting as $item_to_delete) {
2136
+				$ids_to_delete_indexed_by_column_for_row = array();
2137
+				foreach ($fields as $cpk_field) {
2138
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2139
+						$ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2140
+							$item_to_delete[ $cpk_field->get_qualified_column() ];
2141
+					}
2142
+				}
2143
+				$ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2144
+			}
2145
+		} else {
2146
+			// so there's no primary key and no combined key...
2147
+			// sorry, can't help you
2148
+			throw new EE_Error(
2149
+				sprintf(
2150
+					esc_html__(
2151
+						"Cannot delete objects of type %s because there is no primary key NOR combined key",
2152
+						"event_espresso"
2153
+					),
2154
+					get_class($this)
2155
+				)
2156
+			);
2157
+		}
2158
+		return $ids_to_delete_indexed_by_column;
2159
+	}
2160
+
2161
+
2162
+	/**
2163
+	 * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2164
+	 * the corresponding query_part for the query performing the delete.
2165
+	 *
2166
+	 * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2167
+	 * @return string
2168
+	 * @throws EE_Error
2169
+	 */
2170
+	protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2171
+	{
2172
+		$query_part = '';
2173
+		if (empty($ids_to_delete_indexed_by_column)) {
2174
+			return $query_part;
2175
+		} elseif ($this->has_primary_key_field()) {
2176
+			$query = array();
2177
+			foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2178
+				$query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2179
+			}
2180
+			$query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2181
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2182
+			$ways_to_identify_a_row = array();
2183
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2184
+				$values_for_each_combined_primary_key_for_a_row = array();
2185
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2186
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2187
+				}
2188
+				$ways_to_identify_a_row[] = '('
2189
+											. implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2190
+											. ')';
2191
+			}
2192
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2193
+		}
2194
+		return $query_part;
2195
+	}
2196
+
2197
+
2198
+
2199
+	/**
2200
+	 * Gets the model field by the fully qualified name
2201
+	 * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2202
+	 * @return EE_Model_Field_Base
2203
+	 */
2204
+	public function get_field_by_column($qualified_column_name)
2205
+	{
2206
+		foreach ($this->field_settings(true) as $field_name => $field_obj) {
2207
+			if ($field_obj->get_qualified_column() === $qualified_column_name) {
2208
+				return $field_obj;
2209
+			}
2210
+		}
2211
+		throw new EE_Error(
2212
+			sprintf(
2213
+				esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2214
+				$this->get_this_model_name(),
2215
+				$qualified_column_name
2216
+			)
2217
+		);
2218
+	}
2219
+
2220
+
2221
+
2222
+	/**
2223
+	 * Count all the rows that match criteria the model query params.
2224
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2225
+	 * column
2226
+	 *
2227
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2228
+	 * @param string $field_to_count field on model to count by (not column name)
2229
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2230
+	 *                               that by the setting $distinct to TRUE;
2231
+	 * @return int
2232
+	 * @throws EE_Error
2233
+	 */
2234
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2235
+	{
2236
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2237
+		if ($field_to_count) {
2238
+			$field_obj = $this->field_settings_for($field_to_count);
2239
+			$column_to_count = $field_obj->get_qualified_column();
2240
+		} elseif ($this->has_primary_key_field()) {
2241
+			$pk_field_obj = $this->get_primary_key_field();
2242
+			$column_to_count = $pk_field_obj->get_qualified_column();
2243
+		} else {
2244
+			// there's no primary key
2245
+			// if we're counting distinct items, and there's no primary key,
2246
+			// we need to list out the columns for distinction;
2247
+			// otherwise we can just use star
2248
+			if ($distinct) {
2249
+				$columns_to_use = array();
2250
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2251
+					$columns_to_use[] = $field_obj->get_qualified_column();
2252
+				}
2253
+				$column_to_count = implode(',', $columns_to_use);
2254
+			} else {
2255
+				$column_to_count = '*';
2256
+			}
2257
+		}
2258
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2259
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2260
+		return (int) $this->_do_wpdb_query('get_var', array($SQL));
2261
+	}
2262
+
2263
+
2264
+
2265
+	/**
2266
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2267
+	 *
2268
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2269
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2270
+	 * @return float
2271
+	 * @throws EE_Error
2272
+	 */
2273
+	public function sum($query_params, $field_to_sum = null)
2274
+	{
2275
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2276
+		if ($field_to_sum) {
2277
+			$field_obj = $this->field_settings_for($field_to_sum);
2278
+		} else {
2279
+			$field_obj = $this->get_primary_key_field();
2280
+		}
2281
+		$column_to_count = $field_obj->get_qualified_column();
2282
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2283
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2284
+		$data_type = $field_obj->get_wpdb_data_type();
2285
+		if ($data_type === '%d' || $data_type === '%s') {
2286
+			return (float) $return_value;
2287
+		}
2288
+		// must be %f
2289
+		return (float) $return_value;
2290
+	}
2291
+
2292
+
2293
+
2294
+	/**
2295
+	 * Just calls the specified method on $wpdb with the given arguments
2296
+	 * Consolidates a little extra error handling code
2297
+	 *
2298
+	 * @param string $wpdb_method
2299
+	 * @param array  $arguments_to_provide
2300
+	 * @throws EE_Error
2301
+	 * @global wpdb  $wpdb
2302
+	 * @return mixed
2303
+	 */
2304
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2305
+	{
2306
+		// if we're in maintenance mode level 2, DON'T run any queries
2307
+		// because level 2 indicates the database needs updating and
2308
+		// is probably out of sync with the code
2309
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2310
+			throw new EE_Error(sprintf(esc_html__(
2311
+				"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.",
2312
+				"event_espresso"
2313
+			)));
2314
+		}
2315
+		/** @type WPDB $wpdb */
2316
+		global $wpdb;
2317
+		if (! method_exists($wpdb, $wpdb_method)) {
2318
+			throw new EE_Error(sprintf(esc_html__(
2319
+				'There is no method named "%s" on Wordpress\' $wpdb object',
2320
+				'event_espresso'
2321
+			), $wpdb_method));
2322
+		}
2323
+		if (WP_DEBUG) {
2324
+			$old_show_errors_value = $wpdb->show_errors;
2325
+			$wpdb->show_errors(false);
2326
+		}
2327
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2328
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2329
+		if (WP_DEBUG) {
2330
+			$wpdb->show_errors($old_show_errors_value);
2331
+			if (! empty($wpdb->last_error)) {
2332
+				throw new EE_Error(sprintf(esc_html__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2333
+			}
2334
+			if ($result === false) {
2335
+				throw new EE_Error(sprintf(esc_html__(
2336
+					'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2337
+					'event_espresso'
2338
+				), $wpdb_method, var_export($arguments_to_provide, true)));
2339
+			}
2340
+		} elseif ($result === false) {
2341
+			EE_Error::add_error(
2342
+				sprintf(
2343
+					esc_html__(
2344
+						'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"',
2345
+						'event_espresso'
2346
+					),
2347
+					$wpdb_method,
2348
+					var_export($arguments_to_provide, true),
2349
+					$wpdb->last_error
2350
+				),
2351
+				__FILE__,
2352
+				__FUNCTION__,
2353
+				__LINE__
2354
+			);
2355
+		}
2356
+		return $result;
2357
+	}
2358
+
2359
+
2360
+
2361
+	/**
2362
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2363
+	 * and if there's an error tries to verify the DB is correct. Uses
2364
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2365
+	 * we should try to fix the EE core db, the addons, or just give up
2366
+	 *
2367
+	 * @param string $wpdb_method
2368
+	 * @param array  $arguments_to_provide
2369
+	 * @return mixed
2370
+	 */
2371
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2372
+	{
2373
+		/** @type WPDB $wpdb */
2374
+		global $wpdb;
2375
+		$wpdb->last_error = null;
2376
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2377
+		// was there an error running the query? but we don't care on new activations
2378
+		// (we're going to setup the DB anyway on new activations)
2379
+		if (
2380
+			($result === false || ! empty($wpdb->last_error))
2381
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2382
+		) {
2383
+			switch (EEM_Base::$_db_verification_level) {
2384
+				case EEM_Base::db_verified_none:
2385
+					// let's double-check core's DB
2386
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2387
+					break;
2388
+				case EEM_Base::db_verified_core:
2389
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2390
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2391
+					break;
2392
+				case EEM_Base::db_verified_addons:
2393
+					// ummmm... you in trouble
2394
+					return $result;
2395
+					break;
2396
+			}
2397
+			if (! empty($error_message)) {
2398
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2399
+				trigger_error($error_message);
2400
+			}
2401
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2402
+		}
2403
+		return $result;
2404
+	}
2405
+
2406
+
2407
+
2408
+	/**
2409
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2410
+	 * EEM_Base::$_db_verification_level
2411
+	 *
2412
+	 * @param string $wpdb_method
2413
+	 * @param array  $arguments_to_provide
2414
+	 * @return string
2415
+	 */
2416
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2417
+	{
2418
+		/** @type WPDB $wpdb */
2419
+		global $wpdb;
2420
+		// ok remember that we've already attempted fixing the core db, in case the problem persists
2421
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2422
+		$error_message = sprintf(
2423
+			esc_html__(
2424
+				'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2425
+				'event_espresso'
2426
+			),
2427
+			$wpdb->last_error,
2428
+			$wpdb_method,
2429
+			wp_json_encode($arguments_to_provide)
2430
+		);
2431
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2432
+		return $error_message;
2433
+	}
2434
+
2435
+
2436
+
2437
+	/**
2438
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2439
+	 * EEM_Base::$_db_verification_level
2440
+	 *
2441
+	 * @param $wpdb_method
2442
+	 * @param $arguments_to_provide
2443
+	 * @return string
2444
+	 */
2445
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2446
+	{
2447
+		/** @type WPDB $wpdb */
2448
+		global $wpdb;
2449
+		// ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2450
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2451
+		$error_message = sprintf(
2452
+			esc_html__(
2453
+				'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2454
+				'event_espresso'
2455
+			),
2456
+			$wpdb->last_error,
2457
+			$wpdb_method,
2458
+			wp_json_encode($arguments_to_provide)
2459
+		);
2460
+		EE_System::instance()->initialize_addons();
2461
+		return $error_message;
2462
+	}
2463
+
2464
+
2465
+
2466
+	/**
2467
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2468
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2469
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2470
+	 * ..."
2471
+	 *
2472
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2473
+	 * @return string
2474
+	 */
2475
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2476
+	{
2477
+		return " FROM " . $model_query_info->get_full_join_sql() .
2478
+			   $model_query_info->get_where_sql() .
2479
+			   $model_query_info->get_group_by_sql() .
2480
+			   $model_query_info->get_having_sql() .
2481
+			   $model_query_info->get_order_by_sql() .
2482
+			   $model_query_info->get_limit_sql();
2483
+	}
2484
+
2485
+
2486
+
2487
+	/**
2488
+	 * Set to easily debug the next X queries ran from this model.
2489
+	 *
2490
+	 * @param int $count
2491
+	 */
2492
+	public function show_next_x_db_queries($count = 1)
2493
+	{
2494
+		$this->_show_next_x_db_queries = $count;
2495
+	}
2496
+
2497
+
2498
+
2499
+	/**
2500
+	 * @param $sql_query
2501
+	 */
2502
+	public function show_db_query_if_previously_requested($sql_query)
2503
+	{
2504
+		if ($this->_show_next_x_db_queries > 0) {
2505
+			echo esc_html($sql_query);
2506
+			$this->_show_next_x_db_queries--;
2507
+		}
2508
+	}
2509
+
2510
+
2511
+
2512
+	/**
2513
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2514
+	 * There are the 3 cases:
2515
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2516
+	 * $otherModelObject has no ID, it is first saved.
2517
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2518
+	 * has no ID, it is first saved.
2519
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2520
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2521
+	 * join table
2522
+	 *
2523
+	 * @param        EE_Base_Class                     /int $thisModelObject
2524
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2525
+	 * @param string $relationName                     , key in EEM_Base::_relations
2526
+	 *                                                 an attendee to a group, you also want to specify which role they
2527
+	 *                                                 will have in that group. So you would use this parameter to
2528
+	 *                                                 specify array('role-column-name'=>'role-id')
2529
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2530
+	 *                                                 to for relation to methods that allow you to further specify
2531
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2532
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2533
+	 *                                                 because these will be inserted in any new rows created as well.
2534
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2535
+	 * @throws EE_Error
2536
+	 */
2537
+	public function add_relationship_to(
2538
+		$id_or_obj,
2539
+		$other_model_id_or_obj,
2540
+		$relationName,
2541
+		$extra_join_model_fields_n_values = array()
2542
+	) {
2543
+		$relation_obj = $this->related_settings_for($relationName);
2544
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2545
+	}
2546
+
2547
+
2548
+
2549
+	/**
2550
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2551
+	 * There are the 3 cases:
2552
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2553
+	 * error
2554
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2555
+	 * an error
2556
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2557
+	 *
2558
+	 * @param        EE_Base_Class /int $id_or_obj
2559
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2560
+	 * @param string $relationName key in EEM_Base::_relations
2561
+	 * @return boolean of success
2562
+	 * @throws EE_Error
2563
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2564
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2565
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2566
+	 *                             because these will be inserted in any new rows created as well.
2567
+	 */
2568
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2569
+	{
2570
+		$relation_obj = $this->related_settings_for($relationName);
2571
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2572
+	}
2573
+
2574
+
2575
+
2576
+	/**
2577
+	 * @param mixed           $id_or_obj
2578
+	 * @param string          $relationName
2579
+	 * @param array           $where_query_params
2580
+	 * @param EE_Base_Class[] objects to which relations were removed
2581
+	 * @return \EE_Base_Class[]
2582
+	 * @throws EE_Error
2583
+	 */
2584
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2585
+	{
2586
+		$relation_obj = $this->related_settings_for($relationName);
2587
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2588
+	}
2589
+
2590
+
2591
+
2592
+	/**
2593
+	 * Gets all the related items of the specified $model_name, using $query_params.
2594
+	 * Note: by default, we remove the "default query params"
2595
+	 * because we want to get even deleted items etc.
2596
+	 *
2597
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2598
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2599
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2600
+	 * @return EE_Base_Class[]
2601
+	 * @throws EE_Error
2602
+	 */
2603
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2604
+	{
2605
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2606
+		$relation_settings = $this->related_settings_for($model_name);
2607
+		return $relation_settings->get_all_related($model_obj, $query_params);
2608
+	}
2609
+
2610
+
2611
+
2612
+	/**
2613
+	 * Deletes all the model objects across the relation indicated by $model_name
2614
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2615
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2616
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2617
+	 *
2618
+	 * @param EE_Base_Class|int|string $id_or_obj
2619
+	 * @param string                   $model_name
2620
+	 * @param array                    $query_params
2621
+	 * @return int how many deleted
2622
+	 * @throws EE_Error
2623
+	 */
2624
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2625
+	{
2626
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2627
+		$relation_settings = $this->related_settings_for($model_name);
2628
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2629
+	}
2630
+
2631
+
2632
+
2633
+	/**
2634
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2635
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2636
+	 * the model objects can't be hard deleted because of blocking related model objects,
2637
+	 * just does a soft-delete on them instead.
2638
+	 *
2639
+	 * @param EE_Base_Class|int|string $id_or_obj
2640
+	 * @param string                   $model_name
2641
+	 * @param array                    $query_params
2642
+	 * @return int how many deleted
2643
+	 * @throws EE_Error
2644
+	 */
2645
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2646
+	{
2647
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2648
+		$relation_settings = $this->related_settings_for($model_name);
2649
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2650
+	}
2651
+
2652
+
2653
+
2654
+	/**
2655
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2656
+	 * unless otherwise specified in the $query_params
2657
+	 *
2658
+	 * @param        int             /EE_Base_Class $id_or_obj
2659
+	 * @param string $model_name     like 'Event', or 'Registration'
2660
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2661
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2662
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2663
+	 *                               that by the setting $distinct to TRUE;
2664
+	 * @return int
2665
+	 * @throws EE_Error
2666
+	 */
2667
+	public function count_related(
2668
+		$id_or_obj,
2669
+		$model_name,
2670
+		$query_params = array(),
2671
+		$field_to_count = null,
2672
+		$distinct = false
2673
+	) {
2674
+		$related_model = $this->get_related_model_obj($model_name);
2675
+		// we're just going to use the query params on the related model's normal get_all query,
2676
+		// except add a condition to say to match the current mod
2677
+		if (! isset($query_params['default_where_conditions'])) {
2678
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2679
+		}
2680
+		$this_model_name = $this->get_this_model_name();
2681
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2682
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2683
+		return $related_model->count($query_params, $field_to_count, $distinct);
2684
+	}
2685
+
2686
+
2687
+
2688
+	/**
2689
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2690
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2691
+	 *
2692
+	 * @param        int           /EE_Base_Class $id_or_obj
2693
+	 * @param string $model_name   like 'Event', or 'Registration'
2694
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2695
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2696
+	 * @return float
2697
+	 * @throws EE_Error
2698
+	 */
2699
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2700
+	{
2701
+		$related_model = $this->get_related_model_obj($model_name);
2702
+		if (! is_array($query_params)) {
2703
+			EE_Error::doing_it_wrong(
2704
+				'EEM_Base::sum_related',
2705
+				sprintf(
2706
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2707
+					gettype($query_params)
2708
+				),
2709
+				'4.6.0'
2710
+			);
2711
+			$query_params = array();
2712
+		}
2713
+		// we're just going to use the query params on the related model's normal get_all query,
2714
+		// except add a condition to say to match the current mod
2715
+		if (! isset($query_params['default_where_conditions'])) {
2716
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2717
+		}
2718
+		$this_model_name = $this->get_this_model_name();
2719
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2720
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2721
+		return $related_model->sum($query_params, $field_to_sum);
2722
+	}
2723
+
2724
+
2725
+
2726
+	/**
2727
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2728
+	 * $modelObject
2729
+	 *
2730
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2731
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2732
+	 * @param array               $query_params     @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2733
+	 * @return EE_Base_Class
2734
+	 * @throws EE_Error
2735
+	 */
2736
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2737
+	{
2738
+		$query_params['limit'] = 1;
2739
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2740
+		if ($results) {
2741
+			return array_shift($results);
2742
+		}
2743
+		return null;
2744
+	}
2745
+
2746
+
2747
+
2748
+	/**
2749
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2750
+	 *
2751
+	 * @return string
2752
+	 */
2753
+	public function get_this_model_name()
2754
+	{
2755
+		return str_replace("EEM_", "", get_class($this));
2756
+	}
2757
+
2758
+
2759
+
2760
+	/**
2761
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2762
+	 *
2763
+	 * @return EE_Any_Foreign_Model_Name_Field
2764
+	 * @throws EE_Error
2765
+	 */
2766
+	public function get_field_containing_related_model_name()
2767
+	{
2768
+		foreach ($this->field_settings(true) as $field) {
2769
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2770
+				$field_with_model_name = $field;
2771
+			}
2772
+		}
2773
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2774
+			throw new EE_Error(sprintf(
2775
+				esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2776
+				$this->get_this_model_name()
2777
+			));
2778
+		}
2779
+		return $field_with_model_name;
2780
+	}
2781
+
2782
+
2783
+
2784
+	/**
2785
+	 * Inserts a new entry into the database, for each table.
2786
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2787
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2788
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2789
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2790
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2791
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2792
+	 *
2793
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2794
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2795
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2796
+	 *                              of EEM_Base)
2797
+	 * @return int|string new primary key on main table that got inserted
2798
+	 * @throws EE_Error
2799
+	 */
2800
+	public function insert($field_n_values)
2801
+	{
2802
+		/**
2803
+		 * Filters the fields and their values before inserting an item using the models
2804
+		 *
2805
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2806
+		 * @param EEM_Base $model           the model used
2807
+		 */
2808
+		$field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2809
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2810
+			$main_table = $this->_get_main_table();
2811
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2812
+			if ($new_id !== false) {
2813
+				foreach ($this->_get_other_tables() as $other_table) {
2814
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2815
+				}
2816
+			}
2817
+			/**
2818
+			 * Done just after attempting to insert a new model object
2819
+			 *
2820
+			 * @param EEM_Base   $model           used
2821
+			 * @param array      $fields_n_values fields and their values
2822
+			 * @param int|string the              ID of the newly-inserted model object
2823
+			 */
2824
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2825
+			return $new_id;
2826
+		}
2827
+		return false;
2828
+	}
2829
+
2830
+
2831
+
2832
+	/**
2833
+	 * Checks that the result would satisfy the unique indexes on this model
2834
+	 *
2835
+	 * @param array  $field_n_values
2836
+	 * @param string $action
2837
+	 * @return boolean
2838
+	 * @throws EE_Error
2839
+	 */
2840
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2841
+	{
2842
+		foreach ($this->unique_indexes() as $index_name => $index) {
2843
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2844
+			if ($this->exists(array($uniqueness_where_params))) {
2845
+				EE_Error::add_error(
2846
+					sprintf(
2847
+						esc_html__(
2848
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2849
+							"event_espresso"
2850
+						),
2851
+						$action,
2852
+						$this->_get_class_name(),
2853
+						$index_name,
2854
+						implode(",", $index->field_names()),
2855
+						http_build_query($uniqueness_where_params)
2856
+					),
2857
+					__FILE__,
2858
+					__FUNCTION__,
2859
+					__LINE__
2860
+				);
2861
+				return false;
2862
+			}
2863
+		}
2864
+		return true;
2865
+	}
2866
+
2867
+
2868
+
2869
+	/**
2870
+	 * Checks the database for an item that conflicts (ie, if this item were
2871
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2872
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2873
+	 * can be either an EE_Base_Class or an array of fields n values
2874
+	 *
2875
+	 * @param EE_Base_Class|array $obj_or_fields_array
2876
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2877
+	 *                                                 when looking for conflicts
2878
+	 *                                                 (ie, if false, we ignore the model object's primary key
2879
+	 *                                                 when finding "conflicts". If true, it's also considered).
2880
+	 *                                                 Only works for INT primary key,
2881
+	 *                                                 STRING primary keys cannot be ignored
2882
+	 * @throws EE_Error
2883
+	 * @return EE_Base_Class|array
2884
+	 */
2885
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2886
+	{
2887
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2888
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2889
+		} elseif (is_array($obj_or_fields_array)) {
2890
+			$fields_n_values = $obj_or_fields_array;
2891
+		} else {
2892
+			throw new EE_Error(
2893
+				sprintf(
2894
+					esc_html__(
2895
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2896
+						"event_espresso"
2897
+					),
2898
+					get_class($this),
2899
+					$obj_or_fields_array
2900
+				)
2901
+			);
2902
+		}
2903
+		$query_params = array();
2904
+		if (
2905
+			$this->has_primary_key_field()
2906
+			&& ($include_primary_key
2907
+				|| $this->get_primary_key_field()
2908
+				   instanceof
2909
+				   EE_Primary_Key_String_Field)
2910
+			&& isset($fields_n_values[ $this->primary_key_name() ])
2911
+		) {
2912
+			$query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2913
+		}
2914
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2915
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2916
+			$query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2917
+		}
2918
+		// if there is nothing to base this search on, then we shouldn't find anything
2919
+		if (empty($query_params)) {
2920
+			return array();
2921
+		}
2922
+		return $this->get_one($query_params);
2923
+	}
2924
+
2925
+
2926
+
2927
+	/**
2928
+	 * Like count, but is optimized and returns a boolean instead of an int
2929
+	 *
2930
+	 * @param array $query_params
2931
+	 * @return boolean
2932
+	 * @throws EE_Error
2933
+	 */
2934
+	public function exists($query_params)
2935
+	{
2936
+		$query_params['limit'] = 1;
2937
+		return $this->count($query_params) > 0;
2938
+	}
2939
+
2940
+
2941
+
2942
+	/**
2943
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2944
+	 *
2945
+	 * @param int|string $id
2946
+	 * @return boolean
2947
+	 * @throws EE_Error
2948
+	 */
2949
+	public function exists_by_ID($id)
2950
+	{
2951
+		return $this->exists(
2952
+			array(
2953
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2954
+				array(
2955
+					$this->primary_key_name() => $id,
2956
+				),
2957
+			)
2958
+		);
2959
+	}
2960
+
2961
+
2962
+
2963
+	/**
2964
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2965
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2966
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2967
+	 * on the main table)
2968
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
2969
+	 * cases where we want to call it directly rather than via insert().
2970
+	 *
2971
+	 * @access   protected
2972
+	 * @param EE_Table_Base $table
2973
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2974
+	 *                                       float
2975
+	 * @param int           $new_id          for now we assume only int keys
2976
+	 * @throws EE_Error
2977
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2978
+	 * @return int ID of new row inserted, or FALSE on failure
2979
+	 */
2980
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2981
+	{
2982
+		global $wpdb;
2983
+		$insertion_col_n_values = array();
2984
+		$format_for_insertion = array();
2985
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2986
+		foreach ($fields_on_table as $field_name => $field_obj) {
2987
+			// check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2988
+			if ($field_obj->is_auto_increment()) {
2989
+				continue;
2990
+			}
2991
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2992
+			// if the value we want to assign it to is NULL, just don't mention it for the insertion
2993
+			if ($prepared_value !== null) {
2994
+				$insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
2995
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
2996
+			}
2997
+		}
2998
+		if ($table instanceof EE_Secondary_Table && $new_id) {
2999
+			// its not the main table, so we should have already saved the main table's PK which we just inserted
3000
+			// so add the fk to the main table as a column
3001
+			$insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3002
+			$format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
3003
+		}
3004
+		// insert the new entry
3005
+		$result = $this->_do_wpdb_query(
3006
+			'insert',
3007
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion)
3008
+		);
3009
+		if ($result === false) {
3010
+			return false;
3011
+		}
3012
+		// ok, now what do we return for the ID of the newly-inserted thing?
3013
+		if ($this->has_primary_key_field()) {
3014
+			if ($this->get_primary_key_field()->is_auto_increment()) {
3015
+				return $wpdb->insert_id;
3016
+			}
3017
+			// it's not an auto-increment primary key, so
3018
+			// it must have been supplied
3019
+			return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3020
+		}
3021
+		// we can't return a  primary key because there is none. instead return
3022
+		// a unique string indicating this model
3023
+		return $this->get_index_primary_key_string($fields_n_values);
3024
+	}
3025
+
3026
+
3027
+
3028
+	/**
3029
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3030
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3031
+	 * and there is no default, we pass it along. WPDB will take care of it)
3032
+	 *
3033
+	 * @param EE_Model_Field_Base $field_obj
3034
+	 * @param array               $fields_n_values
3035
+	 * @return mixed string|int|float depending on what the table column will be expecting
3036
+	 * @throws EE_Error
3037
+	 */
3038
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3039
+	{
3040
+		// if this field doesn't allow nullable, don't allow it
3041
+		if (
3042
+			! $field_obj->is_nullable()
3043
+			&& (
3044
+				! isset($fields_n_values[ $field_obj->get_name() ])
3045
+				|| $fields_n_values[ $field_obj->get_name() ] === null
3046
+			)
3047
+		) {
3048
+			$fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3049
+		}
3050
+		$unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3051
+			? $fields_n_values[ $field_obj->get_name() ]
3052
+			: null;
3053
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3054
+	}
3055
+
3056
+
3057
+
3058
+	/**
3059
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3060
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3061
+	 * the field's prepare_for_set() method.
3062
+	 *
3063
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3064
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3065
+	 *                                   top of file)
3066
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3067
+	 *                                   $value is a custom selection
3068
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3069
+	 */
3070
+	private function _prepare_value_for_use_in_db($value, $field)
3071
+	{
3072
+		if ($field && $field instanceof EE_Model_Field_Base) {
3073
+			// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3074
+			switch ($this->_values_already_prepared_by_model_object) {
3075
+				/** @noinspection PhpMissingBreakStatementInspection */
3076
+				case self::not_prepared_by_model_object:
3077
+					$value = $field->prepare_for_set($value);
3078
+				// purposefully left out "return"
3079
+				case self::prepared_by_model_object:
3080
+					/** @noinspection SuspiciousAssignmentsInspection */
3081
+					$value = $field->prepare_for_use_in_db($value);
3082
+				case self::prepared_for_use_in_db:
3083
+					// leave the value alone
3084
+			}
3085
+			return $value;
3086
+			// phpcs:enable
3087
+		}
3088
+		return $value;
3089
+	}
3090
+
3091
+
3092
+
3093
+	/**
3094
+	 * Returns the main table on this model
3095
+	 *
3096
+	 * @return EE_Primary_Table
3097
+	 * @throws EE_Error
3098
+	 */
3099
+	protected function _get_main_table()
3100
+	{
3101
+		foreach ($this->_tables as $table) {
3102
+			if ($table instanceof EE_Primary_Table) {
3103
+				return $table;
3104
+			}
3105
+		}
3106
+		throw new EE_Error(sprintf(esc_html__(
3107
+			'There are no main tables on %s. They should be added to _tables array in the constructor',
3108
+			'event_espresso'
3109
+		), get_class($this)));
3110
+	}
3111
+
3112
+
3113
+
3114
+	/**
3115
+	 * table
3116
+	 * returns EE_Primary_Table table name
3117
+	 *
3118
+	 * @return string
3119
+	 * @throws EE_Error
3120
+	 */
3121
+	public function table()
3122
+	{
3123
+		return $this->_get_main_table()->get_table_name();
3124
+	}
3125
+
3126
+
3127
+
3128
+	/**
3129
+	 * table
3130
+	 * returns first EE_Secondary_Table table name
3131
+	 *
3132
+	 * @return string
3133
+	 */
3134
+	public function second_table()
3135
+	{
3136
+		// grab second table from tables array
3137
+		$second_table = end($this->_tables);
3138
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3139
+	}
3140
+
3141
+
3142
+
3143
+	/**
3144
+	 * get_table_obj_by_alias
3145
+	 * returns table name given it's alias
3146
+	 *
3147
+	 * @param string $table_alias
3148
+	 * @return EE_Primary_Table | EE_Secondary_Table
3149
+	 */
3150
+	public function get_table_obj_by_alias($table_alias = '')
3151
+	{
3152
+		return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3153
+	}
3154
+
3155
+
3156
+
3157
+	/**
3158
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3159
+	 *
3160
+	 * @return EE_Secondary_Table[]
3161
+	 */
3162
+	protected function _get_other_tables()
3163
+	{
3164
+		$other_tables = array();
3165
+		foreach ($this->_tables as $table_alias => $table) {
3166
+			if ($table instanceof EE_Secondary_Table) {
3167
+				$other_tables[ $table_alias ] = $table;
3168
+			}
3169
+		}
3170
+		return $other_tables;
3171
+	}
3172
+
3173
+
3174
+
3175
+	/**
3176
+	 * Finds all the fields that correspond to the given table
3177
+	 *
3178
+	 * @param string $table_alias , array key in EEM_Base::_tables
3179
+	 * @return EE_Model_Field_Base[]
3180
+	 */
3181
+	public function _get_fields_for_table($table_alias)
3182
+	{
3183
+		return $this->_fields[ $table_alias ];
3184
+	}
3185
+
3186
+
3187
+
3188
+	/**
3189
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3190
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3191
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3192
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3193
+	 * related Registration, Transaction, and Payment models.
3194
+	 *
3195
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3196
+	 * @return EE_Model_Query_Info_Carrier
3197
+	 * @throws EE_Error
3198
+	 */
3199
+	public function _extract_related_models_from_query($query_params)
3200
+	{
3201
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3202
+		if (array_key_exists(0, $query_params)) {
3203
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3204
+		}
3205
+		if (array_key_exists('group_by', $query_params)) {
3206
+			if (is_array($query_params['group_by'])) {
3207
+				$this->_extract_related_models_from_sub_params_array_values(
3208
+					$query_params['group_by'],
3209
+					$query_info_carrier,
3210
+					'group_by'
3211
+				);
3212
+			} elseif (! empty($query_params['group_by'])) {
3213
+				$this->_extract_related_model_info_from_query_param(
3214
+					$query_params['group_by'],
3215
+					$query_info_carrier,
3216
+					'group_by'
3217
+				);
3218
+			}
3219
+		}
3220
+		if (array_key_exists('having', $query_params)) {
3221
+			$this->_extract_related_models_from_sub_params_array_keys(
3222
+				$query_params[0],
3223
+				$query_info_carrier,
3224
+				'having'
3225
+			);
3226
+		}
3227
+		if (array_key_exists('order_by', $query_params)) {
3228
+			if (is_array($query_params['order_by'])) {
3229
+				$this->_extract_related_models_from_sub_params_array_keys(
3230
+					$query_params['order_by'],
3231
+					$query_info_carrier,
3232
+					'order_by'
3233
+				);
3234
+			} elseif (! empty($query_params['order_by'])) {
3235
+				$this->_extract_related_model_info_from_query_param(
3236
+					$query_params['order_by'],
3237
+					$query_info_carrier,
3238
+					'order_by'
3239
+				);
3240
+			}
3241
+		}
3242
+		if (array_key_exists('force_join', $query_params)) {
3243
+			$this->_extract_related_models_from_sub_params_array_values(
3244
+				$query_params['force_join'],
3245
+				$query_info_carrier,
3246
+				'force_join'
3247
+			);
3248
+		}
3249
+		$this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3250
+		return $query_info_carrier;
3251
+	}
3252
+
3253
+
3254
+
3255
+	/**
3256
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3257
+	 *
3258
+	 * @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
3259
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3260
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3261
+	 * @throws EE_Error
3262
+	 * @return \EE_Model_Query_Info_Carrier
3263
+	 */
3264
+	private function _extract_related_models_from_sub_params_array_keys(
3265
+		$sub_query_params,
3266
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3267
+		$query_param_type
3268
+	) {
3269
+		if (! empty($sub_query_params)) {
3270
+			$sub_query_params = (array) $sub_query_params;
3271
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3272
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3273
+				$this->_extract_related_model_info_from_query_param(
3274
+					$param,
3275
+					$model_query_info_carrier,
3276
+					$query_param_type
3277
+				);
3278
+				// if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3279
+				// indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3280
+				// extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3281
+				// of array('Registration.TXN_ID'=>23)
3282
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3283
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3284
+					if (! is_array($possibly_array_of_params)) {
3285
+						throw new EE_Error(sprintf(
3286
+							esc_html__(
3287
+								"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'))",
3288
+								"event_espresso"
3289
+							),
3290
+							$param,
3291
+							$possibly_array_of_params
3292
+						));
3293
+					}
3294
+					$this->_extract_related_models_from_sub_params_array_keys(
3295
+						$possibly_array_of_params,
3296
+						$model_query_info_carrier,
3297
+						$query_param_type
3298
+					);
3299
+				} elseif (
3300
+					$query_param_type === 0 // ie WHERE
3301
+						  && is_array($possibly_array_of_params)
3302
+						  && isset($possibly_array_of_params[2])
3303
+						  && $possibly_array_of_params[2] == true
3304
+				) {
3305
+					// then $possible_array_of_params looks something like array('<','DTT_sold',true)
3306
+					// indicating that $possible_array_of_params[1] is actually a field name,
3307
+					// from which we should extract query parameters!
3308
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3309
+						throw new EE_Error(sprintf(esc_html__(
3310
+							"Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3311
+							"event_espresso"
3312
+						), $query_param_type, implode(",", $possibly_array_of_params)));
3313
+					}
3314
+					$this->_extract_related_model_info_from_query_param(
3315
+						$possibly_array_of_params[1],
3316
+						$model_query_info_carrier,
3317
+						$query_param_type
3318
+					);
3319
+				}
3320
+			}
3321
+		}
3322
+		return $model_query_info_carrier;
3323
+	}
3324
+
3325
+
3326
+
3327
+	/**
3328
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3329
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3330
+	 *
3331
+	 * @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
3332
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3333
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3334
+	 * @throws EE_Error
3335
+	 * @return \EE_Model_Query_Info_Carrier
3336
+	 */
3337
+	private function _extract_related_models_from_sub_params_array_values(
3338
+		$sub_query_params,
3339
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3340
+		$query_param_type
3341
+	) {
3342
+		if (! empty($sub_query_params)) {
3343
+			if (! is_array($sub_query_params)) {
3344
+				throw new EE_Error(sprintf(
3345
+					esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3346
+					$sub_query_params
3347
+				));
3348
+			}
3349
+			foreach ($sub_query_params as $param) {
3350
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3351
+				$this->_extract_related_model_info_from_query_param(
3352
+					$param,
3353
+					$model_query_info_carrier,
3354
+					$query_param_type
3355
+				);
3356
+			}
3357
+		}
3358
+		return $model_query_info_carrier;
3359
+	}
3360
+
3361
+
3362
+	/**
3363
+	 * Extract all the query parts from  model query params
3364
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3365
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3366
+	 * but use them in a different order. Eg, we need to know what models we are querying
3367
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3368
+	 * other models before we can finalize the where clause SQL.
3369
+	 *
3370
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3371
+	 * @throws EE_Error
3372
+	 * @return EE_Model_Query_Info_Carrier
3373
+	 * @throws ModelConfigurationException
3374
+	 */
3375
+	public function _create_model_query_info_carrier($query_params)
3376
+	{
3377
+		if (! is_array($query_params)) {
3378
+			EE_Error::doing_it_wrong(
3379
+				'EEM_Base::_create_model_query_info_carrier',
3380
+				sprintf(
3381
+					esc_html__(
3382
+						'$query_params should be an array, you passed a variable of type %s',
3383
+						'event_espresso'
3384
+					),
3385
+					gettype($query_params)
3386
+				),
3387
+				'4.6.0'
3388
+			);
3389
+			$query_params = array();
3390
+		}
3391
+		$query_params[0] = isset($query_params[0]) ? $query_params[0] : array();
3392
+		// first check if we should alter the query to account for caps or not
3393
+		// because the caps might require us to do extra joins
3394
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3395
+			$query_params[0] = array_replace_recursive(
3396
+				$query_params[0],
3397
+				$this->caps_where_conditions(
3398
+					$query_params['caps']
3399
+				)
3400
+			);
3401
+		}
3402
+
3403
+		// check if we should alter the query to remove data related to protected
3404
+		// custom post types
3405
+		if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3406
+			$where_param_key_for_password = $this->modelChainAndPassword();
3407
+			// only include if related to a cpt where no password has been set
3408
+			$query_params[0]['OR*nopassword'] = array(
3409
+				$where_param_key_for_password => '',
3410
+				$where_param_key_for_password . '*' => array('IS_NULL')
3411
+			);
3412
+		}
3413
+		$query_object = $this->_extract_related_models_from_query($query_params);
3414
+		// verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3415
+		foreach ($query_params[0] as $key => $value) {
3416
+			if (is_int($key)) {
3417
+				throw new EE_Error(
3418
+					sprintf(
3419
+						esc_html__(
3420
+							"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.",
3421
+							"event_espresso"
3422
+						),
3423
+						$key,
3424
+						var_export($value, true),
3425
+						var_export($query_params, true),
3426
+						get_class($this)
3427
+					)
3428
+				);
3429
+			}
3430
+		}
3431
+		if (
3432
+			array_key_exists('default_where_conditions', $query_params)
3433
+			&& ! empty($query_params['default_where_conditions'])
3434
+		) {
3435
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3436
+		} else {
3437
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3438
+		}
3439
+		$query_params[0] = array_merge(
3440
+			$this->_get_default_where_conditions_for_models_in_query(
3441
+				$query_object,
3442
+				$use_default_where_conditions,
3443
+				$query_params[0]
3444
+			),
3445
+			$query_params[0]
3446
+		);
3447
+		$query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3448
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3449
+		// So we need to setup a subquery and use that for the main join.
3450
+		// Note for now this only works on the primary table for the model.
3451
+		// So for instance, you could set the limit array like this:
3452
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3453
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3454
+			$query_object->set_main_model_join_sql(
3455
+				$this->_construct_limit_join_select(
3456
+					$query_params['on_join_limit'][0],
3457
+					$query_params['on_join_limit'][1]
3458
+				)
3459
+			);
3460
+		}
3461
+		// set limit
3462
+		if (array_key_exists('limit', $query_params)) {
3463
+			if (is_array($query_params['limit'])) {
3464
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3465
+					$e = sprintf(
3466
+						esc_html__(
3467
+							"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)",
3468
+							"event_espresso"
3469
+						),
3470
+						http_build_query($query_params['limit'])
3471
+					);
3472
+					throw new EE_Error($e . "|" . $e);
3473
+				}
3474
+				// they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3475
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3476
+			} elseif (! empty($query_params['limit'])) {
3477
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3478
+			}
3479
+		}
3480
+		// set order by
3481
+		if (array_key_exists('order_by', $query_params)) {
3482
+			if (is_array($query_params['order_by'])) {
3483
+				// if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3484
+				// specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3485
+				// including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3486
+				if (array_key_exists('order', $query_params)) {
3487
+					throw new EE_Error(
3488
+						sprintf(
3489
+							esc_html__(
3490
+								"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 ",
3491
+								"event_espresso"
3492
+							),
3493
+							get_class($this),
3494
+							implode(", ", array_keys($query_params['order_by'])),
3495
+							implode(", ", $query_params['order_by']),
3496
+							$query_params['order']
3497
+						)
3498
+					);
3499
+				}
3500
+				$this->_extract_related_models_from_sub_params_array_keys(
3501
+					$query_params['order_by'],
3502
+					$query_object,
3503
+					'order_by'
3504
+				);
3505
+				// assume it's an array of fields to order by
3506
+				$order_array = array();
3507
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3508
+					$order = $this->_extract_order($order);
3509
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3510
+				}
3511
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3512
+			} elseif (! empty($query_params['order_by'])) {
3513
+				$this->_extract_related_model_info_from_query_param(
3514
+					$query_params['order_by'],
3515
+					$query_object,
3516
+					'order',
3517
+					$query_params['order_by']
3518
+				);
3519
+				$order = isset($query_params['order'])
3520
+					? $this->_extract_order($query_params['order'])
3521
+					: 'DESC';
3522
+				$query_object->set_order_by_sql(
3523
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3524
+				);
3525
+			}
3526
+		}
3527
+		// if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3528
+		if (
3529
+			! array_key_exists('order_by', $query_params)
3530
+			&& array_key_exists('order', $query_params)
3531
+			&& ! empty($query_params['order'])
3532
+		) {
3533
+			$pk_field = $this->get_primary_key_field();
3534
+			$order = $this->_extract_order($query_params['order']);
3535
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3536
+		}
3537
+		// set group by
3538
+		if (array_key_exists('group_by', $query_params)) {
3539
+			if (is_array($query_params['group_by'])) {
3540
+				// it's an array, so assume we'll be grouping by a bunch of stuff
3541
+				$group_by_array = array();
3542
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3543
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3544
+				}
3545
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3546
+			} elseif (! empty($query_params['group_by'])) {
3547
+				$query_object->set_group_by_sql(
3548
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3549
+				);
3550
+			}
3551
+		}
3552
+		// set having
3553
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3554
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3555
+		}
3556
+		// now, just verify they didn't pass anything wack
3557
+		foreach ($query_params as $query_key => $query_value) {
3558
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3559
+				throw new EE_Error(
3560
+					sprintf(
3561
+						esc_html__(
3562
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3563
+							'event_espresso'
3564
+						),
3565
+						$query_key,
3566
+						get_class($this),
3567
+						//                      print_r( $this->_allowed_query_params, TRUE )
3568
+						implode(',', $this->_allowed_query_params)
3569
+					)
3570
+				);
3571
+			}
3572
+		}
3573
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3574
+		if (empty($main_model_join_sql)) {
3575
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3576
+		}
3577
+		return $query_object;
3578
+	}
3579
+
3580
+
3581
+
3582
+	/**
3583
+	 * Gets the where conditions that should be imposed on the query based on the
3584
+	 * context (eg reading frontend, backend, edit or delete).
3585
+	 *
3586
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3587
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3588
+	 * @throws EE_Error
3589
+	 */
3590
+	public function caps_where_conditions($context = self::caps_read)
3591
+	{
3592
+		EEM_Base::verify_is_valid_cap_context($context);
3593
+		$cap_where_conditions = array();
3594
+		$cap_restrictions = $this->caps_missing($context);
3595
+		/**
3596
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3597
+		 */
3598
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3599
+			$cap_where_conditions = array_replace_recursive(
3600
+				$cap_where_conditions,
3601
+				$restriction_if_no_cap->get_default_where_conditions()
3602
+			);
3603
+		}
3604
+		return apply_filters(
3605
+			'FHEE__EEM_Base__caps_where_conditions__return',
3606
+			$cap_where_conditions,
3607
+			$this,
3608
+			$context,
3609
+			$cap_restrictions
3610
+		);
3611
+	}
3612
+
3613
+
3614
+
3615
+	/**
3616
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3617
+	 * otherwise throws an exception
3618
+	 *
3619
+	 * @param string $should_be_order_string
3620
+	 * @return string either ASC, asc, DESC or desc
3621
+	 * @throws EE_Error
3622
+	 */
3623
+	private function _extract_order($should_be_order_string)
3624
+	{
3625
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3626
+			return $should_be_order_string;
3627
+		}
3628
+		throw new EE_Error(
3629
+			sprintf(
3630
+				esc_html__(
3631
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3632
+					"event_espresso"
3633
+				),
3634
+				get_class($this),
3635
+				$should_be_order_string
3636
+			)
3637
+		);
3638
+	}
3639
+
3640
+
3641
+
3642
+	/**
3643
+	 * Looks at all the models which are included in this query, and asks each
3644
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3645
+	 * so they can be merged
3646
+	 *
3647
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3648
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3649
+	 *                                                                  'none' means NO default where conditions will
3650
+	 *                                                                  be used AT ALL during this query.
3651
+	 *                                                                  'other_models_only' means default where
3652
+	 *                                                                  conditions from other models will be used, but
3653
+	 *                                                                  not for this primary model. 'all', the default,
3654
+	 *                                                                  means default where conditions will apply as
3655
+	 *                                                                  normal
3656
+	 * @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
3657
+	 * @throws EE_Error
3658
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3659
+	 */
3660
+	private function _get_default_where_conditions_for_models_in_query(
3661
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3662
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3663
+		$where_query_params = array()
3664
+	) {
3665
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3666
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3667
+			throw new EE_Error(sprintf(
3668
+				esc_html__(
3669
+					"You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3670
+					"event_espresso"
3671
+				),
3672
+				$use_default_where_conditions,
3673
+				implode(", ", $allowed_used_default_where_conditions_values)
3674
+			));
3675
+		}
3676
+		$universal_query_params = array();
3677
+		if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3678
+			$universal_query_params = $this->_get_default_where_conditions();
3679
+		} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3680
+			$universal_query_params = $this->_get_minimum_where_conditions();
3681
+		}
3682
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3683
+			$related_model = $this->get_related_model_obj($model_name);
3684
+			if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3685
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3686
+			} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3687
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3688
+			} else {
3689
+				// we don't want to add full or even minimum default where conditions from this model, so just continue
3690
+				continue;
3691
+			}
3692
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3693
+				$related_model_universal_where_params,
3694
+				$where_query_params,
3695
+				$related_model,
3696
+				$model_relation_path
3697
+			);
3698
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3699
+				$universal_query_params,
3700
+				$overrides
3701
+			);
3702
+		}
3703
+		return $universal_query_params;
3704
+	}
3705
+
3706
+
3707
+
3708
+	/**
3709
+	 * Determines whether or not we should use default where conditions for the model in question
3710
+	 * (this model, or other related models).
3711
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3712
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3713
+	 * We should use default where conditions on related models when they requested to use default where conditions
3714
+	 * on all models, or specifically just on other related models
3715
+	 * @param      $default_where_conditions_value
3716
+	 * @param bool $for_this_model false means this is for OTHER related models
3717
+	 * @return bool
3718
+	 */
3719
+	private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3720
+	{
3721
+		return (
3722
+				   $for_this_model
3723
+				   && in_array(
3724
+					   $default_where_conditions_value,
3725
+					   array(
3726
+						   EEM_Base::default_where_conditions_all,
3727
+						   EEM_Base::default_where_conditions_this_only,
3728
+						   EEM_Base::default_where_conditions_minimum_others,
3729
+					   ),
3730
+					   true
3731
+				   )
3732
+			   )
3733
+			   || (
3734
+				   ! $for_this_model
3735
+				   && in_array(
3736
+					   $default_where_conditions_value,
3737
+					   array(
3738
+						   EEM_Base::default_where_conditions_all,
3739
+						   EEM_Base::default_where_conditions_others_only,
3740
+					   ),
3741
+					   true
3742
+				   )
3743
+			   );
3744
+	}
3745
+
3746
+	/**
3747
+	 * Determines whether or not we should use default minimum conditions for the model in question
3748
+	 * (this model, or other related models).
3749
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3750
+	 * where conditions.
3751
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3752
+	 * on this model or others
3753
+	 * @param      $default_where_conditions_value
3754
+	 * @param bool $for_this_model false means this is for OTHER related models
3755
+	 * @return bool
3756
+	 */
3757
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3758
+	{
3759
+		return (
3760
+				   $for_this_model
3761
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3762
+			   )
3763
+			   || (
3764
+				   ! $for_this_model
3765
+				   && in_array(
3766
+					   $default_where_conditions_value,
3767
+					   array(
3768
+						   EEM_Base::default_where_conditions_minimum_others,
3769
+						   EEM_Base::default_where_conditions_minimum_all,
3770
+					   ),
3771
+					   true
3772
+				   )
3773
+			   );
3774
+	}
3775
+
3776
+
3777
+	/**
3778
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3779
+	 * then we also add a special where condition which allows for that model's primary key
3780
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3781
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3782
+	 *
3783
+	 * @param array    $default_where_conditions
3784
+	 * @param array    $provided_where_conditions
3785
+	 * @param EEM_Base $model
3786
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3787
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3788
+	 * @throws EE_Error
3789
+	 */
3790
+	private function _override_defaults_or_make_null_friendly(
3791
+		$default_where_conditions,
3792
+		$provided_where_conditions,
3793
+		$model,
3794
+		$model_relation_path
3795
+	) {
3796
+		$null_friendly_where_conditions = array();
3797
+		$none_overridden = true;
3798
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3799
+		foreach ($default_where_conditions as $key => $val) {
3800
+			if (isset($provided_where_conditions[ $key ])) {
3801
+				$none_overridden = false;
3802
+			} else {
3803
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3804
+			}
3805
+		}
3806
+		if ($none_overridden && $default_where_conditions) {
3807
+			if ($model->has_primary_key_field()) {
3808
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3809
+																				. "."
3810
+																				. $model->primary_key_name() ] = array('IS NULL');
3811
+			}/*else{
3812 3812
                 //@todo NO PK, use other defaults
3813 3813
             }*/
3814
-        }
3815
-        return $null_friendly_where_conditions;
3816
-    }
3817
-
3818
-
3819
-
3820
-    /**
3821
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3822
-     * default where conditions on all get_all, update, and delete queries done by this model.
3823
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3824
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3825
-     *
3826
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3827
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3828
-     */
3829
-    private function _get_default_where_conditions($model_relation_path = null)
3830
-    {
3831
-        if ($this->_ignore_where_strategy) {
3832
-            return array();
3833
-        }
3834
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3835
-    }
3836
-
3837
-
3838
-
3839
-    /**
3840
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3841
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3842
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3843
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3844
-     * Similar to _get_default_where_conditions
3845
-     *
3846
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3847
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3848
-     */
3849
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3850
-    {
3851
-        if ($this->_ignore_where_strategy) {
3852
-            return array();
3853
-        }
3854
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3855
-    }
3856
-
3857
-
3858
-
3859
-    /**
3860
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3861
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3862
-     *
3863
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3864
-     * @return string
3865
-     * @throws EE_Error
3866
-     */
3867
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3868
-    {
3869
-        $selects = $this->_get_columns_to_select_for_this_model();
3870
-        foreach (
3871
-            $model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included
3872
-        ) {
3873
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3874
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3875
-            foreach ($other_model_selects as $key => $value) {
3876
-                $selects[] = $value;
3877
-            }
3878
-        }
3879
-        return implode(", ", $selects);
3880
-    }
3881
-
3882
-
3883
-
3884
-    /**
3885
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3886
-     * So that's going to be the columns for all the fields on the model
3887
-     *
3888
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3889
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3890
-     */
3891
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3892
-    {
3893
-        $fields = $this->field_settings();
3894
-        $selects = array();
3895
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3896
-            $model_relation_chain,
3897
-            $this->get_this_model_name()
3898
-        );
3899
-        foreach ($fields as $field_obj) {
3900
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3901
-                         . $field_obj->get_table_alias()
3902
-                         . "."
3903
-                         . $field_obj->get_table_column()
3904
-                         . " AS '"
3905
-                         . $table_alias_with_model_relation_chain_prefix
3906
-                         . $field_obj->get_table_alias()
3907
-                         . "."
3908
-                         . $field_obj->get_table_column()
3909
-                         . "'";
3910
-        }
3911
-        // make sure we are also getting the PKs of each table
3912
-        $tables = $this->get_tables();
3913
-        if (count($tables) > 1) {
3914
-            foreach ($tables as $table_obj) {
3915
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3916
-                                       . $table_obj->get_fully_qualified_pk_column();
3917
-                if (! in_array($qualified_pk_column, $selects)) {
3918
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3919
-                }
3920
-            }
3921
-        }
3922
-        return $selects;
3923
-    }
3924
-
3925
-
3926
-
3927
-    /**
3928
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3929
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3930
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3931
-     * SQL for joining, and the data types
3932
-     *
3933
-     * @param null|string                 $original_query_param
3934
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3935
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3936
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3937
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3938
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3939
-     *                                                          or 'Registration's
3940
-     * @param string                      $original_query_param what it originally was (eg
3941
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3942
-     *                                                          matches $query_param
3943
-     * @throws EE_Error
3944
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3945
-     */
3946
-    private function _extract_related_model_info_from_query_param(
3947
-        $query_param,
3948
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3949
-        $query_param_type,
3950
-        $original_query_param = null
3951
-    ) {
3952
-        if ($original_query_param === null) {
3953
-            $original_query_param = $query_param;
3954
-        }
3955
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3956
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3957
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
3958
-        $allow_fields = in_array(
3959
-            $query_param_type,
3960
-            array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
3961
-            true
3962
-        );
3963
-        // check to see if we have a field on this model
3964
-        $this_model_fields = $this->field_settings(true);
3965
-        if (array_key_exists($query_param, $this_model_fields)) {
3966
-            if ($allow_fields) {
3967
-                return;
3968
-            }
3969
-            throw new EE_Error(
3970
-                sprintf(
3971
-                    esc_html__(
3972
-                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3973
-                        "event_espresso"
3974
-                    ),
3975
-                    $query_param,
3976
-                    get_class($this),
3977
-                    $query_param_type,
3978
-                    $original_query_param
3979
-                )
3980
-            );
3981
-        }
3982
-        // check if this is a special logic query param
3983
-        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3984
-            if ($allow_logic_query_params) {
3985
-                return;
3986
-            }
3987
-            throw new EE_Error(
3988
-                sprintf(
3989
-                    esc_html__(
3990
-                        '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',
3991
-                        'event_espresso'
3992
-                    ),
3993
-                    implode('", "', $this->_logic_query_param_keys),
3994
-                    $query_param,
3995
-                    get_class($this),
3996
-                    '<br />',
3997
-                    "\t"
3998
-                    . ' $passed_in_query_info = <pre>'
3999
-                    . print_r($passed_in_query_info, true)
4000
-                    . '</pre>'
4001
-                    . "\n\t"
4002
-                    . ' $query_param_type = '
4003
-                    . $query_param_type
4004
-                    . "\n\t"
4005
-                    . ' $original_query_param = '
4006
-                    . $original_query_param
4007
-                )
4008
-            );
4009
-        }
4010
-        // check if it's a custom selection
4011
-        if (
4012
-            $this->_custom_selections instanceof CustomSelects
4013
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4014
-        ) {
4015
-            return;
4016
-        }
4017
-        // check if has a model name at the beginning
4018
-        // and
4019
-        // check if it's a field on a related model
4020
-        if (
4021
-            $this->extractJoinModelFromQueryParams(
4022
-                $passed_in_query_info,
4023
-                $query_param,
4024
-                $original_query_param,
4025
-                $query_param_type
4026
-            )
4027
-        ) {
4028
-            return;
4029
-        }
4030
-
4031
-        // ok so $query_param didn't start with a model name
4032
-        // and we previously confirmed it wasn't a logic query param or field on the current model
4033
-        // it's wack, that's what it is
4034
-        throw new EE_Error(
4035
-            sprintf(
4036
-                esc_html__(
4037
-                    "There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4038
-                    "event_espresso"
4039
-                ),
4040
-                $query_param,
4041
-                get_class($this),
4042
-                $query_param_type,
4043
-                $original_query_param
4044
-            )
4045
-        );
4046
-    }
4047
-
4048
-
4049
-    /**
4050
-     * Extracts any possible join model information from the provided possible_join_string.
4051
-     * This method will read the provided $possible_join_string value and determine if there are any possible model join
4052
-     * parts that should be added to the query.
4053
-     *
4054
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4055
-     * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4056
-     * @param null|string                 $original_query_param
4057
-     * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4058
-     *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
4059
-     * @return bool  returns true if a join was added and false if not.
4060
-     * @throws EE_Error
4061
-     */
4062
-    private function extractJoinModelFromQueryParams(
4063
-        EE_Model_Query_Info_Carrier $query_info_carrier,
4064
-        $possible_join_string,
4065
-        $original_query_param,
4066
-        $query_parameter_type
4067
-    ) {
4068
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4069
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4070
-                $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4071
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4072
-                if ($possible_join_string === '') {
4073
-                    // nothing left to $query_param
4074
-                    // we should actually end in a field name, not a model like this!
4075
-                    throw new EE_Error(
4076
-                        sprintf(
4077
-                            esc_html__(
4078
-                                "Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4079
-                                "event_espresso"
4080
-                            ),
4081
-                            $possible_join_string,
4082
-                            $query_parameter_type,
4083
-                            get_class($this),
4084
-                            $valid_related_model_name
4085
-                        )
4086
-                    );
4087
-                }
4088
-                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4089
-                $related_model_obj->_extract_related_model_info_from_query_param(
4090
-                    $possible_join_string,
4091
-                    $query_info_carrier,
4092
-                    $query_parameter_type,
4093
-                    $original_query_param
4094
-                );
4095
-                return true;
4096
-            }
4097
-            if ($possible_join_string === $valid_related_model_name) {
4098
-                $this->_add_join_to_model(
4099
-                    $valid_related_model_name,
4100
-                    $query_info_carrier,
4101
-                    $original_query_param
4102
-                );
4103
-                return true;
4104
-            }
4105
-        }
4106
-        return false;
4107
-    }
4108
-
4109
-
4110
-    /**
4111
-     * Extracts related models from Custom Selects and sets up any joins for those related models.
4112
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4113
-     * @throws EE_Error
4114
-     */
4115
-    private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4116
-    {
4117
-        if (
4118
-            $this->_custom_selections instanceof CustomSelects
4119
-            && ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4120
-                || $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4121
-            )
4122
-        ) {
4123
-            $original_selects = $this->_custom_selections->originalSelects();
4124
-            foreach ($original_selects as $alias => $select_configuration) {
4125
-                $this->extractJoinModelFromQueryParams(
4126
-                    $query_info_carrier,
4127
-                    $select_configuration[0],
4128
-                    $select_configuration[0],
4129
-                    'custom_selects'
4130
-                );
4131
-            }
4132
-        }
4133
-    }
4134
-
4135
-
4136
-
4137
-    /**
4138
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4139
-     * and store it on $passed_in_query_info
4140
-     *
4141
-     * @param string                      $model_name
4142
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4143
-     * @param string                      $original_query_param used to extract the relation chain between the queried
4144
-     *                                                          model and $model_name. Eg, if we are querying Event,
4145
-     *                                                          and are adding a join to 'Payment' with the original
4146
-     *                                                          query param key
4147
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4148
-     *                                                          to extract 'Registration.Transaction.Payment', in case
4149
-     *                                                          Payment wants to add default query params so that it
4150
-     *                                                          will know what models to prepend onto its default query
4151
-     *                                                          params or in case it wants to rename tables (in case
4152
-     *                                                          there are multiple joins to the same table)
4153
-     * @return void
4154
-     * @throws EE_Error
4155
-     */
4156
-    private function _add_join_to_model(
4157
-        $model_name,
4158
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4159
-        $original_query_param
4160
-    ) {
4161
-        $relation_obj = $this->related_settings_for($model_name);
4162
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4163
-        // check if the relation is HABTM, because then we're essentially doing two joins
4164
-        // If so, join first to the JOIN table, and add its data types, and then continue as normal
4165
-        if ($relation_obj instanceof EE_HABTM_Relation) {
4166
-            $join_model_obj = $relation_obj->get_join_model();
4167
-            // replace the model specified with the join model for this relation chain, whi
4168
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4169
-                $model_name,
4170
-                $join_model_obj->get_this_model_name(),
4171
-                $model_relation_chain
4172
-            );
4173
-            $passed_in_query_info->merge(
4174
-                new EE_Model_Query_Info_Carrier(
4175
-                    array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4176
-                    $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4177
-                )
4178
-            );
4179
-        }
4180
-        // now just join to the other table pointed to by the relation object, and add its data types
4181
-        $passed_in_query_info->merge(
4182
-            new EE_Model_Query_Info_Carrier(
4183
-                array($model_relation_chain => $model_name),
4184
-                $relation_obj->get_join_statement($model_relation_chain)
4185
-            )
4186
-        );
4187
-    }
4188
-
4189
-
4190
-
4191
-    /**
4192
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4193
-     *
4194
-     * @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
4195
-     * @return string of SQL
4196
-     * @throws EE_Error
4197
-     */
4198
-    private function _construct_where_clause($where_params)
4199
-    {
4200
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4201
-        if ($SQL) {
4202
-            return " WHERE " . $SQL;
4203
-        }
4204
-        return '';
4205
-    }
4206
-
4207
-
4208
-
4209
-    /**
4210
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4211
-     * and should be passed HAVING parameters, not WHERE parameters
4212
-     *
4213
-     * @param array $having_params
4214
-     * @return string
4215
-     * @throws EE_Error
4216
-     */
4217
-    private function _construct_having_clause($having_params)
4218
-    {
4219
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4220
-        if ($SQL) {
4221
-            return " HAVING " . $SQL;
4222
-        }
4223
-        return '';
4224
-    }
4225
-
4226
-
4227
-    /**
4228
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4229
-     * Event_Meta.meta_value = 'foo'))"
4230
-     *
4231
-     * @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
4232
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4233
-     * @throws EE_Error
4234
-     * @return string of SQL
4235
-     */
4236
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4237
-    {
4238
-        $where_clauses = array();
4239
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4240
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4241
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
4242
-                switch ($query_param) {
4243
-                    case 'not':
4244
-                    case 'NOT':
4245
-                        $where_clauses[] = "! ("
4246
-                                           . $this->_construct_condition_clause_recursive(
4247
-                                               $op_and_value_or_sub_condition,
4248
-                                               $glue
4249
-                                           )
4250
-                                           . ")";
4251
-                        break;
4252
-                    case 'and':
4253
-                    case 'AND':
4254
-                        $where_clauses[] = " ("
4255
-                                           . $this->_construct_condition_clause_recursive(
4256
-                                               $op_and_value_or_sub_condition,
4257
-                                               ' AND '
4258
-                                           )
4259
-                                           . ")";
4260
-                        break;
4261
-                    case 'or':
4262
-                    case 'OR':
4263
-                        $where_clauses[] = " ("
4264
-                                           . $this->_construct_condition_clause_recursive(
4265
-                                               $op_and_value_or_sub_condition,
4266
-                                               ' OR '
4267
-                                           )
4268
-                                           . ")";
4269
-                        break;
4270
-                }
4271
-            } else {
4272
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4273
-                // if it's not a normal field, maybe it's a custom selection?
4274
-                if (! $field_obj) {
4275
-                    if ($this->_custom_selections instanceof CustomSelects) {
4276
-                        $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4277
-                    } else {
4278
-                        throw new EE_Error(sprintf(esc_html__(
4279
-                            "%s is neither a valid model field name, nor a custom selection",
4280
-                            "event_espresso"
4281
-                        ), $query_param));
4282
-                    }
4283
-                }
4284
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4285
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4286
-            }
4287
-        }
4288
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4289
-    }
4290
-
4291
-
4292
-
4293
-    /**
4294
-     * Takes the input parameter and extract the table name (alias) and column name
4295
-     *
4296
-     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4297
-     * @throws EE_Error
4298
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4299
-     */
4300
-    private function _deduce_column_name_from_query_param($query_param)
4301
-    {
4302
-        $field = $this->_deduce_field_from_query_param($query_param);
4303
-        if ($field) {
4304
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4305
-                $field->get_model_name(),
4306
-                $query_param
4307
-            );
4308
-            return $table_alias_prefix . $field->get_qualified_column();
4309
-        }
4310
-        if (
4311
-            $this->_custom_selections instanceof CustomSelects
4312
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4313
-        ) {
4314
-            // maybe it's custom selection item?
4315
-            // if so, just use it as the "column name"
4316
-            return $query_param;
4317
-        }
4318
-        $custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4319
-            ? implode(',', $this->_custom_selections->columnAliases())
4320
-            : '';
4321
-        throw new EE_Error(
4322
-            sprintf(
4323
-                esc_html__(
4324
-                    "%s is not a valid field on this model, nor a custom selection (%s)",
4325
-                    "event_espresso"
4326
-                ),
4327
-                $query_param,
4328
-                $custom_select_aliases
4329
-            )
4330
-        );
4331
-    }
4332
-
4333
-
4334
-
4335
-    /**
4336
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4337
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4338
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4339
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4340
-     *
4341
-     * @param string $condition_query_param_key
4342
-     * @return string
4343
-     */
4344
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4345
-    {
4346
-        $pos_of_star = strpos($condition_query_param_key, '*');
4347
-        if ($pos_of_star === false) {
4348
-            return $condition_query_param_key;
4349
-        }
4350
-        $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4351
-        return $condition_query_param_sans_star;
4352
-    }
4353
-
4354
-
4355
-
4356
-    /**
4357
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4358
-     *
4359
-     * @param                            mixed      array | string    $op_and_value
4360
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4361
-     * @throws EE_Error
4362
-     * @return string
4363
-     */
4364
-    private function _construct_op_and_value($op_and_value, $field_obj)
4365
-    {
4366
-        if (is_array($op_and_value)) {
4367
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4368
-            if (! $operator) {
4369
-                $php_array_like_string = array();
4370
-                foreach ($op_and_value as $key => $value) {
4371
-                    $php_array_like_string[] = "$key=>$value";
4372
-                }
4373
-                throw new EE_Error(
4374
-                    sprintf(
4375
-                        esc_html__(
4376
-                            "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))",
4377
-                            "event_espresso"
4378
-                        ),
4379
-                        implode(",", $php_array_like_string)
4380
-                    )
4381
-                );
4382
-            }
4383
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4384
-        } else {
4385
-            $operator = '=';
4386
-            $value = $op_and_value;
4387
-        }
4388
-        // check to see if the value is actually another field
4389
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4390
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4391
-        }
4392
-        if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4393
-            // in this case, the value should be an array, or at least a comma-separated list
4394
-            // it will need to handle a little differently
4395
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4396
-            // note: $cleaned_value has already been run through $wpdb->prepare()
4397
-            return $operator . SP . $cleaned_value;
4398
-        }
4399
-        if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4400
-            // the value should be an array with count of two.
4401
-            if (count($value) !== 2) {
4402
-                throw new EE_Error(
4403
-                    sprintf(
4404
-                        esc_html__(
4405
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4406
-                            'event_espresso'
4407
-                        ),
4408
-                        "BETWEEN"
4409
-                    )
4410
-                );
4411
-            }
4412
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4413
-            return $operator . SP . $cleaned_value;
4414
-        }
4415
-        if (in_array($operator, $this->valid_null_style_operators())) {
4416
-            if ($value !== null) {
4417
-                throw new EE_Error(
4418
-                    sprintf(
4419
-                        esc_html__(
4420
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4421
-                            "event_espresso"
4422
-                        ),
4423
-                        $value,
4424
-                        $operator
4425
-                    )
4426
-                );
4427
-            }
4428
-            return $operator;
4429
-        }
4430
-        if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4431
-            // if the operator is 'LIKE', we want to allow percent signs (%) and not
4432
-            // remove other junk. So just treat it as a string.
4433
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4434
-        }
4435
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4436
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4437
-        }
4438
-        if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4439
-            throw new EE_Error(
4440
-                sprintf(
4441
-                    esc_html__(
4442
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4443
-                        'event_espresso'
4444
-                    ),
4445
-                    $operator,
4446
-                    $operator
4447
-                )
4448
-            );
4449
-        }
4450
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4451
-            throw new EE_Error(
4452
-                sprintf(
4453
-                    esc_html__(
4454
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4455
-                        'event_espresso'
4456
-                    ),
4457
-                    $operator,
4458
-                    $operator
4459
-                )
4460
-            );
4461
-        }
4462
-        throw new EE_Error(
4463
-            sprintf(
4464
-                esc_html__(
4465
-                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4466
-                    "event_espresso"
4467
-                ),
4468
-                http_build_query($op_and_value)
4469
-            )
4470
-        );
4471
-    }
4472
-
4473
-
4474
-
4475
-    /**
4476
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4477
-     *
4478
-     * @param array                      $values
4479
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4480
-     *                                              '%s'
4481
-     * @return string
4482
-     * @throws EE_Error
4483
-     */
4484
-    public function _construct_between_value($values, $field_obj)
4485
-    {
4486
-        $cleaned_values = array();
4487
-        foreach ($values as $value) {
4488
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4489
-        }
4490
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4491
-    }
4492
-
4493
-
4494
-    /**
4495
-     * Takes an array or a comma-separated list of $values and cleans them
4496
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4497
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4498
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4499
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4500
-     *
4501
-     * @param mixed                      $values    array or comma-separated string
4502
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4503
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4504
-     * @throws EE_Error
4505
-     */
4506
-    public function _construct_in_value($values, $field_obj)
4507
-    {
4508
-        $prepped = [];
4509
-        // check if the value is a CSV list
4510
-        if (is_string($values)) {
4511
-            // in which case, turn it into an array
4512
-            $values = explode(',', $values);
4513
-        }
4514
-        // make sure we only have one of each value in the list
4515
-        $values = array_unique($values);
4516
-        foreach ($values as $value) {
4517
-            $prepped[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4518
-        }
4519
-        // we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4520
-        // but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4521
-        // which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4522
-        if (empty($prepped)) {
4523
-            $all_fields = $this->field_settings();
4524
-            $first_field    = reset($all_fields);
4525
-            $main_table = $this->_get_main_table();
4526
-            $prepped[]  = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4527
-        }
4528
-        return '(' . implode(',', $prepped) . ')';
4529
-    }
4530
-
4531
-
4532
-
4533
-    /**
4534
-     * @param mixed                      $value
4535
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4536
-     * @throws EE_Error
4537
-     * @return false|null|string
4538
-     */
4539
-    private function _wpdb_prepare_using_field($value, $field_obj)
4540
-    {
4541
-        /** @type WPDB $wpdb */
4542
-        global $wpdb;
4543
-        if ($field_obj instanceof EE_Model_Field_Base) {
4544
-            return $wpdb->prepare(
4545
-                $field_obj->get_wpdb_data_type(),
4546
-                $this->_prepare_value_for_use_in_db($value, $field_obj)
4547
-            );
4548
-        } //$field_obj should really just be a data type
4549
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4550
-            throw new EE_Error(
4551
-                sprintf(
4552
-                    esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4553
-                    $field_obj,
4554
-                    implode(",", $this->_valid_wpdb_data_types)
4555
-                )
4556
-            );
4557
-        }
4558
-        return $wpdb->prepare($field_obj, $value);
4559
-    }
4560
-
4561
-
4562
-
4563
-    /**
4564
-     * Takes the input parameter and finds the model field that it indicates.
4565
-     *
4566
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4567
-     * @throws EE_Error
4568
-     * @return EE_Model_Field_Base
4569
-     */
4570
-    protected function _deduce_field_from_query_param($query_param_name)
4571
-    {
4572
-        // ok, now proceed with deducing which part is the model's name, and which is the field's name
4573
-        // which will help us find the database table and column
4574
-        $query_param_parts = explode(".", $query_param_name);
4575
-        if (empty($query_param_parts)) {
4576
-            throw new EE_Error(sprintf(esc_html__(
4577
-                "_extract_column_name is empty when trying to extract column and table name from %s",
4578
-                'event_espresso'
4579
-            ), $query_param_name));
4580
-        }
4581
-        $number_of_parts = count($query_param_parts);
4582
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4583
-        if ($number_of_parts === 1) {
4584
-            $field_name = $last_query_param_part;
4585
-            $model_obj = $this;
4586
-        } else {// $number_of_parts >= 2
4587
-            // the last part is the column name, and there are only 2parts. therefore...
4588
-            $field_name = $last_query_param_part;
4589
-            $model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4590
-        }
4591
-        try {
4592
-            return $model_obj->field_settings_for($field_name);
4593
-        } catch (EE_Error $e) {
4594
-            return null;
4595
-        }
4596
-    }
4597
-
4598
-
4599
-
4600
-    /**
4601
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4602
-     * alias and column which corresponds to it
4603
-     *
4604
-     * @param string $field_name
4605
-     * @throws EE_Error
4606
-     * @return string
4607
-     */
4608
-    public function _get_qualified_column_for_field($field_name)
4609
-    {
4610
-        $all_fields = $this->field_settings();
4611
-        $field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4612
-        if ($field) {
4613
-            return $field->get_qualified_column();
4614
-        }
4615
-        throw new EE_Error(
4616
-            sprintf(
4617
-                esc_html__(
4618
-                    "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.",
4619
-                    'event_espresso'
4620
-                ),
4621
-                $field_name,
4622
-                get_class($this)
4623
-            )
4624
-        );
4625
-    }
4626
-
4627
-
4628
-
4629
-    /**
4630
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4631
-     * Example usage:
4632
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4633
-     *      array(),
4634
-     *      ARRAY_A,
4635
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4636
-     *  );
4637
-     * is equivalent to
4638
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4639
-     * and
4640
-     *  EEM_Event::instance()->get_all_wpdb_results(
4641
-     *      array(
4642
-     *          array(
4643
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4644
-     *          ),
4645
-     *          ARRAY_A,
4646
-     *          implode(
4647
-     *              ', ',
4648
-     *              array_merge(
4649
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4650
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4651
-     *              )
4652
-     *          )
4653
-     *      )
4654
-     *  );
4655
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4656
-     *
4657
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4658
-     *                                            and the one whose fields you are selecting for example: when querying
4659
-     *                                            tickets model and selecting fields from the tickets model you would
4660
-     *                                            leave this parameter empty, because no models are needed to join
4661
-     *                                            between the queried model and the selected one. Likewise when
4662
-     *                                            querying the datetime model and selecting fields from the tickets
4663
-     *                                            model, it would also be left empty, because there is a direct
4664
-     *                                            relation from datetimes to tickets, so no model is needed to join
4665
-     *                                            them together. However, when querying from the event model and
4666
-     *                                            selecting fields from the ticket model, you should provide the string
4667
-     *                                            'Datetime', indicating that the event model must first join to the
4668
-     *                                            datetime model in order to find its relation to ticket model.
4669
-     *                                            Also, when querying from the venue model and selecting fields from
4670
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4671
-     *                                            indicating you need to join the venue model to the event model,
4672
-     *                                            to the datetime model, in order to find its relation to the ticket model.
4673
-     *                                            This string is used to deduce the prefix that gets added onto the
4674
-     *                                            models' tables qualified columns
4675
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4676
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4677
-     *                                            qualified column names
4678
-     * @return array|string
4679
-     */
4680
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4681
-    {
4682
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4683
-        $qualified_columns = array();
4684
-        foreach ($this->field_settings() as $field_name => $field) {
4685
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4686
-        }
4687
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4688
-    }
4689
-
4690
-
4691
-
4692
-    /**
4693
-     * constructs the select use on special limit joins
4694
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4695
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4696
-     * (as that is typically where the limits would be set).
4697
-     *
4698
-     * @param  string       $table_alias The table the select is being built for
4699
-     * @param  mixed|string $limit       The limit for this select
4700
-     * @return string                The final select join element for the query.
4701
-     */
4702
-    public function _construct_limit_join_select($table_alias, $limit)
4703
-    {
4704
-        $SQL = '';
4705
-        foreach ($this->_tables as $table_obj) {
4706
-            if ($table_obj instanceof EE_Primary_Table) {
4707
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4708
-                    ? $table_obj->get_select_join_limit($limit)
4709
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4710
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4711
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4712
-                    ? $table_obj->get_select_join_limit_join($limit)
4713
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4714
-            }
4715
-        }
4716
-        return $SQL;
4717
-    }
4718
-
4719
-
4720
-
4721
-    /**
4722
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4723
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4724
-     *
4725
-     * @return string SQL
4726
-     * @throws EE_Error
4727
-     */
4728
-    public function _construct_internal_join()
4729
-    {
4730
-        $SQL = $this->_get_main_table()->get_table_sql();
4731
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4732
-        return $SQL;
4733
-    }
4734
-
4735
-
4736
-
4737
-    /**
4738
-     * Constructs the SQL for joining all the tables on this model.
4739
-     * Normally $alias should be the primary table's alias, but in cases where
4740
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4741
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4742
-     * alias, this will construct SQL like:
4743
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4744
-     * With $alias being a secondary table's alias, this will construct SQL like:
4745
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4746
-     *
4747
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4748
-     * @return string
4749
-     */
4750
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4751
-    {
4752
-        $SQL = '';
4753
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4754
-        foreach ($this->_tables as $table_obj) {
4755
-            if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4756
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4757
-                    // so we're joining to this table, meaning the table is already in
4758
-                    // the FROM statement, BUT the primary table isn't. So we want
4759
-                    // to add the inverse join sql
4760
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4761
-                } else {
4762
-                    // just add a regular JOIN to this table from the primary table
4763
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4764
-                }
4765
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4766
-        }
4767
-        return $SQL;
4768
-    }
4769
-
4770
-
4771
-
4772
-    /**
4773
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4774
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4775
-     * their data type (eg, '%s', '%d', etc)
4776
-     *
4777
-     * @return array
4778
-     */
4779
-    public function _get_data_types()
4780
-    {
4781
-        $data_types = array();
4782
-        foreach ($this->field_settings() as $field_obj) {
4783
-            // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4784
-            /** @var $field_obj EE_Model_Field_Base */
4785
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4786
-        }
4787
-        return $data_types;
4788
-    }
4789
-
4790
-
4791
-
4792
-    /**
4793
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4794
-     *
4795
-     * @param string $model_name
4796
-     * @throws EE_Error
4797
-     * @return EEM_Base
4798
-     */
4799
-    public function get_related_model_obj($model_name)
4800
-    {
4801
-        $model_classname = "EEM_" . $model_name;
4802
-        if (! class_exists($model_classname)) {
4803
-            throw new EE_Error(sprintf(esc_html__(
4804
-                "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4805
-                'event_espresso'
4806
-            ), $model_name, $model_classname));
4807
-        }
4808
-        return call_user_func($model_classname . "::instance");
4809
-    }
4810
-
4811
-
4812
-
4813
-    /**
4814
-     * Returns the array of EE_ModelRelations for this model.
4815
-     *
4816
-     * @return EE_Model_Relation_Base[]
4817
-     */
4818
-    public function relation_settings()
4819
-    {
4820
-        return $this->_model_relations;
4821
-    }
4822
-
4823
-
4824
-
4825
-    /**
4826
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4827
-     * because without THOSE models, this model probably doesn't have much purpose.
4828
-     * (Eg, without an event, datetimes have little purpose.)
4829
-     *
4830
-     * @return EE_Belongs_To_Relation[]
4831
-     */
4832
-    public function belongs_to_relations()
4833
-    {
4834
-        $belongs_to_relations = array();
4835
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4836
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4837
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4838
-            }
4839
-        }
4840
-        return $belongs_to_relations;
4841
-    }
4842
-
4843
-
4844
-
4845
-    /**
4846
-     * Returns the specified EE_Model_Relation, or throws an exception
4847
-     *
4848
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4849
-     * @throws EE_Error
4850
-     * @return EE_Model_Relation_Base
4851
-     */
4852
-    public function related_settings_for($relation_name)
4853
-    {
4854
-        $relatedModels = $this->relation_settings();
4855
-        if (! array_key_exists($relation_name, $relatedModels)) {
4856
-            throw new EE_Error(
4857
-                sprintf(
4858
-                    esc_html__(
4859
-                        'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4860
-                        'event_espresso'
4861
-                    ),
4862
-                    $relation_name,
4863
-                    $this->_get_class_name(),
4864
-                    implode(', ', array_keys($relatedModels))
4865
-                )
4866
-            );
4867
-        }
4868
-        return $relatedModels[ $relation_name ];
4869
-    }
4870
-
4871
-
4872
-
4873
-    /**
4874
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4875
-     * fields
4876
-     *
4877
-     * @param string $fieldName
4878
-     * @param boolean $include_db_only_fields
4879
-     * @throws EE_Error
4880
-     * @return EE_Model_Field_Base
4881
-     */
4882
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
4883
-    {
4884
-        $fieldSettings = $this->field_settings($include_db_only_fields);
4885
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4886
-            throw new EE_Error(sprintf(
4887
-                esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
4888
-                $fieldName,
4889
-                get_class($this)
4890
-            ));
4891
-        }
4892
-        return $fieldSettings[ $fieldName ];
4893
-    }
4894
-
4895
-
4896
-
4897
-    /**
4898
-     * Checks if this field exists on this model
4899
-     *
4900
-     * @param string $fieldName a key in the model's _field_settings array
4901
-     * @return boolean
4902
-     */
4903
-    public function has_field($fieldName)
4904
-    {
4905
-        $fieldSettings = $this->field_settings(true);
4906
-        if (isset($fieldSettings[ $fieldName ])) {
4907
-            return true;
4908
-        }
4909
-        return false;
4910
-    }
4911
-
4912
-
4913
-
4914
-    /**
4915
-     * Returns whether or not this model has a relation to the specified model
4916
-     *
4917
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4918
-     * @return boolean
4919
-     */
4920
-    public function has_relation($relation_name)
4921
-    {
4922
-        $relations = $this->relation_settings();
4923
-        if (isset($relations[ $relation_name ])) {
4924
-            return true;
4925
-        }
4926
-        return false;
4927
-    }
4928
-
4929
-
4930
-
4931
-    /**
4932
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4933
-     * Eg, on EE_Answer that would be ANS_ID field object
4934
-     *
4935
-     * @param $field_obj
4936
-     * @return boolean
4937
-     */
4938
-    public function is_primary_key_field($field_obj)
4939
-    {
4940
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4941
-    }
4942
-
4943
-
4944
-
4945
-    /**
4946
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4947
-     * Eg, on EE_Answer that would be ANS_ID field object
4948
-     *
4949
-     * @return EE_Model_Field_Base
4950
-     * @throws EE_Error
4951
-     */
4952
-    public function get_primary_key_field()
4953
-    {
4954
-        if ($this->_primary_key_field === null) {
4955
-            foreach ($this->field_settings(true) as $field_obj) {
4956
-                if ($this->is_primary_key_field($field_obj)) {
4957
-                    $this->_primary_key_field = $field_obj;
4958
-                    break;
4959
-                }
4960
-            }
4961
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4962
-                throw new EE_Error(sprintf(
4963
-                    esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
4964
-                    get_class($this)
4965
-                ));
4966
-            }
4967
-        }
4968
-        return $this->_primary_key_field;
4969
-    }
4970
-
4971
-
4972
-
4973
-    /**
4974
-     * Returns whether or not not there is a primary key on this model.
4975
-     * Internally does some caching.
4976
-     *
4977
-     * @return boolean
4978
-     */
4979
-    public function has_primary_key_field()
4980
-    {
4981
-        if ($this->_has_primary_key_field === null) {
4982
-            try {
4983
-                $this->get_primary_key_field();
4984
-                $this->_has_primary_key_field = true;
4985
-            } catch (EE_Error $e) {
4986
-                $this->_has_primary_key_field = false;
4987
-            }
4988
-        }
4989
-        return $this->_has_primary_key_field;
4990
-    }
4991
-
4992
-
4993
-
4994
-    /**
4995
-     * Finds the first field of type $field_class_name.
4996
-     *
4997
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4998
-     *                                 EE_Foreign_Key_Field, etc
4999
-     * @return EE_Model_Field_Base or null if none is found
5000
-     */
5001
-    public function get_a_field_of_type($field_class_name)
5002
-    {
5003
-        foreach ($this->field_settings() as $field) {
5004
-            if ($field instanceof $field_class_name) {
5005
-                return $field;
5006
-            }
5007
-        }
5008
-        return null;
5009
-    }
5010
-
5011
-
5012
-
5013
-    /**
5014
-     * Gets a foreign key field pointing to model.
5015
-     *
5016
-     * @param string $model_name eg Event, Registration, not EEM_Event
5017
-     * @return EE_Foreign_Key_Field_Base
5018
-     * @throws EE_Error
5019
-     */
5020
-    public function get_foreign_key_to($model_name)
5021
-    {
5022
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5023
-            foreach ($this->field_settings() as $field) {
5024
-                if (
5025
-                    $field instanceof EE_Foreign_Key_Field_Base
5026
-                    && in_array($model_name, $field->get_model_names_pointed_to())
5027
-                ) {
5028
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5029
-                    break;
5030
-                }
5031
-            }
5032
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5033
-                throw new EE_Error(sprintf(esc_html__(
5034
-                    "There is no foreign key field pointing to model %s on model %s",
5035
-                    'event_espresso'
5036
-                ), $model_name, get_class($this)));
5037
-            }
5038
-        }
5039
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5040
-    }
5041
-
5042
-
5043
-
5044
-    /**
5045
-     * Gets the table name (including $wpdb->prefix) for the table alias
5046
-     *
5047
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5048
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5049
-     *                            Either one works
5050
-     * @return string
5051
-     */
5052
-    public function get_table_for_alias($table_alias)
5053
-    {
5054
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5055
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5056
-    }
5057
-
5058
-
5059
-
5060
-    /**
5061
-     * Returns a flat array of all field son this model, instead of organizing them
5062
-     * by table_alias as they are in the constructor.
5063
-     *
5064
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5065
-     * @return EE_Model_Field_Base[] where the keys are the field's name
5066
-     */
5067
-    public function field_settings($include_db_only_fields = false)
5068
-    {
5069
-        if ($include_db_only_fields) {
5070
-            if ($this->_cached_fields === null) {
5071
-                $this->_cached_fields = array();
5072
-                foreach ($this->_fields as $fields_corresponding_to_table) {
5073
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5074
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5075
-                    }
5076
-                }
5077
-            }
5078
-            return $this->_cached_fields;
5079
-        }
5080
-        if ($this->_cached_fields_non_db_only === null) {
5081
-            $this->_cached_fields_non_db_only = array();
5082
-            foreach ($this->_fields as $fields_corresponding_to_table) {
5083
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5084
-                    /** @var $field_obj EE_Model_Field_Base */
5085
-                    if (! $field_obj->is_db_only_field()) {
5086
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5087
-                    }
5088
-                }
5089
-            }
5090
-        }
5091
-        return $this->_cached_fields_non_db_only;
5092
-    }
5093
-
5094
-
5095
-
5096
-    /**
5097
-     *        cycle though array of attendees and create objects out of each item
5098
-     *
5099
-     * @access        private
5100
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5101
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5102
-     *                           numerically indexed)
5103
-     * @throws EE_Error
5104
-     */
5105
-    protected function _create_objects($rows = array())
5106
-    {
5107
-        $array_of_objects = array();
5108
-        if (empty($rows)) {
5109
-            return array();
5110
-        }
5111
-        $count_if_model_has_no_primary_key = 0;
5112
-        $has_primary_key = $this->has_primary_key_field();
5113
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5114
-        foreach ((array) $rows as $row) {
5115
-            if (empty($row)) {
5116
-                // wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5117
-                return array();
5118
-            }
5119
-            // check if we've already set this object in the results array,
5120
-            // in which case there's no need to process it further (again)
5121
-            if ($has_primary_key) {
5122
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5123
-                    $row,
5124
-                    $primary_key_field->get_qualified_column(),
5125
-                    $primary_key_field->get_table_column()
5126
-                );
5127
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5128
-                    continue;
5129
-                }
5130
-            }
5131
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
5132
-            if (! $classInstance) {
5133
-                throw new EE_Error(
5134
-                    sprintf(
5135
-                        esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
5136
-                        $this->get_this_model_name(),
5137
-                        http_build_query($row)
5138
-                    )
5139
-                );
5140
-            }
5141
-            // set the timezone on the instantiated objects
5142
-            $classInstance->set_timezone($this->_timezone);
5143
-            // make sure if there is any timezone setting present that we set the timezone for the object
5144
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5145
-            $array_of_objects[ $key ] = $classInstance;
5146
-            // also, for all the relations of type BelongsTo, see if we can cache
5147
-            // those related models
5148
-            // (we could do this for other relations too, but if there are conditions
5149
-            // that filtered out some fo the results, then we'd be caching an incomplete set
5150
-            // so it requires a little more thought than just caching them immediately...)
5151
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
5152
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
5153
-                    // check if this model's INFO is present. If so, cache it on the model
5154
-                    $other_model = $relation_obj->get_other_model();
5155
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5156
-                    // if we managed to make a model object from the results, cache it on the main model object
5157
-                    if ($other_model_obj_maybe) {
5158
-                        // set timezone on these other model objects if they are present
5159
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
5160
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
5161
-                    }
5162
-                }
5163
-            }
5164
-            // also, if this was a custom select query, let's see if there are any results for the custom select fields
5165
-            // and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5166
-            // the field in the CustomSelects object
5167
-            if ($this->_custom_selections instanceof CustomSelects) {
5168
-                $classInstance->setCustomSelectsValues(
5169
-                    $this->getValuesForCustomSelectAliasesFromResults($row)
5170
-                );
5171
-            }
5172
-        }
5173
-        return $array_of_objects;
5174
-    }
5175
-
5176
-
5177
-    /**
5178
-     * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5179
-     * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5180
-     *
5181
-     * @param array $db_results_row
5182
-     * @return array
5183
-     */
5184
-    protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5185
-    {
5186
-        $results = array();
5187
-        if ($this->_custom_selections instanceof CustomSelects) {
5188
-            foreach ($this->_custom_selections->columnAliases() as $alias) {
5189
-                if (isset($db_results_row[ $alias ])) {
5190
-                    $results[ $alias ] = $this->convertValueToDataType(
5191
-                        $db_results_row[ $alias ],
5192
-                        $this->_custom_selections->getDataTypeForAlias($alias)
5193
-                    );
5194
-                }
5195
-            }
5196
-        }
5197
-        return $results;
5198
-    }
5199
-
5200
-
5201
-    /**
5202
-     * This will set the value for the given alias
5203
-     * @param string $value
5204
-     * @param string $datatype (one of %d, %s, %f)
5205
-     * @return int|string|float (int for %d, string for %s, float for %f)
5206
-     */
5207
-    protected function convertValueToDataType($value, $datatype)
5208
-    {
5209
-        switch ($datatype) {
5210
-            case '%f':
5211
-                return (float) $value;
5212
-            case '%d':
5213
-                return (int) $value;
5214
-            default:
5215
-                return (string) $value;
5216
-        }
5217
-    }
5218
-
5219
-
5220
-    /**
5221
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5222
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5223
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5224
-     * object (as set in the model_field!).
5225
-     *
5226
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5227
-     */
5228
-    public function create_default_object()
5229
-    {
5230
-        $this_model_fields_and_values = array();
5231
-        // setup the row using default values;
5232
-        foreach ($this->field_settings() as $field_name => $field_obj) {
5233
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5234
-        }
5235
-        $className = $this->_get_class_name();
5236
-        $classInstance = EE_Registry::instance()
5237
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
5238
-        return $classInstance;
5239
-    }
5240
-
5241
-
5242
-
5243
-    /**
5244
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5245
-     *                             or an stdClass where each property is the name of a column,
5246
-     * @return EE_Base_Class
5247
-     * @throws EE_Error
5248
-     */
5249
-    public function instantiate_class_from_array_or_object($cols_n_values)
5250
-    {
5251
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5252
-            $cols_n_values = get_object_vars($cols_n_values);
5253
-        }
5254
-        $primary_key = null;
5255
-        // make sure the array only has keys that are fields/columns on this model
5256
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5257
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5258
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5259
-        }
5260
-        $className = $this->_get_class_name();
5261
-        // check we actually found results that we can use to build our model object
5262
-        // if not, return null
5263
-        if ($this->has_primary_key_field()) {
5264
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5265
-                return null;
5266
-            }
5267
-        } elseif ($this->unique_indexes()) {
5268
-            $first_column = reset($this_model_fields_n_values);
5269
-            if (empty($first_column)) {
5270
-                return null;
5271
-            }
5272
-        }
5273
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5274
-        if ($primary_key) {
5275
-            $classInstance = $this->get_from_entity_map($primary_key);
5276
-            if (! $classInstance) {
5277
-                $classInstance = EE_Registry::instance()
5278
-                                            ->load_class(
5279
-                                                $className,
5280
-                                                array($this_model_fields_n_values, $this->_timezone),
5281
-                                                true,
5282
-                                                false
5283
-                                            );
5284
-                // add this new object to the entity map
5285
-                $classInstance = $this->add_to_entity_map($classInstance);
5286
-            }
5287
-        } else {
5288
-            $classInstance = EE_Registry::instance()
5289
-                                        ->load_class(
5290
-                                            $className,
5291
-                                            array($this_model_fields_n_values, $this->_timezone),
5292
-                                            true,
5293
-                                            false
5294
-                                        );
5295
-        }
5296
-        return $classInstance;
5297
-    }
5298
-
5299
-
5300
-
5301
-    /**
5302
-     * Gets the model object from the  entity map if it exists
5303
-     *
5304
-     * @param int|string $id the ID of the model object
5305
-     * @return EE_Base_Class
5306
-     */
5307
-    public function get_from_entity_map($id)
5308
-    {
5309
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5310
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5311
-    }
5312
-
5313
-
5314
-
5315
-    /**
5316
-     * add_to_entity_map
5317
-     * Adds the object to the model's entity mappings
5318
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5319
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5320
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5321
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5322
-     *        then this method should be called immediately after the update query
5323
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5324
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5325
-     *
5326
-     * @param    EE_Base_Class $object
5327
-     * @throws EE_Error
5328
-     * @return \EE_Base_Class
5329
-     */
5330
-    public function add_to_entity_map(EE_Base_Class $object)
5331
-    {
5332
-        $className = $this->_get_class_name();
5333
-        if (! $object instanceof $className) {
5334
-            throw new EE_Error(sprintf(
5335
-                esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5336
-                is_object($object) ? get_class($object) : $object,
5337
-                $className
5338
-            ));
5339
-        }
5340
-        /** @var $object EE_Base_Class */
5341
-        if (! $object->ID()) {
5342
-            throw new EE_Error(sprintf(esc_html__(
5343
-                "You tried storing a model object with NO ID in the %s entity mapper.",
5344
-                "event_espresso"
5345
-            ), get_class($this)));
5346
-        }
5347
-        // double check it's not already there
5348
-        $classInstance = $this->get_from_entity_map($object->ID());
5349
-        if ($classInstance) {
5350
-            return $classInstance;
5351
-        }
5352
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5353
-        return $object;
5354
-    }
5355
-
5356
-
5357
-
5358
-    /**
5359
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5360
-     * if no identifier is provided, then the entire entity map is emptied
5361
-     *
5362
-     * @param int|string $id the ID of the model object
5363
-     * @return boolean
5364
-     */
5365
-    public function clear_entity_map($id = null)
5366
-    {
5367
-        if (empty($id)) {
5368
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5369
-            return true;
5370
-        }
5371
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5372
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5373
-            return true;
5374
-        }
5375
-        return false;
5376
-    }
5377
-
5378
-
5379
-
5380
-    /**
5381
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5382
-     * Given an array where keys are column (or column alias) names and values,
5383
-     * returns an array of their corresponding field names and database values
5384
-     *
5385
-     * @param array $cols_n_values
5386
-     * @return array
5387
-     */
5388
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5389
-    {
5390
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5391
-    }
5392
-
5393
-
5394
-
5395
-    /**
5396
-     * _deduce_fields_n_values_from_cols_n_values
5397
-     * Given an array where keys are column (or column alias) names and values,
5398
-     * returns an array of their corresponding field names and database values
5399
-     *
5400
-     * @param string $cols_n_values
5401
-     * @return array
5402
-     */
5403
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5404
-    {
5405
-        $this_model_fields_n_values = array();
5406
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5407
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5408
-                $cols_n_values,
5409
-                $table_obj->get_fully_qualified_pk_column(),
5410
-                $table_obj->get_pk_column()
5411
-            );
5412
-            // there is a primary key on this table and its not set. Use defaults for all its columns
5413
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5414
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5415
-                    if (! $field_obj->is_db_only_field()) {
5416
-                        // prepare field as if its coming from db
5417
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5418
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5419
-                    }
5420
-                }
5421
-            } else {
5422
-                // the table's rows existed. Use their values
5423
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5424
-                    if (! $field_obj->is_db_only_field()) {
5425
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5426
-                            $cols_n_values,
5427
-                            $field_obj->get_qualified_column(),
5428
-                            $field_obj->get_table_column()
5429
-                        );
5430
-                    }
5431
-                }
5432
-            }
5433
-        }
5434
-        return $this_model_fields_n_values;
5435
-    }
5436
-
5437
-
5438
-    /**
5439
-     * @param $cols_n_values
5440
-     * @param $qualified_column
5441
-     * @param $regular_column
5442
-     * @return null
5443
-     * @throws EE_Error
5444
-     * @throws ReflectionException
5445
-     */
5446
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5447
-    {
5448
-        $value = null;
5449
-        // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5450
-        // does the field on the model relate to this column retrieved from the db?
5451
-        // or is it a db-only field? (not relating to the model)
5452
-        if (isset($cols_n_values[ $qualified_column ])) {
5453
-            $value = $cols_n_values[ $qualified_column ];
5454
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5455
-            $value = $cols_n_values[ $regular_column ];
5456
-        } elseif (! empty($this->foreign_key_aliases)) {
5457
-            // no PK?  ok check if there is a foreign key alias set for this table
5458
-            // then check if that alias exists in the incoming data
5459
-            // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5460
-            foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5461
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5462
-                    $value = $cols_n_values[ $FK_alias ];
5463
-                    list($pk_class) = explode('.', $PK_column);
5464
-                    $pk_model_name = "EEM_{$pk_class}";
5465
-                    /** @var EEM_Base $pk_model */
5466
-                    $pk_model = EE_Registry::instance()->load_model($pk_model_name);
5467
-                    if ($pk_model instanceof EEM_Base) {
5468
-                        // make sure object is pulled from db and added to entity map
5469
-                        $pk_model->get_one_by_ID($value);
5470
-                    }
5471
-                    break;
5472
-                }
5473
-            }
5474
-        }
5475
-        return $value;
5476
-    }
5477
-
5478
-
5479
-
5480
-    /**
5481
-     * refresh_entity_map_from_db
5482
-     * Makes sure the model object in the entity map at $id assumes the values
5483
-     * of the database (opposite of EE_base_Class::save())
5484
-     *
5485
-     * @param int|string $id
5486
-     * @return EE_Base_Class
5487
-     * @throws EE_Error
5488
-     */
5489
-    public function refresh_entity_map_from_db($id)
5490
-    {
5491
-        $obj_in_map = $this->get_from_entity_map($id);
5492
-        if ($obj_in_map) {
5493
-            $wpdb_results = $this->_get_all_wpdb_results(
5494
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5495
-            );
5496
-            if ($wpdb_results && is_array($wpdb_results)) {
5497
-                $one_row = reset($wpdb_results);
5498
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5499
-                    $obj_in_map->set_from_db($field_name, $db_value);
5500
-                }
5501
-                // clear the cache of related model objects
5502
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5503
-                    $obj_in_map->clear_cache($relation_name, null, true);
5504
-                }
5505
-            }
5506
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5507
-            return $obj_in_map;
5508
-        }
5509
-        return $this->get_one_by_ID($id);
5510
-    }
5511
-
5512
-
5513
-
5514
-    /**
5515
-     * refresh_entity_map_with
5516
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5517
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5518
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5519
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5520
-     *
5521
-     * @param int|string    $id
5522
-     * @param EE_Base_Class $replacing_model_obj
5523
-     * @return \EE_Base_Class
5524
-     * @throws EE_Error
5525
-     */
5526
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5527
-    {
5528
-        $obj_in_map = $this->get_from_entity_map($id);
5529
-        if ($obj_in_map) {
5530
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5531
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5532
-                    $obj_in_map->set($field_name, $value);
5533
-                }
5534
-                // make the model object in the entity map's cache match the $replacing_model_obj
5535
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5536
-                    $obj_in_map->clear_cache($relation_name, null, true);
5537
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5538
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5539
-                    }
5540
-                }
5541
-            }
5542
-            return $obj_in_map;
5543
-        }
5544
-        $this->add_to_entity_map($replacing_model_obj);
5545
-        return $replacing_model_obj;
5546
-    }
5547
-
5548
-
5549
-
5550
-    /**
5551
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5552
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5553
-     * require_once($this->_getClassName().".class.php");
5554
-     *
5555
-     * @return string
5556
-     */
5557
-    private function _get_class_name()
5558
-    {
5559
-        return "EE_" . $this->get_this_model_name();
5560
-    }
5561
-
5562
-
5563
-
5564
-    /**
5565
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5566
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5567
-     * it would be 'Events'.
5568
-     *
5569
-     * @param int $quantity
5570
-     * @return string
5571
-     */
5572
-    public function item_name($quantity = 1)
5573
-    {
5574
-        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5575
-    }
5576
-
5577
-
5578
-
5579
-    /**
5580
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5581
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5582
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5583
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5584
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5585
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5586
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5587
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5588
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5589
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5590
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5591
-     *        return $previousReturnValue.$returnString;
5592
-     * }
5593
-     * require('EEM_Answer.model.php');
5594
-     * $answer=EEM_Answer::instance();
5595
-     * echo $answer->my_callback('monkeys',100);
5596
-     * //will output "you called my_callback! and passed args:monkeys,100"
5597
-     *
5598
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5599
-     * @param array  $args       array of original arguments passed to the function
5600
-     * @throws EE_Error
5601
-     * @return mixed whatever the plugin which calls add_filter decides
5602
-     */
5603
-    public function __call($methodName, $args)
5604
-    {
5605
-        $className = get_class($this);
5606
-        $tagName = "FHEE__{$className}__{$methodName}";
5607
-        if (! has_filter($tagName)) {
5608
-            throw new EE_Error(
5609
-                sprintf(
5610
-                    esc_html__(
5611
-                        '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 );',
5612
-                        'event_espresso'
5613
-                    ),
5614
-                    $methodName,
5615
-                    $className,
5616
-                    $tagName,
5617
-                    '<br />'
5618
-                )
5619
-            );
5620
-        }
5621
-        return apply_filters($tagName, null, $this, $args);
5622
-    }
5623
-
5624
-
5625
-
5626
-    /**
5627
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5628
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5629
-     *
5630
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5631
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5632
-     *                                                       the object's class name
5633
-     *                                                       or object's ID
5634
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5635
-     *                                                       exists in the database. If it does not, we add it
5636
-     * @throws EE_Error
5637
-     * @return EE_Base_Class
5638
-     */
5639
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5640
-    {
5641
-        $className = $this->_get_class_name();
5642
-        if ($base_class_obj_or_id instanceof $className) {
5643
-            $model_object = $base_class_obj_or_id;
5644
-        } else {
5645
-            $primary_key_field = $this->get_primary_key_field();
5646
-            if (
5647
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5648
-                && (
5649
-                    is_int($base_class_obj_or_id)
5650
-                    || is_string($base_class_obj_or_id)
5651
-                )
5652
-            ) {
5653
-                // assume it's an ID.
5654
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5655
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5656
-            } elseif (
5657
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5658
-                && is_string($base_class_obj_or_id)
5659
-            ) {
5660
-                // assume its a string representation of the object
5661
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5662
-            } else {
5663
-                throw new EE_Error(
5664
-                    sprintf(
5665
-                        esc_html__(
5666
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5667
-                            'event_espresso'
5668
-                        ),
5669
-                        $base_class_obj_or_id,
5670
-                        $this->_get_class_name(),
5671
-                        print_r($base_class_obj_or_id, true)
5672
-                    )
5673
-                );
5674
-            }
5675
-        }
5676
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5677
-            $model_object->save();
5678
-        }
5679
-        return $model_object;
5680
-    }
5681
-
5682
-
5683
-
5684
-    /**
5685
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5686
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5687
-     * returns it ID.
5688
-     *
5689
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5690
-     * @return int|string depending on the type of this model object's ID
5691
-     * @throws EE_Error
5692
-     */
5693
-    public function ensure_is_ID($base_class_obj_or_id)
5694
-    {
5695
-        $className = $this->_get_class_name();
5696
-        if ($base_class_obj_or_id instanceof $className) {
5697
-            /** @var $base_class_obj_or_id EE_Base_Class */
5698
-            $id = $base_class_obj_or_id->ID();
5699
-        } elseif (is_int($base_class_obj_or_id)) {
5700
-            // assume it's an ID
5701
-            $id = $base_class_obj_or_id;
5702
-        } elseif (is_string($base_class_obj_or_id)) {
5703
-            // assume its a string representation of the object
5704
-            $id = $base_class_obj_or_id;
5705
-        } else {
5706
-            throw new EE_Error(sprintf(
5707
-                esc_html__(
5708
-                    "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5709
-                    'event_espresso'
5710
-                ),
5711
-                $base_class_obj_or_id,
5712
-                $this->_get_class_name(),
5713
-                print_r($base_class_obj_or_id, true)
5714
-            ));
5715
-        }
5716
-        return $id;
5717
-    }
5718
-
5719
-
5720
-
5721
-    /**
5722
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5723
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5724
-     * been sanitized and converted into the appropriate domain.
5725
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5726
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5727
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5728
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5729
-     * $EVT = EEM_Event::instance(); $old_setting =
5730
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5731
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5732
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5733
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5734
-     *
5735
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5736
-     * @return void
5737
-     */
5738
-    public function assume_values_already_prepared_by_model_object(
5739
-        $values_already_prepared = self::not_prepared_by_model_object
5740
-    ) {
5741
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5742
-    }
5743
-
5744
-
5745
-
5746
-    /**
5747
-     * Read comments for assume_values_already_prepared_by_model_object()
5748
-     *
5749
-     * @return int
5750
-     */
5751
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5752
-    {
5753
-        return $this->_values_already_prepared_by_model_object;
5754
-    }
5755
-
5756
-
5757
-
5758
-    /**
5759
-     * Gets all the indexes on this model
5760
-     *
5761
-     * @return EE_Index[]
5762
-     */
5763
-    public function indexes()
5764
-    {
5765
-        return $this->_indexes;
5766
-    }
5767
-
5768
-
5769
-
5770
-    /**
5771
-     * Gets all the Unique Indexes on this model
5772
-     *
5773
-     * @return EE_Unique_Index[]
5774
-     */
5775
-    public function unique_indexes()
5776
-    {
5777
-        $unique_indexes = array();
5778
-        foreach ($this->_indexes as $name => $index) {
5779
-            if ($index instanceof EE_Unique_Index) {
5780
-                $unique_indexes [ $name ] = $index;
5781
-            }
5782
-        }
5783
-        return $unique_indexes;
5784
-    }
5785
-
5786
-
5787
-
5788
-    /**
5789
-     * Gets all the fields which, when combined, make the primary key.
5790
-     * This is usually just an array with 1 element (the primary key), but in cases
5791
-     * where there is no primary key, it's a combination of fields as defined
5792
-     * on a primary index
5793
-     *
5794
-     * @return EE_Model_Field_Base[] indexed by the field's name
5795
-     * @throws EE_Error
5796
-     */
5797
-    public function get_combined_primary_key_fields()
5798
-    {
5799
-        foreach ($this->indexes() as $index) {
5800
-            if ($index instanceof EE_Primary_Key_Index) {
5801
-                return $index->fields();
5802
-            }
5803
-        }
5804
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5805
-    }
5806
-
5807
-
5808
-
5809
-    /**
5810
-     * Used to build a primary key string (when the model has no primary key),
5811
-     * which can be used a unique string to identify this model object.
5812
-     *
5813
-     * @param array $fields_n_values keys are field names, values are their values.
5814
-     *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5815
-     *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5816
-     *                               before passing it to this function (that will convert it from columns-n-values
5817
-     *                               to field-names-n-values).
5818
-     * @return string
5819
-     * @throws EE_Error
5820
-     */
5821
-    public function get_index_primary_key_string($fields_n_values)
5822
-    {
5823
-        $cols_n_values_for_primary_key_index = array_intersect_key(
5824
-            $fields_n_values,
5825
-            $this->get_combined_primary_key_fields()
5826
-        );
5827
-        return http_build_query($cols_n_values_for_primary_key_index);
5828
-    }
5829
-
5830
-
5831
-
5832
-    /**
5833
-     * Gets the field values from the primary key string
5834
-     *
5835
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5836
-     * @param string $index_primary_key_string
5837
-     * @return null|array
5838
-     * @throws EE_Error
5839
-     */
5840
-    public function parse_index_primary_key_string($index_primary_key_string)
5841
-    {
5842
-        $key_fields = $this->get_combined_primary_key_fields();
5843
-        // check all of them are in the $id
5844
-        $key_vals_in_combined_pk = array();
5845
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5846
-        foreach ($key_fields as $key_field_name => $field_obj) {
5847
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5848
-                return null;
5849
-            }
5850
-        }
5851
-        return $key_vals_in_combined_pk;
5852
-    }
5853
-
5854
-
5855
-
5856
-    /**
5857
-     * verifies that an array of key-value pairs for model fields has a key
5858
-     * for each field comprising the primary key index
5859
-     *
5860
-     * @param array $key_vals
5861
-     * @return boolean
5862
-     * @throws EE_Error
5863
-     */
5864
-    public function has_all_combined_primary_key_fields($key_vals)
5865
-    {
5866
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5867
-        foreach ($keys_it_should_have as $key) {
5868
-            if (! isset($key_vals[ $key ])) {
5869
-                return false;
5870
-            }
5871
-        }
5872
-        return true;
5873
-    }
5874
-
5875
-
5876
-
5877
-    /**
5878
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5879
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5880
-     *
5881
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5882
-     * @param array               $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5883
-     * @throws EE_Error
5884
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5885
-     *                                                              indexed)
5886
-     */
5887
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5888
-    {
5889
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5890
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5891
-        } elseif (is_array($model_object_or_attributes_array)) {
5892
-            $attributes_array = $model_object_or_attributes_array;
5893
-        } else {
5894
-            throw new EE_Error(sprintf(esc_html__(
5895
-                "get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5896
-                "event_espresso"
5897
-            ), $model_object_or_attributes_array));
5898
-        }
5899
-        // even copies obviously won't have the same ID, so remove the primary key
5900
-        // from the WHERE conditions for finding copies (if there is a primary key, of course)
5901
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5902
-            unset($attributes_array[ $this->primary_key_name() ]);
5903
-        }
5904
-        if (isset($query_params[0])) {
5905
-            $query_params[0] = array_merge($attributes_array, $query_params);
5906
-        } else {
5907
-            $query_params[0] = $attributes_array;
5908
-        }
5909
-        return $this->get_all($query_params);
5910
-    }
5911
-
5912
-
5913
-
5914
-    /**
5915
-     * Gets the first copy we find. See get_all_copies for more details
5916
-     *
5917
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5918
-     * @param array $query_params
5919
-     * @return EE_Base_Class
5920
-     * @throws EE_Error
5921
-     */
5922
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5923
-    {
5924
-        if (! is_array($query_params)) {
5925
-            EE_Error::doing_it_wrong(
5926
-                'EEM_Base::get_one_copy',
5927
-                sprintf(
5928
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5929
-                    gettype($query_params)
5930
-                ),
5931
-                '4.6.0'
5932
-            );
5933
-            $query_params = array();
5934
-        }
5935
-        $query_params['limit'] = 1;
5936
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5937
-        if (is_array($copies)) {
5938
-            return array_shift($copies);
5939
-        }
5940
-        return null;
5941
-    }
5942
-
5943
-
5944
-
5945
-    /**
5946
-     * Updates the item with the specified id. Ignores default query parameters because
5947
-     * we have specified the ID, and its assumed we KNOW what we're doing
5948
-     *
5949
-     * @param array      $fields_n_values keys are field names, values are their new values
5950
-     * @param int|string $id              the value of the primary key to update
5951
-     * @return int number of rows updated
5952
-     * @throws EE_Error
5953
-     */
5954
-    public function update_by_ID($fields_n_values, $id)
5955
-    {
5956
-        $query_params = array(
5957
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5958
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5959
-        );
5960
-        return $this->update($fields_n_values, $query_params);
5961
-    }
5962
-
5963
-
5964
-
5965
-    /**
5966
-     * Changes an operator which was supplied to the models into one usable in SQL
5967
-     *
5968
-     * @param string $operator_supplied
5969
-     * @return string an operator which can be used in SQL
5970
-     * @throws EE_Error
5971
-     */
5972
-    private function _prepare_operator_for_sql($operator_supplied)
5973
-    {
5974
-        $sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5975
-            : null;
5976
-        if ($sql_operator) {
5977
-            return $sql_operator;
5978
-        }
5979
-        throw new EE_Error(
5980
-            sprintf(
5981
-                esc_html__(
5982
-                    "The operator '%s' is not in the list of valid operators: %s",
5983
-                    "event_espresso"
5984
-                ),
5985
-                $operator_supplied,
5986
-                implode(",", array_keys($this->_valid_operators))
5987
-            )
5988
-        );
5989
-    }
5990
-
5991
-
5992
-
5993
-    /**
5994
-     * Gets the valid operators
5995
-     * @return array keys are accepted strings, values are the SQL they are converted to
5996
-     */
5997
-    public function valid_operators()
5998
-    {
5999
-        return $this->_valid_operators;
6000
-    }
6001
-
6002
-
6003
-
6004
-    /**
6005
-     * Gets the between-style operators (take 2 arguments).
6006
-     * @return array keys are accepted strings, values are the SQL they are converted to
6007
-     */
6008
-    public function valid_between_style_operators()
6009
-    {
6010
-        return array_intersect(
6011
-            $this->valid_operators(),
6012
-            $this->_between_style_operators
6013
-        );
6014
-    }
6015
-
6016
-    /**
6017
-     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6018
-     * @return array keys are accepted strings, values are the SQL they are converted to
6019
-     */
6020
-    public function valid_like_style_operators()
6021
-    {
6022
-        return array_intersect(
6023
-            $this->valid_operators(),
6024
-            $this->_like_style_operators
6025
-        );
6026
-    }
6027
-
6028
-    /**
6029
-     * Gets the "in"-style operators
6030
-     * @return array keys are accepted strings, values are the SQL they are converted to
6031
-     */
6032
-    public function valid_in_style_operators()
6033
-    {
6034
-        return array_intersect(
6035
-            $this->valid_operators(),
6036
-            $this->_in_style_operators
6037
-        );
6038
-    }
6039
-
6040
-    /**
6041
-     * Gets the "null"-style operators (accept no arguments)
6042
-     * @return array keys are accepted strings, values are the SQL they are converted to
6043
-     */
6044
-    public function valid_null_style_operators()
6045
-    {
6046
-        return array_intersect(
6047
-            $this->valid_operators(),
6048
-            $this->_null_style_operators
6049
-        );
6050
-    }
6051
-
6052
-    /**
6053
-     * Gets an array where keys are the primary keys and values are their 'names'
6054
-     * (as determined by the model object's name() function, which is often overridden)
6055
-     *
6056
-     * @param array $query_params like get_all's
6057
-     * @return string[]
6058
-     * @throws EE_Error
6059
-     */
6060
-    public function get_all_names($query_params = array())
6061
-    {
6062
-        $objs = $this->get_all($query_params);
6063
-        $names = array();
6064
-        foreach ($objs as $obj) {
6065
-            $names[ $obj->ID() ] = $obj->name();
6066
-        }
6067
-        return $names;
6068
-    }
6069
-
6070
-
6071
-
6072
-    /**
6073
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
6074
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6075
-     * this is duplicated effort and reduces efficiency) you would be better to use
6076
-     * array_keys() on $model_objects.
6077
-     *
6078
-     * @param \EE_Base_Class[] $model_objects
6079
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6080
-     *                                               in the returned array
6081
-     * @return array
6082
-     * @throws EE_Error
6083
-     */
6084
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
6085
-    {
6086
-        if (! $this->has_primary_key_field()) {
6087
-            if (WP_DEBUG) {
6088
-                EE_Error::add_error(
6089
-                    esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6090
-                    __FILE__,
6091
-                    __FUNCTION__,
6092
-                    __LINE__
6093
-                );
6094
-            }
6095
-        }
6096
-        $IDs = array();
6097
-        foreach ($model_objects as $model_object) {
6098
-            $id = $model_object->ID();
6099
-            if (! $id) {
6100
-                if ($filter_out_empty_ids) {
6101
-                    continue;
6102
-                }
6103
-                if (WP_DEBUG) {
6104
-                    EE_Error::add_error(
6105
-                        esc_html__(
6106
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6107
-                            'event_espresso'
6108
-                        ),
6109
-                        __FILE__,
6110
-                        __FUNCTION__,
6111
-                        __LINE__
6112
-                    );
6113
-                }
6114
-            }
6115
-            $IDs[] = $id;
6116
-        }
6117
-        return $IDs;
6118
-    }
6119
-
6120
-
6121
-
6122
-    /**
6123
-     * Returns the string used in capabilities relating to this model. If there
6124
-     * are no capabilities that relate to this model returns false
6125
-     *
6126
-     * @return string|false
6127
-     */
6128
-    public function cap_slug()
6129
-    {
6130
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6131
-    }
6132
-
6133
-
6134
-
6135
-    /**
6136
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
6137
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6138
-     * only returns the cap restrictions array in that context (ie, the array
6139
-     * at that key)
6140
-     *
6141
-     * @param string $context
6142
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
6143
-     * @throws EE_Error
6144
-     */
6145
-    public function cap_restrictions($context = EEM_Base::caps_read)
6146
-    {
6147
-        EEM_Base::verify_is_valid_cap_context($context);
6148
-        // check if we ought to run the restriction generator first
6149
-        if (
6150
-            isset($this->_cap_restriction_generators[ $context ])
6151
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6152
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6153
-        ) {
6154
-            $this->_cap_restrictions[ $context ] = array_merge(
6155
-                $this->_cap_restrictions[ $context ],
6156
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6157
-            );
6158
-        }
6159
-        // and make sure we've finalized the construction of each restriction
6160
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6161
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6162
-                $where_conditions_obj->_finalize_construct($this);
6163
-            }
6164
-        }
6165
-        return $this->_cap_restrictions[ $context ];
6166
-    }
6167
-
6168
-
6169
-
6170
-    /**
6171
-     * Indicating whether or not this model thinks its a wp core model
6172
-     *
6173
-     * @return boolean
6174
-     */
6175
-    public function is_wp_core_model()
6176
-    {
6177
-        return $this->_wp_core_model;
6178
-    }
6179
-
6180
-
6181
-
6182
-    /**
6183
-     * Gets all the caps that are missing which impose a restriction on
6184
-     * queries made in this context
6185
-     *
6186
-     * @param string $context one of EEM_Base::caps_ constants
6187
-     * @return EE_Default_Where_Conditions[] indexed by capability name
6188
-     * @throws EE_Error
6189
-     */
6190
-    public function caps_missing($context = EEM_Base::caps_read)
6191
-    {
6192
-        $missing_caps = array();
6193
-        $cap_restrictions = $this->cap_restrictions($context);
6194
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6195
-            if (
6196
-                ! EE_Capabilities::instance()
6197
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6198
-            ) {
6199
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6200
-            }
6201
-        }
6202
-        return $missing_caps;
6203
-    }
6204
-
6205
-
6206
-
6207
-    /**
6208
-     * Gets the mapping from capability contexts to action strings used in capability names
6209
-     *
6210
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6211
-     * one of 'read', 'edit', or 'delete'
6212
-     */
6213
-    public function cap_contexts_to_cap_action_map()
6214
-    {
6215
-        return apply_filters(
6216
-            'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6217
-            $this->_cap_contexts_to_cap_action_map,
6218
-            $this
6219
-        );
6220
-    }
6221
-
6222
-
6223
-
6224
-    /**
6225
-     * Gets the action string for the specified capability context
6226
-     *
6227
-     * @param string $context
6228
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6229
-     * @throws EE_Error
6230
-     */
6231
-    public function cap_action_for_context($context)
6232
-    {
6233
-        $mapping = $this->cap_contexts_to_cap_action_map();
6234
-        if (isset($mapping[ $context ])) {
6235
-            return $mapping[ $context ];
6236
-        }
6237
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6238
-            return $action;
6239
-        }
6240
-        throw new EE_Error(
6241
-            sprintf(
6242
-                esc_html__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6243
-                $context,
6244
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6245
-            )
6246
-        );
6247
-    }
6248
-
6249
-
6250
-
6251
-    /**
6252
-     * Returns all the capability contexts which are valid when querying models
6253
-     *
6254
-     * @return array
6255
-     */
6256
-    public static function valid_cap_contexts()
6257
-    {
6258
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6259
-            self::caps_read,
6260
-            self::caps_read_admin,
6261
-            self::caps_edit,
6262
-            self::caps_delete,
6263
-        ));
6264
-    }
6265
-
6266
-
6267
-
6268
-    /**
6269
-     * Returns all valid options for 'default_where_conditions'
6270
-     *
6271
-     * @return array
6272
-     */
6273
-    public static function valid_default_where_conditions()
6274
-    {
6275
-        return array(
6276
-            EEM_Base::default_where_conditions_all,
6277
-            EEM_Base::default_where_conditions_this_only,
6278
-            EEM_Base::default_where_conditions_others_only,
6279
-            EEM_Base::default_where_conditions_minimum_all,
6280
-            EEM_Base::default_where_conditions_minimum_others,
6281
-            EEM_Base::default_where_conditions_none
6282
-        );
6283
-    }
6284
-
6285
-    // public static function default_where_conditions_full
6286
-    /**
6287
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6288
-     *
6289
-     * @param string $context
6290
-     * @return bool
6291
-     * @throws EE_Error
6292
-     */
6293
-    public static function verify_is_valid_cap_context($context)
6294
-    {
6295
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
6296
-        if (in_array($context, $valid_cap_contexts)) {
6297
-            return true;
6298
-        }
6299
-        throw new EE_Error(
6300
-            sprintf(
6301
-                esc_html__(
6302
-                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6303
-                    'event_espresso'
6304
-                ),
6305
-                $context,
6306
-                'EEM_Base',
6307
-                implode(',', $valid_cap_contexts)
6308
-            )
6309
-        );
6310
-    }
6311
-
6312
-
6313
-
6314
-    /**
6315
-     * Clears all the models field caches. This is only useful when a sub-class
6316
-     * might have added a field or something and these caches might be invalidated
6317
-     */
6318
-    protected function _invalidate_field_caches()
6319
-    {
6320
-        $this->_cache_foreign_key_to_fields = array();
6321
-        $this->_cached_fields = null;
6322
-        $this->_cached_fields_non_db_only = null;
6323
-    }
6324
-
6325
-
6326
-
6327
-    /**
6328
-     * Gets the list of all the where query param keys that relate to logic instead of field names
6329
-     * (eg "and", "or", "not").
6330
-     *
6331
-     * @return array
6332
-     */
6333
-    public function logic_query_param_keys()
6334
-    {
6335
-        return $this->_logic_query_param_keys;
6336
-    }
6337
-
6338
-
6339
-
6340
-    /**
6341
-     * Determines whether or not the where query param array key is for a logic query param.
6342
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6343
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6344
-     *
6345
-     * @param $query_param_key
6346
-     * @return bool
6347
-     */
6348
-    public function is_logic_query_param_key($query_param_key)
6349
-    {
6350
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6351
-            if (
6352
-                $query_param_key === $logic_query_param_key
6353
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6354
-            ) {
6355
-                return true;
6356
-            }
6357
-        }
6358
-        return false;
6359
-    }
6360
-
6361
-    /**
6362
-     * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6363
-     * @since 4.9.74.p
6364
-     * @return boolean
6365
-     */
6366
-    public function hasPassword()
6367
-    {
6368
-        // if we don't yet know if there's a password field, find out and remember it for next time.
6369
-        if ($this->has_password_field === null) {
6370
-            $password_field = $this->getPasswordField();
6371
-            $this->has_password_field = $password_field instanceof EE_Password_Field ? true : false;
6372
-        }
6373
-        return $this->has_password_field;
6374
-    }
6375
-
6376
-    /**
6377
-     * Returns the password field on this model, if there is one
6378
-     * @since 4.9.74.p
6379
-     * @return EE_Password_Field|null
6380
-     */
6381
-    public function getPasswordField()
6382
-    {
6383
-        // if we definetely already know there is a password field or not (because has_password_field is true or false)
6384
-        // there's no need to search for it. If we don't know yet, then find out
6385
-        if ($this->has_password_field === null && $this->password_field === null) {
6386
-            $this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6387
-        }
6388
-        // don't bother setting has_password_field because that's hasPassword()'s job.
6389
-        return $this->password_field;
6390
-    }
6391
-
6392
-
6393
-    /**
6394
-     * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6395
-     * @since 4.9.74.p
6396
-     * @return EE_Model_Field_Base[]
6397
-     * @throws EE_Error
6398
-     */
6399
-    public function getPasswordProtectedFields()
6400
-    {
6401
-        $password_field = $this->getPasswordField();
6402
-        $fields = array();
6403
-        if ($password_field instanceof EE_Password_Field) {
6404
-            $field_names = $password_field->protectedFields();
6405
-            foreach ($field_names as $field_name) {
6406
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6407
-            }
6408
-        }
6409
-        return $fields;
6410
-    }
6411
-
6412
-
6413
-    /**
6414
-     * Checks if the current user can perform the requested action on this model
6415
-     * @since 4.9.74.p
6416
-     * @param string $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6417
-     * @param EE_Base_Class|array $model_obj_or_fields_n_values
6418
-     * @return bool
6419
-     * @throws EE_Error
6420
-     * @throws InvalidArgumentException
6421
-     * @throws InvalidDataTypeException
6422
-     * @throws InvalidInterfaceException
6423
-     * @throws ReflectionException
6424
-     * @throws UnexpectedEntityException
6425
-     */
6426
-    public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6427
-    {
6428
-        if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6429
-            $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6430
-        }
6431
-        if (!is_array($model_obj_or_fields_n_values)) {
6432
-            throw new UnexpectedEntityException(
6433
-                $model_obj_or_fields_n_values,
6434
-                'EE_Base_Class',
6435
-                sprintf(
6436
-                    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'),
6437
-                    __FUNCTION__
6438
-                )
6439
-            );
6440
-        }
6441
-        return $this->exists(
6442
-            $this->alter_query_params_to_restrict_by_ID(
6443
-                $this->get_index_primary_key_string($model_obj_or_fields_n_values),
6444
-                array(
6445
-                    'default_where_conditions' => 'none',
6446
-                    'caps'                     => $cap_to_check,
6447
-                )
6448
-            )
6449
-        );
6450
-    }
6451
-
6452
-    /**
6453
-     * Returns the query param where conditions key to the password affecting this model.
6454
-     * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6455
-     * @since 4.9.74.p
6456
-     * @return null|string
6457
-     * @throws EE_Error
6458
-     * @throws InvalidArgumentException
6459
-     * @throws InvalidDataTypeException
6460
-     * @throws InvalidInterfaceException
6461
-     * @throws ModelConfigurationException
6462
-     * @throws ReflectionException
6463
-     */
6464
-    public function modelChainAndPassword()
6465
-    {
6466
-        if ($this->model_chain_to_password === null) {
6467
-            throw new ModelConfigurationException(
6468
-                $this,
6469
-                esc_html_x(
6470
-                // @codingStandardsIgnoreStart
6471
-                    'Cannot exclude protected data because the model has not specified which model has the password.',
6472
-                    // @codingStandardsIgnoreEnd
6473
-                    '1: model name',
6474
-                    'event_espresso'
6475
-                )
6476
-            );
6477
-        }
6478
-        if ($this->model_chain_to_password === '') {
6479
-            $model_with_password = $this;
6480
-        } else {
6481
-            if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6482
-                $last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6483
-            } else {
6484
-                $last_model_in_chain = $this->model_chain_to_password;
6485
-            }
6486
-            $model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6487
-        }
6488
-
6489
-        $password_field = $model_with_password->getPasswordField();
6490
-        if ($password_field instanceof EE_Password_Field) {
6491
-            $password_field_name = $password_field->get_name();
6492
-        } else {
6493
-            throw new ModelConfigurationException(
6494
-                $this,
6495
-                sprintf(
6496
-                    esc_html_x(
6497
-                        '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"',
6498
-                        '1: model name, 2: special string',
6499
-                        'event_espresso'
6500
-                    ),
6501
-                    $model_with_password->get_this_model_name(),
6502
-                    $this->model_chain_to_password
6503
-                )
6504
-            );
6505
-        }
6506
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6507
-    }
6508
-
6509
-    /**
6510
-     * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6511
-     * or if this model itself has a password affecting access to some of its other fields.
6512
-     * @since 4.9.74.p
6513
-     * @return boolean
6514
-     */
6515
-    public function restrictedByRelatedModelPassword()
6516
-    {
6517
-        return $this->model_chain_to_password !== null;
6518
-    }
3814
+		}
3815
+		return $null_friendly_where_conditions;
3816
+	}
3817
+
3818
+
3819
+
3820
+	/**
3821
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3822
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3823
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3824
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3825
+	 *
3826
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3827
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3828
+	 */
3829
+	private function _get_default_where_conditions($model_relation_path = null)
3830
+	{
3831
+		if ($this->_ignore_where_strategy) {
3832
+			return array();
3833
+		}
3834
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3835
+	}
3836
+
3837
+
3838
+
3839
+	/**
3840
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3841
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3842
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3843
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3844
+	 * Similar to _get_default_where_conditions
3845
+	 *
3846
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3847
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3848
+	 */
3849
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3850
+	{
3851
+		if ($this->_ignore_where_strategy) {
3852
+			return array();
3853
+		}
3854
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3855
+	}
3856
+
3857
+
3858
+
3859
+	/**
3860
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3861
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3862
+	 *
3863
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3864
+	 * @return string
3865
+	 * @throws EE_Error
3866
+	 */
3867
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3868
+	{
3869
+		$selects = $this->_get_columns_to_select_for_this_model();
3870
+		foreach (
3871
+			$model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included
3872
+		) {
3873
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3874
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3875
+			foreach ($other_model_selects as $key => $value) {
3876
+				$selects[] = $value;
3877
+			}
3878
+		}
3879
+		return implode(", ", $selects);
3880
+	}
3881
+
3882
+
3883
+
3884
+	/**
3885
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3886
+	 * So that's going to be the columns for all the fields on the model
3887
+	 *
3888
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3889
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3890
+	 */
3891
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3892
+	{
3893
+		$fields = $this->field_settings();
3894
+		$selects = array();
3895
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3896
+			$model_relation_chain,
3897
+			$this->get_this_model_name()
3898
+		);
3899
+		foreach ($fields as $field_obj) {
3900
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3901
+						 . $field_obj->get_table_alias()
3902
+						 . "."
3903
+						 . $field_obj->get_table_column()
3904
+						 . " AS '"
3905
+						 . $table_alias_with_model_relation_chain_prefix
3906
+						 . $field_obj->get_table_alias()
3907
+						 . "."
3908
+						 . $field_obj->get_table_column()
3909
+						 . "'";
3910
+		}
3911
+		// make sure we are also getting the PKs of each table
3912
+		$tables = $this->get_tables();
3913
+		if (count($tables) > 1) {
3914
+			foreach ($tables as $table_obj) {
3915
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3916
+									   . $table_obj->get_fully_qualified_pk_column();
3917
+				if (! in_array($qualified_pk_column, $selects)) {
3918
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3919
+				}
3920
+			}
3921
+		}
3922
+		return $selects;
3923
+	}
3924
+
3925
+
3926
+
3927
+	/**
3928
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3929
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3930
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3931
+	 * SQL for joining, and the data types
3932
+	 *
3933
+	 * @param null|string                 $original_query_param
3934
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3935
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3936
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3937
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3938
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3939
+	 *                                                          or 'Registration's
3940
+	 * @param string                      $original_query_param what it originally was (eg
3941
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3942
+	 *                                                          matches $query_param
3943
+	 * @throws EE_Error
3944
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3945
+	 */
3946
+	private function _extract_related_model_info_from_query_param(
3947
+		$query_param,
3948
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3949
+		$query_param_type,
3950
+		$original_query_param = null
3951
+	) {
3952
+		if ($original_query_param === null) {
3953
+			$original_query_param = $query_param;
3954
+		}
3955
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3956
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3957
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
3958
+		$allow_fields = in_array(
3959
+			$query_param_type,
3960
+			array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
3961
+			true
3962
+		);
3963
+		// check to see if we have a field on this model
3964
+		$this_model_fields = $this->field_settings(true);
3965
+		if (array_key_exists($query_param, $this_model_fields)) {
3966
+			if ($allow_fields) {
3967
+				return;
3968
+			}
3969
+			throw new EE_Error(
3970
+				sprintf(
3971
+					esc_html__(
3972
+						"Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3973
+						"event_espresso"
3974
+					),
3975
+					$query_param,
3976
+					get_class($this),
3977
+					$query_param_type,
3978
+					$original_query_param
3979
+				)
3980
+			);
3981
+		}
3982
+		// check if this is a special logic query param
3983
+		if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3984
+			if ($allow_logic_query_params) {
3985
+				return;
3986
+			}
3987
+			throw new EE_Error(
3988
+				sprintf(
3989
+					esc_html__(
3990
+						'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',
3991
+						'event_espresso'
3992
+					),
3993
+					implode('", "', $this->_logic_query_param_keys),
3994
+					$query_param,
3995
+					get_class($this),
3996
+					'<br />',
3997
+					"\t"
3998
+					. ' $passed_in_query_info = <pre>'
3999
+					. print_r($passed_in_query_info, true)
4000
+					. '</pre>'
4001
+					. "\n\t"
4002
+					. ' $query_param_type = '
4003
+					. $query_param_type
4004
+					. "\n\t"
4005
+					. ' $original_query_param = '
4006
+					. $original_query_param
4007
+				)
4008
+			);
4009
+		}
4010
+		// check if it's a custom selection
4011
+		if (
4012
+			$this->_custom_selections instanceof CustomSelects
4013
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4014
+		) {
4015
+			return;
4016
+		}
4017
+		// check if has a model name at the beginning
4018
+		// and
4019
+		// check if it's a field on a related model
4020
+		if (
4021
+			$this->extractJoinModelFromQueryParams(
4022
+				$passed_in_query_info,
4023
+				$query_param,
4024
+				$original_query_param,
4025
+				$query_param_type
4026
+			)
4027
+		) {
4028
+			return;
4029
+		}
4030
+
4031
+		// ok so $query_param didn't start with a model name
4032
+		// and we previously confirmed it wasn't a logic query param or field on the current model
4033
+		// it's wack, that's what it is
4034
+		throw new EE_Error(
4035
+			sprintf(
4036
+				esc_html__(
4037
+					"There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4038
+					"event_espresso"
4039
+				),
4040
+				$query_param,
4041
+				get_class($this),
4042
+				$query_param_type,
4043
+				$original_query_param
4044
+			)
4045
+		);
4046
+	}
4047
+
4048
+
4049
+	/**
4050
+	 * Extracts any possible join model information from the provided possible_join_string.
4051
+	 * This method will read the provided $possible_join_string value and determine if there are any possible model join
4052
+	 * parts that should be added to the query.
4053
+	 *
4054
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4055
+	 * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4056
+	 * @param null|string                 $original_query_param
4057
+	 * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4058
+	 *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
4059
+	 * @return bool  returns true if a join was added and false if not.
4060
+	 * @throws EE_Error
4061
+	 */
4062
+	private function extractJoinModelFromQueryParams(
4063
+		EE_Model_Query_Info_Carrier $query_info_carrier,
4064
+		$possible_join_string,
4065
+		$original_query_param,
4066
+		$query_parameter_type
4067
+	) {
4068
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4069
+			if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4070
+				$this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4071
+				$possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4072
+				if ($possible_join_string === '') {
4073
+					// nothing left to $query_param
4074
+					// we should actually end in a field name, not a model like this!
4075
+					throw new EE_Error(
4076
+						sprintf(
4077
+							esc_html__(
4078
+								"Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4079
+								"event_espresso"
4080
+							),
4081
+							$possible_join_string,
4082
+							$query_parameter_type,
4083
+							get_class($this),
4084
+							$valid_related_model_name
4085
+						)
4086
+					);
4087
+				}
4088
+				$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4089
+				$related_model_obj->_extract_related_model_info_from_query_param(
4090
+					$possible_join_string,
4091
+					$query_info_carrier,
4092
+					$query_parameter_type,
4093
+					$original_query_param
4094
+				);
4095
+				return true;
4096
+			}
4097
+			if ($possible_join_string === $valid_related_model_name) {
4098
+				$this->_add_join_to_model(
4099
+					$valid_related_model_name,
4100
+					$query_info_carrier,
4101
+					$original_query_param
4102
+				);
4103
+				return true;
4104
+			}
4105
+		}
4106
+		return false;
4107
+	}
4108
+
4109
+
4110
+	/**
4111
+	 * Extracts related models from Custom Selects and sets up any joins for those related models.
4112
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4113
+	 * @throws EE_Error
4114
+	 */
4115
+	private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4116
+	{
4117
+		if (
4118
+			$this->_custom_selections instanceof CustomSelects
4119
+			&& ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4120
+				|| $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4121
+			)
4122
+		) {
4123
+			$original_selects = $this->_custom_selections->originalSelects();
4124
+			foreach ($original_selects as $alias => $select_configuration) {
4125
+				$this->extractJoinModelFromQueryParams(
4126
+					$query_info_carrier,
4127
+					$select_configuration[0],
4128
+					$select_configuration[0],
4129
+					'custom_selects'
4130
+				);
4131
+			}
4132
+		}
4133
+	}
4134
+
4135
+
4136
+
4137
+	/**
4138
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4139
+	 * and store it on $passed_in_query_info
4140
+	 *
4141
+	 * @param string                      $model_name
4142
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4143
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
4144
+	 *                                                          model and $model_name. Eg, if we are querying Event,
4145
+	 *                                                          and are adding a join to 'Payment' with the original
4146
+	 *                                                          query param key
4147
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4148
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
4149
+	 *                                                          Payment wants to add default query params so that it
4150
+	 *                                                          will know what models to prepend onto its default query
4151
+	 *                                                          params or in case it wants to rename tables (in case
4152
+	 *                                                          there are multiple joins to the same table)
4153
+	 * @return void
4154
+	 * @throws EE_Error
4155
+	 */
4156
+	private function _add_join_to_model(
4157
+		$model_name,
4158
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4159
+		$original_query_param
4160
+	) {
4161
+		$relation_obj = $this->related_settings_for($model_name);
4162
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4163
+		// check if the relation is HABTM, because then we're essentially doing two joins
4164
+		// If so, join first to the JOIN table, and add its data types, and then continue as normal
4165
+		if ($relation_obj instanceof EE_HABTM_Relation) {
4166
+			$join_model_obj = $relation_obj->get_join_model();
4167
+			// replace the model specified with the join model for this relation chain, whi
4168
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4169
+				$model_name,
4170
+				$join_model_obj->get_this_model_name(),
4171
+				$model_relation_chain
4172
+			);
4173
+			$passed_in_query_info->merge(
4174
+				new EE_Model_Query_Info_Carrier(
4175
+					array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4176
+					$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4177
+				)
4178
+			);
4179
+		}
4180
+		// now just join to the other table pointed to by the relation object, and add its data types
4181
+		$passed_in_query_info->merge(
4182
+			new EE_Model_Query_Info_Carrier(
4183
+				array($model_relation_chain => $model_name),
4184
+				$relation_obj->get_join_statement($model_relation_chain)
4185
+			)
4186
+		);
4187
+	}
4188
+
4189
+
4190
+
4191
+	/**
4192
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4193
+	 *
4194
+	 * @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
4195
+	 * @return string of SQL
4196
+	 * @throws EE_Error
4197
+	 */
4198
+	private function _construct_where_clause($where_params)
4199
+	{
4200
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4201
+		if ($SQL) {
4202
+			return " WHERE " . $SQL;
4203
+		}
4204
+		return '';
4205
+	}
4206
+
4207
+
4208
+
4209
+	/**
4210
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4211
+	 * and should be passed HAVING parameters, not WHERE parameters
4212
+	 *
4213
+	 * @param array $having_params
4214
+	 * @return string
4215
+	 * @throws EE_Error
4216
+	 */
4217
+	private function _construct_having_clause($having_params)
4218
+	{
4219
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4220
+		if ($SQL) {
4221
+			return " HAVING " . $SQL;
4222
+		}
4223
+		return '';
4224
+	}
4225
+
4226
+
4227
+	/**
4228
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4229
+	 * Event_Meta.meta_value = 'foo'))"
4230
+	 *
4231
+	 * @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
4232
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4233
+	 * @throws EE_Error
4234
+	 * @return string of SQL
4235
+	 */
4236
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4237
+	{
4238
+		$where_clauses = array();
4239
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4240
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4241
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
4242
+				switch ($query_param) {
4243
+					case 'not':
4244
+					case 'NOT':
4245
+						$where_clauses[] = "! ("
4246
+										   . $this->_construct_condition_clause_recursive(
4247
+											   $op_and_value_or_sub_condition,
4248
+											   $glue
4249
+										   )
4250
+										   . ")";
4251
+						break;
4252
+					case 'and':
4253
+					case 'AND':
4254
+						$where_clauses[] = " ("
4255
+										   . $this->_construct_condition_clause_recursive(
4256
+											   $op_and_value_or_sub_condition,
4257
+											   ' AND '
4258
+										   )
4259
+										   . ")";
4260
+						break;
4261
+					case 'or':
4262
+					case 'OR':
4263
+						$where_clauses[] = " ("
4264
+										   . $this->_construct_condition_clause_recursive(
4265
+											   $op_and_value_or_sub_condition,
4266
+											   ' OR '
4267
+										   )
4268
+										   . ")";
4269
+						break;
4270
+				}
4271
+			} else {
4272
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4273
+				// if it's not a normal field, maybe it's a custom selection?
4274
+				if (! $field_obj) {
4275
+					if ($this->_custom_selections instanceof CustomSelects) {
4276
+						$field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4277
+					} else {
4278
+						throw new EE_Error(sprintf(esc_html__(
4279
+							"%s is neither a valid model field name, nor a custom selection",
4280
+							"event_espresso"
4281
+						), $query_param));
4282
+					}
4283
+				}
4284
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4285
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4286
+			}
4287
+		}
4288
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4289
+	}
4290
+
4291
+
4292
+
4293
+	/**
4294
+	 * Takes the input parameter and extract the table name (alias) and column name
4295
+	 *
4296
+	 * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4297
+	 * @throws EE_Error
4298
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4299
+	 */
4300
+	private function _deduce_column_name_from_query_param($query_param)
4301
+	{
4302
+		$field = $this->_deduce_field_from_query_param($query_param);
4303
+		if ($field) {
4304
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4305
+				$field->get_model_name(),
4306
+				$query_param
4307
+			);
4308
+			return $table_alias_prefix . $field->get_qualified_column();
4309
+		}
4310
+		if (
4311
+			$this->_custom_selections instanceof CustomSelects
4312
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4313
+		) {
4314
+			// maybe it's custom selection item?
4315
+			// if so, just use it as the "column name"
4316
+			return $query_param;
4317
+		}
4318
+		$custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4319
+			? implode(',', $this->_custom_selections->columnAliases())
4320
+			: '';
4321
+		throw new EE_Error(
4322
+			sprintf(
4323
+				esc_html__(
4324
+					"%s is not a valid field on this model, nor a custom selection (%s)",
4325
+					"event_espresso"
4326
+				),
4327
+				$query_param,
4328
+				$custom_select_aliases
4329
+			)
4330
+		);
4331
+	}
4332
+
4333
+
4334
+
4335
+	/**
4336
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4337
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4338
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4339
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4340
+	 *
4341
+	 * @param string $condition_query_param_key
4342
+	 * @return string
4343
+	 */
4344
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4345
+	{
4346
+		$pos_of_star = strpos($condition_query_param_key, '*');
4347
+		if ($pos_of_star === false) {
4348
+			return $condition_query_param_key;
4349
+		}
4350
+		$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4351
+		return $condition_query_param_sans_star;
4352
+	}
4353
+
4354
+
4355
+
4356
+	/**
4357
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4358
+	 *
4359
+	 * @param                            mixed      array | string    $op_and_value
4360
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4361
+	 * @throws EE_Error
4362
+	 * @return string
4363
+	 */
4364
+	private function _construct_op_and_value($op_and_value, $field_obj)
4365
+	{
4366
+		if (is_array($op_and_value)) {
4367
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4368
+			if (! $operator) {
4369
+				$php_array_like_string = array();
4370
+				foreach ($op_and_value as $key => $value) {
4371
+					$php_array_like_string[] = "$key=>$value";
4372
+				}
4373
+				throw new EE_Error(
4374
+					sprintf(
4375
+						esc_html__(
4376
+							"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))",
4377
+							"event_espresso"
4378
+						),
4379
+						implode(",", $php_array_like_string)
4380
+					)
4381
+				);
4382
+			}
4383
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4384
+		} else {
4385
+			$operator = '=';
4386
+			$value = $op_and_value;
4387
+		}
4388
+		// check to see if the value is actually another field
4389
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4390
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4391
+		}
4392
+		if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4393
+			// in this case, the value should be an array, or at least a comma-separated list
4394
+			// it will need to handle a little differently
4395
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4396
+			// note: $cleaned_value has already been run through $wpdb->prepare()
4397
+			return $operator . SP . $cleaned_value;
4398
+		}
4399
+		if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4400
+			// the value should be an array with count of two.
4401
+			if (count($value) !== 2) {
4402
+				throw new EE_Error(
4403
+					sprintf(
4404
+						esc_html__(
4405
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4406
+							'event_espresso'
4407
+						),
4408
+						"BETWEEN"
4409
+					)
4410
+				);
4411
+			}
4412
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4413
+			return $operator . SP . $cleaned_value;
4414
+		}
4415
+		if (in_array($operator, $this->valid_null_style_operators())) {
4416
+			if ($value !== null) {
4417
+				throw new EE_Error(
4418
+					sprintf(
4419
+						esc_html__(
4420
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4421
+							"event_espresso"
4422
+						),
4423
+						$value,
4424
+						$operator
4425
+					)
4426
+				);
4427
+			}
4428
+			return $operator;
4429
+		}
4430
+		if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4431
+			// if the operator is 'LIKE', we want to allow percent signs (%) and not
4432
+			// remove other junk. So just treat it as a string.
4433
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4434
+		}
4435
+		if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4436
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4437
+		}
4438
+		if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4439
+			throw new EE_Error(
4440
+				sprintf(
4441
+					esc_html__(
4442
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4443
+						'event_espresso'
4444
+					),
4445
+					$operator,
4446
+					$operator
4447
+				)
4448
+			);
4449
+		}
4450
+		if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4451
+			throw new EE_Error(
4452
+				sprintf(
4453
+					esc_html__(
4454
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4455
+						'event_espresso'
4456
+					),
4457
+					$operator,
4458
+					$operator
4459
+				)
4460
+			);
4461
+		}
4462
+		throw new EE_Error(
4463
+			sprintf(
4464
+				esc_html__(
4465
+					"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4466
+					"event_espresso"
4467
+				),
4468
+				http_build_query($op_and_value)
4469
+			)
4470
+		);
4471
+	}
4472
+
4473
+
4474
+
4475
+	/**
4476
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4477
+	 *
4478
+	 * @param array                      $values
4479
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4480
+	 *                                              '%s'
4481
+	 * @return string
4482
+	 * @throws EE_Error
4483
+	 */
4484
+	public function _construct_between_value($values, $field_obj)
4485
+	{
4486
+		$cleaned_values = array();
4487
+		foreach ($values as $value) {
4488
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4489
+		}
4490
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4491
+	}
4492
+
4493
+
4494
+	/**
4495
+	 * Takes an array or a comma-separated list of $values and cleans them
4496
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4497
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4498
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4499
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4500
+	 *
4501
+	 * @param mixed                      $values    array or comma-separated string
4502
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4503
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4504
+	 * @throws EE_Error
4505
+	 */
4506
+	public function _construct_in_value($values, $field_obj)
4507
+	{
4508
+		$prepped = [];
4509
+		// check if the value is a CSV list
4510
+		if (is_string($values)) {
4511
+			// in which case, turn it into an array
4512
+			$values = explode(',', $values);
4513
+		}
4514
+		// make sure we only have one of each value in the list
4515
+		$values = array_unique($values);
4516
+		foreach ($values as $value) {
4517
+			$prepped[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4518
+		}
4519
+		// we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4520
+		// but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4521
+		// which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4522
+		if (empty($prepped)) {
4523
+			$all_fields = $this->field_settings();
4524
+			$first_field    = reset($all_fields);
4525
+			$main_table = $this->_get_main_table();
4526
+			$prepped[]  = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4527
+		}
4528
+		return '(' . implode(',', $prepped) . ')';
4529
+	}
4530
+
4531
+
4532
+
4533
+	/**
4534
+	 * @param mixed                      $value
4535
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4536
+	 * @throws EE_Error
4537
+	 * @return false|null|string
4538
+	 */
4539
+	private function _wpdb_prepare_using_field($value, $field_obj)
4540
+	{
4541
+		/** @type WPDB $wpdb */
4542
+		global $wpdb;
4543
+		if ($field_obj instanceof EE_Model_Field_Base) {
4544
+			return $wpdb->prepare(
4545
+				$field_obj->get_wpdb_data_type(),
4546
+				$this->_prepare_value_for_use_in_db($value, $field_obj)
4547
+			);
4548
+		} //$field_obj should really just be a data type
4549
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4550
+			throw new EE_Error(
4551
+				sprintf(
4552
+					esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4553
+					$field_obj,
4554
+					implode(",", $this->_valid_wpdb_data_types)
4555
+				)
4556
+			);
4557
+		}
4558
+		return $wpdb->prepare($field_obj, $value);
4559
+	}
4560
+
4561
+
4562
+
4563
+	/**
4564
+	 * Takes the input parameter and finds the model field that it indicates.
4565
+	 *
4566
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4567
+	 * @throws EE_Error
4568
+	 * @return EE_Model_Field_Base
4569
+	 */
4570
+	protected function _deduce_field_from_query_param($query_param_name)
4571
+	{
4572
+		// ok, now proceed with deducing which part is the model's name, and which is the field's name
4573
+		// which will help us find the database table and column
4574
+		$query_param_parts = explode(".", $query_param_name);
4575
+		if (empty($query_param_parts)) {
4576
+			throw new EE_Error(sprintf(esc_html__(
4577
+				"_extract_column_name is empty when trying to extract column and table name from %s",
4578
+				'event_espresso'
4579
+			), $query_param_name));
4580
+		}
4581
+		$number_of_parts = count($query_param_parts);
4582
+		$last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4583
+		if ($number_of_parts === 1) {
4584
+			$field_name = $last_query_param_part;
4585
+			$model_obj = $this;
4586
+		} else {// $number_of_parts >= 2
4587
+			// the last part is the column name, and there are only 2parts. therefore...
4588
+			$field_name = $last_query_param_part;
4589
+			$model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4590
+		}
4591
+		try {
4592
+			return $model_obj->field_settings_for($field_name);
4593
+		} catch (EE_Error $e) {
4594
+			return null;
4595
+		}
4596
+	}
4597
+
4598
+
4599
+
4600
+	/**
4601
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4602
+	 * alias and column which corresponds to it
4603
+	 *
4604
+	 * @param string $field_name
4605
+	 * @throws EE_Error
4606
+	 * @return string
4607
+	 */
4608
+	public function _get_qualified_column_for_field($field_name)
4609
+	{
4610
+		$all_fields = $this->field_settings();
4611
+		$field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4612
+		if ($field) {
4613
+			return $field->get_qualified_column();
4614
+		}
4615
+		throw new EE_Error(
4616
+			sprintf(
4617
+				esc_html__(
4618
+					"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.",
4619
+					'event_espresso'
4620
+				),
4621
+				$field_name,
4622
+				get_class($this)
4623
+			)
4624
+		);
4625
+	}
4626
+
4627
+
4628
+
4629
+	/**
4630
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4631
+	 * Example usage:
4632
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4633
+	 *      array(),
4634
+	 *      ARRAY_A,
4635
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4636
+	 *  );
4637
+	 * is equivalent to
4638
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4639
+	 * and
4640
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4641
+	 *      array(
4642
+	 *          array(
4643
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4644
+	 *          ),
4645
+	 *          ARRAY_A,
4646
+	 *          implode(
4647
+	 *              ', ',
4648
+	 *              array_merge(
4649
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4650
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4651
+	 *              )
4652
+	 *          )
4653
+	 *      )
4654
+	 *  );
4655
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4656
+	 *
4657
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4658
+	 *                                            and the one whose fields you are selecting for example: when querying
4659
+	 *                                            tickets model and selecting fields from the tickets model you would
4660
+	 *                                            leave this parameter empty, because no models are needed to join
4661
+	 *                                            between the queried model and the selected one. Likewise when
4662
+	 *                                            querying the datetime model and selecting fields from the tickets
4663
+	 *                                            model, it would also be left empty, because there is a direct
4664
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4665
+	 *                                            them together. However, when querying from the event model and
4666
+	 *                                            selecting fields from the ticket model, you should provide the string
4667
+	 *                                            'Datetime', indicating that the event model must first join to the
4668
+	 *                                            datetime model in order to find its relation to ticket model.
4669
+	 *                                            Also, when querying from the venue model and selecting fields from
4670
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4671
+	 *                                            indicating you need to join the venue model to the event model,
4672
+	 *                                            to the datetime model, in order to find its relation to the ticket model.
4673
+	 *                                            This string is used to deduce the prefix that gets added onto the
4674
+	 *                                            models' tables qualified columns
4675
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4676
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4677
+	 *                                            qualified column names
4678
+	 * @return array|string
4679
+	 */
4680
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4681
+	{
4682
+		$table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4683
+		$qualified_columns = array();
4684
+		foreach ($this->field_settings() as $field_name => $field) {
4685
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4686
+		}
4687
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4688
+	}
4689
+
4690
+
4691
+
4692
+	/**
4693
+	 * constructs the select use on special limit joins
4694
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4695
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4696
+	 * (as that is typically where the limits would be set).
4697
+	 *
4698
+	 * @param  string       $table_alias The table the select is being built for
4699
+	 * @param  mixed|string $limit       The limit for this select
4700
+	 * @return string                The final select join element for the query.
4701
+	 */
4702
+	public function _construct_limit_join_select($table_alias, $limit)
4703
+	{
4704
+		$SQL = '';
4705
+		foreach ($this->_tables as $table_obj) {
4706
+			if ($table_obj instanceof EE_Primary_Table) {
4707
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4708
+					? $table_obj->get_select_join_limit($limit)
4709
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4710
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4711
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4712
+					? $table_obj->get_select_join_limit_join($limit)
4713
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4714
+			}
4715
+		}
4716
+		return $SQL;
4717
+	}
4718
+
4719
+
4720
+
4721
+	/**
4722
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4723
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4724
+	 *
4725
+	 * @return string SQL
4726
+	 * @throws EE_Error
4727
+	 */
4728
+	public function _construct_internal_join()
4729
+	{
4730
+		$SQL = $this->_get_main_table()->get_table_sql();
4731
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4732
+		return $SQL;
4733
+	}
4734
+
4735
+
4736
+
4737
+	/**
4738
+	 * Constructs the SQL for joining all the tables on this model.
4739
+	 * Normally $alias should be the primary table's alias, but in cases where
4740
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4741
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4742
+	 * alias, this will construct SQL like:
4743
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4744
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4745
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4746
+	 *
4747
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4748
+	 * @return string
4749
+	 */
4750
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4751
+	{
4752
+		$SQL = '';
4753
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4754
+		foreach ($this->_tables as $table_obj) {
4755
+			if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4756
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4757
+					// so we're joining to this table, meaning the table is already in
4758
+					// the FROM statement, BUT the primary table isn't. So we want
4759
+					// to add the inverse join sql
4760
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4761
+				} else {
4762
+					// just add a regular JOIN to this table from the primary table
4763
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4764
+				}
4765
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4766
+		}
4767
+		return $SQL;
4768
+	}
4769
+
4770
+
4771
+
4772
+	/**
4773
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4774
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4775
+	 * their data type (eg, '%s', '%d', etc)
4776
+	 *
4777
+	 * @return array
4778
+	 */
4779
+	public function _get_data_types()
4780
+	{
4781
+		$data_types = array();
4782
+		foreach ($this->field_settings() as $field_obj) {
4783
+			// $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4784
+			/** @var $field_obj EE_Model_Field_Base */
4785
+			$data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4786
+		}
4787
+		return $data_types;
4788
+	}
4789
+
4790
+
4791
+
4792
+	/**
4793
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4794
+	 *
4795
+	 * @param string $model_name
4796
+	 * @throws EE_Error
4797
+	 * @return EEM_Base
4798
+	 */
4799
+	public function get_related_model_obj($model_name)
4800
+	{
4801
+		$model_classname = "EEM_" . $model_name;
4802
+		if (! class_exists($model_classname)) {
4803
+			throw new EE_Error(sprintf(esc_html__(
4804
+				"You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4805
+				'event_espresso'
4806
+			), $model_name, $model_classname));
4807
+		}
4808
+		return call_user_func($model_classname . "::instance");
4809
+	}
4810
+
4811
+
4812
+
4813
+	/**
4814
+	 * Returns the array of EE_ModelRelations for this model.
4815
+	 *
4816
+	 * @return EE_Model_Relation_Base[]
4817
+	 */
4818
+	public function relation_settings()
4819
+	{
4820
+		return $this->_model_relations;
4821
+	}
4822
+
4823
+
4824
+
4825
+	/**
4826
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4827
+	 * because without THOSE models, this model probably doesn't have much purpose.
4828
+	 * (Eg, without an event, datetimes have little purpose.)
4829
+	 *
4830
+	 * @return EE_Belongs_To_Relation[]
4831
+	 */
4832
+	public function belongs_to_relations()
4833
+	{
4834
+		$belongs_to_relations = array();
4835
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4836
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4837
+				$belongs_to_relations[ $model_name ] = $relation_obj;
4838
+			}
4839
+		}
4840
+		return $belongs_to_relations;
4841
+	}
4842
+
4843
+
4844
+
4845
+	/**
4846
+	 * Returns the specified EE_Model_Relation, or throws an exception
4847
+	 *
4848
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4849
+	 * @throws EE_Error
4850
+	 * @return EE_Model_Relation_Base
4851
+	 */
4852
+	public function related_settings_for($relation_name)
4853
+	{
4854
+		$relatedModels = $this->relation_settings();
4855
+		if (! array_key_exists($relation_name, $relatedModels)) {
4856
+			throw new EE_Error(
4857
+				sprintf(
4858
+					esc_html__(
4859
+						'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4860
+						'event_espresso'
4861
+					),
4862
+					$relation_name,
4863
+					$this->_get_class_name(),
4864
+					implode(', ', array_keys($relatedModels))
4865
+				)
4866
+			);
4867
+		}
4868
+		return $relatedModels[ $relation_name ];
4869
+	}
4870
+
4871
+
4872
+
4873
+	/**
4874
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4875
+	 * fields
4876
+	 *
4877
+	 * @param string $fieldName
4878
+	 * @param boolean $include_db_only_fields
4879
+	 * @throws EE_Error
4880
+	 * @return EE_Model_Field_Base
4881
+	 */
4882
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
4883
+	{
4884
+		$fieldSettings = $this->field_settings($include_db_only_fields);
4885
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4886
+			throw new EE_Error(sprintf(
4887
+				esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
4888
+				$fieldName,
4889
+				get_class($this)
4890
+			));
4891
+		}
4892
+		return $fieldSettings[ $fieldName ];
4893
+	}
4894
+
4895
+
4896
+
4897
+	/**
4898
+	 * Checks if this field exists on this model
4899
+	 *
4900
+	 * @param string $fieldName a key in the model's _field_settings array
4901
+	 * @return boolean
4902
+	 */
4903
+	public function has_field($fieldName)
4904
+	{
4905
+		$fieldSettings = $this->field_settings(true);
4906
+		if (isset($fieldSettings[ $fieldName ])) {
4907
+			return true;
4908
+		}
4909
+		return false;
4910
+	}
4911
+
4912
+
4913
+
4914
+	/**
4915
+	 * Returns whether or not this model has a relation to the specified model
4916
+	 *
4917
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4918
+	 * @return boolean
4919
+	 */
4920
+	public function has_relation($relation_name)
4921
+	{
4922
+		$relations = $this->relation_settings();
4923
+		if (isset($relations[ $relation_name ])) {
4924
+			return true;
4925
+		}
4926
+		return false;
4927
+	}
4928
+
4929
+
4930
+
4931
+	/**
4932
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4933
+	 * Eg, on EE_Answer that would be ANS_ID field object
4934
+	 *
4935
+	 * @param $field_obj
4936
+	 * @return boolean
4937
+	 */
4938
+	public function is_primary_key_field($field_obj)
4939
+	{
4940
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4941
+	}
4942
+
4943
+
4944
+
4945
+	/**
4946
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4947
+	 * Eg, on EE_Answer that would be ANS_ID field object
4948
+	 *
4949
+	 * @return EE_Model_Field_Base
4950
+	 * @throws EE_Error
4951
+	 */
4952
+	public function get_primary_key_field()
4953
+	{
4954
+		if ($this->_primary_key_field === null) {
4955
+			foreach ($this->field_settings(true) as $field_obj) {
4956
+				if ($this->is_primary_key_field($field_obj)) {
4957
+					$this->_primary_key_field = $field_obj;
4958
+					break;
4959
+				}
4960
+			}
4961
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4962
+				throw new EE_Error(sprintf(
4963
+					esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
4964
+					get_class($this)
4965
+				));
4966
+			}
4967
+		}
4968
+		return $this->_primary_key_field;
4969
+	}
4970
+
4971
+
4972
+
4973
+	/**
4974
+	 * Returns whether or not not there is a primary key on this model.
4975
+	 * Internally does some caching.
4976
+	 *
4977
+	 * @return boolean
4978
+	 */
4979
+	public function has_primary_key_field()
4980
+	{
4981
+		if ($this->_has_primary_key_field === null) {
4982
+			try {
4983
+				$this->get_primary_key_field();
4984
+				$this->_has_primary_key_field = true;
4985
+			} catch (EE_Error $e) {
4986
+				$this->_has_primary_key_field = false;
4987
+			}
4988
+		}
4989
+		return $this->_has_primary_key_field;
4990
+	}
4991
+
4992
+
4993
+
4994
+	/**
4995
+	 * Finds the first field of type $field_class_name.
4996
+	 *
4997
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4998
+	 *                                 EE_Foreign_Key_Field, etc
4999
+	 * @return EE_Model_Field_Base or null if none is found
5000
+	 */
5001
+	public function get_a_field_of_type($field_class_name)
5002
+	{
5003
+		foreach ($this->field_settings() as $field) {
5004
+			if ($field instanceof $field_class_name) {
5005
+				return $field;
5006
+			}
5007
+		}
5008
+		return null;
5009
+	}
5010
+
5011
+
5012
+
5013
+	/**
5014
+	 * Gets a foreign key field pointing to model.
5015
+	 *
5016
+	 * @param string $model_name eg Event, Registration, not EEM_Event
5017
+	 * @return EE_Foreign_Key_Field_Base
5018
+	 * @throws EE_Error
5019
+	 */
5020
+	public function get_foreign_key_to($model_name)
5021
+	{
5022
+		if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5023
+			foreach ($this->field_settings() as $field) {
5024
+				if (
5025
+					$field instanceof EE_Foreign_Key_Field_Base
5026
+					&& in_array($model_name, $field->get_model_names_pointed_to())
5027
+				) {
5028
+					$this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5029
+					break;
5030
+				}
5031
+			}
5032
+			if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5033
+				throw new EE_Error(sprintf(esc_html__(
5034
+					"There is no foreign key field pointing to model %s on model %s",
5035
+					'event_espresso'
5036
+				), $model_name, get_class($this)));
5037
+			}
5038
+		}
5039
+		return $this->_cache_foreign_key_to_fields[ $model_name ];
5040
+	}
5041
+
5042
+
5043
+
5044
+	/**
5045
+	 * Gets the table name (including $wpdb->prefix) for the table alias
5046
+	 *
5047
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5048
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5049
+	 *                            Either one works
5050
+	 * @return string
5051
+	 */
5052
+	public function get_table_for_alias($table_alias)
5053
+	{
5054
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5055
+		return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5056
+	}
5057
+
5058
+
5059
+
5060
+	/**
5061
+	 * Returns a flat array of all field son this model, instead of organizing them
5062
+	 * by table_alias as they are in the constructor.
5063
+	 *
5064
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5065
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
5066
+	 */
5067
+	public function field_settings($include_db_only_fields = false)
5068
+	{
5069
+		if ($include_db_only_fields) {
5070
+			if ($this->_cached_fields === null) {
5071
+				$this->_cached_fields = array();
5072
+				foreach ($this->_fields as $fields_corresponding_to_table) {
5073
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5074
+						$this->_cached_fields[ $field_name ] = $field_obj;
5075
+					}
5076
+				}
5077
+			}
5078
+			return $this->_cached_fields;
5079
+		}
5080
+		if ($this->_cached_fields_non_db_only === null) {
5081
+			$this->_cached_fields_non_db_only = array();
5082
+			foreach ($this->_fields as $fields_corresponding_to_table) {
5083
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5084
+					/** @var $field_obj EE_Model_Field_Base */
5085
+					if (! $field_obj->is_db_only_field()) {
5086
+						$this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5087
+					}
5088
+				}
5089
+			}
5090
+		}
5091
+		return $this->_cached_fields_non_db_only;
5092
+	}
5093
+
5094
+
5095
+
5096
+	/**
5097
+	 *        cycle though array of attendees and create objects out of each item
5098
+	 *
5099
+	 * @access        private
5100
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5101
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5102
+	 *                           numerically indexed)
5103
+	 * @throws EE_Error
5104
+	 */
5105
+	protected function _create_objects($rows = array())
5106
+	{
5107
+		$array_of_objects = array();
5108
+		if (empty($rows)) {
5109
+			return array();
5110
+		}
5111
+		$count_if_model_has_no_primary_key = 0;
5112
+		$has_primary_key = $this->has_primary_key_field();
5113
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5114
+		foreach ((array) $rows as $row) {
5115
+			if (empty($row)) {
5116
+				// wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5117
+				return array();
5118
+			}
5119
+			// check if we've already set this object in the results array,
5120
+			// in which case there's no need to process it further (again)
5121
+			if ($has_primary_key) {
5122
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5123
+					$row,
5124
+					$primary_key_field->get_qualified_column(),
5125
+					$primary_key_field->get_table_column()
5126
+				);
5127
+				if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5128
+					continue;
5129
+				}
5130
+			}
5131
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
5132
+			if (! $classInstance) {
5133
+				throw new EE_Error(
5134
+					sprintf(
5135
+						esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
5136
+						$this->get_this_model_name(),
5137
+						http_build_query($row)
5138
+					)
5139
+				);
5140
+			}
5141
+			// set the timezone on the instantiated objects
5142
+			$classInstance->set_timezone($this->_timezone);
5143
+			// make sure if there is any timezone setting present that we set the timezone for the object
5144
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5145
+			$array_of_objects[ $key ] = $classInstance;
5146
+			// also, for all the relations of type BelongsTo, see if we can cache
5147
+			// those related models
5148
+			// (we could do this for other relations too, but if there are conditions
5149
+			// that filtered out some fo the results, then we'd be caching an incomplete set
5150
+			// so it requires a little more thought than just caching them immediately...)
5151
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
5152
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
5153
+					// check if this model's INFO is present. If so, cache it on the model
5154
+					$other_model = $relation_obj->get_other_model();
5155
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5156
+					// if we managed to make a model object from the results, cache it on the main model object
5157
+					if ($other_model_obj_maybe) {
5158
+						// set timezone on these other model objects if they are present
5159
+						$other_model_obj_maybe->set_timezone($this->_timezone);
5160
+						$classInstance->cache($modelName, $other_model_obj_maybe);
5161
+					}
5162
+				}
5163
+			}
5164
+			// also, if this was a custom select query, let's see if there are any results for the custom select fields
5165
+			// and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5166
+			// the field in the CustomSelects object
5167
+			if ($this->_custom_selections instanceof CustomSelects) {
5168
+				$classInstance->setCustomSelectsValues(
5169
+					$this->getValuesForCustomSelectAliasesFromResults($row)
5170
+				);
5171
+			}
5172
+		}
5173
+		return $array_of_objects;
5174
+	}
5175
+
5176
+
5177
+	/**
5178
+	 * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5179
+	 * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5180
+	 *
5181
+	 * @param array $db_results_row
5182
+	 * @return array
5183
+	 */
5184
+	protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5185
+	{
5186
+		$results = array();
5187
+		if ($this->_custom_selections instanceof CustomSelects) {
5188
+			foreach ($this->_custom_selections->columnAliases() as $alias) {
5189
+				if (isset($db_results_row[ $alias ])) {
5190
+					$results[ $alias ] = $this->convertValueToDataType(
5191
+						$db_results_row[ $alias ],
5192
+						$this->_custom_selections->getDataTypeForAlias($alias)
5193
+					);
5194
+				}
5195
+			}
5196
+		}
5197
+		return $results;
5198
+	}
5199
+
5200
+
5201
+	/**
5202
+	 * This will set the value for the given alias
5203
+	 * @param string $value
5204
+	 * @param string $datatype (one of %d, %s, %f)
5205
+	 * @return int|string|float (int for %d, string for %s, float for %f)
5206
+	 */
5207
+	protected function convertValueToDataType($value, $datatype)
5208
+	{
5209
+		switch ($datatype) {
5210
+			case '%f':
5211
+				return (float) $value;
5212
+			case '%d':
5213
+				return (int) $value;
5214
+			default:
5215
+				return (string) $value;
5216
+		}
5217
+	}
5218
+
5219
+
5220
+	/**
5221
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5222
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5223
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5224
+	 * object (as set in the model_field!).
5225
+	 *
5226
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5227
+	 */
5228
+	public function create_default_object()
5229
+	{
5230
+		$this_model_fields_and_values = array();
5231
+		// setup the row using default values;
5232
+		foreach ($this->field_settings() as $field_name => $field_obj) {
5233
+			$this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5234
+		}
5235
+		$className = $this->_get_class_name();
5236
+		$classInstance = EE_Registry::instance()
5237
+									->load_class($className, array($this_model_fields_and_values), false, false);
5238
+		return $classInstance;
5239
+	}
5240
+
5241
+
5242
+
5243
+	/**
5244
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5245
+	 *                             or an stdClass where each property is the name of a column,
5246
+	 * @return EE_Base_Class
5247
+	 * @throws EE_Error
5248
+	 */
5249
+	public function instantiate_class_from_array_or_object($cols_n_values)
5250
+	{
5251
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5252
+			$cols_n_values = get_object_vars($cols_n_values);
5253
+		}
5254
+		$primary_key = null;
5255
+		// make sure the array only has keys that are fields/columns on this model
5256
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5257
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5258
+			$primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5259
+		}
5260
+		$className = $this->_get_class_name();
5261
+		// check we actually found results that we can use to build our model object
5262
+		// if not, return null
5263
+		if ($this->has_primary_key_field()) {
5264
+			if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5265
+				return null;
5266
+			}
5267
+		} elseif ($this->unique_indexes()) {
5268
+			$first_column = reset($this_model_fields_n_values);
5269
+			if (empty($first_column)) {
5270
+				return null;
5271
+			}
5272
+		}
5273
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5274
+		if ($primary_key) {
5275
+			$classInstance = $this->get_from_entity_map($primary_key);
5276
+			if (! $classInstance) {
5277
+				$classInstance = EE_Registry::instance()
5278
+											->load_class(
5279
+												$className,
5280
+												array($this_model_fields_n_values, $this->_timezone),
5281
+												true,
5282
+												false
5283
+											);
5284
+				// add this new object to the entity map
5285
+				$classInstance = $this->add_to_entity_map($classInstance);
5286
+			}
5287
+		} else {
5288
+			$classInstance = EE_Registry::instance()
5289
+										->load_class(
5290
+											$className,
5291
+											array($this_model_fields_n_values, $this->_timezone),
5292
+											true,
5293
+											false
5294
+										);
5295
+		}
5296
+		return $classInstance;
5297
+	}
5298
+
5299
+
5300
+
5301
+	/**
5302
+	 * Gets the model object from the  entity map if it exists
5303
+	 *
5304
+	 * @param int|string $id the ID of the model object
5305
+	 * @return EE_Base_Class
5306
+	 */
5307
+	public function get_from_entity_map($id)
5308
+	{
5309
+		return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5310
+			? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5311
+	}
5312
+
5313
+
5314
+
5315
+	/**
5316
+	 * add_to_entity_map
5317
+	 * Adds the object to the model's entity mappings
5318
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5319
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5320
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5321
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5322
+	 *        then this method should be called immediately after the update query
5323
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5324
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5325
+	 *
5326
+	 * @param    EE_Base_Class $object
5327
+	 * @throws EE_Error
5328
+	 * @return \EE_Base_Class
5329
+	 */
5330
+	public function add_to_entity_map(EE_Base_Class $object)
5331
+	{
5332
+		$className = $this->_get_class_name();
5333
+		if (! $object instanceof $className) {
5334
+			throw new EE_Error(sprintf(
5335
+				esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5336
+				is_object($object) ? get_class($object) : $object,
5337
+				$className
5338
+			));
5339
+		}
5340
+		/** @var $object EE_Base_Class */
5341
+		if (! $object->ID()) {
5342
+			throw new EE_Error(sprintf(esc_html__(
5343
+				"You tried storing a model object with NO ID in the %s entity mapper.",
5344
+				"event_espresso"
5345
+			), get_class($this)));
5346
+		}
5347
+		// double check it's not already there
5348
+		$classInstance = $this->get_from_entity_map($object->ID());
5349
+		if ($classInstance) {
5350
+			return $classInstance;
5351
+		}
5352
+		$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5353
+		return $object;
5354
+	}
5355
+
5356
+
5357
+
5358
+	/**
5359
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5360
+	 * if no identifier is provided, then the entire entity map is emptied
5361
+	 *
5362
+	 * @param int|string $id the ID of the model object
5363
+	 * @return boolean
5364
+	 */
5365
+	public function clear_entity_map($id = null)
5366
+	{
5367
+		if (empty($id)) {
5368
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5369
+			return true;
5370
+		}
5371
+		if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5372
+			unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5373
+			return true;
5374
+		}
5375
+		return false;
5376
+	}
5377
+
5378
+
5379
+
5380
+	/**
5381
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5382
+	 * Given an array where keys are column (or column alias) names and values,
5383
+	 * returns an array of their corresponding field names and database values
5384
+	 *
5385
+	 * @param array $cols_n_values
5386
+	 * @return array
5387
+	 */
5388
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5389
+	{
5390
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5391
+	}
5392
+
5393
+
5394
+
5395
+	/**
5396
+	 * _deduce_fields_n_values_from_cols_n_values
5397
+	 * Given an array where keys are column (or column alias) names and values,
5398
+	 * returns an array of their corresponding field names and database values
5399
+	 *
5400
+	 * @param string $cols_n_values
5401
+	 * @return array
5402
+	 */
5403
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5404
+	{
5405
+		$this_model_fields_n_values = array();
5406
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5407
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5408
+				$cols_n_values,
5409
+				$table_obj->get_fully_qualified_pk_column(),
5410
+				$table_obj->get_pk_column()
5411
+			);
5412
+			// there is a primary key on this table and its not set. Use defaults for all its columns
5413
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5414
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5415
+					if (! $field_obj->is_db_only_field()) {
5416
+						// prepare field as if its coming from db
5417
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5418
+						$this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5419
+					}
5420
+				}
5421
+			} else {
5422
+				// the table's rows existed. Use their values
5423
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5424
+					if (! $field_obj->is_db_only_field()) {
5425
+						$this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5426
+							$cols_n_values,
5427
+							$field_obj->get_qualified_column(),
5428
+							$field_obj->get_table_column()
5429
+						);
5430
+					}
5431
+				}
5432
+			}
5433
+		}
5434
+		return $this_model_fields_n_values;
5435
+	}
5436
+
5437
+
5438
+	/**
5439
+	 * @param $cols_n_values
5440
+	 * @param $qualified_column
5441
+	 * @param $regular_column
5442
+	 * @return null
5443
+	 * @throws EE_Error
5444
+	 * @throws ReflectionException
5445
+	 */
5446
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5447
+	{
5448
+		$value = null;
5449
+		// ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5450
+		// does the field on the model relate to this column retrieved from the db?
5451
+		// or is it a db-only field? (not relating to the model)
5452
+		if (isset($cols_n_values[ $qualified_column ])) {
5453
+			$value = $cols_n_values[ $qualified_column ];
5454
+		} elseif (isset($cols_n_values[ $regular_column ])) {
5455
+			$value = $cols_n_values[ $regular_column ];
5456
+		} elseif (! empty($this->foreign_key_aliases)) {
5457
+			// no PK?  ok check if there is a foreign key alias set for this table
5458
+			// then check if that alias exists in the incoming data
5459
+			// AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5460
+			foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5461
+				if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5462
+					$value = $cols_n_values[ $FK_alias ];
5463
+					list($pk_class) = explode('.', $PK_column);
5464
+					$pk_model_name = "EEM_{$pk_class}";
5465
+					/** @var EEM_Base $pk_model */
5466
+					$pk_model = EE_Registry::instance()->load_model($pk_model_name);
5467
+					if ($pk_model instanceof EEM_Base) {
5468
+						// make sure object is pulled from db and added to entity map
5469
+						$pk_model->get_one_by_ID($value);
5470
+					}
5471
+					break;
5472
+				}
5473
+			}
5474
+		}
5475
+		return $value;
5476
+	}
5477
+
5478
+
5479
+
5480
+	/**
5481
+	 * refresh_entity_map_from_db
5482
+	 * Makes sure the model object in the entity map at $id assumes the values
5483
+	 * of the database (opposite of EE_base_Class::save())
5484
+	 *
5485
+	 * @param int|string $id
5486
+	 * @return EE_Base_Class
5487
+	 * @throws EE_Error
5488
+	 */
5489
+	public function refresh_entity_map_from_db($id)
5490
+	{
5491
+		$obj_in_map = $this->get_from_entity_map($id);
5492
+		if ($obj_in_map) {
5493
+			$wpdb_results = $this->_get_all_wpdb_results(
5494
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5495
+			);
5496
+			if ($wpdb_results && is_array($wpdb_results)) {
5497
+				$one_row = reset($wpdb_results);
5498
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5499
+					$obj_in_map->set_from_db($field_name, $db_value);
5500
+				}
5501
+				// clear the cache of related model objects
5502
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5503
+					$obj_in_map->clear_cache($relation_name, null, true);
5504
+				}
5505
+			}
5506
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5507
+			return $obj_in_map;
5508
+		}
5509
+		return $this->get_one_by_ID($id);
5510
+	}
5511
+
5512
+
5513
+
5514
+	/**
5515
+	 * refresh_entity_map_with
5516
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5517
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5518
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5519
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5520
+	 *
5521
+	 * @param int|string    $id
5522
+	 * @param EE_Base_Class $replacing_model_obj
5523
+	 * @return \EE_Base_Class
5524
+	 * @throws EE_Error
5525
+	 */
5526
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5527
+	{
5528
+		$obj_in_map = $this->get_from_entity_map($id);
5529
+		if ($obj_in_map) {
5530
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5531
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5532
+					$obj_in_map->set($field_name, $value);
5533
+				}
5534
+				// make the model object in the entity map's cache match the $replacing_model_obj
5535
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5536
+					$obj_in_map->clear_cache($relation_name, null, true);
5537
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5538
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5539
+					}
5540
+				}
5541
+			}
5542
+			return $obj_in_map;
5543
+		}
5544
+		$this->add_to_entity_map($replacing_model_obj);
5545
+		return $replacing_model_obj;
5546
+	}
5547
+
5548
+
5549
+
5550
+	/**
5551
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5552
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5553
+	 * require_once($this->_getClassName().".class.php");
5554
+	 *
5555
+	 * @return string
5556
+	 */
5557
+	private function _get_class_name()
5558
+	{
5559
+		return "EE_" . $this->get_this_model_name();
5560
+	}
5561
+
5562
+
5563
+
5564
+	/**
5565
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5566
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5567
+	 * it would be 'Events'.
5568
+	 *
5569
+	 * @param int $quantity
5570
+	 * @return string
5571
+	 */
5572
+	public function item_name($quantity = 1)
5573
+	{
5574
+		return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5575
+	}
5576
+
5577
+
5578
+
5579
+	/**
5580
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5581
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5582
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5583
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5584
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5585
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5586
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5587
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5588
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5589
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5590
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5591
+	 *        return $previousReturnValue.$returnString;
5592
+	 * }
5593
+	 * require('EEM_Answer.model.php');
5594
+	 * $answer=EEM_Answer::instance();
5595
+	 * echo $answer->my_callback('monkeys',100);
5596
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5597
+	 *
5598
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5599
+	 * @param array  $args       array of original arguments passed to the function
5600
+	 * @throws EE_Error
5601
+	 * @return mixed whatever the plugin which calls add_filter decides
5602
+	 */
5603
+	public function __call($methodName, $args)
5604
+	{
5605
+		$className = get_class($this);
5606
+		$tagName = "FHEE__{$className}__{$methodName}";
5607
+		if (! has_filter($tagName)) {
5608
+			throw new EE_Error(
5609
+				sprintf(
5610
+					esc_html__(
5611
+						'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 );',
5612
+						'event_espresso'
5613
+					),
5614
+					$methodName,
5615
+					$className,
5616
+					$tagName,
5617
+					'<br />'
5618
+				)
5619
+			);
5620
+		}
5621
+		return apply_filters($tagName, null, $this, $args);
5622
+	}
5623
+
5624
+
5625
+
5626
+	/**
5627
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5628
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5629
+	 *
5630
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5631
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5632
+	 *                                                       the object's class name
5633
+	 *                                                       or object's ID
5634
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5635
+	 *                                                       exists in the database. If it does not, we add it
5636
+	 * @throws EE_Error
5637
+	 * @return EE_Base_Class
5638
+	 */
5639
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5640
+	{
5641
+		$className = $this->_get_class_name();
5642
+		if ($base_class_obj_or_id instanceof $className) {
5643
+			$model_object = $base_class_obj_or_id;
5644
+		} else {
5645
+			$primary_key_field = $this->get_primary_key_field();
5646
+			if (
5647
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5648
+				&& (
5649
+					is_int($base_class_obj_or_id)
5650
+					|| is_string($base_class_obj_or_id)
5651
+				)
5652
+			) {
5653
+				// assume it's an ID.
5654
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5655
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5656
+			} elseif (
5657
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5658
+				&& is_string($base_class_obj_or_id)
5659
+			) {
5660
+				// assume its a string representation of the object
5661
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5662
+			} else {
5663
+				throw new EE_Error(
5664
+					sprintf(
5665
+						esc_html__(
5666
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5667
+							'event_espresso'
5668
+						),
5669
+						$base_class_obj_or_id,
5670
+						$this->_get_class_name(),
5671
+						print_r($base_class_obj_or_id, true)
5672
+					)
5673
+				);
5674
+			}
5675
+		}
5676
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5677
+			$model_object->save();
5678
+		}
5679
+		return $model_object;
5680
+	}
5681
+
5682
+
5683
+
5684
+	/**
5685
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5686
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5687
+	 * returns it ID.
5688
+	 *
5689
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5690
+	 * @return int|string depending on the type of this model object's ID
5691
+	 * @throws EE_Error
5692
+	 */
5693
+	public function ensure_is_ID($base_class_obj_or_id)
5694
+	{
5695
+		$className = $this->_get_class_name();
5696
+		if ($base_class_obj_or_id instanceof $className) {
5697
+			/** @var $base_class_obj_or_id EE_Base_Class */
5698
+			$id = $base_class_obj_or_id->ID();
5699
+		} elseif (is_int($base_class_obj_or_id)) {
5700
+			// assume it's an ID
5701
+			$id = $base_class_obj_or_id;
5702
+		} elseif (is_string($base_class_obj_or_id)) {
5703
+			// assume its a string representation of the object
5704
+			$id = $base_class_obj_or_id;
5705
+		} else {
5706
+			throw new EE_Error(sprintf(
5707
+				esc_html__(
5708
+					"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5709
+					'event_espresso'
5710
+				),
5711
+				$base_class_obj_or_id,
5712
+				$this->_get_class_name(),
5713
+				print_r($base_class_obj_or_id, true)
5714
+			));
5715
+		}
5716
+		return $id;
5717
+	}
5718
+
5719
+
5720
+
5721
+	/**
5722
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5723
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5724
+	 * been sanitized and converted into the appropriate domain.
5725
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5726
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5727
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5728
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5729
+	 * $EVT = EEM_Event::instance(); $old_setting =
5730
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5731
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5732
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5733
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5734
+	 *
5735
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5736
+	 * @return void
5737
+	 */
5738
+	public function assume_values_already_prepared_by_model_object(
5739
+		$values_already_prepared = self::not_prepared_by_model_object
5740
+	) {
5741
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5742
+	}
5743
+
5744
+
5745
+
5746
+	/**
5747
+	 * Read comments for assume_values_already_prepared_by_model_object()
5748
+	 *
5749
+	 * @return int
5750
+	 */
5751
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5752
+	{
5753
+		return $this->_values_already_prepared_by_model_object;
5754
+	}
5755
+
5756
+
5757
+
5758
+	/**
5759
+	 * Gets all the indexes on this model
5760
+	 *
5761
+	 * @return EE_Index[]
5762
+	 */
5763
+	public function indexes()
5764
+	{
5765
+		return $this->_indexes;
5766
+	}
5767
+
5768
+
5769
+
5770
+	/**
5771
+	 * Gets all the Unique Indexes on this model
5772
+	 *
5773
+	 * @return EE_Unique_Index[]
5774
+	 */
5775
+	public function unique_indexes()
5776
+	{
5777
+		$unique_indexes = array();
5778
+		foreach ($this->_indexes as $name => $index) {
5779
+			if ($index instanceof EE_Unique_Index) {
5780
+				$unique_indexes [ $name ] = $index;
5781
+			}
5782
+		}
5783
+		return $unique_indexes;
5784
+	}
5785
+
5786
+
5787
+
5788
+	/**
5789
+	 * Gets all the fields which, when combined, make the primary key.
5790
+	 * This is usually just an array with 1 element (the primary key), but in cases
5791
+	 * where there is no primary key, it's a combination of fields as defined
5792
+	 * on a primary index
5793
+	 *
5794
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5795
+	 * @throws EE_Error
5796
+	 */
5797
+	public function get_combined_primary_key_fields()
5798
+	{
5799
+		foreach ($this->indexes() as $index) {
5800
+			if ($index instanceof EE_Primary_Key_Index) {
5801
+				return $index->fields();
5802
+			}
5803
+		}
5804
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5805
+	}
5806
+
5807
+
5808
+
5809
+	/**
5810
+	 * Used to build a primary key string (when the model has no primary key),
5811
+	 * which can be used a unique string to identify this model object.
5812
+	 *
5813
+	 * @param array $fields_n_values keys are field names, values are their values.
5814
+	 *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5815
+	 *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5816
+	 *                               before passing it to this function (that will convert it from columns-n-values
5817
+	 *                               to field-names-n-values).
5818
+	 * @return string
5819
+	 * @throws EE_Error
5820
+	 */
5821
+	public function get_index_primary_key_string($fields_n_values)
5822
+	{
5823
+		$cols_n_values_for_primary_key_index = array_intersect_key(
5824
+			$fields_n_values,
5825
+			$this->get_combined_primary_key_fields()
5826
+		);
5827
+		return http_build_query($cols_n_values_for_primary_key_index);
5828
+	}
5829
+
5830
+
5831
+
5832
+	/**
5833
+	 * Gets the field values from the primary key string
5834
+	 *
5835
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5836
+	 * @param string $index_primary_key_string
5837
+	 * @return null|array
5838
+	 * @throws EE_Error
5839
+	 */
5840
+	public function parse_index_primary_key_string($index_primary_key_string)
5841
+	{
5842
+		$key_fields = $this->get_combined_primary_key_fields();
5843
+		// check all of them are in the $id
5844
+		$key_vals_in_combined_pk = array();
5845
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5846
+		foreach ($key_fields as $key_field_name => $field_obj) {
5847
+			if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5848
+				return null;
5849
+			}
5850
+		}
5851
+		return $key_vals_in_combined_pk;
5852
+	}
5853
+
5854
+
5855
+
5856
+	/**
5857
+	 * verifies that an array of key-value pairs for model fields has a key
5858
+	 * for each field comprising the primary key index
5859
+	 *
5860
+	 * @param array $key_vals
5861
+	 * @return boolean
5862
+	 * @throws EE_Error
5863
+	 */
5864
+	public function has_all_combined_primary_key_fields($key_vals)
5865
+	{
5866
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5867
+		foreach ($keys_it_should_have as $key) {
5868
+			if (! isset($key_vals[ $key ])) {
5869
+				return false;
5870
+			}
5871
+		}
5872
+		return true;
5873
+	}
5874
+
5875
+
5876
+
5877
+	/**
5878
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5879
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5880
+	 *
5881
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5882
+	 * @param array               $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5883
+	 * @throws EE_Error
5884
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5885
+	 *                                                              indexed)
5886
+	 */
5887
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5888
+	{
5889
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5890
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5891
+		} elseif (is_array($model_object_or_attributes_array)) {
5892
+			$attributes_array = $model_object_or_attributes_array;
5893
+		} else {
5894
+			throw new EE_Error(sprintf(esc_html__(
5895
+				"get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5896
+				"event_espresso"
5897
+			), $model_object_or_attributes_array));
5898
+		}
5899
+		// even copies obviously won't have the same ID, so remove the primary key
5900
+		// from the WHERE conditions for finding copies (if there is a primary key, of course)
5901
+		if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5902
+			unset($attributes_array[ $this->primary_key_name() ]);
5903
+		}
5904
+		if (isset($query_params[0])) {
5905
+			$query_params[0] = array_merge($attributes_array, $query_params);
5906
+		} else {
5907
+			$query_params[0] = $attributes_array;
5908
+		}
5909
+		return $this->get_all($query_params);
5910
+	}
5911
+
5912
+
5913
+
5914
+	/**
5915
+	 * Gets the first copy we find. See get_all_copies for more details
5916
+	 *
5917
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5918
+	 * @param array $query_params
5919
+	 * @return EE_Base_Class
5920
+	 * @throws EE_Error
5921
+	 */
5922
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5923
+	{
5924
+		if (! is_array($query_params)) {
5925
+			EE_Error::doing_it_wrong(
5926
+				'EEM_Base::get_one_copy',
5927
+				sprintf(
5928
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5929
+					gettype($query_params)
5930
+				),
5931
+				'4.6.0'
5932
+			);
5933
+			$query_params = array();
5934
+		}
5935
+		$query_params['limit'] = 1;
5936
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5937
+		if (is_array($copies)) {
5938
+			return array_shift($copies);
5939
+		}
5940
+		return null;
5941
+	}
5942
+
5943
+
5944
+
5945
+	/**
5946
+	 * Updates the item with the specified id. Ignores default query parameters because
5947
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5948
+	 *
5949
+	 * @param array      $fields_n_values keys are field names, values are their new values
5950
+	 * @param int|string $id              the value of the primary key to update
5951
+	 * @return int number of rows updated
5952
+	 * @throws EE_Error
5953
+	 */
5954
+	public function update_by_ID($fields_n_values, $id)
5955
+	{
5956
+		$query_params = array(
5957
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5958
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5959
+		);
5960
+		return $this->update($fields_n_values, $query_params);
5961
+	}
5962
+
5963
+
5964
+
5965
+	/**
5966
+	 * Changes an operator which was supplied to the models into one usable in SQL
5967
+	 *
5968
+	 * @param string $operator_supplied
5969
+	 * @return string an operator which can be used in SQL
5970
+	 * @throws EE_Error
5971
+	 */
5972
+	private function _prepare_operator_for_sql($operator_supplied)
5973
+	{
5974
+		$sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5975
+			: null;
5976
+		if ($sql_operator) {
5977
+			return $sql_operator;
5978
+		}
5979
+		throw new EE_Error(
5980
+			sprintf(
5981
+				esc_html__(
5982
+					"The operator '%s' is not in the list of valid operators: %s",
5983
+					"event_espresso"
5984
+				),
5985
+				$operator_supplied,
5986
+				implode(",", array_keys($this->_valid_operators))
5987
+			)
5988
+		);
5989
+	}
5990
+
5991
+
5992
+
5993
+	/**
5994
+	 * Gets the valid operators
5995
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5996
+	 */
5997
+	public function valid_operators()
5998
+	{
5999
+		return $this->_valid_operators;
6000
+	}
6001
+
6002
+
6003
+
6004
+	/**
6005
+	 * Gets the between-style operators (take 2 arguments).
6006
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6007
+	 */
6008
+	public function valid_between_style_operators()
6009
+	{
6010
+		return array_intersect(
6011
+			$this->valid_operators(),
6012
+			$this->_between_style_operators
6013
+		);
6014
+	}
6015
+
6016
+	/**
6017
+	 * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6018
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6019
+	 */
6020
+	public function valid_like_style_operators()
6021
+	{
6022
+		return array_intersect(
6023
+			$this->valid_operators(),
6024
+			$this->_like_style_operators
6025
+		);
6026
+	}
6027
+
6028
+	/**
6029
+	 * Gets the "in"-style operators
6030
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6031
+	 */
6032
+	public function valid_in_style_operators()
6033
+	{
6034
+		return array_intersect(
6035
+			$this->valid_operators(),
6036
+			$this->_in_style_operators
6037
+		);
6038
+	}
6039
+
6040
+	/**
6041
+	 * Gets the "null"-style operators (accept no arguments)
6042
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6043
+	 */
6044
+	public function valid_null_style_operators()
6045
+	{
6046
+		return array_intersect(
6047
+			$this->valid_operators(),
6048
+			$this->_null_style_operators
6049
+		);
6050
+	}
6051
+
6052
+	/**
6053
+	 * Gets an array where keys are the primary keys and values are their 'names'
6054
+	 * (as determined by the model object's name() function, which is often overridden)
6055
+	 *
6056
+	 * @param array $query_params like get_all's
6057
+	 * @return string[]
6058
+	 * @throws EE_Error
6059
+	 */
6060
+	public function get_all_names($query_params = array())
6061
+	{
6062
+		$objs = $this->get_all($query_params);
6063
+		$names = array();
6064
+		foreach ($objs as $obj) {
6065
+			$names[ $obj->ID() ] = $obj->name();
6066
+		}
6067
+		return $names;
6068
+	}
6069
+
6070
+
6071
+
6072
+	/**
6073
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
6074
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6075
+	 * this is duplicated effort and reduces efficiency) you would be better to use
6076
+	 * array_keys() on $model_objects.
6077
+	 *
6078
+	 * @param \EE_Base_Class[] $model_objects
6079
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6080
+	 *                                               in the returned array
6081
+	 * @return array
6082
+	 * @throws EE_Error
6083
+	 */
6084
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
6085
+	{
6086
+		if (! $this->has_primary_key_field()) {
6087
+			if (WP_DEBUG) {
6088
+				EE_Error::add_error(
6089
+					esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6090
+					__FILE__,
6091
+					__FUNCTION__,
6092
+					__LINE__
6093
+				);
6094
+			}
6095
+		}
6096
+		$IDs = array();
6097
+		foreach ($model_objects as $model_object) {
6098
+			$id = $model_object->ID();
6099
+			if (! $id) {
6100
+				if ($filter_out_empty_ids) {
6101
+					continue;
6102
+				}
6103
+				if (WP_DEBUG) {
6104
+					EE_Error::add_error(
6105
+						esc_html__(
6106
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6107
+							'event_espresso'
6108
+						),
6109
+						__FILE__,
6110
+						__FUNCTION__,
6111
+						__LINE__
6112
+					);
6113
+				}
6114
+			}
6115
+			$IDs[] = $id;
6116
+		}
6117
+		return $IDs;
6118
+	}
6119
+
6120
+
6121
+
6122
+	/**
6123
+	 * Returns the string used in capabilities relating to this model. If there
6124
+	 * are no capabilities that relate to this model returns false
6125
+	 *
6126
+	 * @return string|false
6127
+	 */
6128
+	public function cap_slug()
6129
+	{
6130
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6131
+	}
6132
+
6133
+
6134
+
6135
+	/**
6136
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
6137
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6138
+	 * only returns the cap restrictions array in that context (ie, the array
6139
+	 * at that key)
6140
+	 *
6141
+	 * @param string $context
6142
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
6143
+	 * @throws EE_Error
6144
+	 */
6145
+	public function cap_restrictions($context = EEM_Base::caps_read)
6146
+	{
6147
+		EEM_Base::verify_is_valid_cap_context($context);
6148
+		// check if we ought to run the restriction generator first
6149
+		if (
6150
+			isset($this->_cap_restriction_generators[ $context ])
6151
+			&& $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6152
+			&& ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6153
+		) {
6154
+			$this->_cap_restrictions[ $context ] = array_merge(
6155
+				$this->_cap_restrictions[ $context ],
6156
+				$this->_cap_restriction_generators[ $context ]->generate_restrictions()
6157
+			);
6158
+		}
6159
+		// and make sure we've finalized the construction of each restriction
6160
+		foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6161
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6162
+				$where_conditions_obj->_finalize_construct($this);
6163
+			}
6164
+		}
6165
+		return $this->_cap_restrictions[ $context ];
6166
+	}
6167
+
6168
+
6169
+
6170
+	/**
6171
+	 * Indicating whether or not this model thinks its a wp core model
6172
+	 *
6173
+	 * @return boolean
6174
+	 */
6175
+	public function is_wp_core_model()
6176
+	{
6177
+		return $this->_wp_core_model;
6178
+	}
6179
+
6180
+
6181
+
6182
+	/**
6183
+	 * Gets all the caps that are missing which impose a restriction on
6184
+	 * queries made in this context
6185
+	 *
6186
+	 * @param string $context one of EEM_Base::caps_ constants
6187
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
6188
+	 * @throws EE_Error
6189
+	 */
6190
+	public function caps_missing($context = EEM_Base::caps_read)
6191
+	{
6192
+		$missing_caps = array();
6193
+		$cap_restrictions = $this->cap_restrictions($context);
6194
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6195
+			if (
6196
+				! EE_Capabilities::instance()
6197
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6198
+			) {
6199
+				$missing_caps[ $cap ] = $restriction_if_no_cap;
6200
+			}
6201
+		}
6202
+		return $missing_caps;
6203
+	}
6204
+
6205
+
6206
+
6207
+	/**
6208
+	 * Gets the mapping from capability contexts to action strings used in capability names
6209
+	 *
6210
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6211
+	 * one of 'read', 'edit', or 'delete'
6212
+	 */
6213
+	public function cap_contexts_to_cap_action_map()
6214
+	{
6215
+		return apply_filters(
6216
+			'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6217
+			$this->_cap_contexts_to_cap_action_map,
6218
+			$this
6219
+		);
6220
+	}
6221
+
6222
+
6223
+
6224
+	/**
6225
+	 * Gets the action string for the specified capability context
6226
+	 *
6227
+	 * @param string $context
6228
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6229
+	 * @throws EE_Error
6230
+	 */
6231
+	public function cap_action_for_context($context)
6232
+	{
6233
+		$mapping = $this->cap_contexts_to_cap_action_map();
6234
+		if (isset($mapping[ $context ])) {
6235
+			return $mapping[ $context ];
6236
+		}
6237
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6238
+			return $action;
6239
+		}
6240
+		throw new EE_Error(
6241
+			sprintf(
6242
+				esc_html__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6243
+				$context,
6244
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6245
+			)
6246
+		);
6247
+	}
6248
+
6249
+
6250
+
6251
+	/**
6252
+	 * Returns all the capability contexts which are valid when querying models
6253
+	 *
6254
+	 * @return array
6255
+	 */
6256
+	public static function valid_cap_contexts()
6257
+	{
6258
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6259
+			self::caps_read,
6260
+			self::caps_read_admin,
6261
+			self::caps_edit,
6262
+			self::caps_delete,
6263
+		));
6264
+	}
6265
+
6266
+
6267
+
6268
+	/**
6269
+	 * Returns all valid options for 'default_where_conditions'
6270
+	 *
6271
+	 * @return array
6272
+	 */
6273
+	public static function valid_default_where_conditions()
6274
+	{
6275
+		return array(
6276
+			EEM_Base::default_where_conditions_all,
6277
+			EEM_Base::default_where_conditions_this_only,
6278
+			EEM_Base::default_where_conditions_others_only,
6279
+			EEM_Base::default_where_conditions_minimum_all,
6280
+			EEM_Base::default_where_conditions_minimum_others,
6281
+			EEM_Base::default_where_conditions_none
6282
+		);
6283
+	}
6284
+
6285
+	// public static function default_where_conditions_full
6286
+	/**
6287
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6288
+	 *
6289
+	 * @param string $context
6290
+	 * @return bool
6291
+	 * @throws EE_Error
6292
+	 */
6293
+	public static function verify_is_valid_cap_context($context)
6294
+	{
6295
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
6296
+		if (in_array($context, $valid_cap_contexts)) {
6297
+			return true;
6298
+		}
6299
+		throw new EE_Error(
6300
+			sprintf(
6301
+				esc_html__(
6302
+					'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6303
+					'event_espresso'
6304
+				),
6305
+				$context,
6306
+				'EEM_Base',
6307
+				implode(',', $valid_cap_contexts)
6308
+			)
6309
+		);
6310
+	}
6311
+
6312
+
6313
+
6314
+	/**
6315
+	 * Clears all the models field caches. This is only useful when a sub-class
6316
+	 * might have added a field or something and these caches might be invalidated
6317
+	 */
6318
+	protected function _invalidate_field_caches()
6319
+	{
6320
+		$this->_cache_foreign_key_to_fields = array();
6321
+		$this->_cached_fields = null;
6322
+		$this->_cached_fields_non_db_only = null;
6323
+	}
6324
+
6325
+
6326
+
6327
+	/**
6328
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
6329
+	 * (eg "and", "or", "not").
6330
+	 *
6331
+	 * @return array
6332
+	 */
6333
+	public function logic_query_param_keys()
6334
+	{
6335
+		return $this->_logic_query_param_keys;
6336
+	}
6337
+
6338
+
6339
+
6340
+	/**
6341
+	 * Determines whether or not the where query param array key is for a logic query param.
6342
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6343
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6344
+	 *
6345
+	 * @param $query_param_key
6346
+	 * @return bool
6347
+	 */
6348
+	public function is_logic_query_param_key($query_param_key)
6349
+	{
6350
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6351
+			if (
6352
+				$query_param_key === $logic_query_param_key
6353
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
6354
+			) {
6355
+				return true;
6356
+			}
6357
+		}
6358
+		return false;
6359
+	}
6360
+
6361
+	/**
6362
+	 * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6363
+	 * @since 4.9.74.p
6364
+	 * @return boolean
6365
+	 */
6366
+	public function hasPassword()
6367
+	{
6368
+		// if we don't yet know if there's a password field, find out and remember it for next time.
6369
+		if ($this->has_password_field === null) {
6370
+			$password_field = $this->getPasswordField();
6371
+			$this->has_password_field = $password_field instanceof EE_Password_Field ? true : false;
6372
+		}
6373
+		return $this->has_password_field;
6374
+	}
6375
+
6376
+	/**
6377
+	 * Returns the password field on this model, if there is one
6378
+	 * @since 4.9.74.p
6379
+	 * @return EE_Password_Field|null
6380
+	 */
6381
+	public function getPasswordField()
6382
+	{
6383
+		// if we definetely already know there is a password field or not (because has_password_field is true or false)
6384
+		// there's no need to search for it. If we don't know yet, then find out
6385
+		if ($this->has_password_field === null && $this->password_field === null) {
6386
+			$this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6387
+		}
6388
+		// don't bother setting has_password_field because that's hasPassword()'s job.
6389
+		return $this->password_field;
6390
+	}
6391
+
6392
+
6393
+	/**
6394
+	 * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6395
+	 * @since 4.9.74.p
6396
+	 * @return EE_Model_Field_Base[]
6397
+	 * @throws EE_Error
6398
+	 */
6399
+	public function getPasswordProtectedFields()
6400
+	{
6401
+		$password_field = $this->getPasswordField();
6402
+		$fields = array();
6403
+		if ($password_field instanceof EE_Password_Field) {
6404
+			$field_names = $password_field->protectedFields();
6405
+			foreach ($field_names as $field_name) {
6406
+				$fields[ $field_name ] = $this->field_settings_for($field_name);
6407
+			}
6408
+		}
6409
+		return $fields;
6410
+	}
6411
+
6412
+
6413
+	/**
6414
+	 * Checks if the current user can perform the requested action on this model
6415
+	 * @since 4.9.74.p
6416
+	 * @param string $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6417
+	 * @param EE_Base_Class|array $model_obj_or_fields_n_values
6418
+	 * @return bool
6419
+	 * @throws EE_Error
6420
+	 * @throws InvalidArgumentException
6421
+	 * @throws InvalidDataTypeException
6422
+	 * @throws InvalidInterfaceException
6423
+	 * @throws ReflectionException
6424
+	 * @throws UnexpectedEntityException
6425
+	 */
6426
+	public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6427
+	{
6428
+		if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6429
+			$model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6430
+		}
6431
+		if (!is_array($model_obj_or_fields_n_values)) {
6432
+			throw new UnexpectedEntityException(
6433
+				$model_obj_or_fields_n_values,
6434
+				'EE_Base_Class',
6435
+				sprintf(
6436
+					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'),
6437
+					__FUNCTION__
6438
+				)
6439
+			);
6440
+		}
6441
+		return $this->exists(
6442
+			$this->alter_query_params_to_restrict_by_ID(
6443
+				$this->get_index_primary_key_string($model_obj_or_fields_n_values),
6444
+				array(
6445
+					'default_where_conditions' => 'none',
6446
+					'caps'                     => $cap_to_check,
6447
+				)
6448
+			)
6449
+		);
6450
+	}
6451
+
6452
+	/**
6453
+	 * Returns the query param where conditions key to the password affecting this model.
6454
+	 * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6455
+	 * @since 4.9.74.p
6456
+	 * @return null|string
6457
+	 * @throws EE_Error
6458
+	 * @throws InvalidArgumentException
6459
+	 * @throws InvalidDataTypeException
6460
+	 * @throws InvalidInterfaceException
6461
+	 * @throws ModelConfigurationException
6462
+	 * @throws ReflectionException
6463
+	 */
6464
+	public function modelChainAndPassword()
6465
+	{
6466
+		if ($this->model_chain_to_password === null) {
6467
+			throw new ModelConfigurationException(
6468
+				$this,
6469
+				esc_html_x(
6470
+				// @codingStandardsIgnoreStart
6471
+					'Cannot exclude protected data because the model has not specified which model has the password.',
6472
+					// @codingStandardsIgnoreEnd
6473
+					'1: model name',
6474
+					'event_espresso'
6475
+				)
6476
+			);
6477
+		}
6478
+		if ($this->model_chain_to_password === '') {
6479
+			$model_with_password = $this;
6480
+		} else {
6481
+			if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6482
+				$last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6483
+			} else {
6484
+				$last_model_in_chain = $this->model_chain_to_password;
6485
+			}
6486
+			$model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6487
+		}
6488
+
6489
+		$password_field = $model_with_password->getPasswordField();
6490
+		if ($password_field instanceof EE_Password_Field) {
6491
+			$password_field_name = $password_field->get_name();
6492
+		} else {
6493
+			throw new ModelConfigurationException(
6494
+				$this,
6495
+				sprintf(
6496
+					esc_html_x(
6497
+						'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"',
6498
+						'1: model name, 2: special string',
6499
+						'event_espresso'
6500
+					),
6501
+					$model_with_password->get_this_model_name(),
6502
+					$this->model_chain_to_password
6503
+				)
6504
+			);
6505
+		}
6506
+		return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6507
+	}
6508
+
6509
+	/**
6510
+	 * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6511
+	 * or if this model itself has a password affecting access to some of its other fields.
6512
+	 * @since 4.9.74.p
6513
+	 * @return boolean
6514
+	 */
6515
+	public function restrictedByRelatedModelPassword()
6516
+	{
6517
+		return $this->model_chain_to_password !== null;
6518
+	}
6519 6519
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Transaction.model.php 2 patches
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -143,7 +143,7 @@  discard block
 block discarded – undo
143 143
                 ),
144 144
             ],
145 145
         ];
146
-        $this->_model_relations        = [
146
+        $this->_model_relations = [
147 147
             'Registration'   => new EE_Has_Many_Relation(),
148 148
             'Payment'        => new EE_Has_Many_Relation(),
149 149
             'Status'         => new EE_Belongs_To_Relation(),
@@ -211,7 +211,7 @@  discard block
 block discarded – undo
211 211
             ],
212 212
             OBJECT,
213 213
             [
214
-                'txnDate' => ['DATE(' . $query_interval . ')', '%s'],
214
+                'txnDate' => ['DATE('.$query_interval.')', '%s'],
215 215
                 'revenue' => ['SUM(TransactionTable.TXN_paid)', '%d'],
216 216
             ]
217 217
         );
@@ -230,17 +230,17 @@  discard block
 block discarded – undo
230 230
     public function get_revenue_per_event_report($period = '-1 month')
231 231
     {
232 232
         global $wpdb;
233
-        $transaction_table          = $wpdb->prefix . 'esp_transaction';
234
-        $registration_table         = $wpdb->prefix . 'esp_registration';
235
-        $registration_payment_table = $wpdb->prefix . 'esp_registration_payment';
233
+        $transaction_table          = $wpdb->prefix.'esp_transaction';
234
+        $registration_table         = $wpdb->prefix.'esp_registration';
235
+        $registration_payment_table = $wpdb->prefix.'esp_registration_payment';
236 236
         $event_table                = $wpdb->posts;
237
-        $payment_table              = $wpdb->prefix . 'esp_payment';
237
+        $payment_table              = $wpdb->prefix.'esp_payment';
238 238
         $sql_date                   = date('Y-m-d H:i:s', strtotime($period));
239 239
         $approved_payment_status    = EEM_Payment::status_id_approved;
240 240
         $extra_event_on_join        = '';
241 241
         // exclude events not authored by user if permissions in effect
242
-        if (! EE_Registry::instance()->CAP->current_user_can('ee_read_others_registrations', 'reg_per_event_report')) {
243
-            $extra_event_on_join = ' AND Event.post_author = ' . get_current_user_id();
242
+        if ( ! EE_Registry::instance()->CAP->current_user_can('ee_read_others_registrations', 'reg_per_event_report')) {
243
+            $extra_event_on_join = ' AND Event.post_author = '.get_current_user_id();
244 244
         }
245 245
 
246 246
         return $wpdb->get_results(
@@ -318,7 +318,7 @@  discard block
 block discarded – undo
318 318
     public function update_based_on_payments($transaction_obj_or_id, $save_txn = true)
319 319
     {
320 320
         EE_Error::doing_it_wrong(
321
-            __CLASS__ . '::' . __FUNCTION__,
321
+            __CLASS__.'::'.__FUNCTION__,
322 322
             sprintf(
323 323
                 esc_html__('This method is deprecated. Please use "%s" instead', 'event_espresso'),
324 324
                 'EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()'
@@ -390,7 +390,7 @@  discard block
 block discarded – undo
390 390
             $time_to_leave_alone
391 391
         );
392 392
         // now that we have the ids to delete
393
-        if (! empty($txn_ids) && is_array($txn_ids)) {
393
+        if ( ! empty($txn_ids) && is_array($txn_ids)) {
394 394
             // first, make sure these TXN's are removed the "ee_locked_transactions" array
395 395
             EEM_Transaction::unset_locked_transactions($txn_ids);
396 396
 
@@ -403,7 +403,7 @@  discard block
 block discarded – undo
403 403
             // let's get deleting...
404 404
             // We got the ids from the original query to get them FROM
405 405
             // the db (which is sanitized) so no need to prepare them again.
406
-            $query   = $wpdb->prepare("DELETE FROM " . $this->table() . " WHERE TXN_ID IN ( $format )", $txn_ids);
406
+            $query   = $wpdb->prepare("DELETE FROM ".$this->table()." WHERE TXN_ID IN ( $format )", $txn_ids);
407 407
             $deleted = $wpdb->query($query);
408 408
         }
409 409
         if ($deleted) {
@@ -427,8 +427,8 @@  discard block
 block discarded – undo
427 427
         $locked_transactions = get_option('ee_locked_transactions', []);
428 428
         $update              = false;
429 429
         foreach ($transaction_IDs as $TXN_ID) {
430
-            if (isset($locked_transactions[ $TXN_ID ])) {
431
-                unset($locked_transactions[ $TXN_ID ]);
430
+            if (isset($locked_transactions[$TXN_ID])) {
431
+                unset($locked_transactions[$TXN_ID]);
432 432
                 $update = true;
433 433
             }
434 434
         }
Please login to merge, or discard this patch.
Indentation   +457 added lines, -457 removed lines patch added patch discarded remove patch
@@ -19,231 +19,231 @@  discard block
 block discarded – undo
19 19
  */
20 20
 class EEM_Transaction extends EEM_Base
21 21
 {
22
-    // private instance of the Transaction object
23
-    protected static $_instance;
24
-
25
-    /**
26
-     * Status ID(STS_ID on esp_status table) to indicate the transaction is complete,
27
-     * but payment is pending. This is the state for transactions where payment is promised
28
-     * from an offline gateway.
29
-     */
30
-    //  const open_status_code = 'TPN';
31
-
32
-    /**
33
-     * Status ID(STS_ID on esp_status table) to indicate the transaction failed,
34
-     * either due to a technical reason (server or computer crash during registration),
35
-     *  or some other reason that prevent the collection of any useful contact information from any of the registrants
36
-     */
37
-    const failed_status_code = 'TFL';
38
-
39
-    /**
40
-     * Status ID(STS_ID on esp_status table) to indicate the transaction was abandoned,
41
-     * either due to a technical reason (server or computer crash during registration),
42
-     * or due to an abandoned cart after registrant chose not to complete the registration process
43
-     * HOWEVER...
44
-     * an abandoned TXN differs from a failed TXN in that it was able to capture contact information for at least one
45
-     * registrant
46
-     */
47
-    const abandoned_status_code = 'TAB';
48
-
49
-    /**
50
-     * Status ID(STS_ID on esp_status table) to indicate an incomplete transaction,
51
-     * meaning that monies are still owing: TXN_paid < TXN_total
52
-     */
53
-    const incomplete_status_code = 'TIN';
54
-
55
-    /**
56
-     * Status ID (STS_ID on esp_status table) to indicate a complete transaction.
57
-     * meaning that NO monies are owing: TXN_paid == TXN_total
58
-     */
59
-    const complete_status_code = 'TCM';
60
-
61
-    /**
62
-     *  Status ID(STS_ID on esp_status table) to indicate the transaction is overpaid.
63
-     *  This is the same as complete, but site admins actually owe clients the moneys!  TXN_paid > TXN_total
64
-     */
65
-    const overpaid_status_code = 'TOP';
66
-
67
-
68
-    /**
69
-     *    private constructor to prevent direct creation
70
-     *
71
-     * @Constructor
72
-     * @access protected
73
-     *
74
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
75
-     *                         incoming timezone data that gets saved). Note this just sends the timezone info to the
76
-     *                         date time model field objects.  Default is NULL (and will be assumed using the set
77
-     *                         timezone in the 'timezone_string' wp option)
78
-     *
79
-     * @throws EE_Error
80
-     */
81
-    protected function __construct($timezone)
82
-    {
83
-        $this->singular_item = esc_html__('Transaction', 'event_espresso');
84
-        $this->plural_item   = esc_html__('Transactions', 'event_espresso');
85
-
86
-        $this->_tables                 = [
87
-            'TransactionTable' => new EE_Primary_Table('esp_transaction', 'TXN_ID'),
88
-        ];
89
-        $this->_fields                 = [
90
-            'TransactionTable' => [
91
-                'TXN_ID'           => new EE_Primary_Key_Int_Field('TXN_ID', esc_html__('Transaction ID', 'event_espresso')),
92
-                'TXN_timestamp'    => new EE_Datetime_Field(
93
-                    'TXN_timestamp',
94
-                    esc_html__('date when transaction was created', 'event_espresso'),
95
-                    false,
96
-                    EE_Datetime_Field::now,
97
-                    $timezone
98
-                ),
99
-                'TXN_total'        => new EE_Money_Field(
100
-                    'TXN_total',
101
-                    esc_html__('Total value of Transaction', 'event_espresso'),
102
-                    false,
103
-                    0
104
-                ),
105
-                'TXN_paid'         => new EE_Money_Field(
106
-                    'TXN_paid',
107
-                    esc_html__('Amount paid towards transaction to date', 'event_espresso'),
108
-                    false,
109
-                    0
110
-                ),
111
-                'STS_ID'           => new EE_Foreign_Key_String_Field(
112
-                    'STS_ID',
113
-                    esc_html__('Status ID', 'event_espresso'),
114
-                    false,
115
-                    EEM_Transaction::failed_status_code,
116
-                    'Status'
117
-                ),
118
-                'TXN_session_data' => new EE_Serialized_Text_Field(
119
-                    'TXN_session_data',
120
-                    esc_html__('Serialized session data', 'event_espresso'),
121
-                    true,
122
-                    ''
123
-                ),
124
-                'TXN_hash_salt'    => new EE_Plain_Text_Field(
125
-                    'TXN_hash_salt',
126
-                    esc_html__('Transaction Hash Salt', 'event_espresso'),
127
-                    true,
128
-                    ''
129
-                ),
130
-                'PMD_ID'           => new EE_Foreign_Key_Int_Field(
131
-                    'PMD_ID',
132
-                    esc_html__("Last Used Payment Method", 'event_espresso'),
133
-                    true,
134
-                    null,
135
-                    'Payment_Method'
136
-                ),
137
-                'TXN_reg_steps'    => new EE_Serialized_Text_Field(
138
-                    'TXN_reg_steps',
139
-                    esc_html__('Registration Steps', 'event_espresso'),
140
-                    false,
141
-                    []
142
-                ),
143
-            ],
144
-        ];
145
-        $this->_model_relations        = [
146
-            'Registration'   => new EE_Has_Many_Relation(),
147
-            'Payment'        => new EE_Has_Many_Relation(),
148
-            'Status'         => new EE_Belongs_To_Relation(),
149
-            'Line_Item'      => new EE_Has_Many_Relation(false),
150
-            // you can delete a transaction without needing to delete its line items
151
-            'Payment_Method' => new EE_Belongs_To_Relation(),
152
-            'Message'        => new EE_Has_Many_Relation(),
153
-        ];
154
-        $this->_model_chain_to_wp_user = 'Registration.Event';
155
-        parent::__construct($timezone);
156
-    }
157
-
158
-
159
-    /**
160
-     *    txn_status_array
161
-     * get list of transaction statuses
162
-     *
163
-     * @access public
164
-     * @return array
165
-     */
166
-    public static function txn_status_array()
167
-    {
168
-        return apply_filters(
169
-            'FHEE__EEM_Transaction__txn_status_array',
170
-            [
171
-                EEM_Transaction::overpaid_status_code,
172
-                EEM_Transaction::complete_status_code,
173
-                EEM_Transaction::incomplete_status_code,
174
-                EEM_Transaction::abandoned_status_code,
175
-                EEM_Transaction::failed_status_code,
176
-            ]
177
-        );
178
-    }
179
-
180
-
181
-    /**
182
-     *        get the revenue per day  for the Transaction Admin page Reports Tab
183
-     *
184
-     * @access        public
185
-     *
186
-     * @param string $period
187
-     *
188
-     * @return stdClass[]
189
-     * @throws EE_Error
190
-     * @throws EE_Error
191
-     */
192
-    public function get_revenue_per_day_report($period = '-1 month')
193
-    {
194
-        $sql_date = $this->convert_datetime_for_query(
195
-            'TXN_timestamp',
196
-            date('Y-m-d H:i:s', strtotime($period)),
197
-            'Y-m-d H:i:s',
198
-            'UTC'
199
-        );
200
-
201
-        $query_interval = EEH_DTT_Helper::get_sql_query_interval_for_offset($this->get_timezone(), 'TXN_timestamp');
202
-
203
-        return $this->_get_all_wpdb_results(
204
-            [
205
-                [
206
-                    'TXN_timestamp' => ['>=', $sql_date],
207
-                ],
208
-                'group_by' => 'txnDate',
209
-                'order_by' => ['TXN_timestamp' => 'ASC'],
210
-            ],
211
-            OBJECT,
212
-            [
213
-                'txnDate' => ['DATE(' . $query_interval . ')', '%s'],
214
-                'revenue' => ['SUM(TransactionTable.TXN_paid)', '%d'],
215
-            ]
216
-        );
217
-    }
218
-
219
-
220
-    /**
221
-     *        get the revenue per event  for the Transaction Admin page Reports Tab
222
-     *
223
-     * @access        public
224
-     *
225
-     * @param string $period
226
-     *
227
-     * @return EE_Transaction[]
228
-     */
229
-    public function get_revenue_per_event_report($period = '-1 month')
230
-    {
231
-        global $wpdb;
232
-        $transaction_table          = $wpdb->prefix . 'esp_transaction';
233
-        $registration_table         = $wpdb->prefix . 'esp_registration';
234
-        $registration_payment_table = $wpdb->prefix . 'esp_registration_payment';
235
-        $event_table                = $wpdb->posts;
236
-        $payment_table              = $wpdb->prefix . 'esp_payment';
237
-        $sql_date                   = date('Y-m-d H:i:s', strtotime($period));
238
-        $approved_payment_status    = EEM_Payment::status_id_approved;
239
-        $extra_event_on_join        = '';
240
-        // exclude events not authored by user if permissions in effect
241
-        if (! EE_Registry::instance()->CAP->current_user_can('ee_read_others_registrations', 'reg_per_event_report')) {
242
-            $extra_event_on_join = ' AND Event.post_author = ' . get_current_user_id();
243
-        }
244
-
245
-        return $wpdb->get_results(
246
-            "SELECT
22
+	// private instance of the Transaction object
23
+	protected static $_instance;
24
+
25
+	/**
26
+	 * Status ID(STS_ID on esp_status table) to indicate the transaction is complete,
27
+	 * but payment is pending. This is the state for transactions where payment is promised
28
+	 * from an offline gateway.
29
+	 */
30
+	//  const open_status_code = 'TPN';
31
+
32
+	/**
33
+	 * Status ID(STS_ID on esp_status table) to indicate the transaction failed,
34
+	 * either due to a technical reason (server or computer crash during registration),
35
+	 *  or some other reason that prevent the collection of any useful contact information from any of the registrants
36
+	 */
37
+	const failed_status_code = 'TFL';
38
+
39
+	/**
40
+	 * Status ID(STS_ID on esp_status table) to indicate the transaction was abandoned,
41
+	 * either due to a technical reason (server or computer crash during registration),
42
+	 * or due to an abandoned cart after registrant chose not to complete the registration process
43
+	 * HOWEVER...
44
+	 * an abandoned TXN differs from a failed TXN in that it was able to capture contact information for at least one
45
+	 * registrant
46
+	 */
47
+	const abandoned_status_code = 'TAB';
48
+
49
+	/**
50
+	 * Status ID(STS_ID on esp_status table) to indicate an incomplete transaction,
51
+	 * meaning that monies are still owing: TXN_paid < TXN_total
52
+	 */
53
+	const incomplete_status_code = 'TIN';
54
+
55
+	/**
56
+	 * Status ID (STS_ID on esp_status table) to indicate a complete transaction.
57
+	 * meaning that NO monies are owing: TXN_paid == TXN_total
58
+	 */
59
+	const complete_status_code = 'TCM';
60
+
61
+	/**
62
+	 *  Status ID(STS_ID on esp_status table) to indicate the transaction is overpaid.
63
+	 *  This is the same as complete, but site admins actually owe clients the moneys!  TXN_paid > TXN_total
64
+	 */
65
+	const overpaid_status_code = 'TOP';
66
+
67
+
68
+	/**
69
+	 *    private constructor to prevent direct creation
70
+	 *
71
+	 * @Constructor
72
+	 * @access protected
73
+	 *
74
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
75
+	 *                         incoming timezone data that gets saved). Note this just sends the timezone info to the
76
+	 *                         date time model field objects.  Default is NULL (and will be assumed using the set
77
+	 *                         timezone in the 'timezone_string' wp option)
78
+	 *
79
+	 * @throws EE_Error
80
+	 */
81
+	protected function __construct($timezone)
82
+	{
83
+		$this->singular_item = esc_html__('Transaction', 'event_espresso');
84
+		$this->plural_item   = esc_html__('Transactions', 'event_espresso');
85
+
86
+		$this->_tables                 = [
87
+			'TransactionTable' => new EE_Primary_Table('esp_transaction', 'TXN_ID'),
88
+		];
89
+		$this->_fields                 = [
90
+			'TransactionTable' => [
91
+				'TXN_ID'           => new EE_Primary_Key_Int_Field('TXN_ID', esc_html__('Transaction ID', 'event_espresso')),
92
+				'TXN_timestamp'    => new EE_Datetime_Field(
93
+					'TXN_timestamp',
94
+					esc_html__('date when transaction was created', 'event_espresso'),
95
+					false,
96
+					EE_Datetime_Field::now,
97
+					$timezone
98
+				),
99
+				'TXN_total'        => new EE_Money_Field(
100
+					'TXN_total',
101
+					esc_html__('Total value of Transaction', 'event_espresso'),
102
+					false,
103
+					0
104
+				),
105
+				'TXN_paid'         => new EE_Money_Field(
106
+					'TXN_paid',
107
+					esc_html__('Amount paid towards transaction to date', 'event_espresso'),
108
+					false,
109
+					0
110
+				),
111
+				'STS_ID'           => new EE_Foreign_Key_String_Field(
112
+					'STS_ID',
113
+					esc_html__('Status ID', 'event_espresso'),
114
+					false,
115
+					EEM_Transaction::failed_status_code,
116
+					'Status'
117
+				),
118
+				'TXN_session_data' => new EE_Serialized_Text_Field(
119
+					'TXN_session_data',
120
+					esc_html__('Serialized session data', 'event_espresso'),
121
+					true,
122
+					''
123
+				),
124
+				'TXN_hash_salt'    => new EE_Plain_Text_Field(
125
+					'TXN_hash_salt',
126
+					esc_html__('Transaction Hash Salt', 'event_espresso'),
127
+					true,
128
+					''
129
+				),
130
+				'PMD_ID'           => new EE_Foreign_Key_Int_Field(
131
+					'PMD_ID',
132
+					esc_html__("Last Used Payment Method", 'event_espresso'),
133
+					true,
134
+					null,
135
+					'Payment_Method'
136
+				),
137
+				'TXN_reg_steps'    => new EE_Serialized_Text_Field(
138
+					'TXN_reg_steps',
139
+					esc_html__('Registration Steps', 'event_espresso'),
140
+					false,
141
+					[]
142
+				),
143
+			],
144
+		];
145
+		$this->_model_relations        = [
146
+			'Registration'   => new EE_Has_Many_Relation(),
147
+			'Payment'        => new EE_Has_Many_Relation(),
148
+			'Status'         => new EE_Belongs_To_Relation(),
149
+			'Line_Item'      => new EE_Has_Many_Relation(false),
150
+			// you can delete a transaction without needing to delete its line items
151
+			'Payment_Method' => new EE_Belongs_To_Relation(),
152
+			'Message'        => new EE_Has_Many_Relation(),
153
+		];
154
+		$this->_model_chain_to_wp_user = 'Registration.Event';
155
+		parent::__construct($timezone);
156
+	}
157
+
158
+
159
+	/**
160
+	 *    txn_status_array
161
+	 * get list of transaction statuses
162
+	 *
163
+	 * @access public
164
+	 * @return array
165
+	 */
166
+	public static function txn_status_array()
167
+	{
168
+		return apply_filters(
169
+			'FHEE__EEM_Transaction__txn_status_array',
170
+			[
171
+				EEM_Transaction::overpaid_status_code,
172
+				EEM_Transaction::complete_status_code,
173
+				EEM_Transaction::incomplete_status_code,
174
+				EEM_Transaction::abandoned_status_code,
175
+				EEM_Transaction::failed_status_code,
176
+			]
177
+		);
178
+	}
179
+
180
+
181
+	/**
182
+	 *        get the revenue per day  for the Transaction Admin page Reports Tab
183
+	 *
184
+	 * @access        public
185
+	 *
186
+	 * @param string $period
187
+	 *
188
+	 * @return stdClass[]
189
+	 * @throws EE_Error
190
+	 * @throws EE_Error
191
+	 */
192
+	public function get_revenue_per_day_report($period = '-1 month')
193
+	{
194
+		$sql_date = $this->convert_datetime_for_query(
195
+			'TXN_timestamp',
196
+			date('Y-m-d H:i:s', strtotime($period)),
197
+			'Y-m-d H:i:s',
198
+			'UTC'
199
+		);
200
+
201
+		$query_interval = EEH_DTT_Helper::get_sql_query_interval_for_offset($this->get_timezone(), 'TXN_timestamp');
202
+
203
+		return $this->_get_all_wpdb_results(
204
+			[
205
+				[
206
+					'TXN_timestamp' => ['>=', $sql_date],
207
+				],
208
+				'group_by' => 'txnDate',
209
+				'order_by' => ['TXN_timestamp' => 'ASC'],
210
+			],
211
+			OBJECT,
212
+			[
213
+				'txnDate' => ['DATE(' . $query_interval . ')', '%s'],
214
+				'revenue' => ['SUM(TransactionTable.TXN_paid)', '%d'],
215
+			]
216
+		);
217
+	}
218
+
219
+
220
+	/**
221
+	 *        get the revenue per event  for the Transaction Admin page Reports Tab
222
+	 *
223
+	 * @access        public
224
+	 *
225
+	 * @param string $period
226
+	 *
227
+	 * @return EE_Transaction[]
228
+	 */
229
+	public function get_revenue_per_event_report($period = '-1 month')
230
+	{
231
+		global $wpdb;
232
+		$transaction_table          = $wpdb->prefix . 'esp_transaction';
233
+		$registration_table         = $wpdb->prefix . 'esp_registration';
234
+		$registration_payment_table = $wpdb->prefix . 'esp_registration_payment';
235
+		$event_table                = $wpdb->posts;
236
+		$payment_table              = $wpdb->prefix . 'esp_payment';
237
+		$sql_date                   = date('Y-m-d H:i:s', strtotime($period));
238
+		$approved_payment_status    = EEM_Payment::status_id_approved;
239
+		$extra_event_on_join        = '';
240
+		// exclude events not authored by user if permissions in effect
241
+		if (! EE_Registry::instance()->CAP->current_user_can('ee_read_others_registrations', 'reg_per_event_report')) {
242
+			$extra_event_on_join = ' AND Event.post_author = ' . get_current_user_id();
243
+		}
244
+
245
+		return $wpdb->get_results(
246
+			"SELECT
247 247
 			Transaction_Event.event_name AS event_name,
248 248
 			SUM(Transaction_Event.paid) AS revenue
249 249
 			FROM
@@ -271,236 +271,236 @@  discard block
 block discarded – undo
271 271
 					$extra_event_on_join
272 272
 				) AS Transaction_Event
273 273
 			GROUP BY event_name"
274
-        );
275
-    }
276
-
277
-
278
-    /**
279
-     * Gets the current transaction given the reg_url_link, or assumes the reg_url_link is in the
280
-     * request global variable. Either way, tries to find the current transaction (through
281
-     * the registration pointed to by reg_url_link), if not returns null
282
-     *
283
-     * @param string $reg_url_link
284
-     *
285
-     * @return EE_Transaction
286
-     * @throws EE_Error
287
-     */
288
-    public function get_transaction_from_reg_url_link($reg_url_link = '')
289
-    {
290
-        if (empty($reg_url_link)) {
291
-            $request      = LoaderFactory::getLoader()->getShared(RequestInterface::class);
292
-            $reg_url_link = $request->getRequestParam('e_reg_url_link');
293
-        }
294
-        return $this->get_one(
295
-            [
296
-                [
297
-                    'Registration.REG_url_link' => $reg_url_link,
298
-                ],
299
-            ]
300
-        );
301
-    }
302
-
303
-
304
-    /**
305
-     * Updates the provided EE_Transaction with all the applicable payments
306
-     * (or fetch the EE_Transaction from its ID)
307
-     *
308
-     * @param EE_Transaction|int $transaction_obj_or_id
309
-     * @param boolean            $save_txn whether or not to save the transaction during this function call
310
-     *
311
-     * @return array
312
-     * @throws EE_Error
313
-     * @throws ReflectionException
314
-     * @deprecated
315
-     *
316
-     */
317
-    public function update_based_on_payments($transaction_obj_or_id, $save_txn = true)
318
-    {
319
-        EE_Error::doing_it_wrong(
320
-            __CLASS__ . '::' . __FUNCTION__,
321
-            sprintf(
322
-                esc_html__('This method is deprecated. Please use "%s" instead', 'event_espresso'),
323
-                'EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()'
324
-            ),
325
-            '4.6.0'
326
-        );
327
-        /** @type EE_Transaction_Processor $transaction_processor */
328
-        $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
329
-
330
-        return $transaction_processor->update_transaction_and_registrations_after_checkout_or_payment(
331
-            $this->ensure_is_obj($transaction_obj_or_id)
332
-        );
333
-    }
334
-
335
-
336
-    /**
337
-     * Deletes "junk" transactions that were probably added by bots. There might be TONS
338
-     * of these, so we are very careful to NOT select (which the models do even when deleting),
339
-     * and so we only use wpdb directly and only do minimal joins.
340
-     * Transactions are considered "junk" if they're failed for longer than a week.
341
-     * Also, there is an extra check for payments related to the transaction, because if a transaction has a payment on
342
-     * it, it's probably not junk (regardless of what status it has).
343
-     * The downside to this approach is that is addons are listening for object deletions
344
-     * on EEM_Base::delete() they won't be notified of this.  However, there is an action that plugins can hook into
345
-     * to catch these types of deletions.
346
-     *
347
-     * @return int
348
-     * @throws EE_Error
349
-     * @throws EE_Error
350
-     * @global WPDB $wpdb
351
-     */
352
-    public function delete_junk_transactions()
353
-    {
354
-        global $wpdb;
355
-        $deleted             = false;
356
-        $time_to_leave_alone = (int) apply_filters(
357
-            'FHEE__EEM_Transaction__delete_junk_transactions__time_to_leave_alone',
358
-            WEEK_IN_SECONDS
359
-        );
360
-
361
-
362
-        /**
363
-         * This allows code to filter the query arguments used for retrieving the transaction IDs to delete.
364
-         * Useful for plugins that want to exclude transactions matching certain query parameters.
365
-         * The query parameters should be in the format accepted by the EEM_Base model queries.
366
-         */
367
-        $ids_query = apply_filters(
368
-            'FHEE__EEM_Transaction__delete_junk_transactions__initial_query_args',
369
-            [
370
-                0          => [
371
-                    'STS_ID'         => EEM_Transaction::failed_status_code,
372
-                    'Payment.PAY_ID' => ['IS NULL'],
373
-                    'TXN_timestamp'  => ['<', time() - $time_to_leave_alone],
374
-                ],
375
-                'order_by' => ['TXN_timestamp' => 'ASC'],
376
-                'limit'    => 1000,
377
-            ],
378
-            $time_to_leave_alone
379
-        );
380
-
381
-
382
-        /**
383
-         * This filter is for when code needs to filter the list of transaction ids that represent transactions
384
-         * about to be deleted based on some other criteria that isn't easily done via the query args filter.
385
-         */
386
-        $txn_ids = apply_filters(
387
-            'FHEE__EEM_Transaction__delete_junk_transactions__transaction_ids_to_delete',
388
-            EEM_Transaction::instance()->get_col($ids_query, 'TXN_ID'),
389
-            $time_to_leave_alone
390
-        );
391
-        // now that we have the ids to delete
392
-        if (! empty($txn_ids) && is_array($txn_ids)) {
393
-            // first, make sure these TXN's are removed the "ee_locked_transactions" array
394
-            EEM_Transaction::unset_locked_transactions($txn_ids);
395
-
396
-            // Create IDs placeholder.
397
-            $placeholders = array_fill(0, count($txn_ids), '%d');
398
-
399
-            // Glue it together to use inside $wpdb->prepare.
400
-            $format = implode(', ', $placeholders);
401
-
402
-            // let's get deleting...
403
-            // We got the ids from the original query to get them FROM
404
-            // the db (which is sanitized) so no need to prepare them again.
405
-            $query   = $wpdb->prepare("DELETE FROM " . $this->table() . " WHERE TXN_ID IN ( $format )", $txn_ids);
406
-            $deleted = $wpdb->query($query);
407
-        }
408
-        if ($deleted) {
409
-            /**
410
-             * Allows code to do something after the transactions have been deleted.
411
-             */
412
-            do_action('AHEE__EEM_Transaction__delete_junk_transactions__successful_deletion', $txn_ids);
413
-        }
414
-
415
-        return $deleted;
416
-    }
417
-
418
-
419
-    /**
420
-     * @param array $transaction_IDs
421
-     *
422
-     * @return bool
423
-     */
424
-    public static function unset_locked_transactions(array $transaction_IDs)
425
-    {
426
-        $locked_transactions = get_option('ee_locked_transactions', []);
427
-        $update              = false;
428
-        foreach ($transaction_IDs as $TXN_ID) {
429
-            if (isset($locked_transactions[ $TXN_ID ])) {
430
-                unset($locked_transactions[ $TXN_ID ]);
431
-                $update = true;
432
-            }
433
-        }
434
-        if ($update) {
435
-            update_option('ee_locked_transactions', $locked_transactions);
436
-        }
437
-
438
-        return $update;
439
-    }
440
-
441
-
442
-    /**
443
-     * returns an array of EE_Transaction objects whose timestamp is greater than
444
-     * the current time minus the session lifespan, which defaults to 60 minutes
445
-     *
446
-     * @return EE_Base_Class[]|EE_Transaction[]
447
-     * @throws EE_Error
448
-     * @throws InvalidArgumentException
449
-     * @throws InvalidDataTypeException
450
-     * @throws InvalidInterfaceException
451
-     */
452
-    public function get_transactions_in_progress()
453
-    {
454
-        return $this->_get_transactions_in_progress();
455
-    }
456
-
457
-
458
-    /**
459
-     * returns an array of EE_Transaction objects whose timestamp is less than
460
-     * the current time minus the session lifespan, which defaults to 60 minutes
461
-     *
462
-     * @return EE_Base_Class[]|EE_Transaction[]
463
-     * @throws EE_Error
464
-     * @throws InvalidArgumentException
465
-     * @throws InvalidDataTypeException
466
-     * @throws InvalidInterfaceException
467
-     */
468
-    public function get_transactions_not_in_progress()
469
-    {
470
-        return $this->_get_transactions_in_progress('<=');
471
-    }
472
-
473
-
474
-    /**
475
-     * @param string $comparison
476
-     * @return EE_Transaction[]
477
-     * @throws EE_Error
478
-     * @throws InvalidArgumentException
479
-     * @throws InvalidDataTypeException
480
-     * @throws InvalidInterfaceException
481
-     */
482
-    private function _get_transactions_in_progress($comparison = '>=')
483
-    {
484
-        $comparison = $comparison === '>=' || $comparison === '<='
485
-            ? $comparison
486
-            : '>=';
487
-        /** @var EventEspresso\core\domain\values\session\SessionLifespan $session_lifespan */
488
-        $session_lifespan = LoaderFactory::getLoader()->getShared(
489
-            'EventEspresso\core\domain\values\session\SessionLifespan'
490
-        );
491
-        return $this->get_all(
492
-            [
493
-                [
494
-                    'TXN_timestamp' => [
495
-                        $comparison,
496
-                        $session_lifespan->expiration(),
497
-                    ],
498
-                    'STS_ID'        => [
499
-                        '!=',
500
-                        EEM_Transaction::complete_status_code,
501
-                    ],
502
-                ],
503
-            ]
504
-        );
505
-    }
274
+		);
275
+	}
276
+
277
+
278
+	/**
279
+	 * Gets the current transaction given the reg_url_link, or assumes the reg_url_link is in the
280
+	 * request global variable. Either way, tries to find the current transaction (through
281
+	 * the registration pointed to by reg_url_link), if not returns null
282
+	 *
283
+	 * @param string $reg_url_link
284
+	 *
285
+	 * @return EE_Transaction
286
+	 * @throws EE_Error
287
+	 */
288
+	public function get_transaction_from_reg_url_link($reg_url_link = '')
289
+	{
290
+		if (empty($reg_url_link)) {
291
+			$request      = LoaderFactory::getLoader()->getShared(RequestInterface::class);
292
+			$reg_url_link = $request->getRequestParam('e_reg_url_link');
293
+		}
294
+		return $this->get_one(
295
+			[
296
+				[
297
+					'Registration.REG_url_link' => $reg_url_link,
298
+				],
299
+			]
300
+		);
301
+	}
302
+
303
+
304
+	/**
305
+	 * Updates the provided EE_Transaction with all the applicable payments
306
+	 * (or fetch the EE_Transaction from its ID)
307
+	 *
308
+	 * @param EE_Transaction|int $transaction_obj_or_id
309
+	 * @param boolean            $save_txn whether or not to save the transaction during this function call
310
+	 *
311
+	 * @return array
312
+	 * @throws EE_Error
313
+	 * @throws ReflectionException
314
+	 * @deprecated
315
+	 *
316
+	 */
317
+	public function update_based_on_payments($transaction_obj_or_id, $save_txn = true)
318
+	{
319
+		EE_Error::doing_it_wrong(
320
+			__CLASS__ . '::' . __FUNCTION__,
321
+			sprintf(
322
+				esc_html__('This method is deprecated. Please use "%s" instead', 'event_espresso'),
323
+				'EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()'
324
+			),
325
+			'4.6.0'
326
+		);
327
+		/** @type EE_Transaction_Processor $transaction_processor */
328
+		$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
329
+
330
+		return $transaction_processor->update_transaction_and_registrations_after_checkout_or_payment(
331
+			$this->ensure_is_obj($transaction_obj_or_id)
332
+		);
333
+	}
334
+
335
+
336
+	/**
337
+	 * Deletes "junk" transactions that were probably added by bots. There might be TONS
338
+	 * of these, so we are very careful to NOT select (which the models do even when deleting),
339
+	 * and so we only use wpdb directly and only do minimal joins.
340
+	 * Transactions are considered "junk" if they're failed for longer than a week.
341
+	 * Also, there is an extra check for payments related to the transaction, because if a transaction has a payment on
342
+	 * it, it's probably not junk (regardless of what status it has).
343
+	 * The downside to this approach is that is addons are listening for object deletions
344
+	 * on EEM_Base::delete() they won't be notified of this.  However, there is an action that plugins can hook into
345
+	 * to catch these types of deletions.
346
+	 *
347
+	 * @return int
348
+	 * @throws EE_Error
349
+	 * @throws EE_Error
350
+	 * @global WPDB $wpdb
351
+	 */
352
+	public function delete_junk_transactions()
353
+	{
354
+		global $wpdb;
355
+		$deleted             = false;
356
+		$time_to_leave_alone = (int) apply_filters(
357
+			'FHEE__EEM_Transaction__delete_junk_transactions__time_to_leave_alone',
358
+			WEEK_IN_SECONDS
359
+		);
360
+
361
+
362
+		/**
363
+		 * This allows code to filter the query arguments used for retrieving the transaction IDs to delete.
364
+		 * Useful for plugins that want to exclude transactions matching certain query parameters.
365
+		 * The query parameters should be in the format accepted by the EEM_Base model queries.
366
+		 */
367
+		$ids_query = apply_filters(
368
+			'FHEE__EEM_Transaction__delete_junk_transactions__initial_query_args',
369
+			[
370
+				0          => [
371
+					'STS_ID'         => EEM_Transaction::failed_status_code,
372
+					'Payment.PAY_ID' => ['IS NULL'],
373
+					'TXN_timestamp'  => ['<', time() - $time_to_leave_alone],
374
+				],
375
+				'order_by' => ['TXN_timestamp' => 'ASC'],
376
+				'limit'    => 1000,
377
+			],
378
+			$time_to_leave_alone
379
+		);
380
+
381
+
382
+		/**
383
+		 * This filter is for when code needs to filter the list of transaction ids that represent transactions
384
+		 * about to be deleted based on some other criteria that isn't easily done via the query args filter.
385
+		 */
386
+		$txn_ids = apply_filters(
387
+			'FHEE__EEM_Transaction__delete_junk_transactions__transaction_ids_to_delete',
388
+			EEM_Transaction::instance()->get_col($ids_query, 'TXN_ID'),
389
+			$time_to_leave_alone
390
+		);
391
+		// now that we have the ids to delete
392
+		if (! empty($txn_ids) && is_array($txn_ids)) {
393
+			// first, make sure these TXN's are removed the "ee_locked_transactions" array
394
+			EEM_Transaction::unset_locked_transactions($txn_ids);
395
+
396
+			// Create IDs placeholder.
397
+			$placeholders = array_fill(0, count($txn_ids), '%d');
398
+
399
+			// Glue it together to use inside $wpdb->prepare.
400
+			$format = implode(', ', $placeholders);
401
+
402
+			// let's get deleting...
403
+			// We got the ids from the original query to get them FROM
404
+			// the db (which is sanitized) so no need to prepare them again.
405
+			$query   = $wpdb->prepare("DELETE FROM " . $this->table() . " WHERE TXN_ID IN ( $format )", $txn_ids);
406
+			$deleted = $wpdb->query($query);
407
+		}
408
+		if ($deleted) {
409
+			/**
410
+			 * Allows code to do something after the transactions have been deleted.
411
+			 */
412
+			do_action('AHEE__EEM_Transaction__delete_junk_transactions__successful_deletion', $txn_ids);
413
+		}
414
+
415
+		return $deleted;
416
+	}
417
+
418
+
419
+	/**
420
+	 * @param array $transaction_IDs
421
+	 *
422
+	 * @return bool
423
+	 */
424
+	public static function unset_locked_transactions(array $transaction_IDs)
425
+	{
426
+		$locked_transactions = get_option('ee_locked_transactions', []);
427
+		$update              = false;
428
+		foreach ($transaction_IDs as $TXN_ID) {
429
+			if (isset($locked_transactions[ $TXN_ID ])) {
430
+				unset($locked_transactions[ $TXN_ID ]);
431
+				$update = true;
432
+			}
433
+		}
434
+		if ($update) {
435
+			update_option('ee_locked_transactions', $locked_transactions);
436
+		}
437
+
438
+		return $update;
439
+	}
440
+
441
+
442
+	/**
443
+	 * returns an array of EE_Transaction objects whose timestamp is greater than
444
+	 * the current time minus the session lifespan, which defaults to 60 minutes
445
+	 *
446
+	 * @return EE_Base_Class[]|EE_Transaction[]
447
+	 * @throws EE_Error
448
+	 * @throws InvalidArgumentException
449
+	 * @throws InvalidDataTypeException
450
+	 * @throws InvalidInterfaceException
451
+	 */
452
+	public function get_transactions_in_progress()
453
+	{
454
+		return $this->_get_transactions_in_progress();
455
+	}
456
+
457
+
458
+	/**
459
+	 * returns an array of EE_Transaction objects whose timestamp is less than
460
+	 * the current time minus the session lifespan, which defaults to 60 minutes
461
+	 *
462
+	 * @return EE_Base_Class[]|EE_Transaction[]
463
+	 * @throws EE_Error
464
+	 * @throws InvalidArgumentException
465
+	 * @throws InvalidDataTypeException
466
+	 * @throws InvalidInterfaceException
467
+	 */
468
+	public function get_transactions_not_in_progress()
469
+	{
470
+		return $this->_get_transactions_in_progress('<=');
471
+	}
472
+
473
+
474
+	/**
475
+	 * @param string $comparison
476
+	 * @return EE_Transaction[]
477
+	 * @throws EE_Error
478
+	 * @throws InvalidArgumentException
479
+	 * @throws InvalidDataTypeException
480
+	 * @throws InvalidInterfaceException
481
+	 */
482
+	private function _get_transactions_in_progress($comparison = '>=')
483
+	{
484
+		$comparison = $comparison === '>=' || $comparison === '<='
485
+			? $comparison
486
+			: '>=';
487
+		/** @var EventEspresso\core\domain\values\session\SessionLifespan $session_lifespan */
488
+		$session_lifespan = LoaderFactory::getLoader()->getShared(
489
+			'EventEspresso\core\domain\values\session\SessionLifespan'
490
+		);
491
+		return $this->get_all(
492
+			[
493
+				[
494
+					'TXN_timestamp' => [
495
+						$comparison,
496
+						$session_lifespan->expiration(),
497
+					],
498
+					'STS_ID'        => [
499
+						'!=',
500
+						EEM_Transaction::complete_status_code,
501
+					],
502
+				],
503
+			]
504
+		);
505
+	}
506 506
 }
Please login to merge, or discard this patch.