Completed
Branch models-cleanup/main (0d2dda)
by
unknown
09:34
created
core/db_classes/EE_Event_Message_Template.class.php 2 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -14,7 +14,7 @@  discard block
 block discarded – undo
14 14
 
15 15
     /**
16 16
      * @param array $props_n_values
17
-     * @param null  $timezone
17
+     * @param string|null  $timezone
18 18
      * @return EE_Event_Message_Template|mixed
19 19
      */
20 20
     public static function new_instance($props_n_values = array(), $timezone = '')
@@ -26,7 +26,7 @@  discard block
 block discarded – undo
26 26
 
27 27
     /**
28 28
      * @param array $props_n_values
29
-     * @param null  $timezone
29
+     * @param string|null  $timezone
30 30
      * @return EE_Event_Message_Template
31 31
      */
32 32
     public static function new_instance_from_db($props_n_values = array(), $timezone = '')
Please login to merge, or discard this patch.
Indentation   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -12,25 +12,25 @@
 block discarded – undo
12 12
 class EE_Event_Message_Template extends EE_Base_Class
13 13
 {
14 14
 
15
-    /**
16
-     * @param array $props_n_values
17
-     * @param null  $timezone
18
-     * @return EE_Event_Message_Template|mixed
19
-     */
20
-    public static function new_instance($props_n_values = array(), $timezone = '')
21
-    {
22
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone);
23
-        return $has_object ? $has_object : new self($props_n_values, false, $timezone);
24
-    }
15
+	/**
16
+	 * @param array $props_n_values
17
+	 * @param null  $timezone
18
+	 * @return EE_Event_Message_Template|mixed
19
+	 */
20
+	public static function new_instance($props_n_values = array(), $timezone = '')
21
+	{
22
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone);
23
+		return $has_object ? $has_object : new self($props_n_values, false, $timezone);
24
+	}
25 25
 
26 26
 
27
-    /**
28
-     * @param array $props_n_values
29
-     * @param null  $timezone
30
-     * @return EE_Event_Message_Template
31
-     */
32
-    public static function new_instance_from_db($props_n_values = array(), $timezone = '')
33
-    {
34
-        return new self($props_n_values, true, $timezone);
35
-    }
27
+	/**
28
+	 * @param array $props_n_values
29
+	 * @param null  $timezone
30
+	 * @return EE_Event_Message_Template
31
+	 */
32
+	public static function new_instance_from_db($props_n_values = array(), $timezone = '')
33
+	{
34
+		return new self($props_n_values, true, $timezone);
35
+	}
36 36
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Extra_Join.class.php 2 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -14,7 +14,7 @@  discard block
 block discarded – undo
14 14
 
15 15
     /**
16 16
      * @param array $props_n_values
17
-     * @param null  $timezone
17
+     * @param string|null  $timezone
18 18
      * @return EE_Extra_Join|mixed
19 19
      */
20 20
     public static function new_instance($props_n_values = array(), $timezone = '')
@@ -26,7 +26,7 @@  discard block
 block discarded – undo
26 26
 
27 27
     /**
28 28
      * @param array $props_n_values
29
-     * @param null  $timezone
29
+     * @param string|null  $timezone
30 30
      * @return EE_Extra_Join
31 31
      */
32 32
     public static function new_instance_from_db($props_n_values = array(), $timezone = '')
Please login to merge, or discard this patch.
Indentation   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -12,25 +12,25 @@
 block discarded – undo
12 12
 class EE_Extra_Join extends EE_Base_Class
13 13
 {
14 14
 
15
-    /**
16
-     * @param array $props_n_values
17
-     * @param null  $timezone
18
-     * @return EE_Extra_Join|mixed
19
-     */
20
-    public static function new_instance($props_n_values = array(), $timezone = '')
21
-    {
22
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone);
23
-        return $has_object ? $has_object : new self($props_n_values, false, $timezone);
24
-    }
15
+	/**
16
+	 * @param array $props_n_values
17
+	 * @param null  $timezone
18
+	 * @return EE_Extra_Join|mixed
19
+	 */
20
+	public static function new_instance($props_n_values = array(), $timezone = '')
21
+	{
22
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone);
23
+		return $has_object ? $has_object : new self($props_n_values, false, $timezone);
24
+	}
25 25
 
26 26
 
27
-    /**
28
-     * @param array $props_n_values
29
-     * @param null  $timezone
30
-     * @return EE_Extra_Join
31
-     */
32
-    public static function new_instance_from_db($props_n_values = array(), $timezone = '')
33
-    {
34
-        return new self($props_n_values, true, $timezone);
35
-    }
27
+	/**
28
+	 * @param array $props_n_values
29
+	 * @param null  $timezone
30
+	 * @return EE_Extra_Join
31
+	 */
32
+	public static function new_instance_from_db($props_n_values = array(), $timezone = '')
33
+	{
34
+		return new self($props_n_values, true, $timezone);
35
+	}
36 36
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Question_Option.class.php 2 patches
Doc Comments   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -39,7 +39,7 @@  discard block
 block discarded – undo
39 39
      * @param array  $props_n_values  incoming values from the database
40 40
      * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
41 41
      *                                the website will be used.
42
-     * @return EE_Attendee
42
+     * @return EE_Question_Option
43 43
      */
44 44
     public static function new_instance_from_db($props_n_values = array(), $timezone = '')
45 45
     {
@@ -51,7 +51,7 @@  discard block
 block discarded – undo
51 51
      * Sets the option's key value
52 52
      *
53 53
      * @param string $value
54
-     * @return bool success
54
+     * @return boolean|null success
55 55
      */
56 56
     public function set_value($value)
57 57
     {
@@ -63,7 +63,7 @@  discard block
 block discarded – undo
63 63
      * Sets the option's Display Text
64 64
      *
65 65
      * @param string $text
66
-     * @return bool success
66
+     * @return boolean|null success
67 67
      */
68 68
     public function set_desc($text)
69 69
     {
@@ -76,7 +76,7 @@  discard block
 block discarded – undo
76 76
      *
77 77
      * @access public
78 78
      * @param integer $order
79
-     * @return bool      $success
79
+     * @return boolean|null      $success
80 80
      */
81 81
     public function set_order($order)
82 82
     {
@@ -88,7 +88,7 @@  discard block
 block discarded – undo
88 88
      * Sets the ID of the related question
89 89
      *
90 90
      * @param int $question_ID
91
-     * @return bool success
91
+     * @return boolean|null success
92 92
      */
93 93
     public function set_question_ID($question_ID)
94 94
     {
@@ -100,7 +100,7 @@  discard block
 block discarded – undo
100 100
      * Sets the option's opt_group
101 101
      *
102 102
      * @param string $text
103
-     * @return bool success
103
+     * @return string success
104 104
      */
105 105
     public function set_opt_group($text)
106 106
     {
@@ -222,7 +222,7 @@  discard block
 block discarded – undo
222 222
      * Sets QSO_system
223 223
      *
224 224
      * @param string $QSO_system
225
-     * @return bool
225
+     * @return boolean|null
226 226
      */
227 227
     public function set_system($QSO_system)
228 228
     {
Please login to merge, or discard this patch.
Indentation   +218 added lines, -218 removed lines patch added patch discarded remove patch
@@ -10,222 +10,222 @@
 block discarded – undo
10 10
 class EE_Question_Option extends EE_Soft_Delete_Base_Class implements EEI_Duplicatable
11 11
 {
12 12
 
13
-    /**
14
-     * Question Option Opt Group Name
15
-     *
16
-     * @access protected
17
-     * @var string
18
-     */
19
-    protected $_QSO_opt_group = null;
20
-
21
-
22
-    /**
23
-     *
24
-     * @param array  $props_n_values          incoming values
25
-     * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
26
-     *                                        used.)
27
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
28
-     *                                        date_format and the second value is the time format
29
-     * @return EE_Attendee
30
-     */
31
-    public static function new_instance($props_n_values = array(), $timezone = '', $date_formats = array())
32
-    {
33
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
34
-        return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
35
-    }
36
-
37
-
38
-    /**
39
-     * @param array  $props_n_values  incoming values from the database
40
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
41
-     *                                the website will be used.
42
-     * @return EE_Attendee
43
-     */
44
-    public static function new_instance_from_db($props_n_values = array(), $timezone = '')
45
-    {
46
-        return new self($props_n_values, true, $timezone);
47
-    }
48
-
49
-
50
-    /**
51
-     * Sets the option's key value
52
-     *
53
-     * @param string $value
54
-     * @return bool success
55
-     */
56
-    public function set_value($value)
57
-    {
58
-        $this->set('QSO_value', $value);
59
-    }
60
-
61
-
62
-    /**
63
-     * Sets the option's Display Text
64
-     *
65
-     * @param string $text
66
-     * @return bool success
67
-     */
68
-    public function set_desc($text)
69
-    {
70
-        $this->set('QSO_desc', $text);
71
-    }
72
-
73
-
74
-    /**
75
-     * Sets the order for this option
76
-     *
77
-     * @access public
78
-     * @param integer $order
79
-     * @return bool      $success
80
-     */
81
-    public function set_order($order)
82
-    {
83
-        $this->set('QSO_order', $order);
84
-    }
85
-
86
-
87
-    /**
88
-     * Sets the ID of the related question
89
-     *
90
-     * @param int $question_ID
91
-     * @return bool success
92
-     */
93
-    public function set_question_ID($question_ID)
94
-    {
95
-        $this->set('QST_ID', $question_ID);
96
-    }
97
-
98
-
99
-    /**
100
-     * Sets the option's opt_group
101
-     *
102
-     * @param string $text
103
-     * @return bool success
104
-     */
105
-    public function set_opt_group($text)
106
-    {
107
-        return $this->_QSO_opt_group = $text;
108
-    }
109
-
110
-
111
-    /**
112
-     * Gets the option's key value
113
-     *
114
-     * @return string
115
-     */
116
-    public function value()
117
-    {
118
-        return $this->get('QSO_value');
119
-    }
120
-
121
-
122
-    /**
123
-     * Gets the option's display text
124
-     *
125
-     * @return string
126
-     */
127
-    public function desc()
128
-    {
129
-        return $this->get('QSO_desc');
130
-    }
131
-
132
-
133
-    /**
134
-     * Returns whether this option has been deleted or not
135
-     *
136
-     * @return boolean
137
-     */
138
-    public function deleted()
139
-    {
140
-        return $this->get('QSO_deleted');
141
-    }
142
-
143
-
144
-    /**
145
-     * Returns the order or the Question Option
146
-     *
147
-     * @access public
148
-     * @return integer
149
-     */
150
-    public function order()
151
-    {
152
-        return $this->get('QSO_option');
153
-    }
154
-
155
-
156
-    /**
157
-     * Gets the related question's ID
158
-     *
159
-     * @return int
160
-     */
161
-    public function question_ID()
162
-    {
163
-        return $this->get('QST_ID');
164
-    }
165
-
166
-
167
-    /**
168
-     * Returns the question related to this question option
169
-     *
170
-     * @return EE_Question
171
-     */
172
-    public function question()
173
-    {
174
-        return $this->get_first_related('Question');
175
-    }
176
-
177
-
178
-    /**
179
-     * Gets the option's opt_group
180
-     *
181
-     * @return string
182
-     */
183
-    public function opt_group()
184
-    {
185
-        return $this->_QSO_opt_group;
186
-    }
187
-
188
-    /**
189
-     * Duplicates this question option. By default the new question option will be for the same question,
190
-     * but that can be overriden by setting the 'QST_ID' option
191
-     *
192
-     * @param array $options {
193
-     * @type int    $QST_ID  the QST_ID attribute of this question option, otherwise it will be for the same question
194
-     *                       as the original
195
-     */
196
-    public function duplicate($options = array())
197
-    {
198
-        $new_question_option = clone $this;
199
-        $new_question_option->set('QSO_ID', null);
200
-        if (
201
-            array_key_exists(
202
-                'QST_ID',
203
-                $options
204
-            )
205
-        ) {// use array_key_exists instead of isset because NULL might be a valid value
206
-            $new_question_option->set_question_ID($options['QST_ID']);
207
-        }
208
-        $new_question_option->save();
209
-    }
210
-
211
-    /**
212
-     * Gets the QSO_system value
213
-     *
214
-     * @return string|null
215
-     */
216
-    public function system()
217
-    {
218
-        return $this->get('QSO_system');
219
-    }
220
-
221
-    /**
222
-     * Sets QSO_system
223
-     *
224
-     * @param string $QSO_system
225
-     * @return bool
226
-     */
227
-    public function set_system($QSO_system)
228
-    {
229
-        return $this->set('QSO_system', $QSO_system);
230
-    }
13
+	/**
14
+	 * Question Option Opt Group Name
15
+	 *
16
+	 * @access protected
17
+	 * @var string
18
+	 */
19
+	protected $_QSO_opt_group = null;
20
+
21
+
22
+	/**
23
+	 *
24
+	 * @param array  $props_n_values          incoming values
25
+	 * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
26
+	 *                                        used.)
27
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
28
+	 *                                        date_format and the second value is the time format
29
+	 * @return EE_Attendee
30
+	 */
31
+	public static function new_instance($props_n_values = array(), $timezone = '', $date_formats = array())
32
+	{
33
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
34
+		return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
35
+	}
36
+
37
+
38
+	/**
39
+	 * @param array  $props_n_values  incoming values from the database
40
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
41
+	 *                                the website will be used.
42
+	 * @return EE_Attendee
43
+	 */
44
+	public static function new_instance_from_db($props_n_values = array(), $timezone = '')
45
+	{
46
+		return new self($props_n_values, true, $timezone);
47
+	}
48
+
49
+
50
+	/**
51
+	 * Sets the option's key value
52
+	 *
53
+	 * @param string $value
54
+	 * @return bool success
55
+	 */
56
+	public function set_value($value)
57
+	{
58
+		$this->set('QSO_value', $value);
59
+	}
60
+
61
+
62
+	/**
63
+	 * Sets the option's Display Text
64
+	 *
65
+	 * @param string $text
66
+	 * @return bool success
67
+	 */
68
+	public function set_desc($text)
69
+	{
70
+		$this->set('QSO_desc', $text);
71
+	}
72
+
73
+
74
+	/**
75
+	 * Sets the order for this option
76
+	 *
77
+	 * @access public
78
+	 * @param integer $order
79
+	 * @return bool      $success
80
+	 */
81
+	public function set_order($order)
82
+	{
83
+		$this->set('QSO_order', $order);
84
+	}
85
+
86
+
87
+	/**
88
+	 * Sets the ID of the related question
89
+	 *
90
+	 * @param int $question_ID
91
+	 * @return bool success
92
+	 */
93
+	public function set_question_ID($question_ID)
94
+	{
95
+		$this->set('QST_ID', $question_ID);
96
+	}
97
+
98
+
99
+	/**
100
+	 * Sets the option's opt_group
101
+	 *
102
+	 * @param string $text
103
+	 * @return bool success
104
+	 */
105
+	public function set_opt_group($text)
106
+	{
107
+		return $this->_QSO_opt_group = $text;
108
+	}
109
+
110
+
111
+	/**
112
+	 * Gets the option's key value
113
+	 *
114
+	 * @return string
115
+	 */
116
+	public function value()
117
+	{
118
+		return $this->get('QSO_value');
119
+	}
120
+
121
+
122
+	/**
123
+	 * Gets the option's display text
124
+	 *
125
+	 * @return string
126
+	 */
127
+	public function desc()
128
+	{
129
+		return $this->get('QSO_desc');
130
+	}
131
+
132
+
133
+	/**
134
+	 * Returns whether this option has been deleted or not
135
+	 *
136
+	 * @return boolean
137
+	 */
138
+	public function deleted()
139
+	{
140
+		return $this->get('QSO_deleted');
141
+	}
142
+
143
+
144
+	/**
145
+	 * Returns the order or the Question Option
146
+	 *
147
+	 * @access public
148
+	 * @return integer
149
+	 */
150
+	public function order()
151
+	{
152
+		return $this->get('QSO_option');
153
+	}
154
+
155
+
156
+	/**
157
+	 * Gets the related question's ID
158
+	 *
159
+	 * @return int
160
+	 */
161
+	public function question_ID()
162
+	{
163
+		return $this->get('QST_ID');
164
+	}
165
+
166
+
167
+	/**
168
+	 * Returns the question related to this question option
169
+	 *
170
+	 * @return EE_Question
171
+	 */
172
+	public function question()
173
+	{
174
+		return $this->get_first_related('Question');
175
+	}
176
+
177
+
178
+	/**
179
+	 * Gets the option's opt_group
180
+	 *
181
+	 * @return string
182
+	 */
183
+	public function opt_group()
184
+	{
185
+		return $this->_QSO_opt_group;
186
+	}
187
+
188
+	/**
189
+	 * Duplicates this question option. By default the new question option will be for the same question,
190
+	 * but that can be overriden by setting the 'QST_ID' option
191
+	 *
192
+	 * @param array $options {
193
+	 * @type int    $QST_ID  the QST_ID attribute of this question option, otherwise it will be for the same question
194
+	 *                       as the original
195
+	 */
196
+	public function duplicate($options = array())
197
+	{
198
+		$new_question_option = clone $this;
199
+		$new_question_option->set('QSO_ID', null);
200
+		if (
201
+			array_key_exists(
202
+				'QST_ID',
203
+				$options
204
+			)
205
+		) {// use array_key_exists instead of isset because NULL might be a valid value
206
+			$new_question_option->set_question_ID($options['QST_ID']);
207
+		}
208
+		$new_question_option->save();
209
+	}
210
+
211
+	/**
212
+	 * Gets the QSO_system value
213
+	 *
214
+	 * @return string|null
215
+	 */
216
+	public function system()
217
+	{
218
+		return $this->get('QSO_system');
219
+	}
220
+
221
+	/**
222
+	 * Sets QSO_system
223
+	 *
224
+	 * @param string $QSO_system
225
+	 * @return bool
226
+	 */
227
+	public function set_system($QSO_system)
228
+	{
229
+		return $this->set('QSO_system', $QSO_system);
230
+	}
231 231
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Registration.class.php 2 patches
Doc Comments   +3 added lines, -2 removed lines patch added patch discarded remove patch
@@ -1353,7 +1353,7 @@  discard block
 block discarded – undo
1353 1353
      * Sets deleted
1354 1354
      *
1355 1355
      * @param boolean $deleted
1356
-     * @return bool
1356
+     * @return boolean|null
1357 1357
      * @throws EE_Error
1358 1358
      * @throws RuntimeException
1359 1359
      */
@@ -1411,6 +1411,7 @@  discard block
 block discarded – undo
1411 1411
      * @param int | EE_Datetime $DTT_OR_ID      The datetime the registration is being checked against
1412 1412
      * @param bool              $check_approved This is used to indicate whether the caller wants can_checkin to also
1413 1413
      *                                          consider registration status as well as datetime access.
1414
+     * @param integer $DTT_OR_ID
1414 1415
      * @return bool
1415 1416
      * @throws EE_Error
1416 1417
      */
@@ -1593,7 +1594,7 @@  discard block
 block discarded – undo
1593 1594
      * Returns the latest datetime related to this registration (via the ticket attached to the registration).
1594 1595
      * "Latest" is defined by the `DTT_EVT_start` column.
1595 1596
      *
1596
-     * @return EE_Datetime|null
1597
+     * @return null|EE_Base_Class
1597 1598
      * @throws EE_Error
1598 1599
      */
1599 1600
     public function get_latest_related_datetime()
Please login to merge, or discard this patch.
Indentation   +2076 added lines, -2076 removed lines patch added patch discarded remove patch
@@ -17,2080 +17,2080 @@
 block discarded – undo
17 17
 {
18 18
 
19 19
 
20
-    /**
21
-     * Used to reference when a registration has never been checked in.
22
-     *
23
-     * @deprecated use \EE_Checkin::status_checked_never instead
24
-     * @type int
25
-     */
26
-    const checkin_status_never = 2;
27
-
28
-    /**
29
-     * Used to reference when a registration has been checked in.
30
-     *
31
-     * @deprecated use \EE_Checkin::status_checked_in instead
32
-     * @type int
33
-     */
34
-    const checkin_status_in = 1;
35
-
36
-
37
-    /**
38
-     * Used to reference when a registration has been checked out.
39
-     *
40
-     * @deprecated use \EE_Checkin::status_checked_out instead
41
-     * @type int
42
-     */
43
-    const checkin_status_out = 0;
44
-
45
-
46
-    /**
47
-     * extra meta key for tracking reg status os trashed registrations
48
-     *
49
-     * @type string
50
-     */
51
-    const PRE_TRASH_REG_STATUS_KEY = 'pre_trash_registration_status';
52
-
53
-
54
-    /**
55
-     * extra meta key for tracking if registration has reserved ticket
56
-     *
57
-     * @type string
58
-     */
59
-    const HAS_RESERVED_TICKET_KEY = 'has_reserved_ticket';
60
-
61
-
62
-    /**
63
-     * @param array  $props_n_values          incoming values
64
-     * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
65
-     *                                        used.)
66
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
67
-     *                                        date_format and the second value is the time format
68
-     * @return EE_Registration
69
-     * @throws EE_Error
70
-     */
71
-    public static function new_instance($props_n_values = array(), $timezone = '', $date_formats = array())
72
-    {
73
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
74
-        return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
75
-    }
76
-
77
-
78
-    /**
79
-     * @param array  $props_n_values  incoming values from the database
80
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
81
-     *                                the website will be used.
82
-     * @return EE_Registration
83
-     */
84
-    public static function new_instance_from_db($props_n_values = array(), $timezone = '')
85
-    {
86
-        return new self($props_n_values, true, $timezone);
87
-    }
88
-
89
-
90
-    /**
91
-     *        Set Event ID
92
-     *
93
-     * @param        int $EVT_ID Event ID
94
-     * @throws EE_Error
95
-     * @throws RuntimeException
96
-     */
97
-    public function set_event($EVT_ID = 0)
98
-    {
99
-        $this->set('EVT_ID', $EVT_ID);
100
-    }
101
-
102
-
103
-    /**
104
-     * Overrides parent set() method so that all calls to set( 'REG_code', $REG_code ) OR set( 'STS_ID', $STS_ID ) can
105
-     * be routed to internal methods
106
-     *
107
-     * @param string $field_name
108
-     * @param mixed  $field_value
109
-     * @param bool   $use_default
110
-     * @throws EE_Error
111
-     * @throws EntityNotFoundException
112
-     * @throws InvalidArgumentException
113
-     * @throws InvalidDataTypeException
114
-     * @throws InvalidInterfaceException
115
-     * @throws ReflectionException
116
-     * @throws RuntimeException
117
-     */
118
-    public function set($field_name, $field_value, $use_default = false)
119
-    {
120
-        switch ($field_name) {
121
-            case 'REG_code':
122
-                if (! empty($field_value) && $this->reg_code() === null) {
123
-                    $this->set_reg_code($field_value, $use_default);
124
-                }
125
-                break;
126
-            case 'STS_ID':
127
-                $this->set_status($field_value, $use_default);
128
-                break;
129
-            default:
130
-                parent::set($field_name, $field_value, $use_default);
131
-        }
132
-    }
133
-
134
-
135
-    /**
136
-     * Set Status ID
137
-     * updates the registration status and ALSO...
138
-     * calls reserve_registration_space() if the reg status changes TO approved from any other reg status
139
-     * calls release_registration_space() if the reg status changes FROM approved to any other reg status
140
-     *
141
-     * @param string                $new_STS_ID
142
-     * @param boolean               $use_default
143
-     * @param ContextInterface|null $context
144
-     * @return bool
145
-     * @throws DomainException
146
-     * @throws EE_Error
147
-     * @throws EntityNotFoundException
148
-     * @throws InvalidArgumentException
149
-     * @throws InvalidDataTypeException
150
-     * @throws InvalidInterfaceException
151
-     * @throws ReflectionException
152
-     * @throws RuntimeException
153
-     * @throws UnexpectedEntityException
154
-     */
155
-    public function set_status($new_STS_ID = null, $use_default = false, ContextInterface $context = null)
156
-    {
157
-        // get current REG_Status
158
-        $old_STS_ID = $this->status_ID();
159
-        // if status has changed
160
-        if (
161
-            $old_STS_ID !== $new_STS_ID // and that status has actually changed
162
-            && ! empty($old_STS_ID) // and that old status is actually set
163
-            && ! empty($new_STS_ID) // as well as the new status
164
-            && $this->ID() // ensure registration is in the db
165
-        ) {
166
-            // update internal status first
167
-            parent::set('STS_ID', $new_STS_ID, $use_default);
168
-            // THEN handle other changes that occur when reg status changes
169
-            // TO approved
170
-            if ($new_STS_ID === EEM_Registration::status_id_approved) {
171
-                // reserve a space by incrementing ticket and datetime sold values
172
-                $this->reserveRegistrationSpace();
173
-                do_action('AHEE__EE_Registration__set_status__to_approved', $this, $old_STS_ID, $new_STS_ID, $context);
174
-                // OR FROM  approved
175
-            } elseif ($old_STS_ID === EEM_Registration::status_id_approved) {
176
-                // release a space by decrementing ticket and datetime sold values
177
-                $this->releaseRegistrationSpace();
178
-                do_action(
179
-                    'AHEE__EE_Registration__set_status__from_approved',
180
-                    $this,
181
-                    $old_STS_ID,
182
-                    $new_STS_ID,
183
-                    $context
184
-                );
185
-            }
186
-            // update status
187
-            parent::set('STS_ID', $new_STS_ID, $use_default);
188
-            $this->updateIfCanceledOrReinstated($new_STS_ID, $old_STS_ID, $context);
189
-            if ($this->statusChangeUpdatesTransaction($context)) {
190
-                $this->updateTransactionAfterStatusChange();
191
-            }
192
-            do_action('AHEE__EE_Registration__set_status__after_update', $this, $old_STS_ID, $new_STS_ID, $context);
193
-            return true;
194
-        }
195
-        // even though the old value matches the new value, it's still good to
196
-        // allow the parent set method to have a say
197
-        parent::set('STS_ID', $new_STS_ID, $use_default);
198
-        return true;
199
-    }
200
-
201
-
202
-    /**
203
-     * update REGs and TXN when cancelled or declined registrations involved
204
-     *
205
-     * @param string                $new_STS_ID
206
-     * @param string                $old_STS_ID
207
-     * @param ContextInterface|null $context
208
-     * @throws EE_Error
209
-     * @throws InvalidArgumentException
210
-     * @throws InvalidDataTypeException
211
-     * @throws InvalidInterfaceException
212
-     * @throws ReflectionException
213
-     * @throws RuntimeException
214
-     */
215
-    private function updateIfCanceledOrReinstated($new_STS_ID, $old_STS_ID, ContextInterface $context = null)
216
-    {
217
-        // these reg statuses should not be considered in any calculations involving monies owing
218
-        $closed_reg_statuses = EEM_Registration::closed_reg_statuses();
219
-        // true if registration has been cancelled or declined
220
-        $this->updateIfCanceled(
221
-            $closed_reg_statuses,
222
-            $new_STS_ID,
223
-            $old_STS_ID,
224
-            $context
225
-        );
226
-        $this->updateIfReinstated(
227
-            $closed_reg_statuses,
228
-            $new_STS_ID,
229
-            $old_STS_ID,
230
-            $context
231
-        );
232
-    }
233
-
234
-
235
-    /**
236
-     * update REGs and TXN when cancelled or declined registrations involved
237
-     *
238
-     * @param array                 $closed_reg_statuses
239
-     * @param string                $new_STS_ID
240
-     * @param string                $old_STS_ID
241
-     * @param ContextInterface|null $context
242
-     * @throws EE_Error
243
-     * @throws InvalidArgumentException
244
-     * @throws InvalidDataTypeException
245
-     * @throws InvalidInterfaceException
246
-     * @throws ReflectionException
247
-     * @throws RuntimeException
248
-     */
249
-    private function updateIfCanceled(
250
-        array $closed_reg_statuses,
251
-        $new_STS_ID,
252
-        $old_STS_ID,
253
-        ContextInterface $context = null
254
-    ) {
255
-        // true if registration has been cancelled or declined
256
-        if (
257
-            in_array($new_STS_ID, $closed_reg_statuses, true)
258
-            && ! in_array($old_STS_ID, $closed_reg_statuses, true)
259
-        ) {
260
-            /** @type EE_Registration_Processor $registration_processor */
261
-            $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
262
-            /** @type EE_Transaction_Processor $transaction_processor */
263
-            $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
264
-            // cancelled or declined registration
265
-            $registration_processor->update_registration_after_being_canceled_or_declined(
266
-                $this,
267
-                $closed_reg_statuses
268
-            );
269
-            $transaction_processor->update_transaction_after_canceled_or_declined_registration(
270
-                $this,
271
-                $closed_reg_statuses,
272
-                false
273
-            );
274
-            do_action(
275
-                'AHEE__EE_Registration__set_status__canceled_or_declined',
276
-                $this,
277
-                $old_STS_ID,
278
-                $new_STS_ID,
279
-                $context
280
-            );
281
-            return;
282
-        }
283
-    }
284
-
285
-
286
-    /**
287
-     * update REGs and TXN when cancelled or declined registrations involved
288
-     *
289
-     * @param array                 $closed_reg_statuses
290
-     * @param string                $new_STS_ID
291
-     * @param string                $old_STS_ID
292
-     * @param ContextInterface|null $context
293
-     * @throws EE_Error
294
-     * @throws InvalidArgumentException
295
-     * @throws InvalidDataTypeException
296
-     * @throws InvalidInterfaceException
297
-     * @throws ReflectionException
298
-     */
299
-    private function updateIfReinstated(
300
-        array $closed_reg_statuses,
301
-        $new_STS_ID,
302
-        $old_STS_ID,
303
-        ContextInterface $context = null
304
-    ) {
305
-        // true if reinstating cancelled or declined registration
306
-        if (
307
-            in_array($old_STS_ID, $closed_reg_statuses, true)
308
-            && ! in_array($new_STS_ID, $closed_reg_statuses, true)
309
-        ) {
310
-            /** @type EE_Registration_Processor $registration_processor */
311
-            $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
312
-            /** @type EE_Transaction_Processor $transaction_processor */
313
-            $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
314
-            // reinstating cancelled or declined registration
315
-            $registration_processor->update_canceled_or_declined_registration_after_being_reinstated(
316
-                $this,
317
-                $closed_reg_statuses
318
-            );
319
-            $transaction_processor->update_transaction_after_reinstating_canceled_registration(
320
-                $this,
321
-                $closed_reg_statuses,
322
-                false
323
-            );
324
-            do_action(
325
-                'AHEE__EE_Registration__set_status__after_reinstated',
326
-                $this,
327
-                $old_STS_ID,
328
-                $new_STS_ID,
329
-                $context
330
-            );
331
-        }
332
-    }
333
-
334
-
335
-    /**
336
-     * @param ContextInterface|null $context
337
-     * @return bool
338
-     */
339
-    private function statusChangeUpdatesTransaction(ContextInterface $context = null)
340
-    {
341
-        $contexts_that_do_not_update_transaction = (array) apply_filters(
342
-            'AHEE__EE_Registration__statusChangeUpdatesTransaction__contexts_that_do_not_update_transaction',
343
-            array('spco_reg_step_attendee_information_process_registrations'),
344
-            $context,
345
-            $this
346
-        );
347
-        return ! (
348
-            $context instanceof ContextInterface
349
-            && in_array($context->slug(), $contexts_that_do_not_update_transaction, true)
350
-        );
351
-    }
352
-
353
-
354
-    /**
355
-     * @throws EE_Error
356
-     * @throws EntityNotFoundException
357
-     * @throws InvalidArgumentException
358
-     * @throws InvalidDataTypeException
359
-     * @throws InvalidInterfaceException
360
-     * @throws ReflectionException
361
-     * @throws RuntimeException
362
-     */
363
-    private function updateTransactionAfterStatusChange()
364
-    {
365
-        /** @type EE_Transaction_Payments $transaction_payments */
366
-        $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
367
-        $transaction_payments->recalculate_transaction_total($this->transaction(), false);
368
-        $this->transaction()->update_status_based_on_total_paid(true);
369
-    }
370
-
371
-
372
-    /**
373
-     *        get Status ID
374
-     */
375
-    public function status_ID()
376
-    {
377
-        return $this->get('STS_ID');
378
-    }
379
-
380
-
381
-    /**
382
-     * Gets the ticket this registration is for
383
-     *
384
-     * @param boolean $include_archived whether to include archived tickets or not.
385
-     *
386
-     * @return EE_Ticket|EE_Base_Class
387
-     * @throws EE_Error
388
-     */
389
-    public function ticket($include_archived = true)
390
-    {
391
-        $query_params = array();
392
-        if ($include_archived) {
393
-            $query_params['default_where_conditions'] = 'none';
394
-        }
395
-        return $this->get_first_related('Ticket', $query_params);
396
-    }
397
-
398
-
399
-    /**
400
-     * Gets the event this registration is for
401
-     *
402
-     * @return EE_Event
403
-     * @throws EE_Error
404
-     * @throws EntityNotFoundException
405
-     */
406
-    public function event()
407
-    {
408
-        $event = $this->get_first_related('Event');
409
-        if (! $event instanceof \EE_Event) {
410
-            throw new EntityNotFoundException('Event ID', $this->event_ID());
411
-        }
412
-        return $event;
413
-    }
414
-
415
-
416
-    /**
417
-     * Gets the "author" of the registration.  Note that for the purposes of registrations, the author will correspond
418
-     * with the author of the event this registration is for.
419
-     *
420
-     * @since 4.5.0
421
-     * @return int
422
-     * @throws EE_Error
423
-     * @throws EntityNotFoundException
424
-     */
425
-    public function wp_user()
426
-    {
427
-        $event = $this->event();
428
-        if ($event instanceof EE_Event) {
429
-            return $event->wp_user();
430
-        }
431
-        return 0;
432
-    }
433
-
434
-
435
-    /**
436
-     * increments this registration's related ticket sold and corresponding datetime sold values
437
-     *
438
-     * @return void
439
-     * @throws DomainException
440
-     * @throws EE_Error
441
-     * @throws EntityNotFoundException
442
-     * @throws InvalidArgumentException
443
-     * @throws InvalidDataTypeException
444
-     * @throws InvalidInterfaceException
445
-     * @throws ReflectionException
446
-     * @throws UnexpectedEntityException
447
-     */
448
-    private function reserveRegistrationSpace()
449
-    {
450
-        // reserved ticket and datetime counts will be decremented as sold counts are incremented
451
-        // so stop tracking that this reg has a ticket reserved
452
-        $this->release_reserved_ticket(false, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
453
-        $ticket = $this->ticket();
454
-        $ticket->increaseSold();
455
-        // possibly set event status to sold out
456
-        $this->event()->perform_sold_out_status_check();
457
-    }
458
-
459
-
460
-    /**
461
-     * decrements (subtracts) this registration's related ticket sold and corresponding datetime sold values
462
-     *
463
-     * @return void
464
-     * @throws DomainException
465
-     * @throws EE_Error
466
-     * @throws EntityNotFoundException
467
-     * @throws InvalidArgumentException
468
-     * @throws InvalidDataTypeException
469
-     * @throws InvalidInterfaceException
470
-     * @throws ReflectionException
471
-     * @throws UnexpectedEntityException
472
-     */
473
-    private function releaseRegistrationSpace()
474
-    {
475
-        $ticket = $this->ticket();
476
-        $ticket->decreaseSold();
477
-        // possibly change event status from sold out back to previous status
478
-        $this->event()->perform_sold_out_status_check();
479
-    }
480
-
481
-
482
-    /**
483
-     * tracks this registration's ticket reservation in extra meta
484
-     * and can increment related ticket reserved and corresponding datetime reserved values
485
-     *
486
-     * @param bool $update_ticket if true, will increment ticket and datetime reserved count
487
-     * @return void
488
-     * @throws EE_Error
489
-     * @throws InvalidArgumentException
490
-     * @throws InvalidDataTypeException
491
-     * @throws InvalidInterfaceException
492
-     * @throws ReflectionException
493
-     */
494
-    public function reserve_ticket($update_ticket = false, $source = 'unknown')
495
-    {
496
-        // only reserve ticket if space is not currently reserved
497
-        if ((bool) $this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true) !== true) {
498
-            $this->update_extra_meta('reserve_ticket', "{$this->ticket_ID()} from {$source}");
499
-            // IMPORTANT !!!
500
-            // although checking $update_ticket first would be more efficient,
501
-            // we NEED to ALWAYS call update_extra_meta(), which is why that is done first
502
-            if (
503
-                $this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true)
504
-                && $update_ticket
505
-            ) {
506
-                $ticket = $this->ticket();
507
-                $ticket->increaseReserved(1, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
508
-                $ticket->save();
509
-            }
510
-        }
511
-    }
512
-
513
-
514
-    /**
515
-     * stops tracking this registration's ticket reservation in extra meta
516
-     * decrements (subtracts) related ticket reserved and corresponding datetime reserved values
517
-     *
518
-     * @param bool $update_ticket if true, will decrement ticket and datetime reserved count
519
-     * @return void
520
-     * @throws EE_Error
521
-     * @throws InvalidArgumentException
522
-     * @throws InvalidDataTypeException
523
-     * @throws InvalidInterfaceException
524
-     * @throws ReflectionException
525
-     */
526
-    public function release_reserved_ticket($update_ticket = false, $source = 'unknown')
527
-    {
528
-        // only release ticket if space is currently reserved
529
-        if ((bool) $this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true) === true) {
530
-            $this->update_extra_meta('release_reserved_ticket', "{$this->ticket_ID()} from {$source}");
531
-            // IMPORTANT !!!
532
-            // although checking $update_ticket first would be more efficient,
533
-            // we NEED to ALWAYS call update_extra_meta(), which is why that is done first
534
-            if (
535
-                $this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, false)
536
-                && $update_ticket
537
-            ) {
538
-                $ticket = $this->ticket();
539
-                $ticket->decreaseReserved(1, true, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
540
-            }
541
-        }
542
-    }
543
-
544
-
545
-    /**
546
-     * Set Attendee ID
547
-     *
548
-     * @param        int $ATT_ID Attendee ID
549
-     * @throws EE_Error
550
-     * @throws RuntimeException
551
-     */
552
-    public function set_attendee_id($ATT_ID = 0)
553
-    {
554
-        $this->set('ATT_ID', $ATT_ID);
555
-    }
556
-
557
-
558
-    /**
559
-     *        Set Transaction ID
560
-     *
561
-     * @param        int $TXN_ID Transaction ID
562
-     * @throws EE_Error
563
-     * @throws RuntimeException
564
-     */
565
-    public function set_transaction_id($TXN_ID = 0)
566
-    {
567
-        $this->set('TXN_ID', $TXN_ID);
568
-    }
569
-
570
-
571
-    /**
572
-     *        Set Session
573
-     *
574
-     * @param    string $REG_session PHP Session ID
575
-     * @throws EE_Error
576
-     * @throws RuntimeException
577
-     */
578
-    public function set_session($REG_session = '')
579
-    {
580
-        $this->set('REG_session', $REG_session);
581
-    }
582
-
583
-
584
-    /**
585
-     *        Set Registration URL Link
586
-     *
587
-     * @param    string $REG_url_link Registration URL Link
588
-     * @throws EE_Error
589
-     * @throws RuntimeException
590
-     */
591
-    public function set_reg_url_link($REG_url_link = '')
592
-    {
593
-        $this->set('REG_url_link', $REG_url_link);
594
-    }
595
-
596
-
597
-    /**
598
-     *        Set Attendee Counter
599
-     *
600
-     * @param        int $REG_count Primary Attendee
601
-     * @throws EE_Error
602
-     * @throws RuntimeException
603
-     */
604
-    public function set_count($REG_count = 1)
605
-    {
606
-        $this->set('REG_count', $REG_count);
607
-    }
608
-
609
-
610
-    /**
611
-     *        Set Group Size
612
-     *
613
-     * @param        boolean $REG_group_size Group Registration
614
-     * @throws EE_Error
615
-     * @throws RuntimeException
616
-     */
617
-    public function set_group_size($REG_group_size = false)
618
-    {
619
-        $this->set('REG_group_size', $REG_group_size);
620
-    }
621
-
622
-
623
-    /**
624
-     *    is_not_approved -  convenience method that returns TRUE if REG status ID ==
625
-     *    EEM_Registration::status_id_not_approved
626
-     *
627
-     * @return        boolean
628
-     */
629
-    public function is_not_approved()
630
-    {
631
-        return $this->status_ID() == EEM_Registration::status_id_not_approved ? true : false;
632
-    }
633
-
634
-
635
-    /**
636
-     *    is_pending_payment -  convenience method that returns TRUE if REG status ID ==
637
-     *    EEM_Registration::status_id_pending_payment
638
-     *
639
-     * @return        boolean
640
-     */
641
-    public function is_pending_payment()
642
-    {
643
-        return $this->status_ID() == EEM_Registration::status_id_pending_payment ? true : false;
644
-    }
645
-
646
-
647
-    /**
648
-     *    is_approved -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_approved
649
-     *
650
-     * @return        boolean
651
-     */
652
-    public function is_approved()
653
-    {
654
-        return $this->status_ID() == EEM_Registration::status_id_approved ? true : false;
655
-    }
656
-
657
-
658
-    /**
659
-     *    is_cancelled -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_cancelled
660
-     *
661
-     * @return        boolean
662
-     */
663
-    public function is_cancelled()
664
-    {
665
-        return $this->status_ID() == EEM_Registration::status_id_cancelled ? true : false;
666
-    }
667
-
668
-
669
-    /**
670
-     *    is_declined -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_declined
671
-     *
672
-     * @return        boolean
673
-     */
674
-    public function is_declined()
675
-    {
676
-        return $this->status_ID() == EEM_Registration::status_id_declined ? true : false;
677
-    }
678
-
679
-
680
-    /**
681
-     *    is_incomplete -  convenience method that returns TRUE if REG status ID ==
682
-     *    EEM_Registration::status_id_incomplete
683
-     *
684
-     * @return        boolean
685
-     */
686
-    public function is_incomplete()
687
-    {
688
-        return $this->status_ID() == EEM_Registration::status_id_incomplete ? true : false;
689
-    }
690
-
691
-
692
-    /**
693
-     *        Set Registration Date
694
-     *
695
-     * @param        mixed ( int or string ) $REG_date Registration Date - Unix timestamp or string representation of
696
-     *                                                 Date
697
-     * @throws EE_Error
698
-     * @throws RuntimeException
699
-     */
700
-    public function set_reg_date($REG_date = false)
701
-    {
702
-        $this->set('REG_date', $REG_date);
703
-    }
704
-
705
-
706
-    /**
707
-     *    Set final price owing for this registration after all ticket/price modifications
708
-     *
709
-     * @access    public
710
-     * @param    float $REG_final_price
711
-     * @throws EE_Error
712
-     * @throws RuntimeException
713
-     */
714
-    public function set_final_price($REG_final_price = 0.00)
715
-    {
716
-        $this->set('REG_final_price', $REG_final_price);
717
-    }
718
-
719
-
720
-    /**
721
-     *    Set amount paid towards this registration's final price
722
-     *
723
-     * @access    public
724
-     * @param    float $REG_paid
725
-     * @throws EE_Error
726
-     * @throws RuntimeException
727
-     */
728
-    public function set_paid($REG_paid = 0.00)
729
-    {
730
-        $this->set('REG_paid', $REG_paid);
731
-    }
732
-
733
-
734
-    /**
735
-     *        Attendee Is Going
736
-     *
737
-     * @param        boolean $REG_att_is_going Attendee Is Going
738
-     * @throws EE_Error
739
-     * @throws RuntimeException
740
-     */
741
-    public function set_att_is_going($REG_att_is_going = false)
742
-    {
743
-        $this->set('REG_att_is_going', $REG_att_is_going);
744
-    }
745
-
746
-
747
-    /**
748
-     * Gets the related attendee
749
-     *
750
-     * @return EE_Attendee
751
-     * @throws EE_Error
752
-     */
753
-    public function attendee()
754
-    {
755
-        return $this->get_first_related('Attendee');
756
-    }
757
-
758
-
759
-    /**
760
-     *        get Event ID
761
-     */
762
-    public function event_ID()
763
-    {
764
-        return $this->get('EVT_ID');
765
-    }
766
-
767
-
768
-    /**
769
-     *        get Event ID
770
-     */
771
-    public function event_name()
772
-    {
773
-        $event = $this->event_obj();
774
-        if ($event) {
775
-            return $event->name();
776
-        } else {
777
-            return null;
778
-        }
779
-    }
780
-
781
-
782
-    /**
783
-     * Fetches the event this registration is for
784
-     *
785
-     * @return EE_Event
786
-     * @throws EE_Error
787
-     */
788
-    public function event_obj()
789
-    {
790
-        return $this->get_first_related('Event');
791
-    }
792
-
793
-
794
-    /**
795
-     *        get Attendee ID
796
-     */
797
-    public function attendee_ID()
798
-    {
799
-        return $this->get('ATT_ID');
800
-    }
801
-
802
-
803
-    /**
804
-     *        get PHP Session ID
805
-     */
806
-    public function session_ID()
807
-    {
808
-        return $this->get('REG_session');
809
-    }
810
-
811
-
812
-    /**
813
-     * Gets the string which represents the URL trigger for the receipt template in the message template system.
814
-     *
815
-     * @param string $messenger 'pdf' or 'html'.  Default 'html'.
816
-     * @return string
817
-     */
818
-    public function receipt_url($messenger = 'html')
819
-    {
820
-
821
-        /**
822
-         * The below will be deprecated one version after this.  We check first if there is a custom receipt template
823
-         * already in use on old system.  If there is then we just return the standard url for it.
824
-         *
825
-         * @since 4.5.0
826
-         */
827
-        $template_relative_path = 'modules/gateways/Invoice/lib/templates/receipt_body.template.php';
828
-        $has_custom = EEH_Template::locate_template(
829
-            $template_relative_path,
830
-            array(),
831
-            true,
832
-            true,
833
-            true
834
-        );
835
-
836
-        if ($has_custom) {
837
-            return add_query_arg(array('receipt' => 'true'), $this->invoice_url('launch'));
838
-        }
839
-        return apply_filters('FHEE__EE_Registration__receipt_url__receipt_url', '', $this, $messenger, 'receipt');
840
-    }
841
-
842
-
843
-    /**
844
-     * Gets the string which represents the URL trigger for the invoice template in the message template system.
845
-     *
846
-     * @param string $messenger 'pdf' or 'html'.  Default 'html'.
847
-     * @return string
848
-     * @throws EE_Error
849
-     */
850
-    public function invoice_url($messenger = 'html')
851
-    {
852
-        /**
853
-         * The below will be deprecated one version after this.  We check first if there is a custom invoice template
854
-         * already in use on old system.  If there is then we just return the standard url for it.
855
-         *
856
-         * @since 4.5.0
857
-         */
858
-        $template_relative_path = 'modules/gateways/Invoice/lib/templates/invoice_body.template.php';
859
-        $has_custom = EEH_Template::locate_template(
860
-            $template_relative_path,
861
-            array(),
862
-            true,
863
-            true,
864
-            true
865
-        );
866
-
867
-        if ($has_custom) {
868
-            if ($messenger == 'html') {
869
-                return $this->invoice_url('launch');
870
-            }
871
-            $route = $messenger == 'download' || $messenger == 'pdf' ? 'download_invoice' : 'launch_invoice';
872
-
873
-            $query_args = array('ee' => $route, 'id' => $this->reg_url_link());
874
-            if ($messenger == 'html') {
875
-                $query_args['html'] = true;
876
-            }
877
-            return add_query_arg($query_args, get_permalink(EE_Registry::instance()->CFG->core->thank_you_page_id));
878
-        }
879
-        return apply_filters('FHEE__EE_Registration__invoice_url__invoice_url', '', $this, $messenger, 'invoice');
880
-    }
881
-
882
-
883
-    /**
884
-     * get Registration URL Link
885
-     *
886
-     * @access public
887
-     * @return string
888
-     * @throws EE_Error
889
-     */
890
-    public function reg_url_link()
891
-    {
892
-        return (string) $this->get('REG_url_link');
893
-    }
894
-
895
-
896
-    /**
897
-     * Echoes out invoice_url()
898
-     *
899
-     * @param string $type 'download','launch', or 'html' (default is 'launch')
900
-     * @return void
901
-     * @throws EE_Error
902
-     */
903
-    public function e_invoice_url($type = 'launch')
904
-    {
905
-        echo $this->invoice_url($type);
906
-    }
907
-
908
-
909
-    /**
910
-     * Echoes out payment_overview_url
911
-     */
912
-    public function e_payment_overview_url()
913
-    {
914
-        echo $this->payment_overview_url();
915
-    }
916
-
917
-
918
-    /**
919
-     * Gets the URL for the checkout payment options reg step
920
-     * with this registration's REG_url_link added as a query parameter
921
-     *
922
-     * @param bool $clear_session Set to true when you want to clear the session on revisiting the
923
-     *                            payment overview url.
924
-     * @return string
925
-     * @throws InvalidInterfaceException
926
-     * @throws InvalidDataTypeException
927
-     * @throws EE_Error
928
-     * @throws InvalidArgumentException
929
-     */
930
-    public function payment_overview_url($clear_session = false)
931
-    {
932
-        return add_query_arg(
933
-            (array) apply_filters(
934
-                'FHEE__EE_Registration__payment_overview_url__query_args',
935
-                array(
936
-                    'e_reg_url_link' => $this->reg_url_link(),
937
-                    'step'           => 'payment_options',
938
-                    'revisit'        => true,
939
-                    'clear_session'  => (bool) $clear_session,
940
-                ),
941
-                $this
942
-            ),
943
-            EE_Registry::instance()->CFG->core->reg_page_url()
944
-        );
945
-    }
946
-
947
-
948
-    /**
949
-     * Gets the URL for the checkout attendee information reg step
950
-     * with this registration's REG_url_link added as a query parameter
951
-     *
952
-     * @return string
953
-     * @throws InvalidInterfaceException
954
-     * @throws InvalidDataTypeException
955
-     * @throws EE_Error
956
-     * @throws InvalidArgumentException
957
-     */
958
-    public function edit_attendee_information_url()
959
-    {
960
-        return add_query_arg(
961
-            (array) apply_filters(
962
-                'FHEE__EE_Registration__edit_attendee_information_url__query_args',
963
-                array(
964
-                    'e_reg_url_link' => $this->reg_url_link(),
965
-                    'step'           => 'attendee_information',
966
-                    'revisit'        => true,
967
-                ),
968
-                $this
969
-            ),
970
-            EE_Registry::instance()->CFG->core->reg_page_url()
971
-        );
972
-    }
973
-
974
-
975
-    /**
976
-     * Simply generates and returns the appropriate admin_url link to edit this registration
977
-     *
978
-     * @return string
979
-     * @throws EE_Error
980
-     */
981
-    public function get_admin_edit_url()
982
-    {
983
-        return EEH_URL::add_query_args_and_nonce(
984
-            array(
985
-                'page'    => 'espresso_registrations',
986
-                'action'  => 'view_registration',
987
-                '_REG_ID' => $this->ID(),
988
-            ),
989
-            admin_url('admin.php')
990
-        );
991
-    }
992
-
993
-
994
-    /**
995
-     *    is_primary_registrant?
996
-     */
997
-    public function is_primary_registrant()
998
-    {
999
-        return $this->get('REG_count') === 1 ? true : false;
1000
-    }
1001
-
1002
-
1003
-    /**
1004
-     * This returns the primary registration object for this registration group (which may be this object).
1005
-     *
1006
-     * @return EE_Registration
1007
-     * @throws EE_Error
1008
-     */
1009
-    public function get_primary_registration()
1010
-    {
1011
-        if ($this->is_primary_registrant()) {
1012
-            return $this;
1013
-        }
1014
-
1015
-        // k reg_count !== 1 so let's get the EE_Registration object matching this txn_id and reg_count == 1
1016
-        /** @var EE_Registration $primary_registrant */
1017
-        $primary_registrant = EEM_Registration::instance()->get_one(
1018
-            array(
1019
-                array(
1020
-                    'TXN_ID'    => $this->transaction_ID(),
1021
-                    'REG_count' => 1,
1022
-                ),
1023
-            )
1024
-        );
1025
-        return $primary_registrant;
1026
-    }
1027
-
1028
-
1029
-    /**
1030
-     *        get  Attendee Number
1031
-     *
1032
-     * @access        public
1033
-     */
1034
-    public function count()
1035
-    {
1036
-        return $this->get('REG_count');
1037
-    }
1038
-
1039
-
1040
-    /**
1041
-     *        get Group Size
1042
-     */
1043
-    public function group_size()
1044
-    {
1045
-        return $this->get('REG_group_size');
1046
-    }
1047
-
1048
-
1049
-    /**
1050
-     *        get Registration Date
1051
-     */
1052
-    public function date()
1053
-    {
1054
-        return $this->get('REG_date');
1055
-    }
1056
-
1057
-
1058
-    /**
1059
-     * gets a pretty date
1060
-     *
1061
-     * @param string $date_format
1062
-     * @param string $time_format
1063
-     * @return string
1064
-     * @throws EE_Error
1065
-     */
1066
-    public function pretty_date($date_format = null, $time_format = null)
1067
-    {
1068
-        return $this->get_datetime('REG_date', $date_format, $time_format);
1069
-    }
1070
-
1071
-
1072
-    /**
1073
-     * final_price
1074
-     * the registration's share of the transaction total, so that the
1075
-     * sum of all the transaction's REG_final_prices equal the transaction's total
1076
-     *
1077
-     * @return float
1078
-     * @throws EE_Error
1079
-     */
1080
-    public function final_price()
1081
-    {
1082
-        return $this->get('REG_final_price');
1083
-    }
1084
-
1085
-
1086
-    /**
1087
-     * pretty_final_price
1088
-     *  final price as formatted string, with correct decimal places and currency symbol
1089
-     *
1090
-     * @return string
1091
-     * @throws EE_Error
1092
-     */
1093
-    public function pretty_final_price()
1094
-    {
1095
-        return $this->get_pretty('REG_final_price');
1096
-    }
1097
-
1098
-
1099
-    /**
1100
-     * get paid (yeah)
1101
-     *
1102
-     * @return float
1103
-     * @throws EE_Error
1104
-     */
1105
-    public function paid()
1106
-    {
1107
-        return $this->get('REG_paid');
1108
-    }
1109
-
1110
-
1111
-    /**
1112
-     * pretty_paid
1113
-     *
1114
-     * @return float
1115
-     * @throws EE_Error
1116
-     */
1117
-    public function pretty_paid()
1118
-    {
1119
-        return $this->get_pretty('REG_paid');
1120
-    }
1121
-
1122
-
1123
-    /**
1124
-     * owes_monies_and_can_pay
1125
-     * whether or not this registration has monies owing and it's' status allows payment
1126
-     *
1127
-     * @param array $requires_payment
1128
-     * @return bool
1129
-     * @throws EE_Error
1130
-     */
1131
-    public function owes_monies_and_can_pay($requires_payment = array())
1132
-    {
1133
-        // these reg statuses require payment (if event is not free)
1134
-        $requires_payment = ! empty($requires_payment)
1135
-            ? $requires_payment
1136
-            : EEM_Registration::reg_statuses_that_allow_payment();
1137
-        if (
1138
-            in_array($this->status_ID(), $requires_payment) &&
1139
-            $this->final_price() != 0 &&
1140
-            $this->final_price() != $this->paid()
1141
-        ) {
1142
-            return true;
1143
-        } else {
1144
-            return false;
1145
-        }
1146
-    }
1147
-
1148
-
1149
-    /**
1150
-     * Prints out the return value of $this->pretty_status()
1151
-     *
1152
-     * @param bool $show_icons
1153
-     * @return void
1154
-     * @throws EE_Error
1155
-     */
1156
-    public function e_pretty_status($show_icons = false)
1157
-    {
1158
-        echo $this->pretty_status($show_icons);
1159
-    }
1160
-
1161
-
1162
-    /**
1163
-     * Returns a nice version of the status for displaying to customers
1164
-     *
1165
-     * @param bool $show_icons
1166
-     * @return string
1167
-     * @throws EE_Error
1168
-     */
1169
-    public function pretty_status($show_icons = false)
1170
-    {
1171
-        $status = EEM_Status::instance()->localized_status(
1172
-            array($this->status_ID() => esc_html__('unknown', 'event_espresso')),
1173
-            false,
1174
-            'sentence'
1175
-        );
1176
-        $icon = '';
1177
-        switch ($this->status_ID()) {
1178
-            case EEM_Registration::status_id_approved:
1179
-                $icon = $show_icons
1180
-                    ? '<span class="dashicons dashicons-star-filled ee-icon-size-16 green-text"></span>'
1181
-                    : '';
1182
-                break;
1183
-            case EEM_Registration::status_id_pending_payment:
1184
-                $icon = $show_icons
1185
-                    ? '<span class="dashicons dashicons-star-half ee-icon-size-16 orange-text"></span>'
1186
-                    : '';
1187
-                break;
1188
-            case EEM_Registration::status_id_not_approved:
1189
-                $icon = $show_icons
1190
-                    ? '<span class="dashicons dashicons-marker ee-icon-size-16 orange-text"></span>'
1191
-                    : '';
1192
-                break;
1193
-            case EEM_Registration::status_id_cancelled:
1194
-                $icon = $show_icons
1195
-                    ? '<span class="dashicons dashicons-no ee-icon-size-16 lt-grey-text"></span>'
1196
-                    : '';
1197
-                break;
1198
-            case EEM_Registration::status_id_incomplete:
1199
-                $icon = $show_icons
1200
-                    ? '<span class="dashicons dashicons-no ee-icon-size-16 lt-orange-text"></span>'
1201
-                    : '';
1202
-                break;
1203
-            case EEM_Registration::status_id_declined:
1204
-                $icon = $show_icons
1205
-                    ? '<span class="dashicons dashicons-no ee-icon-size-16 red-text"></span>'
1206
-                    : '';
1207
-                break;
1208
-            case EEM_Registration::status_id_wait_list:
1209
-                $icon = $show_icons
1210
-                    ? '<span class="dashicons dashicons-clipboard ee-icon-size-16 purple-text"></span>'
1211
-                    : '';
1212
-                break;
1213
-        }
1214
-        return $icon . $status[ $this->status_ID() ];
1215
-    }
1216
-
1217
-
1218
-    /**
1219
-     *        get Attendee Is Going
1220
-     */
1221
-    public function att_is_going()
1222
-    {
1223
-        return $this->get('REG_att_is_going');
1224
-    }
1225
-
1226
-
1227
-    /**
1228
-     * Gets related answers
1229
-     *
1230
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1231
-     * @return EE_Answer[]
1232
-     * @throws EE_Error
1233
-     */
1234
-    public function answers($query_params = null)
1235
-    {
1236
-        return $this->get_many_related('Answer', $query_params);
1237
-    }
1238
-
1239
-
1240
-    /**
1241
-     * Gets the registration's answer value to the specified question
1242
-     * (either the question's ID or a question object)
1243
-     *
1244
-     * @param EE_Question|int $question
1245
-     * @param bool            $pretty_value
1246
-     * @return array|string if pretty_value= true, the result will always be a string
1247
-     * (because the answer might be an array of answer values, so passing pretty_value=true
1248
-     * will convert it into some kind of string)
1249
-     * @throws EE_Error
1250
-     */
1251
-    public function answer_value_to_question($question, $pretty_value = true)
1252
-    {
1253
-        $question_id = EEM_Question::instance()->ensure_is_ID($question);
1254
-        return EEM_Answer::instance()->get_answer_value_to_question($this, $question_id, $pretty_value);
1255
-    }
1256
-
1257
-
1258
-    /**
1259
-     * question_groups
1260
-     * returns an array of EE_Question_Group objects for this registration
1261
-     *
1262
-     * @return EE_Question_Group[]
1263
-     * @throws EE_Error
1264
-     * @throws InvalidArgumentException
1265
-     * @throws InvalidDataTypeException
1266
-     * @throws InvalidInterfaceException
1267
-     * @throws ReflectionException
1268
-     */
1269
-    public function question_groups()
1270
-    {
1271
-        return EEM_Event::instance()->get_question_groups_for_event($this->event_ID(), $this);
1272
-    }
1273
-
1274
-
1275
-    /**
1276
-     * count_question_groups
1277
-     * returns a count of the number of EE_Question_Group objects for this registration
1278
-     *
1279
-     * @return int
1280
-     * @throws EE_Error
1281
-     * @throws EntityNotFoundException
1282
-     * @throws InvalidArgumentException
1283
-     * @throws InvalidDataTypeException
1284
-     * @throws InvalidInterfaceException
1285
-     * @throws ReflectionException
1286
-     */
1287
-    public function count_question_groups()
1288
-    {
1289
-        return EEM_Event::instance()->count_related(
1290
-            $this->event_ID(),
1291
-            'Question_Group',
1292
-            [
1293
-                [
1294
-                    'Event_Question_Group.'
1295
-                    . EEM_Event_Question_Group::instance()->fieldNameForContext($this->is_primary_registrant()) => true,
1296
-                ]
1297
-            ]
1298
-        );
1299
-    }
1300
-
1301
-
1302
-    /**
1303
-     * Returns the registration date in the 'standard' string format
1304
-     * (function may be improved in the future to allow for different formats and timezones)
1305
-     *
1306
-     * @return string
1307
-     * @throws EE_Error
1308
-     */
1309
-    public function reg_date()
1310
-    {
1311
-        return $this->get_datetime('REG_date');
1312
-    }
1313
-
1314
-
1315
-    /**
1316
-     * Gets the datetime-ticket for this registration (ie, it can be used to isolate
1317
-     * the ticket this registration purchased, or the datetime they have registered
1318
-     * to attend)
1319
-     *
1320
-     * @return EE_Datetime_Ticket
1321
-     * @throws EE_Error
1322
-     */
1323
-    public function datetime_ticket()
1324
-    {
1325
-        return $this->get_first_related('Datetime_Ticket');
1326
-    }
1327
-
1328
-
1329
-    /**
1330
-     * Sets the registration's datetime_ticket.
1331
-     *
1332
-     * @param EE_Datetime_Ticket $datetime_ticket
1333
-     * @return EE_Datetime_Ticket
1334
-     * @throws EE_Error
1335
-     */
1336
-    public function set_datetime_ticket($datetime_ticket)
1337
-    {
1338
-        return $this->_add_relation_to($datetime_ticket, 'Datetime_Ticket');
1339
-    }
1340
-
1341
-    /**
1342
-     * Gets deleted
1343
-     *
1344
-     * @return bool
1345
-     * @throws EE_Error
1346
-     */
1347
-    public function deleted()
1348
-    {
1349
-        return $this->get('REG_deleted');
1350
-    }
1351
-
1352
-    /**
1353
-     * Sets deleted
1354
-     *
1355
-     * @param boolean $deleted
1356
-     * @return bool
1357
-     * @throws EE_Error
1358
-     * @throws RuntimeException
1359
-     */
1360
-    public function set_deleted($deleted)
1361
-    {
1362
-        if ($deleted) {
1363
-            $this->delete();
1364
-        } else {
1365
-            $this->restore();
1366
-        }
1367
-    }
1368
-
1369
-
1370
-    /**
1371
-     * Get the status object of this object
1372
-     *
1373
-     * @return EE_Status
1374
-     * @throws EE_Error
1375
-     */
1376
-    public function status_obj()
1377
-    {
1378
-        return $this->get_first_related('Status');
1379
-    }
1380
-
1381
-
1382
-    /**
1383
-     * Returns the number of times this registration has checked into any of the datetimes
1384
-     * its available for
1385
-     *
1386
-     * @return int
1387
-     * @throws EE_Error
1388
-     */
1389
-    public function count_checkins()
1390
-    {
1391
-        return $this->get_model()->count_related($this, 'Checkin');
1392
-    }
1393
-
1394
-
1395
-    /**
1396
-     * Returns the number of current Check-ins this registration is checked into for any of the datetimes the
1397
-     * registration is for.  Note, this is ONLY checked in (does not include checkedout)
1398
-     *
1399
-     * @return int
1400
-     * @throws EE_Error
1401
-     */
1402
-    public function count_checkins_not_checkedout()
1403
-    {
1404
-        return $this->get_model()->count_related($this, 'Checkin', array(array('CHK_in' => 1)));
1405
-    }
1406
-
1407
-
1408
-    /**
1409
-     * The purpose of this method is simply to check whether this registration can checkin to the given datetime.
1410
-     *
1411
-     * @param int | EE_Datetime $DTT_OR_ID      The datetime the registration is being checked against
1412
-     * @param bool              $check_approved This is used to indicate whether the caller wants can_checkin to also
1413
-     *                                          consider registration status as well as datetime access.
1414
-     * @return bool
1415
-     * @throws EE_Error
1416
-     */
1417
-    public function can_checkin($DTT_OR_ID, $check_approved = true)
1418
-    {
1419
-        $DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1420
-
1421
-        // first check registration status
1422
-        if (($check_approved && ! $this->is_approved()) || ! $DTT_ID) {
1423
-            return false;
1424
-        }
1425
-        // is there a datetime ticket that matches this dtt_ID?
1426
-        if (
1427
-            ! (EEM_Datetime_Ticket::instance()->exists(
1428
-                array(
1429
-                array(
1430
-                    'TKT_ID' => $this->get('TKT_ID'),
1431
-                    'DTT_ID' => $DTT_ID,
1432
-                ),
1433
-                )
1434
-            ))
1435
-        ) {
1436
-            return false;
1437
-        }
1438
-
1439
-        // final check is against TKT_uses
1440
-        return $this->verify_can_checkin_against_TKT_uses($DTT_ID);
1441
-    }
1442
-
1443
-
1444
-    /**
1445
-     * This method verifies whether the user can checkin for the given datetime considering the max uses value set on
1446
-     * the ticket. To do this,  a query is done to get the count of the datetime records already checked into.  If the
1447
-     * datetime given does not have a check-in record and checking in for that datetime will exceed the allowed uses,
1448
-     * then return false.  Otherwise return true.
1449
-     *
1450
-     * @param int | EE_Datetime $DTT_OR_ID The datetime the registration is being checked against
1451
-     * @return bool true means can checkin.  false means cannot checkin.
1452
-     * @throws EE_Error
1453
-     */
1454
-    public function verify_can_checkin_against_TKT_uses($DTT_OR_ID)
1455
-    {
1456
-        $DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1457
-
1458
-        if (! $DTT_ID) {
1459
-            return false;
1460
-        }
1461
-
1462
-        $max_uses = $this->ticket() instanceof EE_Ticket ? $this->ticket()->uses() : EE_INF;
1463
-
1464
-        // if max uses is not set or equals infinity then return true cause its not a factor for whether user can
1465
-        // check-in or not.
1466
-        if (! $max_uses || $max_uses === EE_INF) {
1467
-            return true;
1468
-        }
1469
-
1470
-        // does this datetime have a checkin record?  If so, then the dtt count has already been verified so we can just
1471
-        // go ahead and toggle.
1472
-        if (EEM_Checkin::instance()->exists(array(array('REG_ID' => $this->ID(), 'DTT_ID' => $DTT_ID)))) {
1473
-            return true;
1474
-        }
1475
-
1476
-        // made it here so the last check is whether the number of checkins per unique datetime on this registration
1477
-        // disallows further check-ins.
1478
-        $count_unique_dtt_checkins = EEM_Checkin::instance()->count(
1479
-            array(
1480
-                array(
1481
-                    'REG_ID' => $this->ID(),
1482
-                    'CHK_in' => true,
1483
-                ),
1484
-            ),
1485
-            'DTT_ID',
1486
-            true
1487
-        );
1488
-        // checkins have already reached their max number of uses
1489
-        // so registrant can NOT checkin
1490
-        if ($count_unique_dtt_checkins >= $max_uses) {
1491
-            EE_Error::add_error(
1492
-                esc_html__(
1493
-                    'Check-in denied because number of datetime uses for the ticket has been reached or exceeded.',
1494
-                    'event_espresso'
1495
-                ),
1496
-                __FILE__,
1497
-                __FUNCTION__,
1498
-                __LINE__
1499
-            );
1500
-            return false;
1501
-        }
1502
-        return true;
1503
-    }
1504
-
1505
-
1506
-    /**
1507
-     * toggle Check-in status for this registration
1508
-     * Check-ins are toggled in the following order:
1509
-     * never checked in -> checked in
1510
-     * checked in -> checked out
1511
-     * checked out -> checked in
1512
-     *
1513
-     * @param  int $DTT_ID  include specific datetime to toggle Check-in for.
1514
-     *                      If not included or null, then it is assumed latest datetime is being toggled.
1515
-     * @param bool $verify  If true then can_checkin() is used to verify whether the person
1516
-     *                      can be checked in or not.  Otherwise this forces change in checkin status.
1517
-     * @return bool|int     the chk_in status toggled to OR false if nothing got changed.
1518
-     * @throws EE_Error
1519
-     */
1520
-    public function toggle_checkin_status($DTT_ID = null, $verify = false)
1521
-    {
1522
-        if (empty($DTT_ID)) {
1523
-            $datetime = $this->get_latest_related_datetime();
1524
-            $DTT_ID = $datetime instanceof EE_Datetime ? $datetime->ID() : 0;
1525
-            // verify the registration can checkin for the given DTT_ID
1526
-        } elseif (! $this->can_checkin($DTT_ID, $verify)) {
1527
-            EE_Error::add_error(
1528
-                sprintf(
1529
-                    esc_html__(
1530
-                        'The given registration (ID:%1$d) can not be checked in to the given DTT_ID (%2$d), because the registration does not have access',
1531
-                        'event_espresso'
1532
-                    ),
1533
-                    $this->ID(),
1534
-                    $DTT_ID
1535
-                ),
1536
-                __FILE__,
1537
-                __FUNCTION__,
1538
-                __LINE__
1539
-            );
1540
-            return false;
1541
-        }
1542
-        $status_paths = array(
1543
-            EE_Checkin::status_checked_never => EE_Checkin::status_checked_in,
1544
-            EE_Checkin::status_checked_in    => EE_Checkin::status_checked_out,
1545
-            EE_Checkin::status_checked_out   => EE_Checkin::status_checked_in,
1546
-        );
1547
-        // start by getting the current status so we know what status we'll be changing to.
1548
-        $cur_status = $this->check_in_status_for_datetime($DTT_ID, null);
1549
-        $status_to = $status_paths[ $cur_status ];
1550
-        // database only records true for checked IN or false for checked OUT
1551
-        // no record ( null ) means checked in NEVER, but we obviously don't save that
1552
-        $new_status = $status_to === EE_Checkin::status_checked_in ? true : false;
1553
-        // add relation - note Check-ins are always creating new rows
1554
-        // because we are keeping track of Check-ins over time.
1555
-        // Eventually we'll probably want to show a list table
1556
-        // for the individual Check-ins so that they can be managed.
1557
-        $checkin = EE_Checkin::new_instance(
1558
-            array(
1559
-                'REG_ID' => $this->ID(),
1560
-                'DTT_ID' => $DTT_ID,
1561
-                'CHK_in' => $new_status,
1562
-            )
1563
-        );
1564
-        // if the record could not be saved then return false
1565
-        if ($checkin->save() === 0) {
1566
-            if (WP_DEBUG) {
1567
-                global $wpdb;
1568
-                $error = sprintf(
1569
-                    esc_html__(
1570
-                        'Registration check in update failed because of the following database error: %1$s%2$s',
1571
-                        'event_espresso'
1572
-                    ),
1573
-                    '<br />',
1574
-                    $wpdb->last_error
1575
-                );
1576
-            } else {
1577
-                $error = esc_html__(
1578
-                    'Registration check in update failed because of an unknown database error',
1579
-                    'event_espresso'
1580
-                );
1581
-            }
1582
-            EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
1583
-            return false;
1584
-        }
1585
-        // Fire a checked_in and checkout_out action.
1586
-        $checked_status = $status_to === EE_Checkin::status_checked_in ? 'checked_in' : 'checked_out';
1587
-        do_action("AHEE__EE_Registration__toggle_checkin_status__{$checked_status}", $this, $DTT_ID);
1588
-        return $status_to;
1589
-    }
1590
-
1591
-
1592
-    /**
1593
-     * Returns the latest datetime related to this registration (via the ticket attached to the registration).
1594
-     * "Latest" is defined by the `DTT_EVT_start` column.
1595
-     *
1596
-     * @return EE_Datetime|null
1597
-     * @throws EE_Error
1598
-     */
1599
-    public function get_latest_related_datetime()
1600
-    {
1601
-        return EEM_Datetime::instance()->get_one(
1602
-            array(
1603
-                array(
1604
-                    'Ticket.Registration.REG_ID' => $this->ID(),
1605
-                ),
1606
-                'order_by' => array('DTT_EVT_start' => 'DESC'),
1607
-            )
1608
-        );
1609
-    }
1610
-
1611
-
1612
-    /**
1613
-     * Returns the earliest datetime related to this registration (via the ticket attached to the registration).
1614
-     * "Earliest" is defined by the `DTT_EVT_start` column.
1615
-     *
1616
-     * @throws EE_Error
1617
-     */
1618
-    public function get_earliest_related_datetime()
1619
-    {
1620
-        return EEM_Datetime::instance()->get_one(
1621
-            array(
1622
-                array(
1623
-                    'Ticket.Registration.REG_ID' => $this->ID(),
1624
-                ),
1625
-                'order_by' => array('DTT_EVT_start' => 'ASC'),
1626
-            )
1627
-        );
1628
-    }
1629
-
1630
-
1631
-    /**
1632
-     * This method simply returns the check-in status for this registration and the given datetime.
1633
-     * If neither the datetime nor the checkin values are provided as arguments,
1634
-     * then this will return the LATEST check-in status for the registration across all datetimes it belongs to.
1635
-     *
1636
-     * @param  int       $DTT_ID  The ID of the datetime we're checking against
1637
-     *                            (if empty we'll get the primary datetime for
1638
-     *                            this registration (via event) and use it's ID);
1639
-     * @param EE_Checkin $checkin If present, we use the given checkin object rather than the dtt_id.
1640
-     *
1641
-     * @return int                Integer representing Check-in status.
1642
-     * @throws EE_Error
1643
-     */
1644
-    public function check_in_status_for_datetime($DTT_ID = 0, $checkin = null)
1645
-    {
1646
-        $checkin_query_params = array(
1647
-            'order_by' => array('CHK_timestamp' => 'DESC'),
1648
-        );
1649
-
1650
-        if ($DTT_ID > 0) {
1651
-            $checkin_query_params[0] = array('DTT_ID' => $DTT_ID);
1652
-        }
1653
-
1654
-        // get checkin object (if exists)
1655
-        $checkin = $checkin instanceof EE_Checkin
1656
-            ? $checkin
1657
-            : $this->get_first_related('Checkin', $checkin_query_params);
1658
-        if ($checkin instanceof EE_Checkin) {
1659
-            if ($checkin->get('CHK_in')) {
1660
-                return EE_Checkin::status_checked_in; // checked in
1661
-            }
1662
-            return EE_Checkin::status_checked_out; // had checked in but is now checked out.
1663
-        }
1664
-        return EE_Checkin::status_checked_never; // never been checked in
1665
-    }
1666
-
1667
-
1668
-    /**
1669
-     * This method returns a localized message for the toggled Check-in message.
1670
-     *
1671
-     * @param  int $DTT_ID include specific datetime to get the correct Check-in message.  If not included or null,
1672
-     *                     then it is assumed Check-in for primary datetime was toggled.
1673
-     * @param bool $error  This just flags that you want an error message returned. This is put in so that the error
1674
-     *                     message can be customized with the attendee name.
1675
-     * @return string internationalized message
1676
-     * @throws EE_Error
1677
-     */
1678
-    public function get_checkin_msg($DTT_ID, $error = false)
1679
-    {
1680
-        // let's get the attendee first so we can include the name of the attendee
1681
-        $attendee = $this->get_first_related('Attendee');
1682
-        if ($attendee instanceof EE_Attendee) {
1683
-            if ($error) {
1684
-                return sprintf(__("%s's check-in status was not changed.", "event_espresso"), $attendee->full_name());
1685
-            }
1686
-            $cur_status = $this->check_in_status_for_datetime($DTT_ID);
1687
-            // what is the status message going to be?
1688
-            switch ($cur_status) {
1689
-                case EE_Checkin::status_checked_never:
1690
-                    return sprintf(
1691
-                        __("%s has been removed from Check-in records", "event_espresso"),
1692
-                        $attendee->full_name()
1693
-                    );
1694
-                    break;
1695
-                case EE_Checkin::status_checked_in:
1696
-                    return sprintf(__('%s has been checked in', 'event_espresso'), $attendee->full_name());
1697
-                    break;
1698
-                case EE_Checkin::status_checked_out:
1699
-                    return sprintf(__('%s has been checked out', 'event_espresso'), $attendee->full_name());
1700
-                    break;
1701
-            }
1702
-        }
1703
-        return esc_html__("The check-in status could not be determined.", "event_espresso");
1704
-    }
1705
-
1706
-
1707
-    /**
1708
-     * Returns the related EE_Transaction to this registration
1709
-     *
1710
-     * @return EE_Transaction
1711
-     * @throws EE_Error
1712
-     * @throws EntityNotFoundException
1713
-     */
1714
-    public function transaction()
1715
-    {
1716
-        $transaction = $this->get_first_related('Transaction');
1717
-        if (! $transaction instanceof \EE_Transaction) {
1718
-            throw new EntityNotFoundException('Transaction ID', $this->transaction_ID());
1719
-        }
1720
-        return $transaction;
1721
-    }
1722
-
1723
-
1724
-    /**
1725
-     *        get Registration Code
1726
-     */
1727
-    public function reg_code()
1728
-    {
1729
-        return $this->get('REG_code');
1730
-    }
1731
-
1732
-
1733
-    /**
1734
-     *        get Transaction ID
1735
-     */
1736
-    public function transaction_ID()
1737
-    {
1738
-        return $this->get('TXN_ID');
1739
-    }
1740
-
1741
-
1742
-    /**
1743
-     * @return int
1744
-     * @throws EE_Error
1745
-     */
1746
-    public function ticket_ID()
1747
-    {
1748
-        return $this->get('TKT_ID');
1749
-    }
1750
-
1751
-
1752
-    /**
1753
-     *        Set Registration Code
1754
-     *
1755
-     * @access    public
1756
-     * @param    string  $REG_code Registration Code
1757
-     * @param    boolean $use_default
1758
-     * @throws EE_Error
1759
-     */
1760
-    public function set_reg_code($REG_code, $use_default = false)
1761
-    {
1762
-        if (empty($REG_code)) {
1763
-            EE_Error::add_error(
1764
-                esc_html__('REG_code can not be empty.', 'event_espresso'),
1765
-                __FILE__,
1766
-                __FUNCTION__,
1767
-                __LINE__
1768
-            );
1769
-            return;
1770
-        }
1771
-        if (! $this->reg_code()) {
1772
-            parent::set('REG_code', $REG_code, $use_default);
1773
-        } else {
1774
-            EE_Error::doing_it_wrong(
1775
-                __CLASS__ . '::' . __FUNCTION__,
1776
-                esc_html__('Can not change a registration REG_code once it has been set.', 'event_espresso'),
1777
-                '4.6.0'
1778
-            );
1779
-        }
1780
-    }
1781
-
1782
-
1783
-    /**
1784
-     * Returns all other registrations in the same group as this registrant who have the same ticket option.
1785
-     * Note, if you want to just get all registrations in the same transaction (group), use:
1786
-     *    $registration->transaction()->registrations();
1787
-     *
1788
-     * @since 4.5.0
1789
-     * @return EE_Registration[] or empty array if this isn't a group registration.
1790
-     * @throws EE_Error
1791
-     */
1792
-    public function get_all_other_registrations_in_group()
1793
-    {
1794
-        if ($this->group_size() < 2) {
1795
-            return array();
1796
-        }
1797
-
1798
-        $query[0] = array(
1799
-            'TXN_ID' => $this->transaction_ID(),
1800
-            'REG_ID' => array('!=', $this->ID()),
1801
-            'TKT_ID' => $this->ticket_ID(),
1802
-        );
1803
-        /** @var EE_Registration[] $registrations */
1804
-        $registrations = $this->get_model()->get_all($query);
1805
-        return $registrations;
1806
-    }
1807
-
1808
-    /**
1809
-     * Return the link to the admin details for the object.
1810
-     *
1811
-     * @return string
1812
-     * @throws EE_Error
1813
-     */
1814
-    public function get_admin_details_link()
1815
-    {
1816
-        EE_Registry::instance()->load_helper('URL');
1817
-        return EEH_URL::add_query_args_and_nonce(
1818
-            array(
1819
-                'page'    => 'espresso_registrations',
1820
-                'action'  => 'view_registration',
1821
-                '_REG_ID' => $this->ID(),
1822
-            ),
1823
-            admin_url('admin.php')
1824
-        );
1825
-    }
1826
-
1827
-    /**
1828
-     * Returns the link to the editor for the object.  Sometimes this is the same as the details.
1829
-     *
1830
-     * @return string
1831
-     * @throws EE_Error
1832
-     */
1833
-    public function get_admin_edit_link()
1834
-    {
1835
-        return $this->get_admin_details_link();
1836
-    }
1837
-
1838
-    /**
1839
-     * Returns the link to a settings page for the object.
1840
-     *
1841
-     * @return string
1842
-     * @throws EE_Error
1843
-     */
1844
-    public function get_admin_settings_link()
1845
-    {
1846
-        return $this->get_admin_details_link();
1847
-    }
1848
-
1849
-    /**
1850
-     * Returns the link to the "overview" for the object (typically the "list table" view).
1851
-     *
1852
-     * @return string
1853
-     */
1854
-    public function get_admin_overview_link()
1855
-    {
1856
-        EE_Registry::instance()->load_helper('URL');
1857
-        return EEH_URL::add_query_args_and_nonce(
1858
-            array(
1859
-                'page' => 'espresso_registrations',
1860
-            ),
1861
-            admin_url('admin.php')
1862
-        );
1863
-    }
1864
-
1865
-
1866
-    /**
1867
-     * @param array $query_params
1868
-     *
1869
-     * @return \EE_Registration[]
1870
-     * @throws EE_Error
1871
-     */
1872
-    public function payments($query_params = array())
1873
-    {
1874
-        return $this->get_many_related('Payment', $query_params);
1875
-    }
1876
-
1877
-
1878
-    /**
1879
-     * @param array $query_params
1880
-     *
1881
-     * @return \EE_Registration_Payment[]
1882
-     * @throws EE_Error
1883
-     */
1884
-    public function registration_payments($query_params = array())
1885
-    {
1886
-        return $this->get_many_related('Registration_Payment', $query_params);
1887
-    }
1888
-
1889
-
1890
-    /**
1891
-     * This grabs the payment method corresponding to the last payment made for the amount owing on the registration.
1892
-     * Note: if there are no payments on the registration there will be no payment method returned.
1893
-     *
1894
-     * @return EE_Payment_Method|null
1895
-     */
1896
-    public function payment_method()
1897
-    {
1898
-        return EEM_Payment_Method::instance()->get_last_used_for_registration($this);
1899
-    }
1900
-
1901
-
1902
-    /**
1903
-     * @return \EE_Line_Item
1904
-     * @throws EntityNotFoundException
1905
-     * @throws EE_Error
1906
-     */
1907
-    public function ticket_line_item()
1908
-    {
1909
-        $ticket = $this->ticket();
1910
-        $transaction = $this->transaction();
1911
-        $line_item = null;
1912
-        $ticket_line_items = \EEH_Line_Item::get_line_items_by_object_type_and_IDs(
1913
-            $transaction->total_line_item(),
1914
-            'Ticket',
1915
-            array($ticket->ID())
1916
-        );
1917
-        foreach ($ticket_line_items as $ticket_line_item) {
1918
-            if (
1919
-                $ticket_line_item instanceof \EE_Line_Item
1920
-                && $ticket_line_item->OBJ_type() === 'Ticket'
1921
-                && $ticket_line_item->OBJ_ID() === $ticket->ID()
1922
-            ) {
1923
-                $line_item = $ticket_line_item;
1924
-                break;
1925
-            }
1926
-        }
1927
-        if (! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
1928
-            throw new EntityNotFoundException('Line Item Ticket ID', $ticket->ID());
1929
-        }
1930
-        return $line_item;
1931
-    }
1932
-
1933
-
1934
-    /**
1935
-     * Soft Deletes this model object.
1936
-     *
1937
-     * @return boolean | int
1938
-     * @throws RuntimeException
1939
-     * @throws EE_Error
1940
-     */
1941
-    public function delete()
1942
-    {
1943
-        if ($this->update_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY, $this->status_ID()) === true) {
1944
-            $this->set_status(EEM_Registration::status_id_cancelled);
1945
-        }
1946
-        return parent::delete();
1947
-    }
1948
-
1949
-
1950
-    /**
1951
-     * Restores whatever the previous status was on a registration before it was trashed (if possible)
1952
-     *
1953
-     * @throws EE_Error
1954
-     * @throws RuntimeException
1955
-     */
1956
-    public function restore()
1957
-    {
1958
-        $previous_status = $this->get_extra_meta(
1959
-            EE_Registration::PRE_TRASH_REG_STATUS_KEY,
1960
-            true,
1961
-            EEM_Registration::status_id_cancelled
1962
-        );
1963
-        if ($previous_status) {
1964
-            $this->delete_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY);
1965
-            $this->set_status($previous_status);
1966
-        }
1967
-        return parent::restore();
1968
-    }
1969
-
1970
-
1971
-    /**
1972
-     * possibly toggle Registration status based on comparison of REG_paid vs REG_final_price
1973
-     *
1974
-     * @param  boolean $trigger_set_status_logic EE_Registration::set_status() can trigger additional logic
1975
-     *                                           depending on whether the reg status changes to or from "Approved"
1976
-     * @return boolean whether the Registration status was updated
1977
-     * @throws EE_Error
1978
-     * @throws RuntimeException
1979
-     */
1980
-    public function updateStatusBasedOnTotalPaid($trigger_set_status_logic = true)
1981
-    {
1982
-        $paid = $this->paid();
1983
-        $price = $this->final_price();
1984
-        switch (true) {
1985
-            // overpaid or paid
1986
-            case EEH_Money::compare_floats($paid, $price, '>'):
1987
-            case EEH_Money::compare_floats($paid, $price):
1988
-                $new_status = EEM_Registration::status_id_approved;
1989
-                break;
1990
-            //  underpaid
1991
-            case EEH_Money::compare_floats($paid, $price, '<'):
1992
-                $new_status = EEM_Registration::status_id_pending_payment;
1993
-                break;
1994
-            // uhhh Houston...
1995
-            default:
1996
-                throw new RuntimeException(
1997
-                    esc_html__('The total paid calculation for this registration is inaccurate.', 'event_espresso')
1998
-                );
1999
-        }
2000
-        if ($new_status !== $this->status_ID()) {
2001
-            if ($trigger_set_status_logic) {
2002
-                return $this->set_status($new_status);
2003
-            }
2004
-            parent::set('STS_ID', $new_status);
2005
-            return true;
2006
-        }
2007
-        return false;
2008
-    }
2009
-
2010
-
2011
-    /*************************** DEPRECATED ***************************/
2012
-
2013
-
2014
-    /**
2015
-     * @deprecated
2016
-     * @since     4.7.0
2017
-     * @access    public
2018
-     */
2019
-    public function price_paid()
2020
-    {
2021
-        EE_Error::doing_it_wrong(
2022
-            'EE_Registration::price_paid()',
2023
-            esc_html__(
2024
-                'This method is deprecated, please use EE_Registration::final_price() instead.',
2025
-                'event_espresso'
2026
-            ),
2027
-            '4.7.0'
2028
-        );
2029
-        return $this->final_price();
2030
-    }
2031
-
2032
-
2033
-    /**
2034
-     * @deprecated
2035
-     * @since     4.7.0
2036
-     * @access    public
2037
-     * @param    float $REG_final_price
2038
-     * @throws EE_Error
2039
-     * @throws RuntimeException
2040
-     */
2041
-    public function set_price_paid($REG_final_price = 0.00)
2042
-    {
2043
-        EE_Error::doing_it_wrong(
2044
-            'EE_Registration::set_price_paid()',
2045
-            esc_html__(
2046
-                'This method is deprecated, please use EE_Registration::set_final_price() instead.',
2047
-                'event_espresso'
2048
-            ),
2049
-            '4.7.0'
2050
-        );
2051
-        $this->set_final_price($REG_final_price);
2052
-    }
2053
-
2054
-
2055
-    /**
2056
-     * @deprecated
2057
-     * @since 4.7.0
2058
-     * @return string
2059
-     * @throws EE_Error
2060
-     */
2061
-    public function pretty_price_paid()
2062
-    {
2063
-        EE_Error::doing_it_wrong(
2064
-            'EE_Registration::pretty_price_paid()',
2065
-            esc_html__(
2066
-                'This method is deprecated, please use EE_Registration::pretty_final_price() instead.',
2067
-                'event_espresso'
2068
-            ),
2069
-            '4.7.0'
2070
-        );
2071
-        return $this->pretty_final_price();
2072
-    }
2073
-
2074
-
2075
-    /**
2076
-     * Gets the primary datetime related to this registration via the related Event to this registration
2077
-     *
2078
-     * @deprecated 4.9.17
2079
-     * @return EE_Datetime
2080
-     * @throws EE_Error
2081
-     * @throws EntityNotFoundException
2082
-     */
2083
-    public function get_related_primary_datetime()
2084
-    {
2085
-        EE_Error::doing_it_wrong(
2086
-            __METHOD__,
2087
-            esc_html__(
2088
-                'Use EE_Registration::get_latest_related_datetime() or EE_Registration::get_earliest_related_datetime()',
2089
-                'event_espresso'
2090
-            ),
2091
-            '4.9.17',
2092
-            '5.0.0'
2093
-        );
2094
-        return $this->event()->primary_datetime();
2095
-    }
20
+	/**
21
+	 * Used to reference when a registration has never been checked in.
22
+	 *
23
+	 * @deprecated use \EE_Checkin::status_checked_never instead
24
+	 * @type int
25
+	 */
26
+	const checkin_status_never = 2;
27
+
28
+	/**
29
+	 * Used to reference when a registration has been checked in.
30
+	 *
31
+	 * @deprecated use \EE_Checkin::status_checked_in instead
32
+	 * @type int
33
+	 */
34
+	const checkin_status_in = 1;
35
+
36
+
37
+	/**
38
+	 * Used to reference when a registration has been checked out.
39
+	 *
40
+	 * @deprecated use \EE_Checkin::status_checked_out instead
41
+	 * @type int
42
+	 */
43
+	const checkin_status_out = 0;
44
+
45
+
46
+	/**
47
+	 * extra meta key for tracking reg status os trashed registrations
48
+	 *
49
+	 * @type string
50
+	 */
51
+	const PRE_TRASH_REG_STATUS_KEY = 'pre_trash_registration_status';
52
+
53
+
54
+	/**
55
+	 * extra meta key for tracking if registration has reserved ticket
56
+	 *
57
+	 * @type string
58
+	 */
59
+	const HAS_RESERVED_TICKET_KEY = 'has_reserved_ticket';
60
+
61
+
62
+	/**
63
+	 * @param array  $props_n_values          incoming values
64
+	 * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
65
+	 *                                        used.)
66
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
67
+	 *                                        date_format and the second value is the time format
68
+	 * @return EE_Registration
69
+	 * @throws EE_Error
70
+	 */
71
+	public static function new_instance($props_n_values = array(), $timezone = '', $date_formats = array())
72
+	{
73
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
74
+		return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
75
+	}
76
+
77
+
78
+	/**
79
+	 * @param array  $props_n_values  incoming values from the database
80
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
81
+	 *                                the website will be used.
82
+	 * @return EE_Registration
83
+	 */
84
+	public static function new_instance_from_db($props_n_values = array(), $timezone = '')
85
+	{
86
+		return new self($props_n_values, true, $timezone);
87
+	}
88
+
89
+
90
+	/**
91
+	 *        Set Event ID
92
+	 *
93
+	 * @param        int $EVT_ID Event ID
94
+	 * @throws EE_Error
95
+	 * @throws RuntimeException
96
+	 */
97
+	public function set_event($EVT_ID = 0)
98
+	{
99
+		$this->set('EVT_ID', $EVT_ID);
100
+	}
101
+
102
+
103
+	/**
104
+	 * Overrides parent set() method so that all calls to set( 'REG_code', $REG_code ) OR set( 'STS_ID', $STS_ID ) can
105
+	 * be routed to internal methods
106
+	 *
107
+	 * @param string $field_name
108
+	 * @param mixed  $field_value
109
+	 * @param bool   $use_default
110
+	 * @throws EE_Error
111
+	 * @throws EntityNotFoundException
112
+	 * @throws InvalidArgumentException
113
+	 * @throws InvalidDataTypeException
114
+	 * @throws InvalidInterfaceException
115
+	 * @throws ReflectionException
116
+	 * @throws RuntimeException
117
+	 */
118
+	public function set($field_name, $field_value, $use_default = false)
119
+	{
120
+		switch ($field_name) {
121
+			case 'REG_code':
122
+				if (! empty($field_value) && $this->reg_code() === null) {
123
+					$this->set_reg_code($field_value, $use_default);
124
+				}
125
+				break;
126
+			case 'STS_ID':
127
+				$this->set_status($field_value, $use_default);
128
+				break;
129
+			default:
130
+				parent::set($field_name, $field_value, $use_default);
131
+		}
132
+	}
133
+
134
+
135
+	/**
136
+	 * Set Status ID
137
+	 * updates the registration status and ALSO...
138
+	 * calls reserve_registration_space() if the reg status changes TO approved from any other reg status
139
+	 * calls release_registration_space() if the reg status changes FROM approved to any other reg status
140
+	 *
141
+	 * @param string                $new_STS_ID
142
+	 * @param boolean               $use_default
143
+	 * @param ContextInterface|null $context
144
+	 * @return bool
145
+	 * @throws DomainException
146
+	 * @throws EE_Error
147
+	 * @throws EntityNotFoundException
148
+	 * @throws InvalidArgumentException
149
+	 * @throws InvalidDataTypeException
150
+	 * @throws InvalidInterfaceException
151
+	 * @throws ReflectionException
152
+	 * @throws RuntimeException
153
+	 * @throws UnexpectedEntityException
154
+	 */
155
+	public function set_status($new_STS_ID = null, $use_default = false, ContextInterface $context = null)
156
+	{
157
+		// get current REG_Status
158
+		$old_STS_ID = $this->status_ID();
159
+		// if status has changed
160
+		if (
161
+			$old_STS_ID !== $new_STS_ID // and that status has actually changed
162
+			&& ! empty($old_STS_ID) // and that old status is actually set
163
+			&& ! empty($new_STS_ID) // as well as the new status
164
+			&& $this->ID() // ensure registration is in the db
165
+		) {
166
+			// update internal status first
167
+			parent::set('STS_ID', $new_STS_ID, $use_default);
168
+			// THEN handle other changes that occur when reg status changes
169
+			// TO approved
170
+			if ($new_STS_ID === EEM_Registration::status_id_approved) {
171
+				// reserve a space by incrementing ticket and datetime sold values
172
+				$this->reserveRegistrationSpace();
173
+				do_action('AHEE__EE_Registration__set_status__to_approved', $this, $old_STS_ID, $new_STS_ID, $context);
174
+				// OR FROM  approved
175
+			} elseif ($old_STS_ID === EEM_Registration::status_id_approved) {
176
+				// release a space by decrementing ticket and datetime sold values
177
+				$this->releaseRegistrationSpace();
178
+				do_action(
179
+					'AHEE__EE_Registration__set_status__from_approved',
180
+					$this,
181
+					$old_STS_ID,
182
+					$new_STS_ID,
183
+					$context
184
+				);
185
+			}
186
+			// update status
187
+			parent::set('STS_ID', $new_STS_ID, $use_default);
188
+			$this->updateIfCanceledOrReinstated($new_STS_ID, $old_STS_ID, $context);
189
+			if ($this->statusChangeUpdatesTransaction($context)) {
190
+				$this->updateTransactionAfterStatusChange();
191
+			}
192
+			do_action('AHEE__EE_Registration__set_status__after_update', $this, $old_STS_ID, $new_STS_ID, $context);
193
+			return true;
194
+		}
195
+		// even though the old value matches the new value, it's still good to
196
+		// allow the parent set method to have a say
197
+		parent::set('STS_ID', $new_STS_ID, $use_default);
198
+		return true;
199
+	}
200
+
201
+
202
+	/**
203
+	 * update REGs and TXN when cancelled or declined registrations involved
204
+	 *
205
+	 * @param string                $new_STS_ID
206
+	 * @param string                $old_STS_ID
207
+	 * @param ContextInterface|null $context
208
+	 * @throws EE_Error
209
+	 * @throws InvalidArgumentException
210
+	 * @throws InvalidDataTypeException
211
+	 * @throws InvalidInterfaceException
212
+	 * @throws ReflectionException
213
+	 * @throws RuntimeException
214
+	 */
215
+	private function updateIfCanceledOrReinstated($new_STS_ID, $old_STS_ID, ContextInterface $context = null)
216
+	{
217
+		// these reg statuses should not be considered in any calculations involving monies owing
218
+		$closed_reg_statuses = EEM_Registration::closed_reg_statuses();
219
+		// true if registration has been cancelled or declined
220
+		$this->updateIfCanceled(
221
+			$closed_reg_statuses,
222
+			$new_STS_ID,
223
+			$old_STS_ID,
224
+			$context
225
+		);
226
+		$this->updateIfReinstated(
227
+			$closed_reg_statuses,
228
+			$new_STS_ID,
229
+			$old_STS_ID,
230
+			$context
231
+		);
232
+	}
233
+
234
+
235
+	/**
236
+	 * update REGs and TXN when cancelled or declined registrations involved
237
+	 *
238
+	 * @param array                 $closed_reg_statuses
239
+	 * @param string                $new_STS_ID
240
+	 * @param string                $old_STS_ID
241
+	 * @param ContextInterface|null $context
242
+	 * @throws EE_Error
243
+	 * @throws InvalidArgumentException
244
+	 * @throws InvalidDataTypeException
245
+	 * @throws InvalidInterfaceException
246
+	 * @throws ReflectionException
247
+	 * @throws RuntimeException
248
+	 */
249
+	private function updateIfCanceled(
250
+		array $closed_reg_statuses,
251
+		$new_STS_ID,
252
+		$old_STS_ID,
253
+		ContextInterface $context = null
254
+	) {
255
+		// true if registration has been cancelled or declined
256
+		if (
257
+			in_array($new_STS_ID, $closed_reg_statuses, true)
258
+			&& ! in_array($old_STS_ID, $closed_reg_statuses, true)
259
+		) {
260
+			/** @type EE_Registration_Processor $registration_processor */
261
+			$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
262
+			/** @type EE_Transaction_Processor $transaction_processor */
263
+			$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
264
+			// cancelled or declined registration
265
+			$registration_processor->update_registration_after_being_canceled_or_declined(
266
+				$this,
267
+				$closed_reg_statuses
268
+			);
269
+			$transaction_processor->update_transaction_after_canceled_or_declined_registration(
270
+				$this,
271
+				$closed_reg_statuses,
272
+				false
273
+			);
274
+			do_action(
275
+				'AHEE__EE_Registration__set_status__canceled_or_declined',
276
+				$this,
277
+				$old_STS_ID,
278
+				$new_STS_ID,
279
+				$context
280
+			);
281
+			return;
282
+		}
283
+	}
284
+
285
+
286
+	/**
287
+	 * update REGs and TXN when cancelled or declined registrations involved
288
+	 *
289
+	 * @param array                 $closed_reg_statuses
290
+	 * @param string                $new_STS_ID
291
+	 * @param string                $old_STS_ID
292
+	 * @param ContextInterface|null $context
293
+	 * @throws EE_Error
294
+	 * @throws InvalidArgumentException
295
+	 * @throws InvalidDataTypeException
296
+	 * @throws InvalidInterfaceException
297
+	 * @throws ReflectionException
298
+	 */
299
+	private function updateIfReinstated(
300
+		array $closed_reg_statuses,
301
+		$new_STS_ID,
302
+		$old_STS_ID,
303
+		ContextInterface $context = null
304
+	) {
305
+		// true if reinstating cancelled or declined registration
306
+		if (
307
+			in_array($old_STS_ID, $closed_reg_statuses, true)
308
+			&& ! in_array($new_STS_ID, $closed_reg_statuses, true)
309
+		) {
310
+			/** @type EE_Registration_Processor $registration_processor */
311
+			$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
312
+			/** @type EE_Transaction_Processor $transaction_processor */
313
+			$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
314
+			// reinstating cancelled or declined registration
315
+			$registration_processor->update_canceled_or_declined_registration_after_being_reinstated(
316
+				$this,
317
+				$closed_reg_statuses
318
+			);
319
+			$transaction_processor->update_transaction_after_reinstating_canceled_registration(
320
+				$this,
321
+				$closed_reg_statuses,
322
+				false
323
+			);
324
+			do_action(
325
+				'AHEE__EE_Registration__set_status__after_reinstated',
326
+				$this,
327
+				$old_STS_ID,
328
+				$new_STS_ID,
329
+				$context
330
+			);
331
+		}
332
+	}
333
+
334
+
335
+	/**
336
+	 * @param ContextInterface|null $context
337
+	 * @return bool
338
+	 */
339
+	private function statusChangeUpdatesTransaction(ContextInterface $context = null)
340
+	{
341
+		$contexts_that_do_not_update_transaction = (array) apply_filters(
342
+			'AHEE__EE_Registration__statusChangeUpdatesTransaction__contexts_that_do_not_update_transaction',
343
+			array('spco_reg_step_attendee_information_process_registrations'),
344
+			$context,
345
+			$this
346
+		);
347
+		return ! (
348
+			$context instanceof ContextInterface
349
+			&& in_array($context->slug(), $contexts_that_do_not_update_transaction, true)
350
+		);
351
+	}
352
+
353
+
354
+	/**
355
+	 * @throws EE_Error
356
+	 * @throws EntityNotFoundException
357
+	 * @throws InvalidArgumentException
358
+	 * @throws InvalidDataTypeException
359
+	 * @throws InvalidInterfaceException
360
+	 * @throws ReflectionException
361
+	 * @throws RuntimeException
362
+	 */
363
+	private function updateTransactionAfterStatusChange()
364
+	{
365
+		/** @type EE_Transaction_Payments $transaction_payments */
366
+		$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
367
+		$transaction_payments->recalculate_transaction_total($this->transaction(), false);
368
+		$this->transaction()->update_status_based_on_total_paid(true);
369
+	}
370
+
371
+
372
+	/**
373
+	 *        get Status ID
374
+	 */
375
+	public function status_ID()
376
+	{
377
+		return $this->get('STS_ID');
378
+	}
379
+
380
+
381
+	/**
382
+	 * Gets the ticket this registration is for
383
+	 *
384
+	 * @param boolean $include_archived whether to include archived tickets or not.
385
+	 *
386
+	 * @return EE_Ticket|EE_Base_Class
387
+	 * @throws EE_Error
388
+	 */
389
+	public function ticket($include_archived = true)
390
+	{
391
+		$query_params = array();
392
+		if ($include_archived) {
393
+			$query_params['default_where_conditions'] = 'none';
394
+		}
395
+		return $this->get_first_related('Ticket', $query_params);
396
+	}
397
+
398
+
399
+	/**
400
+	 * Gets the event this registration is for
401
+	 *
402
+	 * @return EE_Event
403
+	 * @throws EE_Error
404
+	 * @throws EntityNotFoundException
405
+	 */
406
+	public function event()
407
+	{
408
+		$event = $this->get_first_related('Event');
409
+		if (! $event instanceof \EE_Event) {
410
+			throw new EntityNotFoundException('Event ID', $this->event_ID());
411
+		}
412
+		return $event;
413
+	}
414
+
415
+
416
+	/**
417
+	 * Gets the "author" of the registration.  Note that for the purposes of registrations, the author will correspond
418
+	 * with the author of the event this registration is for.
419
+	 *
420
+	 * @since 4.5.0
421
+	 * @return int
422
+	 * @throws EE_Error
423
+	 * @throws EntityNotFoundException
424
+	 */
425
+	public function wp_user()
426
+	{
427
+		$event = $this->event();
428
+		if ($event instanceof EE_Event) {
429
+			return $event->wp_user();
430
+		}
431
+		return 0;
432
+	}
433
+
434
+
435
+	/**
436
+	 * increments this registration's related ticket sold and corresponding datetime sold values
437
+	 *
438
+	 * @return void
439
+	 * @throws DomainException
440
+	 * @throws EE_Error
441
+	 * @throws EntityNotFoundException
442
+	 * @throws InvalidArgumentException
443
+	 * @throws InvalidDataTypeException
444
+	 * @throws InvalidInterfaceException
445
+	 * @throws ReflectionException
446
+	 * @throws UnexpectedEntityException
447
+	 */
448
+	private function reserveRegistrationSpace()
449
+	{
450
+		// reserved ticket and datetime counts will be decremented as sold counts are incremented
451
+		// so stop tracking that this reg has a ticket reserved
452
+		$this->release_reserved_ticket(false, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
453
+		$ticket = $this->ticket();
454
+		$ticket->increaseSold();
455
+		// possibly set event status to sold out
456
+		$this->event()->perform_sold_out_status_check();
457
+	}
458
+
459
+
460
+	/**
461
+	 * decrements (subtracts) this registration's related ticket sold and corresponding datetime sold values
462
+	 *
463
+	 * @return void
464
+	 * @throws DomainException
465
+	 * @throws EE_Error
466
+	 * @throws EntityNotFoundException
467
+	 * @throws InvalidArgumentException
468
+	 * @throws InvalidDataTypeException
469
+	 * @throws InvalidInterfaceException
470
+	 * @throws ReflectionException
471
+	 * @throws UnexpectedEntityException
472
+	 */
473
+	private function releaseRegistrationSpace()
474
+	{
475
+		$ticket = $this->ticket();
476
+		$ticket->decreaseSold();
477
+		// possibly change event status from sold out back to previous status
478
+		$this->event()->perform_sold_out_status_check();
479
+	}
480
+
481
+
482
+	/**
483
+	 * tracks this registration's ticket reservation in extra meta
484
+	 * and can increment related ticket reserved and corresponding datetime reserved values
485
+	 *
486
+	 * @param bool $update_ticket if true, will increment ticket and datetime reserved count
487
+	 * @return void
488
+	 * @throws EE_Error
489
+	 * @throws InvalidArgumentException
490
+	 * @throws InvalidDataTypeException
491
+	 * @throws InvalidInterfaceException
492
+	 * @throws ReflectionException
493
+	 */
494
+	public function reserve_ticket($update_ticket = false, $source = 'unknown')
495
+	{
496
+		// only reserve ticket if space is not currently reserved
497
+		if ((bool) $this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true) !== true) {
498
+			$this->update_extra_meta('reserve_ticket', "{$this->ticket_ID()} from {$source}");
499
+			// IMPORTANT !!!
500
+			// although checking $update_ticket first would be more efficient,
501
+			// we NEED to ALWAYS call update_extra_meta(), which is why that is done first
502
+			if (
503
+				$this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true)
504
+				&& $update_ticket
505
+			) {
506
+				$ticket = $this->ticket();
507
+				$ticket->increaseReserved(1, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
508
+				$ticket->save();
509
+			}
510
+		}
511
+	}
512
+
513
+
514
+	/**
515
+	 * stops tracking this registration's ticket reservation in extra meta
516
+	 * decrements (subtracts) related ticket reserved and corresponding datetime reserved values
517
+	 *
518
+	 * @param bool $update_ticket if true, will decrement ticket and datetime reserved count
519
+	 * @return void
520
+	 * @throws EE_Error
521
+	 * @throws InvalidArgumentException
522
+	 * @throws InvalidDataTypeException
523
+	 * @throws InvalidInterfaceException
524
+	 * @throws ReflectionException
525
+	 */
526
+	public function release_reserved_ticket($update_ticket = false, $source = 'unknown')
527
+	{
528
+		// only release ticket if space is currently reserved
529
+		if ((bool) $this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true) === true) {
530
+			$this->update_extra_meta('release_reserved_ticket', "{$this->ticket_ID()} from {$source}");
531
+			// IMPORTANT !!!
532
+			// although checking $update_ticket first would be more efficient,
533
+			// we NEED to ALWAYS call update_extra_meta(), which is why that is done first
534
+			if (
535
+				$this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, false)
536
+				&& $update_ticket
537
+			) {
538
+				$ticket = $this->ticket();
539
+				$ticket->decreaseReserved(1, true, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
540
+			}
541
+		}
542
+	}
543
+
544
+
545
+	/**
546
+	 * Set Attendee ID
547
+	 *
548
+	 * @param        int $ATT_ID Attendee ID
549
+	 * @throws EE_Error
550
+	 * @throws RuntimeException
551
+	 */
552
+	public function set_attendee_id($ATT_ID = 0)
553
+	{
554
+		$this->set('ATT_ID', $ATT_ID);
555
+	}
556
+
557
+
558
+	/**
559
+	 *        Set Transaction ID
560
+	 *
561
+	 * @param        int $TXN_ID Transaction ID
562
+	 * @throws EE_Error
563
+	 * @throws RuntimeException
564
+	 */
565
+	public function set_transaction_id($TXN_ID = 0)
566
+	{
567
+		$this->set('TXN_ID', $TXN_ID);
568
+	}
569
+
570
+
571
+	/**
572
+	 *        Set Session
573
+	 *
574
+	 * @param    string $REG_session PHP Session ID
575
+	 * @throws EE_Error
576
+	 * @throws RuntimeException
577
+	 */
578
+	public function set_session($REG_session = '')
579
+	{
580
+		$this->set('REG_session', $REG_session);
581
+	}
582
+
583
+
584
+	/**
585
+	 *        Set Registration URL Link
586
+	 *
587
+	 * @param    string $REG_url_link Registration URL Link
588
+	 * @throws EE_Error
589
+	 * @throws RuntimeException
590
+	 */
591
+	public function set_reg_url_link($REG_url_link = '')
592
+	{
593
+		$this->set('REG_url_link', $REG_url_link);
594
+	}
595
+
596
+
597
+	/**
598
+	 *        Set Attendee Counter
599
+	 *
600
+	 * @param        int $REG_count Primary Attendee
601
+	 * @throws EE_Error
602
+	 * @throws RuntimeException
603
+	 */
604
+	public function set_count($REG_count = 1)
605
+	{
606
+		$this->set('REG_count', $REG_count);
607
+	}
608
+
609
+
610
+	/**
611
+	 *        Set Group Size
612
+	 *
613
+	 * @param        boolean $REG_group_size Group Registration
614
+	 * @throws EE_Error
615
+	 * @throws RuntimeException
616
+	 */
617
+	public function set_group_size($REG_group_size = false)
618
+	{
619
+		$this->set('REG_group_size', $REG_group_size);
620
+	}
621
+
622
+
623
+	/**
624
+	 *    is_not_approved -  convenience method that returns TRUE if REG status ID ==
625
+	 *    EEM_Registration::status_id_not_approved
626
+	 *
627
+	 * @return        boolean
628
+	 */
629
+	public function is_not_approved()
630
+	{
631
+		return $this->status_ID() == EEM_Registration::status_id_not_approved ? true : false;
632
+	}
633
+
634
+
635
+	/**
636
+	 *    is_pending_payment -  convenience method that returns TRUE if REG status ID ==
637
+	 *    EEM_Registration::status_id_pending_payment
638
+	 *
639
+	 * @return        boolean
640
+	 */
641
+	public function is_pending_payment()
642
+	{
643
+		return $this->status_ID() == EEM_Registration::status_id_pending_payment ? true : false;
644
+	}
645
+
646
+
647
+	/**
648
+	 *    is_approved -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_approved
649
+	 *
650
+	 * @return        boolean
651
+	 */
652
+	public function is_approved()
653
+	{
654
+		return $this->status_ID() == EEM_Registration::status_id_approved ? true : false;
655
+	}
656
+
657
+
658
+	/**
659
+	 *    is_cancelled -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_cancelled
660
+	 *
661
+	 * @return        boolean
662
+	 */
663
+	public function is_cancelled()
664
+	{
665
+		return $this->status_ID() == EEM_Registration::status_id_cancelled ? true : false;
666
+	}
667
+
668
+
669
+	/**
670
+	 *    is_declined -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_declined
671
+	 *
672
+	 * @return        boolean
673
+	 */
674
+	public function is_declined()
675
+	{
676
+		return $this->status_ID() == EEM_Registration::status_id_declined ? true : false;
677
+	}
678
+
679
+
680
+	/**
681
+	 *    is_incomplete -  convenience method that returns TRUE if REG status ID ==
682
+	 *    EEM_Registration::status_id_incomplete
683
+	 *
684
+	 * @return        boolean
685
+	 */
686
+	public function is_incomplete()
687
+	{
688
+		return $this->status_ID() == EEM_Registration::status_id_incomplete ? true : false;
689
+	}
690
+
691
+
692
+	/**
693
+	 *        Set Registration Date
694
+	 *
695
+	 * @param        mixed ( int or string ) $REG_date Registration Date - Unix timestamp or string representation of
696
+	 *                                                 Date
697
+	 * @throws EE_Error
698
+	 * @throws RuntimeException
699
+	 */
700
+	public function set_reg_date($REG_date = false)
701
+	{
702
+		$this->set('REG_date', $REG_date);
703
+	}
704
+
705
+
706
+	/**
707
+	 *    Set final price owing for this registration after all ticket/price modifications
708
+	 *
709
+	 * @access    public
710
+	 * @param    float $REG_final_price
711
+	 * @throws EE_Error
712
+	 * @throws RuntimeException
713
+	 */
714
+	public function set_final_price($REG_final_price = 0.00)
715
+	{
716
+		$this->set('REG_final_price', $REG_final_price);
717
+	}
718
+
719
+
720
+	/**
721
+	 *    Set amount paid towards this registration's final price
722
+	 *
723
+	 * @access    public
724
+	 * @param    float $REG_paid
725
+	 * @throws EE_Error
726
+	 * @throws RuntimeException
727
+	 */
728
+	public function set_paid($REG_paid = 0.00)
729
+	{
730
+		$this->set('REG_paid', $REG_paid);
731
+	}
732
+
733
+
734
+	/**
735
+	 *        Attendee Is Going
736
+	 *
737
+	 * @param        boolean $REG_att_is_going Attendee Is Going
738
+	 * @throws EE_Error
739
+	 * @throws RuntimeException
740
+	 */
741
+	public function set_att_is_going($REG_att_is_going = false)
742
+	{
743
+		$this->set('REG_att_is_going', $REG_att_is_going);
744
+	}
745
+
746
+
747
+	/**
748
+	 * Gets the related attendee
749
+	 *
750
+	 * @return EE_Attendee
751
+	 * @throws EE_Error
752
+	 */
753
+	public function attendee()
754
+	{
755
+		return $this->get_first_related('Attendee');
756
+	}
757
+
758
+
759
+	/**
760
+	 *        get Event ID
761
+	 */
762
+	public function event_ID()
763
+	{
764
+		return $this->get('EVT_ID');
765
+	}
766
+
767
+
768
+	/**
769
+	 *        get Event ID
770
+	 */
771
+	public function event_name()
772
+	{
773
+		$event = $this->event_obj();
774
+		if ($event) {
775
+			return $event->name();
776
+		} else {
777
+			return null;
778
+		}
779
+	}
780
+
781
+
782
+	/**
783
+	 * Fetches the event this registration is for
784
+	 *
785
+	 * @return EE_Event
786
+	 * @throws EE_Error
787
+	 */
788
+	public function event_obj()
789
+	{
790
+		return $this->get_first_related('Event');
791
+	}
792
+
793
+
794
+	/**
795
+	 *        get Attendee ID
796
+	 */
797
+	public function attendee_ID()
798
+	{
799
+		return $this->get('ATT_ID');
800
+	}
801
+
802
+
803
+	/**
804
+	 *        get PHP Session ID
805
+	 */
806
+	public function session_ID()
807
+	{
808
+		return $this->get('REG_session');
809
+	}
810
+
811
+
812
+	/**
813
+	 * Gets the string which represents the URL trigger for the receipt template in the message template system.
814
+	 *
815
+	 * @param string $messenger 'pdf' or 'html'.  Default 'html'.
816
+	 * @return string
817
+	 */
818
+	public function receipt_url($messenger = 'html')
819
+	{
820
+
821
+		/**
822
+		 * The below will be deprecated one version after this.  We check first if there is a custom receipt template
823
+		 * already in use on old system.  If there is then we just return the standard url for it.
824
+		 *
825
+		 * @since 4.5.0
826
+		 */
827
+		$template_relative_path = 'modules/gateways/Invoice/lib/templates/receipt_body.template.php';
828
+		$has_custom = EEH_Template::locate_template(
829
+			$template_relative_path,
830
+			array(),
831
+			true,
832
+			true,
833
+			true
834
+		);
835
+
836
+		if ($has_custom) {
837
+			return add_query_arg(array('receipt' => 'true'), $this->invoice_url('launch'));
838
+		}
839
+		return apply_filters('FHEE__EE_Registration__receipt_url__receipt_url', '', $this, $messenger, 'receipt');
840
+	}
841
+
842
+
843
+	/**
844
+	 * Gets the string which represents the URL trigger for the invoice template in the message template system.
845
+	 *
846
+	 * @param string $messenger 'pdf' or 'html'.  Default 'html'.
847
+	 * @return string
848
+	 * @throws EE_Error
849
+	 */
850
+	public function invoice_url($messenger = 'html')
851
+	{
852
+		/**
853
+		 * The below will be deprecated one version after this.  We check first if there is a custom invoice template
854
+		 * already in use on old system.  If there is then we just return the standard url for it.
855
+		 *
856
+		 * @since 4.5.0
857
+		 */
858
+		$template_relative_path = 'modules/gateways/Invoice/lib/templates/invoice_body.template.php';
859
+		$has_custom = EEH_Template::locate_template(
860
+			$template_relative_path,
861
+			array(),
862
+			true,
863
+			true,
864
+			true
865
+		);
866
+
867
+		if ($has_custom) {
868
+			if ($messenger == 'html') {
869
+				return $this->invoice_url('launch');
870
+			}
871
+			$route = $messenger == 'download' || $messenger == 'pdf' ? 'download_invoice' : 'launch_invoice';
872
+
873
+			$query_args = array('ee' => $route, 'id' => $this->reg_url_link());
874
+			if ($messenger == 'html') {
875
+				$query_args['html'] = true;
876
+			}
877
+			return add_query_arg($query_args, get_permalink(EE_Registry::instance()->CFG->core->thank_you_page_id));
878
+		}
879
+		return apply_filters('FHEE__EE_Registration__invoice_url__invoice_url', '', $this, $messenger, 'invoice');
880
+	}
881
+
882
+
883
+	/**
884
+	 * get Registration URL Link
885
+	 *
886
+	 * @access public
887
+	 * @return string
888
+	 * @throws EE_Error
889
+	 */
890
+	public function reg_url_link()
891
+	{
892
+		return (string) $this->get('REG_url_link');
893
+	}
894
+
895
+
896
+	/**
897
+	 * Echoes out invoice_url()
898
+	 *
899
+	 * @param string $type 'download','launch', or 'html' (default is 'launch')
900
+	 * @return void
901
+	 * @throws EE_Error
902
+	 */
903
+	public function e_invoice_url($type = 'launch')
904
+	{
905
+		echo $this->invoice_url($type);
906
+	}
907
+
908
+
909
+	/**
910
+	 * Echoes out payment_overview_url
911
+	 */
912
+	public function e_payment_overview_url()
913
+	{
914
+		echo $this->payment_overview_url();
915
+	}
916
+
917
+
918
+	/**
919
+	 * Gets the URL for the checkout payment options reg step
920
+	 * with this registration's REG_url_link added as a query parameter
921
+	 *
922
+	 * @param bool $clear_session Set to true when you want to clear the session on revisiting the
923
+	 *                            payment overview url.
924
+	 * @return string
925
+	 * @throws InvalidInterfaceException
926
+	 * @throws InvalidDataTypeException
927
+	 * @throws EE_Error
928
+	 * @throws InvalidArgumentException
929
+	 */
930
+	public function payment_overview_url($clear_session = false)
931
+	{
932
+		return add_query_arg(
933
+			(array) apply_filters(
934
+				'FHEE__EE_Registration__payment_overview_url__query_args',
935
+				array(
936
+					'e_reg_url_link' => $this->reg_url_link(),
937
+					'step'           => 'payment_options',
938
+					'revisit'        => true,
939
+					'clear_session'  => (bool) $clear_session,
940
+				),
941
+				$this
942
+			),
943
+			EE_Registry::instance()->CFG->core->reg_page_url()
944
+		);
945
+	}
946
+
947
+
948
+	/**
949
+	 * Gets the URL for the checkout attendee information reg step
950
+	 * with this registration's REG_url_link added as a query parameter
951
+	 *
952
+	 * @return string
953
+	 * @throws InvalidInterfaceException
954
+	 * @throws InvalidDataTypeException
955
+	 * @throws EE_Error
956
+	 * @throws InvalidArgumentException
957
+	 */
958
+	public function edit_attendee_information_url()
959
+	{
960
+		return add_query_arg(
961
+			(array) apply_filters(
962
+				'FHEE__EE_Registration__edit_attendee_information_url__query_args',
963
+				array(
964
+					'e_reg_url_link' => $this->reg_url_link(),
965
+					'step'           => 'attendee_information',
966
+					'revisit'        => true,
967
+				),
968
+				$this
969
+			),
970
+			EE_Registry::instance()->CFG->core->reg_page_url()
971
+		);
972
+	}
973
+
974
+
975
+	/**
976
+	 * Simply generates and returns the appropriate admin_url link to edit this registration
977
+	 *
978
+	 * @return string
979
+	 * @throws EE_Error
980
+	 */
981
+	public function get_admin_edit_url()
982
+	{
983
+		return EEH_URL::add_query_args_and_nonce(
984
+			array(
985
+				'page'    => 'espresso_registrations',
986
+				'action'  => 'view_registration',
987
+				'_REG_ID' => $this->ID(),
988
+			),
989
+			admin_url('admin.php')
990
+		);
991
+	}
992
+
993
+
994
+	/**
995
+	 *    is_primary_registrant?
996
+	 */
997
+	public function is_primary_registrant()
998
+	{
999
+		return $this->get('REG_count') === 1 ? true : false;
1000
+	}
1001
+
1002
+
1003
+	/**
1004
+	 * This returns the primary registration object for this registration group (which may be this object).
1005
+	 *
1006
+	 * @return EE_Registration
1007
+	 * @throws EE_Error
1008
+	 */
1009
+	public function get_primary_registration()
1010
+	{
1011
+		if ($this->is_primary_registrant()) {
1012
+			return $this;
1013
+		}
1014
+
1015
+		// k reg_count !== 1 so let's get the EE_Registration object matching this txn_id and reg_count == 1
1016
+		/** @var EE_Registration $primary_registrant */
1017
+		$primary_registrant = EEM_Registration::instance()->get_one(
1018
+			array(
1019
+				array(
1020
+					'TXN_ID'    => $this->transaction_ID(),
1021
+					'REG_count' => 1,
1022
+				),
1023
+			)
1024
+		);
1025
+		return $primary_registrant;
1026
+	}
1027
+
1028
+
1029
+	/**
1030
+	 *        get  Attendee Number
1031
+	 *
1032
+	 * @access        public
1033
+	 */
1034
+	public function count()
1035
+	{
1036
+		return $this->get('REG_count');
1037
+	}
1038
+
1039
+
1040
+	/**
1041
+	 *        get Group Size
1042
+	 */
1043
+	public function group_size()
1044
+	{
1045
+		return $this->get('REG_group_size');
1046
+	}
1047
+
1048
+
1049
+	/**
1050
+	 *        get Registration Date
1051
+	 */
1052
+	public function date()
1053
+	{
1054
+		return $this->get('REG_date');
1055
+	}
1056
+
1057
+
1058
+	/**
1059
+	 * gets a pretty date
1060
+	 *
1061
+	 * @param string $date_format
1062
+	 * @param string $time_format
1063
+	 * @return string
1064
+	 * @throws EE_Error
1065
+	 */
1066
+	public function pretty_date($date_format = null, $time_format = null)
1067
+	{
1068
+		return $this->get_datetime('REG_date', $date_format, $time_format);
1069
+	}
1070
+
1071
+
1072
+	/**
1073
+	 * final_price
1074
+	 * the registration's share of the transaction total, so that the
1075
+	 * sum of all the transaction's REG_final_prices equal the transaction's total
1076
+	 *
1077
+	 * @return float
1078
+	 * @throws EE_Error
1079
+	 */
1080
+	public function final_price()
1081
+	{
1082
+		return $this->get('REG_final_price');
1083
+	}
1084
+
1085
+
1086
+	/**
1087
+	 * pretty_final_price
1088
+	 *  final price as formatted string, with correct decimal places and currency symbol
1089
+	 *
1090
+	 * @return string
1091
+	 * @throws EE_Error
1092
+	 */
1093
+	public function pretty_final_price()
1094
+	{
1095
+		return $this->get_pretty('REG_final_price');
1096
+	}
1097
+
1098
+
1099
+	/**
1100
+	 * get paid (yeah)
1101
+	 *
1102
+	 * @return float
1103
+	 * @throws EE_Error
1104
+	 */
1105
+	public function paid()
1106
+	{
1107
+		return $this->get('REG_paid');
1108
+	}
1109
+
1110
+
1111
+	/**
1112
+	 * pretty_paid
1113
+	 *
1114
+	 * @return float
1115
+	 * @throws EE_Error
1116
+	 */
1117
+	public function pretty_paid()
1118
+	{
1119
+		return $this->get_pretty('REG_paid');
1120
+	}
1121
+
1122
+
1123
+	/**
1124
+	 * owes_monies_and_can_pay
1125
+	 * whether or not this registration has monies owing and it's' status allows payment
1126
+	 *
1127
+	 * @param array $requires_payment
1128
+	 * @return bool
1129
+	 * @throws EE_Error
1130
+	 */
1131
+	public function owes_monies_and_can_pay($requires_payment = array())
1132
+	{
1133
+		// these reg statuses require payment (if event is not free)
1134
+		$requires_payment = ! empty($requires_payment)
1135
+			? $requires_payment
1136
+			: EEM_Registration::reg_statuses_that_allow_payment();
1137
+		if (
1138
+			in_array($this->status_ID(), $requires_payment) &&
1139
+			$this->final_price() != 0 &&
1140
+			$this->final_price() != $this->paid()
1141
+		) {
1142
+			return true;
1143
+		} else {
1144
+			return false;
1145
+		}
1146
+	}
1147
+
1148
+
1149
+	/**
1150
+	 * Prints out the return value of $this->pretty_status()
1151
+	 *
1152
+	 * @param bool $show_icons
1153
+	 * @return void
1154
+	 * @throws EE_Error
1155
+	 */
1156
+	public function e_pretty_status($show_icons = false)
1157
+	{
1158
+		echo $this->pretty_status($show_icons);
1159
+	}
1160
+
1161
+
1162
+	/**
1163
+	 * Returns a nice version of the status for displaying to customers
1164
+	 *
1165
+	 * @param bool $show_icons
1166
+	 * @return string
1167
+	 * @throws EE_Error
1168
+	 */
1169
+	public function pretty_status($show_icons = false)
1170
+	{
1171
+		$status = EEM_Status::instance()->localized_status(
1172
+			array($this->status_ID() => esc_html__('unknown', 'event_espresso')),
1173
+			false,
1174
+			'sentence'
1175
+		);
1176
+		$icon = '';
1177
+		switch ($this->status_ID()) {
1178
+			case EEM_Registration::status_id_approved:
1179
+				$icon = $show_icons
1180
+					? '<span class="dashicons dashicons-star-filled ee-icon-size-16 green-text"></span>'
1181
+					: '';
1182
+				break;
1183
+			case EEM_Registration::status_id_pending_payment:
1184
+				$icon = $show_icons
1185
+					? '<span class="dashicons dashicons-star-half ee-icon-size-16 orange-text"></span>'
1186
+					: '';
1187
+				break;
1188
+			case EEM_Registration::status_id_not_approved:
1189
+				$icon = $show_icons
1190
+					? '<span class="dashicons dashicons-marker ee-icon-size-16 orange-text"></span>'
1191
+					: '';
1192
+				break;
1193
+			case EEM_Registration::status_id_cancelled:
1194
+				$icon = $show_icons
1195
+					? '<span class="dashicons dashicons-no ee-icon-size-16 lt-grey-text"></span>'
1196
+					: '';
1197
+				break;
1198
+			case EEM_Registration::status_id_incomplete:
1199
+				$icon = $show_icons
1200
+					? '<span class="dashicons dashicons-no ee-icon-size-16 lt-orange-text"></span>'
1201
+					: '';
1202
+				break;
1203
+			case EEM_Registration::status_id_declined:
1204
+				$icon = $show_icons
1205
+					? '<span class="dashicons dashicons-no ee-icon-size-16 red-text"></span>'
1206
+					: '';
1207
+				break;
1208
+			case EEM_Registration::status_id_wait_list:
1209
+				$icon = $show_icons
1210
+					? '<span class="dashicons dashicons-clipboard ee-icon-size-16 purple-text"></span>'
1211
+					: '';
1212
+				break;
1213
+		}
1214
+		return $icon . $status[ $this->status_ID() ];
1215
+	}
1216
+
1217
+
1218
+	/**
1219
+	 *        get Attendee Is Going
1220
+	 */
1221
+	public function att_is_going()
1222
+	{
1223
+		return $this->get('REG_att_is_going');
1224
+	}
1225
+
1226
+
1227
+	/**
1228
+	 * Gets related answers
1229
+	 *
1230
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1231
+	 * @return EE_Answer[]
1232
+	 * @throws EE_Error
1233
+	 */
1234
+	public function answers($query_params = null)
1235
+	{
1236
+		return $this->get_many_related('Answer', $query_params);
1237
+	}
1238
+
1239
+
1240
+	/**
1241
+	 * Gets the registration's answer value to the specified question
1242
+	 * (either the question's ID or a question object)
1243
+	 *
1244
+	 * @param EE_Question|int $question
1245
+	 * @param bool            $pretty_value
1246
+	 * @return array|string if pretty_value= true, the result will always be a string
1247
+	 * (because the answer might be an array of answer values, so passing pretty_value=true
1248
+	 * will convert it into some kind of string)
1249
+	 * @throws EE_Error
1250
+	 */
1251
+	public function answer_value_to_question($question, $pretty_value = true)
1252
+	{
1253
+		$question_id = EEM_Question::instance()->ensure_is_ID($question);
1254
+		return EEM_Answer::instance()->get_answer_value_to_question($this, $question_id, $pretty_value);
1255
+	}
1256
+
1257
+
1258
+	/**
1259
+	 * question_groups
1260
+	 * returns an array of EE_Question_Group objects for this registration
1261
+	 *
1262
+	 * @return EE_Question_Group[]
1263
+	 * @throws EE_Error
1264
+	 * @throws InvalidArgumentException
1265
+	 * @throws InvalidDataTypeException
1266
+	 * @throws InvalidInterfaceException
1267
+	 * @throws ReflectionException
1268
+	 */
1269
+	public function question_groups()
1270
+	{
1271
+		return EEM_Event::instance()->get_question_groups_for_event($this->event_ID(), $this);
1272
+	}
1273
+
1274
+
1275
+	/**
1276
+	 * count_question_groups
1277
+	 * returns a count of the number of EE_Question_Group objects for this registration
1278
+	 *
1279
+	 * @return int
1280
+	 * @throws EE_Error
1281
+	 * @throws EntityNotFoundException
1282
+	 * @throws InvalidArgumentException
1283
+	 * @throws InvalidDataTypeException
1284
+	 * @throws InvalidInterfaceException
1285
+	 * @throws ReflectionException
1286
+	 */
1287
+	public function count_question_groups()
1288
+	{
1289
+		return EEM_Event::instance()->count_related(
1290
+			$this->event_ID(),
1291
+			'Question_Group',
1292
+			[
1293
+				[
1294
+					'Event_Question_Group.'
1295
+					. EEM_Event_Question_Group::instance()->fieldNameForContext($this->is_primary_registrant()) => true,
1296
+				]
1297
+			]
1298
+		);
1299
+	}
1300
+
1301
+
1302
+	/**
1303
+	 * Returns the registration date in the 'standard' string format
1304
+	 * (function may be improved in the future to allow for different formats and timezones)
1305
+	 *
1306
+	 * @return string
1307
+	 * @throws EE_Error
1308
+	 */
1309
+	public function reg_date()
1310
+	{
1311
+		return $this->get_datetime('REG_date');
1312
+	}
1313
+
1314
+
1315
+	/**
1316
+	 * Gets the datetime-ticket for this registration (ie, it can be used to isolate
1317
+	 * the ticket this registration purchased, or the datetime they have registered
1318
+	 * to attend)
1319
+	 *
1320
+	 * @return EE_Datetime_Ticket
1321
+	 * @throws EE_Error
1322
+	 */
1323
+	public function datetime_ticket()
1324
+	{
1325
+		return $this->get_first_related('Datetime_Ticket');
1326
+	}
1327
+
1328
+
1329
+	/**
1330
+	 * Sets the registration's datetime_ticket.
1331
+	 *
1332
+	 * @param EE_Datetime_Ticket $datetime_ticket
1333
+	 * @return EE_Datetime_Ticket
1334
+	 * @throws EE_Error
1335
+	 */
1336
+	public function set_datetime_ticket($datetime_ticket)
1337
+	{
1338
+		return $this->_add_relation_to($datetime_ticket, 'Datetime_Ticket');
1339
+	}
1340
+
1341
+	/**
1342
+	 * Gets deleted
1343
+	 *
1344
+	 * @return bool
1345
+	 * @throws EE_Error
1346
+	 */
1347
+	public function deleted()
1348
+	{
1349
+		return $this->get('REG_deleted');
1350
+	}
1351
+
1352
+	/**
1353
+	 * Sets deleted
1354
+	 *
1355
+	 * @param boolean $deleted
1356
+	 * @return bool
1357
+	 * @throws EE_Error
1358
+	 * @throws RuntimeException
1359
+	 */
1360
+	public function set_deleted($deleted)
1361
+	{
1362
+		if ($deleted) {
1363
+			$this->delete();
1364
+		} else {
1365
+			$this->restore();
1366
+		}
1367
+	}
1368
+
1369
+
1370
+	/**
1371
+	 * Get the status object of this object
1372
+	 *
1373
+	 * @return EE_Status
1374
+	 * @throws EE_Error
1375
+	 */
1376
+	public function status_obj()
1377
+	{
1378
+		return $this->get_first_related('Status');
1379
+	}
1380
+
1381
+
1382
+	/**
1383
+	 * Returns the number of times this registration has checked into any of the datetimes
1384
+	 * its available for
1385
+	 *
1386
+	 * @return int
1387
+	 * @throws EE_Error
1388
+	 */
1389
+	public function count_checkins()
1390
+	{
1391
+		return $this->get_model()->count_related($this, 'Checkin');
1392
+	}
1393
+
1394
+
1395
+	/**
1396
+	 * Returns the number of current Check-ins this registration is checked into for any of the datetimes the
1397
+	 * registration is for.  Note, this is ONLY checked in (does not include checkedout)
1398
+	 *
1399
+	 * @return int
1400
+	 * @throws EE_Error
1401
+	 */
1402
+	public function count_checkins_not_checkedout()
1403
+	{
1404
+		return $this->get_model()->count_related($this, 'Checkin', array(array('CHK_in' => 1)));
1405
+	}
1406
+
1407
+
1408
+	/**
1409
+	 * The purpose of this method is simply to check whether this registration can checkin to the given datetime.
1410
+	 *
1411
+	 * @param int | EE_Datetime $DTT_OR_ID      The datetime the registration is being checked against
1412
+	 * @param bool              $check_approved This is used to indicate whether the caller wants can_checkin to also
1413
+	 *                                          consider registration status as well as datetime access.
1414
+	 * @return bool
1415
+	 * @throws EE_Error
1416
+	 */
1417
+	public function can_checkin($DTT_OR_ID, $check_approved = true)
1418
+	{
1419
+		$DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1420
+
1421
+		// first check registration status
1422
+		if (($check_approved && ! $this->is_approved()) || ! $DTT_ID) {
1423
+			return false;
1424
+		}
1425
+		// is there a datetime ticket that matches this dtt_ID?
1426
+		if (
1427
+			! (EEM_Datetime_Ticket::instance()->exists(
1428
+				array(
1429
+				array(
1430
+					'TKT_ID' => $this->get('TKT_ID'),
1431
+					'DTT_ID' => $DTT_ID,
1432
+				),
1433
+				)
1434
+			))
1435
+		) {
1436
+			return false;
1437
+		}
1438
+
1439
+		// final check is against TKT_uses
1440
+		return $this->verify_can_checkin_against_TKT_uses($DTT_ID);
1441
+	}
1442
+
1443
+
1444
+	/**
1445
+	 * This method verifies whether the user can checkin for the given datetime considering the max uses value set on
1446
+	 * the ticket. To do this,  a query is done to get the count of the datetime records already checked into.  If the
1447
+	 * datetime given does not have a check-in record and checking in for that datetime will exceed the allowed uses,
1448
+	 * then return false.  Otherwise return true.
1449
+	 *
1450
+	 * @param int | EE_Datetime $DTT_OR_ID The datetime the registration is being checked against
1451
+	 * @return bool true means can checkin.  false means cannot checkin.
1452
+	 * @throws EE_Error
1453
+	 */
1454
+	public function verify_can_checkin_against_TKT_uses($DTT_OR_ID)
1455
+	{
1456
+		$DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1457
+
1458
+		if (! $DTT_ID) {
1459
+			return false;
1460
+		}
1461
+
1462
+		$max_uses = $this->ticket() instanceof EE_Ticket ? $this->ticket()->uses() : EE_INF;
1463
+
1464
+		// if max uses is not set or equals infinity then return true cause its not a factor for whether user can
1465
+		// check-in or not.
1466
+		if (! $max_uses || $max_uses === EE_INF) {
1467
+			return true;
1468
+		}
1469
+
1470
+		// does this datetime have a checkin record?  If so, then the dtt count has already been verified so we can just
1471
+		// go ahead and toggle.
1472
+		if (EEM_Checkin::instance()->exists(array(array('REG_ID' => $this->ID(), 'DTT_ID' => $DTT_ID)))) {
1473
+			return true;
1474
+		}
1475
+
1476
+		// made it here so the last check is whether the number of checkins per unique datetime on this registration
1477
+		// disallows further check-ins.
1478
+		$count_unique_dtt_checkins = EEM_Checkin::instance()->count(
1479
+			array(
1480
+				array(
1481
+					'REG_ID' => $this->ID(),
1482
+					'CHK_in' => true,
1483
+				),
1484
+			),
1485
+			'DTT_ID',
1486
+			true
1487
+		);
1488
+		// checkins have already reached their max number of uses
1489
+		// so registrant can NOT checkin
1490
+		if ($count_unique_dtt_checkins >= $max_uses) {
1491
+			EE_Error::add_error(
1492
+				esc_html__(
1493
+					'Check-in denied because number of datetime uses for the ticket has been reached or exceeded.',
1494
+					'event_espresso'
1495
+				),
1496
+				__FILE__,
1497
+				__FUNCTION__,
1498
+				__LINE__
1499
+			);
1500
+			return false;
1501
+		}
1502
+		return true;
1503
+	}
1504
+
1505
+
1506
+	/**
1507
+	 * toggle Check-in status for this registration
1508
+	 * Check-ins are toggled in the following order:
1509
+	 * never checked in -> checked in
1510
+	 * checked in -> checked out
1511
+	 * checked out -> checked in
1512
+	 *
1513
+	 * @param  int $DTT_ID  include specific datetime to toggle Check-in for.
1514
+	 *                      If not included or null, then it is assumed latest datetime is being toggled.
1515
+	 * @param bool $verify  If true then can_checkin() is used to verify whether the person
1516
+	 *                      can be checked in or not.  Otherwise this forces change in checkin status.
1517
+	 * @return bool|int     the chk_in status toggled to OR false if nothing got changed.
1518
+	 * @throws EE_Error
1519
+	 */
1520
+	public function toggle_checkin_status($DTT_ID = null, $verify = false)
1521
+	{
1522
+		if (empty($DTT_ID)) {
1523
+			$datetime = $this->get_latest_related_datetime();
1524
+			$DTT_ID = $datetime instanceof EE_Datetime ? $datetime->ID() : 0;
1525
+			// verify the registration can checkin for the given DTT_ID
1526
+		} elseif (! $this->can_checkin($DTT_ID, $verify)) {
1527
+			EE_Error::add_error(
1528
+				sprintf(
1529
+					esc_html__(
1530
+						'The given registration (ID:%1$d) can not be checked in to the given DTT_ID (%2$d), because the registration does not have access',
1531
+						'event_espresso'
1532
+					),
1533
+					$this->ID(),
1534
+					$DTT_ID
1535
+				),
1536
+				__FILE__,
1537
+				__FUNCTION__,
1538
+				__LINE__
1539
+			);
1540
+			return false;
1541
+		}
1542
+		$status_paths = array(
1543
+			EE_Checkin::status_checked_never => EE_Checkin::status_checked_in,
1544
+			EE_Checkin::status_checked_in    => EE_Checkin::status_checked_out,
1545
+			EE_Checkin::status_checked_out   => EE_Checkin::status_checked_in,
1546
+		);
1547
+		// start by getting the current status so we know what status we'll be changing to.
1548
+		$cur_status = $this->check_in_status_for_datetime($DTT_ID, null);
1549
+		$status_to = $status_paths[ $cur_status ];
1550
+		// database only records true for checked IN or false for checked OUT
1551
+		// no record ( null ) means checked in NEVER, but we obviously don't save that
1552
+		$new_status = $status_to === EE_Checkin::status_checked_in ? true : false;
1553
+		// add relation - note Check-ins are always creating new rows
1554
+		// because we are keeping track of Check-ins over time.
1555
+		// Eventually we'll probably want to show a list table
1556
+		// for the individual Check-ins so that they can be managed.
1557
+		$checkin = EE_Checkin::new_instance(
1558
+			array(
1559
+				'REG_ID' => $this->ID(),
1560
+				'DTT_ID' => $DTT_ID,
1561
+				'CHK_in' => $new_status,
1562
+			)
1563
+		);
1564
+		// if the record could not be saved then return false
1565
+		if ($checkin->save() === 0) {
1566
+			if (WP_DEBUG) {
1567
+				global $wpdb;
1568
+				$error = sprintf(
1569
+					esc_html__(
1570
+						'Registration check in update failed because of the following database error: %1$s%2$s',
1571
+						'event_espresso'
1572
+					),
1573
+					'<br />',
1574
+					$wpdb->last_error
1575
+				);
1576
+			} else {
1577
+				$error = esc_html__(
1578
+					'Registration check in update failed because of an unknown database error',
1579
+					'event_espresso'
1580
+				);
1581
+			}
1582
+			EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
1583
+			return false;
1584
+		}
1585
+		// Fire a checked_in and checkout_out action.
1586
+		$checked_status = $status_to === EE_Checkin::status_checked_in ? 'checked_in' : 'checked_out';
1587
+		do_action("AHEE__EE_Registration__toggle_checkin_status__{$checked_status}", $this, $DTT_ID);
1588
+		return $status_to;
1589
+	}
1590
+
1591
+
1592
+	/**
1593
+	 * Returns the latest datetime related to this registration (via the ticket attached to the registration).
1594
+	 * "Latest" is defined by the `DTT_EVT_start` column.
1595
+	 *
1596
+	 * @return EE_Datetime|null
1597
+	 * @throws EE_Error
1598
+	 */
1599
+	public function get_latest_related_datetime()
1600
+	{
1601
+		return EEM_Datetime::instance()->get_one(
1602
+			array(
1603
+				array(
1604
+					'Ticket.Registration.REG_ID' => $this->ID(),
1605
+				),
1606
+				'order_by' => array('DTT_EVT_start' => 'DESC'),
1607
+			)
1608
+		);
1609
+	}
1610
+
1611
+
1612
+	/**
1613
+	 * Returns the earliest datetime related to this registration (via the ticket attached to the registration).
1614
+	 * "Earliest" is defined by the `DTT_EVT_start` column.
1615
+	 *
1616
+	 * @throws EE_Error
1617
+	 */
1618
+	public function get_earliest_related_datetime()
1619
+	{
1620
+		return EEM_Datetime::instance()->get_one(
1621
+			array(
1622
+				array(
1623
+					'Ticket.Registration.REG_ID' => $this->ID(),
1624
+				),
1625
+				'order_by' => array('DTT_EVT_start' => 'ASC'),
1626
+			)
1627
+		);
1628
+	}
1629
+
1630
+
1631
+	/**
1632
+	 * This method simply returns the check-in status for this registration and the given datetime.
1633
+	 * If neither the datetime nor the checkin values are provided as arguments,
1634
+	 * then this will return the LATEST check-in status for the registration across all datetimes it belongs to.
1635
+	 *
1636
+	 * @param  int       $DTT_ID  The ID of the datetime we're checking against
1637
+	 *                            (if empty we'll get the primary datetime for
1638
+	 *                            this registration (via event) and use it's ID);
1639
+	 * @param EE_Checkin $checkin If present, we use the given checkin object rather than the dtt_id.
1640
+	 *
1641
+	 * @return int                Integer representing Check-in status.
1642
+	 * @throws EE_Error
1643
+	 */
1644
+	public function check_in_status_for_datetime($DTT_ID = 0, $checkin = null)
1645
+	{
1646
+		$checkin_query_params = array(
1647
+			'order_by' => array('CHK_timestamp' => 'DESC'),
1648
+		);
1649
+
1650
+		if ($DTT_ID > 0) {
1651
+			$checkin_query_params[0] = array('DTT_ID' => $DTT_ID);
1652
+		}
1653
+
1654
+		// get checkin object (if exists)
1655
+		$checkin = $checkin instanceof EE_Checkin
1656
+			? $checkin
1657
+			: $this->get_first_related('Checkin', $checkin_query_params);
1658
+		if ($checkin instanceof EE_Checkin) {
1659
+			if ($checkin->get('CHK_in')) {
1660
+				return EE_Checkin::status_checked_in; // checked in
1661
+			}
1662
+			return EE_Checkin::status_checked_out; // had checked in but is now checked out.
1663
+		}
1664
+		return EE_Checkin::status_checked_never; // never been checked in
1665
+	}
1666
+
1667
+
1668
+	/**
1669
+	 * This method returns a localized message for the toggled Check-in message.
1670
+	 *
1671
+	 * @param  int $DTT_ID include specific datetime to get the correct Check-in message.  If not included or null,
1672
+	 *                     then it is assumed Check-in for primary datetime was toggled.
1673
+	 * @param bool $error  This just flags that you want an error message returned. This is put in so that the error
1674
+	 *                     message can be customized with the attendee name.
1675
+	 * @return string internationalized message
1676
+	 * @throws EE_Error
1677
+	 */
1678
+	public function get_checkin_msg($DTT_ID, $error = false)
1679
+	{
1680
+		// let's get the attendee first so we can include the name of the attendee
1681
+		$attendee = $this->get_first_related('Attendee');
1682
+		if ($attendee instanceof EE_Attendee) {
1683
+			if ($error) {
1684
+				return sprintf(__("%s's check-in status was not changed.", "event_espresso"), $attendee->full_name());
1685
+			}
1686
+			$cur_status = $this->check_in_status_for_datetime($DTT_ID);
1687
+			// what is the status message going to be?
1688
+			switch ($cur_status) {
1689
+				case EE_Checkin::status_checked_never:
1690
+					return sprintf(
1691
+						__("%s has been removed from Check-in records", "event_espresso"),
1692
+						$attendee->full_name()
1693
+					);
1694
+					break;
1695
+				case EE_Checkin::status_checked_in:
1696
+					return sprintf(__('%s has been checked in', 'event_espresso'), $attendee->full_name());
1697
+					break;
1698
+				case EE_Checkin::status_checked_out:
1699
+					return sprintf(__('%s has been checked out', 'event_espresso'), $attendee->full_name());
1700
+					break;
1701
+			}
1702
+		}
1703
+		return esc_html__("The check-in status could not be determined.", "event_espresso");
1704
+	}
1705
+
1706
+
1707
+	/**
1708
+	 * Returns the related EE_Transaction to this registration
1709
+	 *
1710
+	 * @return EE_Transaction
1711
+	 * @throws EE_Error
1712
+	 * @throws EntityNotFoundException
1713
+	 */
1714
+	public function transaction()
1715
+	{
1716
+		$transaction = $this->get_first_related('Transaction');
1717
+		if (! $transaction instanceof \EE_Transaction) {
1718
+			throw new EntityNotFoundException('Transaction ID', $this->transaction_ID());
1719
+		}
1720
+		return $transaction;
1721
+	}
1722
+
1723
+
1724
+	/**
1725
+	 *        get Registration Code
1726
+	 */
1727
+	public function reg_code()
1728
+	{
1729
+		return $this->get('REG_code');
1730
+	}
1731
+
1732
+
1733
+	/**
1734
+	 *        get Transaction ID
1735
+	 */
1736
+	public function transaction_ID()
1737
+	{
1738
+		return $this->get('TXN_ID');
1739
+	}
1740
+
1741
+
1742
+	/**
1743
+	 * @return int
1744
+	 * @throws EE_Error
1745
+	 */
1746
+	public function ticket_ID()
1747
+	{
1748
+		return $this->get('TKT_ID');
1749
+	}
1750
+
1751
+
1752
+	/**
1753
+	 *        Set Registration Code
1754
+	 *
1755
+	 * @access    public
1756
+	 * @param    string  $REG_code Registration Code
1757
+	 * @param    boolean $use_default
1758
+	 * @throws EE_Error
1759
+	 */
1760
+	public function set_reg_code($REG_code, $use_default = false)
1761
+	{
1762
+		if (empty($REG_code)) {
1763
+			EE_Error::add_error(
1764
+				esc_html__('REG_code can not be empty.', 'event_espresso'),
1765
+				__FILE__,
1766
+				__FUNCTION__,
1767
+				__LINE__
1768
+			);
1769
+			return;
1770
+		}
1771
+		if (! $this->reg_code()) {
1772
+			parent::set('REG_code', $REG_code, $use_default);
1773
+		} else {
1774
+			EE_Error::doing_it_wrong(
1775
+				__CLASS__ . '::' . __FUNCTION__,
1776
+				esc_html__('Can not change a registration REG_code once it has been set.', 'event_espresso'),
1777
+				'4.6.0'
1778
+			);
1779
+		}
1780
+	}
1781
+
1782
+
1783
+	/**
1784
+	 * Returns all other registrations in the same group as this registrant who have the same ticket option.
1785
+	 * Note, if you want to just get all registrations in the same transaction (group), use:
1786
+	 *    $registration->transaction()->registrations();
1787
+	 *
1788
+	 * @since 4.5.0
1789
+	 * @return EE_Registration[] or empty array if this isn't a group registration.
1790
+	 * @throws EE_Error
1791
+	 */
1792
+	public function get_all_other_registrations_in_group()
1793
+	{
1794
+		if ($this->group_size() < 2) {
1795
+			return array();
1796
+		}
1797
+
1798
+		$query[0] = array(
1799
+			'TXN_ID' => $this->transaction_ID(),
1800
+			'REG_ID' => array('!=', $this->ID()),
1801
+			'TKT_ID' => $this->ticket_ID(),
1802
+		);
1803
+		/** @var EE_Registration[] $registrations */
1804
+		$registrations = $this->get_model()->get_all($query);
1805
+		return $registrations;
1806
+	}
1807
+
1808
+	/**
1809
+	 * Return the link to the admin details for the object.
1810
+	 *
1811
+	 * @return string
1812
+	 * @throws EE_Error
1813
+	 */
1814
+	public function get_admin_details_link()
1815
+	{
1816
+		EE_Registry::instance()->load_helper('URL');
1817
+		return EEH_URL::add_query_args_and_nonce(
1818
+			array(
1819
+				'page'    => 'espresso_registrations',
1820
+				'action'  => 'view_registration',
1821
+				'_REG_ID' => $this->ID(),
1822
+			),
1823
+			admin_url('admin.php')
1824
+		);
1825
+	}
1826
+
1827
+	/**
1828
+	 * Returns the link to the editor for the object.  Sometimes this is the same as the details.
1829
+	 *
1830
+	 * @return string
1831
+	 * @throws EE_Error
1832
+	 */
1833
+	public function get_admin_edit_link()
1834
+	{
1835
+		return $this->get_admin_details_link();
1836
+	}
1837
+
1838
+	/**
1839
+	 * Returns the link to a settings page for the object.
1840
+	 *
1841
+	 * @return string
1842
+	 * @throws EE_Error
1843
+	 */
1844
+	public function get_admin_settings_link()
1845
+	{
1846
+		return $this->get_admin_details_link();
1847
+	}
1848
+
1849
+	/**
1850
+	 * Returns the link to the "overview" for the object (typically the "list table" view).
1851
+	 *
1852
+	 * @return string
1853
+	 */
1854
+	public function get_admin_overview_link()
1855
+	{
1856
+		EE_Registry::instance()->load_helper('URL');
1857
+		return EEH_URL::add_query_args_and_nonce(
1858
+			array(
1859
+				'page' => 'espresso_registrations',
1860
+			),
1861
+			admin_url('admin.php')
1862
+		);
1863
+	}
1864
+
1865
+
1866
+	/**
1867
+	 * @param array $query_params
1868
+	 *
1869
+	 * @return \EE_Registration[]
1870
+	 * @throws EE_Error
1871
+	 */
1872
+	public function payments($query_params = array())
1873
+	{
1874
+		return $this->get_many_related('Payment', $query_params);
1875
+	}
1876
+
1877
+
1878
+	/**
1879
+	 * @param array $query_params
1880
+	 *
1881
+	 * @return \EE_Registration_Payment[]
1882
+	 * @throws EE_Error
1883
+	 */
1884
+	public function registration_payments($query_params = array())
1885
+	{
1886
+		return $this->get_many_related('Registration_Payment', $query_params);
1887
+	}
1888
+
1889
+
1890
+	/**
1891
+	 * This grabs the payment method corresponding to the last payment made for the amount owing on the registration.
1892
+	 * Note: if there are no payments on the registration there will be no payment method returned.
1893
+	 *
1894
+	 * @return EE_Payment_Method|null
1895
+	 */
1896
+	public function payment_method()
1897
+	{
1898
+		return EEM_Payment_Method::instance()->get_last_used_for_registration($this);
1899
+	}
1900
+
1901
+
1902
+	/**
1903
+	 * @return \EE_Line_Item
1904
+	 * @throws EntityNotFoundException
1905
+	 * @throws EE_Error
1906
+	 */
1907
+	public function ticket_line_item()
1908
+	{
1909
+		$ticket = $this->ticket();
1910
+		$transaction = $this->transaction();
1911
+		$line_item = null;
1912
+		$ticket_line_items = \EEH_Line_Item::get_line_items_by_object_type_and_IDs(
1913
+			$transaction->total_line_item(),
1914
+			'Ticket',
1915
+			array($ticket->ID())
1916
+		);
1917
+		foreach ($ticket_line_items as $ticket_line_item) {
1918
+			if (
1919
+				$ticket_line_item instanceof \EE_Line_Item
1920
+				&& $ticket_line_item->OBJ_type() === 'Ticket'
1921
+				&& $ticket_line_item->OBJ_ID() === $ticket->ID()
1922
+			) {
1923
+				$line_item = $ticket_line_item;
1924
+				break;
1925
+			}
1926
+		}
1927
+		if (! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
1928
+			throw new EntityNotFoundException('Line Item Ticket ID', $ticket->ID());
1929
+		}
1930
+		return $line_item;
1931
+	}
1932
+
1933
+
1934
+	/**
1935
+	 * Soft Deletes this model object.
1936
+	 *
1937
+	 * @return boolean | int
1938
+	 * @throws RuntimeException
1939
+	 * @throws EE_Error
1940
+	 */
1941
+	public function delete()
1942
+	{
1943
+		if ($this->update_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY, $this->status_ID()) === true) {
1944
+			$this->set_status(EEM_Registration::status_id_cancelled);
1945
+		}
1946
+		return parent::delete();
1947
+	}
1948
+
1949
+
1950
+	/**
1951
+	 * Restores whatever the previous status was on a registration before it was trashed (if possible)
1952
+	 *
1953
+	 * @throws EE_Error
1954
+	 * @throws RuntimeException
1955
+	 */
1956
+	public function restore()
1957
+	{
1958
+		$previous_status = $this->get_extra_meta(
1959
+			EE_Registration::PRE_TRASH_REG_STATUS_KEY,
1960
+			true,
1961
+			EEM_Registration::status_id_cancelled
1962
+		);
1963
+		if ($previous_status) {
1964
+			$this->delete_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY);
1965
+			$this->set_status($previous_status);
1966
+		}
1967
+		return parent::restore();
1968
+	}
1969
+
1970
+
1971
+	/**
1972
+	 * possibly toggle Registration status based on comparison of REG_paid vs REG_final_price
1973
+	 *
1974
+	 * @param  boolean $trigger_set_status_logic EE_Registration::set_status() can trigger additional logic
1975
+	 *                                           depending on whether the reg status changes to or from "Approved"
1976
+	 * @return boolean whether the Registration status was updated
1977
+	 * @throws EE_Error
1978
+	 * @throws RuntimeException
1979
+	 */
1980
+	public function updateStatusBasedOnTotalPaid($trigger_set_status_logic = true)
1981
+	{
1982
+		$paid = $this->paid();
1983
+		$price = $this->final_price();
1984
+		switch (true) {
1985
+			// overpaid or paid
1986
+			case EEH_Money::compare_floats($paid, $price, '>'):
1987
+			case EEH_Money::compare_floats($paid, $price):
1988
+				$new_status = EEM_Registration::status_id_approved;
1989
+				break;
1990
+			//  underpaid
1991
+			case EEH_Money::compare_floats($paid, $price, '<'):
1992
+				$new_status = EEM_Registration::status_id_pending_payment;
1993
+				break;
1994
+			// uhhh Houston...
1995
+			default:
1996
+				throw new RuntimeException(
1997
+					esc_html__('The total paid calculation for this registration is inaccurate.', 'event_espresso')
1998
+				);
1999
+		}
2000
+		if ($new_status !== $this->status_ID()) {
2001
+			if ($trigger_set_status_logic) {
2002
+				return $this->set_status($new_status);
2003
+			}
2004
+			parent::set('STS_ID', $new_status);
2005
+			return true;
2006
+		}
2007
+		return false;
2008
+	}
2009
+
2010
+
2011
+	/*************************** DEPRECATED ***************************/
2012
+
2013
+
2014
+	/**
2015
+	 * @deprecated
2016
+	 * @since     4.7.0
2017
+	 * @access    public
2018
+	 */
2019
+	public function price_paid()
2020
+	{
2021
+		EE_Error::doing_it_wrong(
2022
+			'EE_Registration::price_paid()',
2023
+			esc_html__(
2024
+				'This method is deprecated, please use EE_Registration::final_price() instead.',
2025
+				'event_espresso'
2026
+			),
2027
+			'4.7.0'
2028
+		);
2029
+		return $this->final_price();
2030
+	}
2031
+
2032
+
2033
+	/**
2034
+	 * @deprecated
2035
+	 * @since     4.7.0
2036
+	 * @access    public
2037
+	 * @param    float $REG_final_price
2038
+	 * @throws EE_Error
2039
+	 * @throws RuntimeException
2040
+	 */
2041
+	public function set_price_paid($REG_final_price = 0.00)
2042
+	{
2043
+		EE_Error::doing_it_wrong(
2044
+			'EE_Registration::set_price_paid()',
2045
+			esc_html__(
2046
+				'This method is deprecated, please use EE_Registration::set_final_price() instead.',
2047
+				'event_espresso'
2048
+			),
2049
+			'4.7.0'
2050
+		);
2051
+		$this->set_final_price($REG_final_price);
2052
+	}
2053
+
2054
+
2055
+	/**
2056
+	 * @deprecated
2057
+	 * @since 4.7.0
2058
+	 * @return string
2059
+	 * @throws EE_Error
2060
+	 */
2061
+	public function pretty_price_paid()
2062
+	{
2063
+		EE_Error::doing_it_wrong(
2064
+			'EE_Registration::pretty_price_paid()',
2065
+			esc_html__(
2066
+				'This method is deprecated, please use EE_Registration::pretty_final_price() instead.',
2067
+				'event_espresso'
2068
+			),
2069
+			'4.7.0'
2070
+		);
2071
+		return $this->pretty_final_price();
2072
+	}
2073
+
2074
+
2075
+	/**
2076
+	 * Gets the primary datetime related to this registration via the related Event to this registration
2077
+	 *
2078
+	 * @deprecated 4.9.17
2079
+	 * @return EE_Datetime
2080
+	 * @throws EE_Error
2081
+	 * @throws EntityNotFoundException
2082
+	 */
2083
+	public function get_related_primary_datetime()
2084
+	{
2085
+		EE_Error::doing_it_wrong(
2086
+			__METHOD__,
2087
+			esc_html__(
2088
+				'Use EE_Registration::get_latest_related_datetime() or EE_Registration::get_earliest_related_datetime()',
2089
+				'event_espresso'
2090
+			),
2091
+			'4.9.17',
2092
+			'5.0.0'
2093
+		);
2094
+		return $this->event()->primary_datetime();
2095
+	}
2096 2096
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Venue.class.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -30,7 +30,7 @@
 block discarded – undo
30 30
      * @param array  $props_n_values  incoming values from the database
31 31
      * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
32 32
      *                                the website will be used.
33
-     * @return EE_Attendee
33
+     * @return EE_Venue
34 34
      */
35 35
     public static function new_instance_from_db($props_n_values = array(), $timezone = '')
36 36
     {
Please login to merge, or discard this patch.
Indentation   +560 added lines, -560 removed lines patch added patch discarded remove patch
@@ -10,564 +10,564 @@
 block discarded – undo
10 10
 class EE_Venue extends EE_CPT_Base implements EEI_Address
11 11
 {
12 12
 
13
-    /**
14
-     *
15
-     * @param array  $props_n_values          incoming values
16
-     * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
17
-     *                                        used.)
18
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
19
-     *                                        date_format and the second value is the time format
20
-     * @return EE_Attendee
21
-     */
22
-    public static function new_instance($props_n_values = array(), $timezone = '', $date_formats = array())
23
-    {
24
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
25
-        return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
26
-    }
27
-
28
-
29
-    /**
30
-     * @param array  $props_n_values  incoming values from the database
31
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
32
-     *                                the website will be used.
33
-     * @return EE_Attendee
34
-     */
35
-    public static function new_instance_from_db($props_n_values = array(), $timezone = '')
36
-    {
37
-        return new self($props_n_values, true, $timezone);
38
-    }
39
-
40
-
41
-    /**
42
-     * Gets name
43
-     *
44
-     * @return string
45
-     */
46
-    public function name()
47
-    {
48
-        return $this->get('VNU_name');
49
-    }
50
-
51
-
52
-    /**
53
-     * Gets phone
54
-     *
55
-     * @return string
56
-     */
57
-    public function phone()
58
-    {
59
-        return $this->get('VNU_phone');
60
-    }
61
-
62
-
63
-    /**
64
-     * venue_url
65
-     *
66
-     * @return string
67
-     */
68
-    public function venue_url()
69
-    {
70
-        return $this->get('VNU_url');
71
-    }
72
-
73
-
74
-    /**
75
-     * Gets desc
76
-     *
77
-     * @return string
78
-     */
79
-    public function description()
80
-    {
81
-        return $this->get('VNU_desc');
82
-    }
83
-
84
-
85
-    /**
86
-     * Gets short description (AKA: the excerpt)
87
-     *
88
-     * @return string
89
-     */
90
-    public function excerpt()
91
-    {
92
-        return $this->get('VNU_short_desc');
93
-    }
94
-
95
-
96
-    /**
97
-     * Gets identifier
98
-     *
99
-     * @return string
100
-     */
101
-    public function identifier()
102
-    {
103
-        return $this->get('VNU_identifier');
104
-    }
105
-
106
-
107
-    /**
108
-     * Gets address
109
-     *
110
-     * @return string
111
-     */
112
-    public function address()
113
-    {
114
-        return $this->get('VNU_address');
115
-    }
116
-
117
-
118
-    /**
119
-     * Gets address2
120
-     *
121
-     * @return string
122
-     */
123
-    public function address2()
124
-    {
125
-        return $this->get('VNU_address2');
126
-    }
127
-
128
-
129
-    /**
130
-     * Gets city
131
-     *
132
-     * @return string
133
-     */
134
-    public function city()
135
-    {
136
-        return $this->get('VNU_city');
137
-    }
138
-
139
-    /**
140
-     * Gets state
141
-     *
142
-     * @return int
143
-     */
144
-    public function state_ID()
145
-    {
146
-        return $this->get('STA_ID');
147
-    }
148
-
149
-
150
-    /**
151
-     * @return string
152
-     */
153
-    public function state_abbrev()
154
-    {
155
-        return $this->state_obj() instanceof EE_State ? $this->state_obj()->abbrev() : '';
156
-    }
157
-
158
-
159
-    /**
160
-     * @return string
161
-     */
162
-    public function state_name()
163
-    {
164
-        return $this->state_obj() instanceof EE_State ? $this->state_obj()->name() : '';
165
-    }
166
-
167
-
168
-    /**
169
-     * Gets the state for this venue
170
-     *
171
-     * @return EE_State
172
-     */
173
-    public function state_obj()
174
-    {
175
-        return $this->get_first_related('State');
176
-    }
177
-
178
-
179
-    /**
180
-     * either displays the state abbreviation or the state name, as determined
181
-     * by the "FHEE__EEI_Address__state__use_abbreviation" filter.
182
-     * defaults to abbreviation
183
-     *
184
-     * @return string
185
-     */
186
-    public function state()
187
-    {
188
-        if (apply_filters('FHEE__EEI_Address__state__use_abbreviation', true, $this->state_obj())) {
189
-            return $this->state_abbrev();
190
-        } else {
191
-            return $this->state_name();
192
-        }
193
-    }
194
-
195
-
196
-    /**
197
-     * country_ID
198
-     *
199
-     * @return string
200
-     */
201
-    public function country_ID()
202
-    {
203
-        return $this->get('CNT_ISO');
204
-    }
205
-
206
-
207
-    /**
208
-     * @return string
209
-     */
210
-    public function country_name()
211
-    {
212
-        return $this->country_obj() instanceof EE_Country ? $this->country_obj()->name() : '';
213
-    }
214
-
215
-
216
-    /**
217
-     * Gets the country of this venue
218
-     *
219
-     * @return EE_Country
220
-     */
221
-    public function country_obj()
222
-    {
223
-        return $this->get_first_related('Country');
224
-    }
225
-
226
-
227
-    /**
228
-     * either displays the country ISO2 code or the country name, as determined
229
-     * by the "FHEE__EEI_Address__country__use_abbreviation" filter.
230
-     * defaults to abbreviation
231
-     *
232
-     * @return string
233
-     */
234
-    public function country()
235
-    {
236
-        if (apply_filters('FHEE__EEI_Address__country__use_abbreviation', true, $this->country_obj())) {
237
-            return $this->country_ID();
238
-        } else {
239
-            return $this->country_name();
240
-        }
241
-    }
242
-
243
-
244
-    /**
245
-     * Gets zip
246
-     *
247
-     * @return string
248
-     */
249
-    public function zip()
250
-    {
251
-        return $this->get('VNU_zip');
252
-    }
253
-
254
-
255
-    /**
256
-     * Gets capacity
257
-     *
258
-     * @return int
259
-     */
260
-    public function capacity()
261
-    {
262
-        return $this->get_pretty('VNU_capacity', 'symbol');
263
-    }
264
-
265
-
266
-    /**
267
-     * Gets created
268
-     *
269
-     * @return string
270
-     */
271
-    public function created()
272
-    {
273
-        return $this->get('VNU_created');
274
-    }
275
-
276
-
277
-    /**
278
-     * Gets modified
279
-     *
280
-     * @return string
281
-     */
282
-    public function modified()
283
-    {
284
-        return $this->get('VNU_modified');
285
-    }
286
-
287
-
288
-    /**
289
-     * Gets order
290
-     *
291
-     * @return int
292
-     */
293
-    public function order()
294
-    {
295
-        return $this->get('VNU_order');
296
-    }
297
-
298
-
299
-    /**
300
-     * Gets wp_user
301
-     *
302
-     * @return int
303
-     */
304
-    public function wp_user()
305
-    {
306
-        return $this->get('VNU_wp_user');
307
-    }
308
-
309
-
310
-    /**
311
-     * @return string
312
-     */
313
-    public function virtual_phone()
314
-    {
315
-        return $this->get('VNU_virtual_phone');
316
-    }
317
-
318
-
319
-    /**
320
-     * @return string
321
-     */
322
-    public function virtual_url()
323
-    {
324
-        return $this->get('VNU_virtual_url');
325
-    }
326
-
327
-
328
-    /**
329
-     * @return bool
330
-     */
331
-    public function enable_for_gmap()
332
-    {
333
-        return $this->get('VNU_enable_for_gmap');
334
-    }
335
-
336
-
337
-    /**
338
-     * @return string
339
-     */
340
-    public function google_map_link()
341
-    {
342
-        return $this->get('VNU_google_map_link');
343
-    }
344
-
345
-
346
-    /**
347
-     * Gets all events happening at this venue. Query parameters can be added to
348
-     * fetch a subset of those events.
349
-     *
350
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
351
-     * @param bool  $upcoming
352
-     * @return EE_Event[]
353
-     */
354
-    public function events($query_params = array(), $upcoming = false)
355
-    {
356
-        if ($upcoming) {
357
-            $query_params = array(
358
-                array(
359
-                    'status'                 => 'publish',
360
-                    'Datetime.DTT_EVT_start' => array(
361
-                        '>',
362
-                        EEM_Datetime::instance()->current_time_for_query('DTT_EVT_start'),
363
-                    ),
364
-                ),
365
-            );
366
-        }
367
-        return $this->get_many_related('Event', $query_params);
368
-    }
369
-
370
-
371
-    /**
372
-     * Sets address
373
-     */
374
-    public function set_address($address = '')
375
-    {
376
-        $this->set('VNU_address', $address);
377
-    }
378
-
379
-
380
-    /**
381
-     * @param string $address2
382
-     */
383
-    public function set_address2($address2 = '')
384
-    {
385
-        $this->set('VNU_address2', $address2);
386
-    }
387
-
388
-
389
-    /**
390
-     * @param string $city
391
-     */
392
-    public function set_city($city = '')
393
-    {
394
-        $this->set('VNU_city', $city);
395
-    }
396
-
397
-
398
-    /**
399
-     * @param int $state
400
-     */
401
-    public function set_state_ID($state = 0)
402
-    {
403
-        $this->set('STA_ID', $state);
404
-    }
405
-
406
-
407
-    /**
408
-     * Sets the state, given either a state id or state object
409
-     *
410
-     * @param EE_State /int $state_id_or_obj
411
-     * @return EE_State
412
-     */
413
-    public function set_state_obj($state_id_or_obj)
414
-    {
415
-        return $this->_add_relation_to($state_id_or_obj, 'State');
416
-    }
417
-
418
-
419
-    /**
420
-     * @param int $country_ID
421
-     */
422
-    public function set_country_ID($country_ID = 0)
423
-    {
424
-        $this->set('CNT_ISO', $country_ID);
425
-    }
426
-
427
-
428
-    /**
429
-     * Sets the country on the venue
430
-     *
431
-     * @param EE_Country /string $country_id_or_obj
432
-     * @return EE_Country
433
-     */
434
-    public function set_country_obj($country_id_or_obj)
435
-    {
436
-        return $this->_add_relation_to($country_id_or_obj, 'Country');
437
-    }
438
-
439
-
440
-    /**
441
-     * @param string $zip
442
-     */
443
-    public function set_zip($zip = '')
444
-    {
445
-        $this->set('VNU_zip', $zip);
446
-    }
447
-
448
-
449
-    /**
450
-     * @param int $capacity
451
-     */
452
-    public function set_capacity($capacity = 0)
453
-    {
454
-        $this->set('VNU_capacity', $capacity);
455
-    }
456
-
457
-
458
-    /**
459
-     * @param string $created
460
-     */
461
-    public function set_created($created = '')
462
-    {
463
-        $this->set('VNU_created', $created);
464
-    }
465
-
466
-
467
-    /**
468
-     * @param string $desc
469
-     */
470
-    public function set_description($desc = '')
471
-    {
472
-        $this->set('VNU_desc', $desc);
473
-    }
474
-
475
-
476
-    /**
477
-     * @param string $identifier
478
-     */
479
-    public function set_identifier($identifier = '')
480
-    {
481
-        $this->set('VNU_identifier', $identifier);
482
-    }
483
-
484
-
485
-    /**
486
-     * @param string $modified
487
-     */
488
-    public function set_modified($modified = '')
489
-    {
490
-        $this->set('VNU_modified', $modified);
491
-    }
492
-
493
-
494
-    /**
495
-     * @param string $name
496
-     */
497
-    public function set_name($name = '')
498
-    {
499
-        $this->set('VNU_name', $name);
500
-    }
501
-
502
-
503
-    /**
504
-     * @param int $order
505
-     */
506
-    public function set_order($order = 0)
507
-    {
508
-        $this->set('VNU_order', $order);
509
-    }
510
-
511
-
512
-    /**
513
-     * @param string $phone
514
-     */
515
-    public function set_phone($phone = '')
516
-    {
517
-        $this->set('VNU_phone', $phone);
518
-    }
519
-
520
-
521
-    /**
522
-     * @param int $wp_user
523
-     */
524
-    public function set_wp_user($wp_user = 1)
525
-    {
526
-        $this->set('VNU_wp_user', $wp_user);
527
-    }
528
-
529
-
530
-    /**
531
-     * @param string $url
532
-     */
533
-    public function set_venue_url($url = '')
534
-    {
535
-        $this->set('VNU_url', $url);
536
-    }
537
-
538
-
539
-    /**
540
-     * @param string $phone
541
-     */
542
-    public function set_virtual_phone($phone = '')
543
-    {
544
-        $this->set('VNU_virtual_phone', $phone);
545
-    }
546
-
547
-
548
-    /**
549
-     * @param string $url
550
-     */
551
-    public function set_virtual_url($url = '')
552
-    {
553
-        $this->set('VNU_virtual_url', $url);
554
-    }
555
-
556
-
557
-    /**
558
-     * @param string $enable
559
-     */
560
-    public function set_enable_for_gmap($enable = '')
561
-    {
562
-        $this->set('VNU_enable_for_gmap', $enable);
563
-    }
564
-
565
-
566
-    /**
567
-     * @param string $google_map_link
568
-     */
569
-    public function set_google_map_link($google_map_link = '')
570
-    {
571
-        $this->set('VNU_google_map_link', $google_map_link);
572
-    }
13
+	/**
14
+	 *
15
+	 * @param array  $props_n_values          incoming values
16
+	 * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
17
+	 *                                        used.)
18
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
19
+	 *                                        date_format and the second value is the time format
20
+	 * @return EE_Attendee
21
+	 */
22
+	public static function new_instance($props_n_values = array(), $timezone = '', $date_formats = array())
23
+	{
24
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
25
+		return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
26
+	}
27
+
28
+
29
+	/**
30
+	 * @param array  $props_n_values  incoming values from the database
31
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
32
+	 *                                the website will be used.
33
+	 * @return EE_Attendee
34
+	 */
35
+	public static function new_instance_from_db($props_n_values = array(), $timezone = '')
36
+	{
37
+		return new self($props_n_values, true, $timezone);
38
+	}
39
+
40
+
41
+	/**
42
+	 * Gets name
43
+	 *
44
+	 * @return string
45
+	 */
46
+	public function name()
47
+	{
48
+		return $this->get('VNU_name');
49
+	}
50
+
51
+
52
+	/**
53
+	 * Gets phone
54
+	 *
55
+	 * @return string
56
+	 */
57
+	public function phone()
58
+	{
59
+		return $this->get('VNU_phone');
60
+	}
61
+
62
+
63
+	/**
64
+	 * venue_url
65
+	 *
66
+	 * @return string
67
+	 */
68
+	public function venue_url()
69
+	{
70
+		return $this->get('VNU_url');
71
+	}
72
+
73
+
74
+	/**
75
+	 * Gets desc
76
+	 *
77
+	 * @return string
78
+	 */
79
+	public function description()
80
+	{
81
+		return $this->get('VNU_desc');
82
+	}
83
+
84
+
85
+	/**
86
+	 * Gets short description (AKA: the excerpt)
87
+	 *
88
+	 * @return string
89
+	 */
90
+	public function excerpt()
91
+	{
92
+		return $this->get('VNU_short_desc');
93
+	}
94
+
95
+
96
+	/**
97
+	 * Gets identifier
98
+	 *
99
+	 * @return string
100
+	 */
101
+	public function identifier()
102
+	{
103
+		return $this->get('VNU_identifier');
104
+	}
105
+
106
+
107
+	/**
108
+	 * Gets address
109
+	 *
110
+	 * @return string
111
+	 */
112
+	public function address()
113
+	{
114
+		return $this->get('VNU_address');
115
+	}
116
+
117
+
118
+	/**
119
+	 * Gets address2
120
+	 *
121
+	 * @return string
122
+	 */
123
+	public function address2()
124
+	{
125
+		return $this->get('VNU_address2');
126
+	}
127
+
128
+
129
+	/**
130
+	 * Gets city
131
+	 *
132
+	 * @return string
133
+	 */
134
+	public function city()
135
+	{
136
+		return $this->get('VNU_city');
137
+	}
138
+
139
+	/**
140
+	 * Gets state
141
+	 *
142
+	 * @return int
143
+	 */
144
+	public function state_ID()
145
+	{
146
+		return $this->get('STA_ID');
147
+	}
148
+
149
+
150
+	/**
151
+	 * @return string
152
+	 */
153
+	public function state_abbrev()
154
+	{
155
+		return $this->state_obj() instanceof EE_State ? $this->state_obj()->abbrev() : '';
156
+	}
157
+
158
+
159
+	/**
160
+	 * @return string
161
+	 */
162
+	public function state_name()
163
+	{
164
+		return $this->state_obj() instanceof EE_State ? $this->state_obj()->name() : '';
165
+	}
166
+
167
+
168
+	/**
169
+	 * Gets the state for this venue
170
+	 *
171
+	 * @return EE_State
172
+	 */
173
+	public function state_obj()
174
+	{
175
+		return $this->get_first_related('State');
176
+	}
177
+
178
+
179
+	/**
180
+	 * either displays the state abbreviation or the state name, as determined
181
+	 * by the "FHEE__EEI_Address__state__use_abbreviation" filter.
182
+	 * defaults to abbreviation
183
+	 *
184
+	 * @return string
185
+	 */
186
+	public function state()
187
+	{
188
+		if (apply_filters('FHEE__EEI_Address__state__use_abbreviation', true, $this->state_obj())) {
189
+			return $this->state_abbrev();
190
+		} else {
191
+			return $this->state_name();
192
+		}
193
+	}
194
+
195
+
196
+	/**
197
+	 * country_ID
198
+	 *
199
+	 * @return string
200
+	 */
201
+	public function country_ID()
202
+	{
203
+		return $this->get('CNT_ISO');
204
+	}
205
+
206
+
207
+	/**
208
+	 * @return string
209
+	 */
210
+	public function country_name()
211
+	{
212
+		return $this->country_obj() instanceof EE_Country ? $this->country_obj()->name() : '';
213
+	}
214
+
215
+
216
+	/**
217
+	 * Gets the country of this venue
218
+	 *
219
+	 * @return EE_Country
220
+	 */
221
+	public function country_obj()
222
+	{
223
+		return $this->get_first_related('Country');
224
+	}
225
+
226
+
227
+	/**
228
+	 * either displays the country ISO2 code or the country name, as determined
229
+	 * by the "FHEE__EEI_Address__country__use_abbreviation" filter.
230
+	 * defaults to abbreviation
231
+	 *
232
+	 * @return string
233
+	 */
234
+	public function country()
235
+	{
236
+		if (apply_filters('FHEE__EEI_Address__country__use_abbreviation', true, $this->country_obj())) {
237
+			return $this->country_ID();
238
+		} else {
239
+			return $this->country_name();
240
+		}
241
+	}
242
+
243
+
244
+	/**
245
+	 * Gets zip
246
+	 *
247
+	 * @return string
248
+	 */
249
+	public function zip()
250
+	{
251
+		return $this->get('VNU_zip');
252
+	}
253
+
254
+
255
+	/**
256
+	 * Gets capacity
257
+	 *
258
+	 * @return int
259
+	 */
260
+	public function capacity()
261
+	{
262
+		return $this->get_pretty('VNU_capacity', 'symbol');
263
+	}
264
+
265
+
266
+	/**
267
+	 * Gets created
268
+	 *
269
+	 * @return string
270
+	 */
271
+	public function created()
272
+	{
273
+		return $this->get('VNU_created');
274
+	}
275
+
276
+
277
+	/**
278
+	 * Gets modified
279
+	 *
280
+	 * @return string
281
+	 */
282
+	public function modified()
283
+	{
284
+		return $this->get('VNU_modified');
285
+	}
286
+
287
+
288
+	/**
289
+	 * Gets order
290
+	 *
291
+	 * @return int
292
+	 */
293
+	public function order()
294
+	{
295
+		return $this->get('VNU_order');
296
+	}
297
+
298
+
299
+	/**
300
+	 * Gets wp_user
301
+	 *
302
+	 * @return int
303
+	 */
304
+	public function wp_user()
305
+	{
306
+		return $this->get('VNU_wp_user');
307
+	}
308
+
309
+
310
+	/**
311
+	 * @return string
312
+	 */
313
+	public function virtual_phone()
314
+	{
315
+		return $this->get('VNU_virtual_phone');
316
+	}
317
+
318
+
319
+	/**
320
+	 * @return string
321
+	 */
322
+	public function virtual_url()
323
+	{
324
+		return $this->get('VNU_virtual_url');
325
+	}
326
+
327
+
328
+	/**
329
+	 * @return bool
330
+	 */
331
+	public function enable_for_gmap()
332
+	{
333
+		return $this->get('VNU_enable_for_gmap');
334
+	}
335
+
336
+
337
+	/**
338
+	 * @return string
339
+	 */
340
+	public function google_map_link()
341
+	{
342
+		return $this->get('VNU_google_map_link');
343
+	}
344
+
345
+
346
+	/**
347
+	 * Gets all events happening at this venue. Query parameters can be added to
348
+	 * fetch a subset of those events.
349
+	 *
350
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
351
+	 * @param bool  $upcoming
352
+	 * @return EE_Event[]
353
+	 */
354
+	public function events($query_params = array(), $upcoming = false)
355
+	{
356
+		if ($upcoming) {
357
+			$query_params = array(
358
+				array(
359
+					'status'                 => 'publish',
360
+					'Datetime.DTT_EVT_start' => array(
361
+						'>',
362
+						EEM_Datetime::instance()->current_time_for_query('DTT_EVT_start'),
363
+					),
364
+				),
365
+			);
366
+		}
367
+		return $this->get_many_related('Event', $query_params);
368
+	}
369
+
370
+
371
+	/**
372
+	 * Sets address
373
+	 */
374
+	public function set_address($address = '')
375
+	{
376
+		$this->set('VNU_address', $address);
377
+	}
378
+
379
+
380
+	/**
381
+	 * @param string $address2
382
+	 */
383
+	public function set_address2($address2 = '')
384
+	{
385
+		$this->set('VNU_address2', $address2);
386
+	}
387
+
388
+
389
+	/**
390
+	 * @param string $city
391
+	 */
392
+	public function set_city($city = '')
393
+	{
394
+		$this->set('VNU_city', $city);
395
+	}
396
+
397
+
398
+	/**
399
+	 * @param int $state
400
+	 */
401
+	public function set_state_ID($state = 0)
402
+	{
403
+		$this->set('STA_ID', $state);
404
+	}
405
+
406
+
407
+	/**
408
+	 * Sets the state, given either a state id or state object
409
+	 *
410
+	 * @param EE_State /int $state_id_or_obj
411
+	 * @return EE_State
412
+	 */
413
+	public function set_state_obj($state_id_or_obj)
414
+	{
415
+		return $this->_add_relation_to($state_id_or_obj, 'State');
416
+	}
417
+
418
+
419
+	/**
420
+	 * @param int $country_ID
421
+	 */
422
+	public function set_country_ID($country_ID = 0)
423
+	{
424
+		$this->set('CNT_ISO', $country_ID);
425
+	}
426
+
427
+
428
+	/**
429
+	 * Sets the country on the venue
430
+	 *
431
+	 * @param EE_Country /string $country_id_or_obj
432
+	 * @return EE_Country
433
+	 */
434
+	public function set_country_obj($country_id_or_obj)
435
+	{
436
+		return $this->_add_relation_to($country_id_or_obj, 'Country');
437
+	}
438
+
439
+
440
+	/**
441
+	 * @param string $zip
442
+	 */
443
+	public function set_zip($zip = '')
444
+	{
445
+		$this->set('VNU_zip', $zip);
446
+	}
447
+
448
+
449
+	/**
450
+	 * @param int $capacity
451
+	 */
452
+	public function set_capacity($capacity = 0)
453
+	{
454
+		$this->set('VNU_capacity', $capacity);
455
+	}
456
+
457
+
458
+	/**
459
+	 * @param string $created
460
+	 */
461
+	public function set_created($created = '')
462
+	{
463
+		$this->set('VNU_created', $created);
464
+	}
465
+
466
+
467
+	/**
468
+	 * @param string $desc
469
+	 */
470
+	public function set_description($desc = '')
471
+	{
472
+		$this->set('VNU_desc', $desc);
473
+	}
474
+
475
+
476
+	/**
477
+	 * @param string $identifier
478
+	 */
479
+	public function set_identifier($identifier = '')
480
+	{
481
+		$this->set('VNU_identifier', $identifier);
482
+	}
483
+
484
+
485
+	/**
486
+	 * @param string $modified
487
+	 */
488
+	public function set_modified($modified = '')
489
+	{
490
+		$this->set('VNU_modified', $modified);
491
+	}
492
+
493
+
494
+	/**
495
+	 * @param string $name
496
+	 */
497
+	public function set_name($name = '')
498
+	{
499
+		$this->set('VNU_name', $name);
500
+	}
501
+
502
+
503
+	/**
504
+	 * @param int $order
505
+	 */
506
+	public function set_order($order = 0)
507
+	{
508
+		$this->set('VNU_order', $order);
509
+	}
510
+
511
+
512
+	/**
513
+	 * @param string $phone
514
+	 */
515
+	public function set_phone($phone = '')
516
+	{
517
+		$this->set('VNU_phone', $phone);
518
+	}
519
+
520
+
521
+	/**
522
+	 * @param int $wp_user
523
+	 */
524
+	public function set_wp_user($wp_user = 1)
525
+	{
526
+		$this->set('VNU_wp_user', $wp_user);
527
+	}
528
+
529
+
530
+	/**
531
+	 * @param string $url
532
+	 */
533
+	public function set_venue_url($url = '')
534
+	{
535
+		$this->set('VNU_url', $url);
536
+	}
537
+
538
+
539
+	/**
540
+	 * @param string $phone
541
+	 */
542
+	public function set_virtual_phone($phone = '')
543
+	{
544
+		$this->set('VNU_virtual_phone', $phone);
545
+	}
546
+
547
+
548
+	/**
549
+	 * @param string $url
550
+	 */
551
+	public function set_virtual_url($url = '')
552
+	{
553
+		$this->set('VNU_virtual_url', $url);
554
+	}
555
+
556
+
557
+	/**
558
+	 * @param string $enable
559
+	 */
560
+	public function set_enable_for_gmap($enable = '')
561
+	{
562
+		$this->set('VNU_enable_for_gmap', $enable);
563
+	}
564
+
565
+
566
+	/**
567
+	 * @param string $google_map_link
568
+	 */
569
+	public function set_google_map_link($google_map_link = '')
570
+	{
571
+		$this->set('VNU_google_map_link', $google_map_link);
572
+	}
573 573
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Attendee.model.php 2 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -130,7 +130,7 @@  discard block
 block discarded – undo
130 130
     /**
131 131
      * EEM_Attendee constructor.
132 132
      *
133
-     * @param null              $timezone
133
+     * @param string|null              $timezone
134 134
      * @param ModelFieldFactory $model_field_factory
135 135
      * @throws EE_Error
136 136
      * @throws InvalidArgumentException
@@ -351,7 +351,7 @@  discard block
 block discarded – undo
351 351
      * retrieve  a single attendee from db via their ID
352 352
      *
353 353
      * @param $ATT_ID
354
-     * @return mixed array on success, FALSE on fail
354
+     * @return EE_Base_Class|null array on success, FALSE on fail
355 355
      * @deprecated
356 356
      */
357 357
     public function get_attendee_by_ID($ATT_ID = false)
Please login to merge, or discard this patch.
Indentation   +419 added lines, -419 removed lines patch added patch discarded remove patch
@@ -13,432 +13,432 @@
 block discarded – undo
13 13
 class EEM_Attendee extends EEM_CPT_Base
14 14
 {
15 15
 
16
-    // private instance of the Attendee object
17
-    protected static $_instance = null;
16
+	// private instance of the Attendee object
17
+	protected static $_instance = null;
18 18
 
19
-    /**
20
-     * QST_system for questions are strings not integers now,
21
-     * so these constants are deprecated.
22
-     * Please instead use the EEM_Attendee::system_question_* constants
23
-     *
24
-     * @deprecated
25
-     */
26
-    const fname_question_id = 1;
19
+	/**
20
+	 * QST_system for questions are strings not integers now,
21
+	 * so these constants are deprecated.
22
+	 * Please instead use the EEM_Attendee::system_question_* constants
23
+	 *
24
+	 * @deprecated
25
+	 */
26
+	const fname_question_id = 1;
27 27
 
28
-    /**
29
-     * @deprecated
30
-     */
31
-    const lname_question_id = 2;
28
+	/**
29
+	 * @deprecated
30
+	 */
31
+	const lname_question_id = 2;
32 32
 
33 33
 
34
-    /**
35
-     * @deprecated
36
-     */
37
-    const email_question_id = 3;
34
+	/**
35
+	 * @deprecated
36
+	 */
37
+	const email_question_id = 3;
38 38
 
39 39
 
40
-    /**
41
-     * @deprecated
42
-     */
43
-    const address_question_id = 4;
40
+	/**
41
+	 * @deprecated
42
+	 */
43
+	const address_question_id = 4;
44 44
 
45 45
 
46
-    /**
47
-     * @deprecated
48
-     */
49
-    const address2_question_id = 5;
46
+	/**
47
+	 * @deprecated
48
+	 */
49
+	const address2_question_id = 5;
50 50
 
51
-
52
-    /**
53
-     * @deprecated
54
-     */
55
-    const city_question_id = 6;
56
-
57
-
58
-    /**
59
-     * @deprecated
60
-     */
61
-    const state_question_id = 7;
62
-
63
-
64
-    /**
65
-     * @deprecated
66
-     */
67
-    const country_question_id = 8;
68
-
69
-
70
-    /**
71
-     * @deprecated
72
-     */
73
-    const zip_question_id = 9;
74
-
75
-
76
-    /**
77
-     * @deprecated
78
-     */
79
-    const phone_question_id = 10;
80
-
81
-    /**
82
-     * When looking for questions that correspond to attendee fields,
83
-     * look for the question with this QST_system value.
84
-     * These replace the old constants like EEM_Attendee::*_question_id
85
-     */
86
-    const system_question_fname = 'fname';
87
-
88
-    const system_question_lname = 'lname';
89
-
90
-    const system_question_email = 'email';
91
-
92
-    const system_question_email_confirm = 'email_confirm';
93
-
94
-    const system_question_address = 'address';
95
-
96
-    const system_question_address2 = 'address2';
97
-
98
-    const system_question_city = 'city';
99
-
100
-    const system_question_state = 'state';
101
-
102
-    const system_question_country = 'country';
103
-
104
-    const system_question_zip = 'zip';
105
-
106
-    const system_question_phone = 'phone';
107
-
108
-    /**
109
-     * Keys are all the EEM_Attendee::system_question_* constants, which are
110
-     * also all the values of QST_system in the questions table, and values
111
-     * are their corresponding Attendee field names
112
-     *
113
-     * @var array
114
-     */
115
-    protected $_system_question_to_attendee_field_name = array(
116
-        EEM_Attendee::system_question_fname    => 'ATT_fname',
117
-        EEM_Attendee::system_question_lname    => 'ATT_lname',
118
-        EEM_Attendee::system_question_email    => 'ATT_email',
119
-        EEM_Attendee::system_question_address  => 'ATT_address',
120
-        EEM_Attendee::system_question_address2 => 'ATT_address2',
121
-        EEM_Attendee::system_question_city     => 'ATT_city',
122
-        EEM_Attendee::system_question_state    => 'STA_ID',
123
-        EEM_Attendee::system_question_country  => 'CNT_ISO',
124
-        EEM_Attendee::system_question_zip      => 'ATT_zip',
125
-        EEM_Attendee::system_question_phone    => 'ATT_phone',
126
-    );
127
-
128
-
129
-
130
-    /**
131
-     * EEM_Attendee constructor.
132
-     *
133
-     * @param null              $timezone
134
-     * @param ModelFieldFactory $model_field_factory
135
-     * @throws EE_Error
136
-     * @throws InvalidArgumentException
137
-     */
138
-    protected function __construct($timezone = '', ModelFieldFactory $model_field_factory)
139
-    {
140
-        $this->singular_item = esc_html__('Attendee', 'event_espresso');
141
-        $this->plural_item = esc_html__('Attendees', 'event_espresso');
142
-        $this->_tables = array(
143
-            'Attendee_CPT'  => new EE_Primary_Table('posts', 'ID'),
144
-            'Attendee_Meta' => new EE_Secondary_Table(
145
-                'esp_attendee_meta',
146
-                'ATTM_ID',
147
-                'ATT_ID'
148
-            ),
149
-        );
150
-        $this->_fields = array(
151
-            'Attendee_CPT'  => array(
152
-                'ATT_ID'        => $model_field_factory->createPrimaryKeyIntField(
153
-                    'ID',
154
-                    esc_html__('Attendee ID', 'event_espresso')
155
-                ),
156
-                'ATT_full_name' => $model_field_factory->createPlainTextField(
157
-                    'post_title',
158
-                    esc_html__('Attendee Full Name', 'event_espresso'),
159
-                    false,
160
-                    esc_html__('Unknown', 'event_espresso')
161
-                ),
162
-                'ATT_bio'       => $model_field_factory->createPostContentField(
163
-                    'post_content',
164
-                    esc_html__('Attendee Biography', 'event_espresso'),
165
-                    false,
166
-                    esc_html__('No Biography Provided', 'event_espresso')
167
-                ),
168
-                'ATT_slug'      => $model_field_factory->createSlugField(
169
-                    'post_name',
170
-                    esc_html__('Attendee URL Slug', 'event_espresso')
171
-                ),
172
-                'ATT_created'   => $model_field_factory->createDatetimeField(
173
-                    'post_date',
174
-                    esc_html__('Time Attendee Created', 'event_espresso')
175
-                ),
176
-                'ATT_short_bio' => $model_field_factory->createSimpleHtmlField(
177
-                    'post_excerpt',
178
-                    esc_html__('Attendee Short Biography', 'event_espresso'),
179
-                    true,
180
-                    esc_html__('No Biography Provided', 'event_espresso')
181
-                ),
182
-                'ATT_modified'  => $model_field_factory->createDatetimeField(
183
-                    'post_modified',
184
-                    esc_html__('Time Attendee Last Modified', 'event_espresso')
185
-                ),
186
-                'ATT_author'    => $model_field_factory->createWpUserField(
187
-                    'post_author',
188
-                    esc_html__('Creator ID of the first Event attended', 'event_espresso'),
189
-                    false
190
-                ),
191
-                'ATT_parent'    => $model_field_factory->createDbOnlyIntField(
192
-                    'post_parent',
193
-                    esc_html__('Parent Attendee (unused)', 'event_espresso'),
194
-                    false,
195
-                    0
196
-                ),
197
-                'post_type'     => $model_field_factory->createWpPostTypeField('espresso_attendees'),
198
-                'status'        => $model_field_factory->createWpPostStatusField(
199
-                    'post_status',
200
-                    esc_html__('Attendee Status', 'event_espresso'),
201
-                    false,
202
-                    'publish'
203
-                ),
204
-                'password' => new EE_Password_Field(
205
-                    'post_password',
206
-                    __('Password', 'event_espresso'),
207
-                    false,
208
-                    '',
209
-                    array(
210
-                        'ATT_bio',
211
-                        'ATT_short_bio',
212
-                        'ATT_address',
213
-                        'ATT_address2',
214
-                        'ATT_city',
215
-                        'STA_ID',
216
-                        'CNT_ISO',
217
-                        'ATT_zip',
218
-                        'ATT_email',
219
-                        'ATT_phone'
220
-                    )
221
-                )
222
-            ),
223
-            'Attendee_Meta' => array(
224
-                'ATTM_ID'      => $model_field_factory->createDbOnlyIntField(
225
-                    'ATTM_ID',
226
-                    esc_html__('Attendee Meta Row ID', 'event_espresso'),
227
-                    false
228
-                ),
229
-                'ATT_ID_fk'    => $model_field_factory->createDbOnlyIntField(
230
-                    'ATT_ID',
231
-                    esc_html__('Foreign Key to Attendee in Post Table', 'event_espresso'),
232
-                    false
233
-                ),
234
-                'ATT_fname'    => $model_field_factory->createPlainTextField(
235
-                    'ATT_fname',
236
-                    esc_html__('First Name', 'event_espresso')
237
-                ),
238
-                'ATT_lname'    => $model_field_factory->createPlainTextField(
239
-                    'ATT_lname',
240
-                    esc_html__('Last Name', 'event_espresso')
241
-                ),
242
-                'ATT_address'  => $model_field_factory->createPlainTextField(
243
-                    'ATT_address',
244
-                    esc_html__('Address Part 1', 'event_espresso')
245
-                ),
246
-                'ATT_address2' => $model_field_factory->createPlainTextField(
247
-                    'ATT_address2',
248
-                    esc_html__('Address Part 2', 'event_espresso')
249
-                ),
250
-                'ATT_city'     => $model_field_factory->createPlainTextField(
251
-                    'ATT_city',
252
-                    esc_html__('City', 'event_espresso')
253
-                ),
254
-                'STA_ID'       => $model_field_factory->createForeignKeyIntField(
255
-                    'STA_ID',
256
-                    esc_html__('State', 'event_espresso'),
257
-                    true,
258
-                    0,
259
-                    'State'
260
-                ),
261
-                'CNT_ISO'      => $model_field_factory->createForeignKeyStringField(
262
-                    'CNT_ISO',
263
-                    esc_html__('Country', 'event_espresso'),
264
-                    true,
265
-                    '',
266
-                    'Country'
267
-                ),
268
-                'ATT_zip'      => $model_field_factory->createPlainTextField(
269
-                    'ATT_zip',
270
-                    esc_html__('ZIP/Postal Code', 'event_espresso')
271
-                ),
272
-                'ATT_email'    => $model_field_factory->createEmailField(
273
-                    'ATT_email',
274
-                    esc_html__('Email Address', 'event_espresso')
275
-                ),
276
-                'ATT_phone'    => $model_field_factory->createPlainTextField(
277
-                    'ATT_phone',
278
-                    esc_html__('Phone', 'event_espresso')
279
-                ),
280
-            ),
281
-        );
282
-        $this->_model_relations = array(
283
-            'Registration'      => new EE_Has_Many_Relation(),
284
-            'State'             => new EE_Belongs_To_Relation(),
285
-            'Country'           => new EE_Belongs_To_Relation(),
286
-            'Event'             => new EE_HABTM_Relation('Registration', false),
287
-            'WP_User'           => new EE_Belongs_To_Relation(),
288
-            'Message'           => new EE_Has_Many_Any_Relation(false),
289
-            // allow deletion of attendees even if they have messages in the queue for them.
290
-            'Term_Relationship' => new EE_Has_Many_Relation(),
291
-            'Term_Taxonomy'     => new EE_HABTM_Relation('Term_Relationship'),
292
-        );
293
-        $this->_caps_slug = 'contacts';
294
-        $this->model_chain_to_password = '';
295
-        parent::__construct($timezone);
296
-    }
297
-
298
-
299
-
300
-    /**
301
-     * Gets the name of the field on the attendee model corresponding to the system question string
302
-     * which should be one of the keys from EEM_Attendee::_system_question_to_attendee_field_name
303
-     *
304
-     * @param string $system_question_string
305
-     * @return string|null if not found
306
-     */
307
-    public function get_attendee_field_for_system_question($system_question_string)
308
-    {
309
-        return isset($this->_system_question_to_attendee_field_name[ $system_question_string ])
310
-            ? $this->_system_question_to_attendee_field_name[ $system_question_string ]
311
-            : null;
312
-    }
313
-
314
-
315
-
316
-    /**
317
-     * Gets mapping from esp_question.QST_system values to their corresponding attendee field names
318
-     *
319
-     * @return array
320
-     */
321
-    public function system_question_to_attendee_field_mapping()
322
-    {
323
-        return $this->_system_question_to_attendee_field_name;
324
-    }
325
-
326
-
327
-
328
-    /**
329
-     * Gets all the attendees for a transaction (by using the esp_registration as a join table)
330
-     *
331
-     * @param EE_Transaction /int $transaction_id_or_obj EE_Transaction or its ID
332
-     * @return EE_Attendee[]|EE_Base_Class[]
333
-     * @throws EE_Error
334
-     */
335
-    public function get_attendees_for_transaction($transaction_id_or_obj)
336
-    {
337
-        return $this->get_all(
338
-            array(
339
-                array(
340
-                    'Registration.Transaction.TXN_ID' => $transaction_id_or_obj instanceof EE_Transaction
341
-                        ? $transaction_id_or_obj->ID()
342
-                        : $transaction_id_or_obj,
343
-                ),
344
-            )
345
-        );
346
-    }
347
-
348
-
349
-
350
-    /**
351
-     * retrieve  a single attendee from db via their ID
352
-     *
353
-     * @param $ATT_ID
354
-     * @return mixed array on success, FALSE on fail
355
-     * @deprecated
356
-     */
357
-    public function get_attendee_by_ID($ATT_ID = false)
358
-    {
359
-        // retrieve a particular EE_Attendee
360
-        return $this->get_one_by_ID($ATT_ID);
361
-    }
362
-
363
-
364
-
365
-    /**
366
-     * retrieve  a single attendee from db via their ID
367
-     *
368
-     * @param array $where_cols_n_values
369
-     * @return mixed array on success, FALSE on fail
370
-     * @throws EE_Error
371
-     */
372
-    public function get_attendee($where_cols_n_values = array())
373
-    {
374
-        if (empty($where_cols_n_values)) {
375
-            return false;
376
-        }
377
-        $attendee = $this->get_all(array($where_cols_n_values));
378
-        if (! empty($attendee)) {
379
-            return array_shift($attendee);
380
-        }
381
-        return false;
382
-    }
383
-
384
-
385
-
386
-    /**
387
-     * Search for an existing Attendee record in the DB
388
-     *
389
-     * @param array $where_cols_n_values
390
-     * @return bool|mixed
391
-     * @throws EE_Error
392
-     */
393
-    public function find_existing_attendee($where_cols_n_values = null)
394
-    {
395
-        // search by combo of first and last names plus the email address
396
-        $attendee_data_keys = array(
397
-            'ATT_fname' => $this->_ATT_fname,
398
-            'ATT_lname' => $this->_ATT_lname,
399
-            'ATT_email' => $this->_ATT_email,
400
-        );
401
-        // no search params means attendee object already exists.
402
-        $where_cols_n_values = is_array($where_cols_n_values) && ! empty($where_cols_n_values)
403
-            ? $where_cols_n_values
404
-            : $attendee_data_keys;
405
-        $valid_data = true;
406
-        // check for required values
407
-        $valid_data = isset($where_cols_n_values['ATT_fname']) && ! empty($where_cols_n_values['ATT_fname'])
408
-            ? $valid_data
409
-            : false;
410
-        $valid_data = isset($where_cols_n_values['ATT_lname']) && ! empty($where_cols_n_values['ATT_lname'])
411
-            ? $valid_data
412
-            : false;
413
-        $valid_data = isset($where_cols_n_values['ATT_email']) && ! empty($where_cols_n_values['ATT_email'])
414
-            ? $valid_data
415
-            : false;
416
-        if ($valid_data) {
417
-            $attendee = $this->get_attendee($where_cols_n_values);
418
-            if ($attendee instanceof EE_Attendee) {
419
-                return $attendee;
420
-            }
421
-        }
422
-        return false;
423
-    }
424
-
425
-
426
-
427
-    /**
428
-     * Takes an incoming array of EE_Registration ids
429
-     * and sends back a list of corresponding non duplicate EE_Attendee objects.
430
-     *
431
-     * @since  4.3.0
432
-     * @param  array $ids array of EE_Registration ids
433
-     * @return EE_Attendee[]|EE_Base_Class[]
434
-     * @throws EE_Error
435
-     */
436
-    public function get_array_of_contacts_from_reg_ids($ids)
437
-    {
438
-        $ids = (array) $ids;
439
-        $_where = array(
440
-            'Registration.REG_ID' => array('in', $ids),
441
-        );
442
-        return $this->get_all(array($_where));
443
-    }
51
+
52
+	/**
53
+	 * @deprecated
54
+	 */
55
+	const city_question_id = 6;
56
+
57
+
58
+	/**
59
+	 * @deprecated
60
+	 */
61
+	const state_question_id = 7;
62
+
63
+
64
+	/**
65
+	 * @deprecated
66
+	 */
67
+	const country_question_id = 8;
68
+
69
+
70
+	/**
71
+	 * @deprecated
72
+	 */
73
+	const zip_question_id = 9;
74
+
75
+
76
+	/**
77
+	 * @deprecated
78
+	 */
79
+	const phone_question_id = 10;
80
+
81
+	/**
82
+	 * When looking for questions that correspond to attendee fields,
83
+	 * look for the question with this QST_system value.
84
+	 * These replace the old constants like EEM_Attendee::*_question_id
85
+	 */
86
+	const system_question_fname = 'fname';
87
+
88
+	const system_question_lname = 'lname';
89
+
90
+	const system_question_email = 'email';
91
+
92
+	const system_question_email_confirm = 'email_confirm';
93
+
94
+	const system_question_address = 'address';
95
+
96
+	const system_question_address2 = 'address2';
97
+
98
+	const system_question_city = 'city';
99
+
100
+	const system_question_state = 'state';
101
+
102
+	const system_question_country = 'country';
103
+
104
+	const system_question_zip = 'zip';
105
+
106
+	const system_question_phone = 'phone';
107
+
108
+	/**
109
+	 * Keys are all the EEM_Attendee::system_question_* constants, which are
110
+	 * also all the values of QST_system in the questions table, and values
111
+	 * are their corresponding Attendee field names
112
+	 *
113
+	 * @var array
114
+	 */
115
+	protected $_system_question_to_attendee_field_name = array(
116
+		EEM_Attendee::system_question_fname    => 'ATT_fname',
117
+		EEM_Attendee::system_question_lname    => 'ATT_lname',
118
+		EEM_Attendee::system_question_email    => 'ATT_email',
119
+		EEM_Attendee::system_question_address  => 'ATT_address',
120
+		EEM_Attendee::system_question_address2 => 'ATT_address2',
121
+		EEM_Attendee::system_question_city     => 'ATT_city',
122
+		EEM_Attendee::system_question_state    => 'STA_ID',
123
+		EEM_Attendee::system_question_country  => 'CNT_ISO',
124
+		EEM_Attendee::system_question_zip      => 'ATT_zip',
125
+		EEM_Attendee::system_question_phone    => 'ATT_phone',
126
+	);
127
+
128
+
129
+
130
+	/**
131
+	 * EEM_Attendee constructor.
132
+	 *
133
+	 * @param null              $timezone
134
+	 * @param ModelFieldFactory $model_field_factory
135
+	 * @throws EE_Error
136
+	 * @throws InvalidArgumentException
137
+	 */
138
+	protected function __construct($timezone = '', ModelFieldFactory $model_field_factory)
139
+	{
140
+		$this->singular_item = esc_html__('Attendee', 'event_espresso');
141
+		$this->plural_item = esc_html__('Attendees', 'event_espresso');
142
+		$this->_tables = array(
143
+			'Attendee_CPT'  => new EE_Primary_Table('posts', 'ID'),
144
+			'Attendee_Meta' => new EE_Secondary_Table(
145
+				'esp_attendee_meta',
146
+				'ATTM_ID',
147
+				'ATT_ID'
148
+			),
149
+		);
150
+		$this->_fields = array(
151
+			'Attendee_CPT'  => array(
152
+				'ATT_ID'        => $model_field_factory->createPrimaryKeyIntField(
153
+					'ID',
154
+					esc_html__('Attendee ID', 'event_espresso')
155
+				),
156
+				'ATT_full_name' => $model_field_factory->createPlainTextField(
157
+					'post_title',
158
+					esc_html__('Attendee Full Name', 'event_espresso'),
159
+					false,
160
+					esc_html__('Unknown', 'event_espresso')
161
+				),
162
+				'ATT_bio'       => $model_field_factory->createPostContentField(
163
+					'post_content',
164
+					esc_html__('Attendee Biography', 'event_espresso'),
165
+					false,
166
+					esc_html__('No Biography Provided', 'event_espresso')
167
+				),
168
+				'ATT_slug'      => $model_field_factory->createSlugField(
169
+					'post_name',
170
+					esc_html__('Attendee URL Slug', 'event_espresso')
171
+				),
172
+				'ATT_created'   => $model_field_factory->createDatetimeField(
173
+					'post_date',
174
+					esc_html__('Time Attendee Created', 'event_espresso')
175
+				),
176
+				'ATT_short_bio' => $model_field_factory->createSimpleHtmlField(
177
+					'post_excerpt',
178
+					esc_html__('Attendee Short Biography', 'event_espresso'),
179
+					true,
180
+					esc_html__('No Biography Provided', 'event_espresso')
181
+				),
182
+				'ATT_modified'  => $model_field_factory->createDatetimeField(
183
+					'post_modified',
184
+					esc_html__('Time Attendee Last Modified', 'event_espresso')
185
+				),
186
+				'ATT_author'    => $model_field_factory->createWpUserField(
187
+					'post_author',
188
+					esc_html__('Creator ID of the first Event attended', 'event_espresso'),
189
+					false
190
+				),
191
+				'ATT_parent'    => $model_field_factory->createDbOnlyIntField(
192
+					'post_parent',
193
+					esc_html__('Parent Attendee (unused)', 'event_espresso'),
194
+					false,
195
+					0
196
+				),
197
+				'post_type'     => $model_field_factory->createWpPostTypeField('espresso_attendees'),
198
+				'status'        => $model_field_factory->createWpPostStatusField(
199
+					'post_status',
200
+					esc_html__('Attendee Status', 'event_espresso'),
201
+					false,
202
+					'publish'
203
+				),
204
+				'password' => new EE_Password_Field(
205
+					'post_password',
206
+					__('Password', 'event_espresso'),
207
+					false,
208
+					'',
209
+					array(
210
+						'ATT_bio',
211
+						'ATT_short_bio',
212
+						'ATT_address',
213
+						'ATT_address2',
214
+						'ATT_city',
215
+						'STA_ID',
216
+						'CNT_ISO',
217
+						'ATT_zip',
218
+						'ATT_email',
219
+						'ATT_phone'
220
+					)
221
+				)
222
+			),
223
+			'Attendee_Meta' => array(
224
+				'ATTM_ID'      => $model_field_factory->createDbOnlyIntField(
225
+					'ATTM_ID',
226
+					esc_html__('Attendee Meta Row ID', 'event_espresso'),
227
+					false
228
+				),
229
+				'ATT_ID_fk'    => $model_field_factory->createDbOnlyIntField(
230
+					'ATT_ID',
231
+					esc_html__('Foreign Key to Attendee in Post Table', 'event_espresso'),
232
+					false
233
+				),
234
+				'ATT_fname'    => $model_field_factory->createPlainTextField(
235
+					'ATT_fname',
236
+					esc_html__('First Name', 'event_espresso')
237
+				),
238
+				'ATT_lname'    => $model_field_factory->createPlainTextField(
239
+					'ATT_lname',
240
+					esc_html__('Last Name', 'event_espresso')
241
+				),
242
+				'ATT_address'  => $model_field_factory->createPlainTextField(
243
+					'ATT_address',
244
+					esc_html__('Address Part 1', 'event_espresso')
245
+				),
246
+				'ATT_address2' => $model_field_factory->createPlainTextField(
247
+					'ATT_address2',
248
+					esc_html__('Address Part 2', 'event_espresso')
249
+				),
250
+				'ATT_city'     => $model_field_factory->createPlainTextField(
251
+					'ATT_city',
252
+					esc_html__('City', 'event_espresso')
253
+				),
254
+				'STA_ID'       => $model_field_factory->createForeignKeyIntField(
255
+					'STA_ID',
256
+					esc_html__('State', 'event_espresso'),
257
+					true,
258
+					0,
259
+					'State'
260
+				),
261
+				'CNT_ISO'      => $model_field_factory->createForeignKeyStringField(
262
+					'CNT_ISO',
263
+					esc_html__('Country', 'event_espresso'),
264
+					true,
265
+					'',
266
+					'Country'
267
+				),
268
+				'ATT_zip'      => $model_field_factory->createPlainTextField(
269
+					'ATT_zip',
270
+					esc_html__('ZIP/Postal Code', 'event_espresso')
271
+				),
272
+				'ATT_email'    => $model_field_factory->createEmailField(
273
+					'ATT_email',
274
+					esc_html__('Email Address', 'event_espresso')
275
+				),
276
+				'ATT_phone'    => $model_field_factory->createPlainTextField(
277
+					'ATT_phone',
278
+					esc_html__('Phone', 'event_espresso')
279
+				),
280
+			),
281
+		);
282
+		$this->_model_relations = array(
283
+			'Registration'      => new EE_Has_Many_Relation(),
284
+			'State'             => new EE_Belongs_To_Relation(),
285
+			'Country'           => new EE_Belongs_To_Relation(),
286
+			'Event'             => new EE_HABTM_Relation('Registration', false),
287
+			'WP_User'           => new EE_Belongs_To_Relation(),
288
+			'Message'           => new EE_Has_Many_Any_Relation(false),
289
+			// allow deletion of attendees even if they have messages in the queue for them.
290
+			'Term_Relationship' => new EE_Has_Many_Relation(),
291
+			'Term_Taxonomy'     => new EE_HABTM_Relation('Term_Relationship'),
292
+		);
293
+		$this->_caps_slug = 'contacts';
294
+		$this->model_chain_to_password = '';
295
+		parent::__construct($timezone);
296
+	}
297
+
298
+
299
+
300
+	/**
301
+	 * Gets the name of the field on the attendee model corresponding to the system question string
302
+	 * which should be one of the keys from EEM_Attendee::_system_question_to_attendee_field_name
303
+	 *
304
+	 * @param string $system_question_string
305
+	 * @return string|null if not found
306
+	 */
307
+	public function get_attendee_field_for_system_question($system_question_string)
308
+	{
309
+		return isset($this->_system_question_to_attendee_field_name[ $system_question_string ])
310
+			? $this->_system_question_to_attendee_field_name[ $system_question_string ]
311
+			: null;
312
+	}
313
+
314
+
315
+
316
+	/**
317
+	 * Gets mapping from esp_question.QST_system values to their corresponding attendee field names
318
+	 *
319
+	 * @return array
320
+	 */
321
+	public function system_question_to_attendee_field_mapping()
322
+	{
323
+		return $this->_system_question_to_attendee_field_name;
324
+	}
325
+
326
+
327
+
328
+	/**
329
+	 * Gets all the attendees for a transaction (by using the esp_registration as a join table)
330
+	 *
331
+	 * @param EE_Transaction /int $transaction_id_or_obj EE_Transaction or its ID
332
+	 * @return EE_Attendee[]|EE_Base_Class[]
333
+	 * @throws EE_Error
334
+	 */
335
+	public function get_attendees_for_transaction($transaction_id_or_obj)
336
+	{
337
+		return $this->get_all(
338
+			array(
339
+				array(
340
+					'Registration.Transaction.TXN_ID' => $transaction_id_or_obj instanceof EE_Transaction
341
+						? $transaction_id_or_obj->ID()
342
+						: $transaction_id_or_obj,
343
+				),
344
+			)
345
+		);
346
+	}
347
+
348
+
349
+
350
+	/**
351
+	 * retrieve  a single attendee from db via their ID
352
+	 *
353
+	 * @param $ATT_ID
354
+	 * @return mixed array on success, FALSE on fail
355
+	 * @deprecated
356
+	 */
357
+	public function get_attendee_by_ID($ATT_ID = false)
358
+	{
359
+		// retrieve a particular EE_Attendee
360
+		return $this->get_one_by_ID($ATT_ID);
361
+	}
362
+
363
+
364
+
365
+	/**
366
+	 * retrieve  a single attendee from db via their ID
367
+	 *
368
+	 * @param array $where_cols_n_values
369
+	 * @return mixed array on success, FALSE on fail
370
+	 * @throws EE_Error
371
+	 */
372
+	public function get_attendee($where_cols_n_values = array())
373
+	{
374
+		if (empty($where_cols_n_values)) {
375
+			return false;
376
+		}
377
+		$attendee = $this->get_all(array($where_cols_n_values));
378
+		if (! empty($attendee)) {
379
+			return array_shift($attendee);
380
+		}
381
+		return false;
382
+	}
383
+
384
+
385
+
386
+	/**
387
+	 * Search for an existing Attendee record in the DB
388
+	 *
389
+	 * @param array $where_cols_n_values
390
+	 * @return bool|mixed
391
+	 * @throws EE_Error
392
+	 */
393
+	public function find_existing_attendee($where_cols_n_values = null)
394
+	{
395
+		// search by combo of first and last names plus the email address
396
+		$attendee_data_keys = array(
397
+			'ATT_fname' => $this->_ATT_fname,
398
+			'ATT_lname' => $this->_ATT_lname,
399
+			'ATT_email' => $this->_ATT_email,
400
+		);
401
+		// no search params means attendee object already exists.
402
+		$where_cols_n_values = is_array($where_cols_n_values) && ! empty($where_cols_n_values)
403
+			? $where_cols_n_values
404
+			: $attendee_data_keys;
405
+		$valid_data = true;
406
+		// check for required values
407
+		$valid_data = isset($where_cols_n_values['ATT_fname']) && ! empty($where_cols_n_values['ATT_fname'])
408
+			? $valid_data
409
+			: false;
410
+		$valid_data = isset($where_cols_n_values['ATT_lname']) && ! empty($where_cols_n_values['ATT_lname'])
411
+			? $valid_data
412
+			: false;
413
+		$valid_data = isset($where_cols_n_values['ATT_email']) && ! empty($where_cols_n_values['ATT_email'])
414
+			? $valid_data
415
+			: false;
416
+		if ($valid_data) {
417
+			$attendee = $this->get_attendee($where_cols_n_values);
418
+			if ($attendee instanceof EE_Attendee) {
419
+				return $attendee;
420
+			}
421
+		}
422
+		return false;
423
+	}
424
+
425
+
426
+
427
+	/**
428
+	 * Takes an incoming array of EE_Registration ids
429
+	 * and sends back a list of corresponding non duplicate EE_Attendee objects.
430
+	 *
431
+	 * @since  4.3.0
432
+	 * @param  array $ids array of EE_Registration ids
433
+	 * @return EE_Attendee[]|EE_Base_Class[]
434
+	 * @throws EE_Error
435
+	 */
436
+	public function get_array_of_contacts_from_reg_ids($ids)
437
+	{
438
+		$ids = (array) $ids;
439
+		$_where = array(
440
+			'Registration.REG_ID' => array('in', $ids),
441
+		);
442
+		return $this->get_all(array($_where));
443
+	}
444 444
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Base.model.php 3 patches
Doc Comments   +18 added lines, -16 removed lines patch added patch discarded remove patch
@@ -915,7 +915,7 @@  discard block
 block discarded – undo
915 915
      *  on this model (or follows the _model_chain_to_wp_user and uses that model's
916 916
      * foreign key to the WP_User table)
917 917
      *
918
-     * @return string|boolean string on success, boolean false when there is no
918
+     * @return string|false string on success, boolean false when there is no
919 919
      * foreign key to the WP_User table
920 920
      * @throws ReflectionException
921 921
      */
@@ -1045,7 +1045,7 @@  discard block
 block discarded – undo
1045 1045
      *
1046 1046
      * @param array  $query_params
1047 1047
      * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1048
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1048
+     * @param string  $columns_to_select , What columns to select. By default, we select all columns specified by the
1049 1049
      *                                  fields on the model, and the models we joined to in the query. However, you can
1050 1050
      *                                  override this and set the select to "*", or a specific column name, like
1051 1051
      *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
@@ -1212,7 +1212,7 @@  discard block
 block discarded – undo
1212 1212
      * found in the database matching the given query conditions.
1213 1213
      *
1214 1214
      * @param mixed $current_field_value    Value used for the reference point.
1215
-     * @param null  $field_to_order_by      What field is used for the
1215
+     * @param string  $field_to_order_by      What field is used for the
1216 1216
      *                                      reference point.
1217 1217
      * @param int   $limit                  How many to return.
1218 1218
      * @param array $query_params           Extra conditions on the query.
@@ -1247,7 +1247,7 @@  discard block
 block discarded – undo
1247 1247
      * as found in the database matching the given query conditions.
1248 1248
      *
1249 1249
      * @param mixed $current_field_value    Value used for the reference point.
1250
-     * @param null  $field_to_order_by      What field is used for the
1250
+     * @param string  $field_to_order_by      What field is used for the
1251 1251
      *                                      reference point.
1252 1252
      * @param int   $limit                  How many to return.
1253 1253
      * @param array $query_params           Extra conditions on the query.
@@ -1282,7 +1282,7 @@  discard block
 block discarded – undo
1282 1282
      * database matching the given query conditions.
1283 1283
      *
1284 1284
      * @param mixed $current_field_value    Value used for the reference point.
1285
-     * @param null  $field_to_order_by      What field is used for the
1285
+     * @param string  $field_to_order_by      What field is used for the
1286 1286
      *                                      reference point.
1287 1287
      * @param array $query_params           Extra conditions on the query.
1288 1288
      * @param null  $columns_to_select      If left null, then an EE_Base_Class
@@ -1317,7 +1317,7 @@  discard block
 block discarded – undo
1317 1317
      * the database matching the given query conditions.
1318 1318
      *
1319 1319
      * @param mixed $current_field_value    Value used for the reference point.
1320
-     * @param null  $field_to_order_by      What field is used for the
1320
+     * @param string  $field_to_order_by      What field is used for the
1321 1321
      *                                      reference point.
1322 1322
      * @param array $query_params           Extra conditions on the query.
1323 1323
      * @param null  $columns_to_select      If left null, then an EE_Base_Class
@@ -1478,7 +1478,7 @@  discard block
 block discarded – undo
1478 1478
      *
1479 1479
      * @param string $field_name The name of the field the formats are being retrieved for.
1480 1480
      * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1481
-     * @return array formats in an array with the date format first, and the time format last.
1481
+     * @return string[] formats in an array with the date format first, and the time format last.
1482 1482
      * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1483 1483
      * @since 4.6.x
1484 1484
      */
@@ -2478,7 +2478,7 @@  discard block
 block discarded – undo
2478 2478
      * Verifies the EE addons' database is up-to-date and records that we've done it on
2479 2479
      * EEM_Base::$_db_verification_level
2480 2480
      *
2481
-     * @param $wpdb_method
2481
+     * @param string $wpdb_method
2482 2482
      * @param $arguments_to_provide
2483 2483
      * @return string
2484 2484
      * @throws EE_Error
@@ -2597,6 +2597,7 @@  discard block
 block discarded – undo
2597 2597
      *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2598 2598
      *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2599 2599
      *                             because these will be inserted in any new rows created as well.
2600
+     * @param EE_Base_Class $id_or_obj
2600 2601
      * @return boolean of success
2601 2602
      * @throws EE_Error
2602 2603
      */
@@ -2608,7 +2609,7 @@  discard block
 block discarded – undo
2608 2609
 
2609 2610
 
2610 2611
     /**
2611
-     * @param mixed  $id_or_obj
2612
+     * @param EE_Base_Class  $id_or_obj
2612 2613
      * @param string $relationName
2613 2614
      * @param array  $where_query_params
2614 2615
      * @param EE_Base_Class[] objects to which relations were removed
@@ -2649,7 +2650,7 @@  discard block
 block discarded – undo
2649 2650
      * However, if the model objects can't be deleted because of blocking related model objects, then
2650 2651
      * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2651 2652
      *
2652
-     * @param EE_Base_Class|int|string $id_or_obj
2653
+     * @param EE_Base_Class $id_or_obj
2653 2654
      * @param string                   $model_name
2654 2655
      * @param array                    $query_params
2655 2656
      * @return int how many deleted
@@ -2670,7 +2671,7 @@  discard block
 block discarded – undo
2670 2671
      * the model objects can't be hard deleted because of blocking related model objects,
2671 2672
      * just does a soft-delete on them instead.
2672 2673
      *
2673
-     * @param EE_Base_Class|int|string $id_or_obj
2674
+     * @param EE_Base_Class $id_or_obj
2674 2675
      * @param string                   $model_name
2675 2676
      * @param array                    $query_params
2676 2677
      * @return int how many deleted
@@ -2728,6 +2729,7 @@  discard block
 block discarded – undo
2728 2729
      * @param string $model_name   like 'Event', or 'Registration'
2729 2730
      * @param array  $query_params
2730 2731
      * @param string $field_to_sum name of field to count by. By default, uses primary key
2732
+     * @param EE_Base_Class $id_or_obj
2731 2733
      * @return float
2732 2734
      * @throws EE_Error
2733 2735
      * @throws ReflectionException
@@ -3761,7 +3763,7 @@  discard block
 block discarded – undo
3761 3763
      * We should use default where conditions on related models when they requested to use default where conditions
3762 3764
      * on all models, or specifically just on other related models
3763 3765
      *
3764
-     * @param      $default_where_conditions_value
3766
+     * @param      string $default_where_conditions_value
3765 3767
      * @param bool $for_this_model false means this is for OTHER related models
3766 3768
      * @return bool
3767 3769
      */
@@ -3801,7 +3803,7 @@  discard block
 block discarded – undo
3801 3803
      * We should use minimum where conditions on related models if they requested to use minimum where conditions
3802 3804
      * on this model or others
3803 3805
      *
3804
-     * @param      $default_where_conditions_value
3806
+     * @param      string $default_where_conditions_value
3805 3807
      * @param bool $for_this_model false means this is for OTHER related models
3806 3808
      * @return bool
3807 3809
      */
@@ -4990,7 +4992,7 @@  discard block
 block discarded – undo
4990 4992
      * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4991 4993
      * Eg, on EE_Answer that would be ANS_ID field object
4992 4994
      *
4993
-     * @param $field_obj
4995
+     * @param EE_Model_Field_Base $field_obj
4994 4996
      * @return boolean
4995 4997
      */
4996 4998
     public function is_primary_key_field($field_obj)
@@ -5799,7 +5801,7 @@  discard block
 block discarded – undo
5799 5801
     /**
5800 5802
      * Read comments for assume_values_already_prepared_by_model_object()
5801 5803
      *
5802
-     * @return int
5804
+     * @return boolean
5803 5805
      */
5804 5806
     public function get_assumption_concerning_values_already_prepared_by_model_object()
5805 5807
     {
@@ -6434,7 +6436,7 @@  discard block
 block discarded – undo
6434 6436
     /**
6435 6437
      * Returns the password field on this model, if there is one
6436 6438
      *
6437
-     * @return EE_Password_Field|null
6439
+     * @return EE_Model_Field_Base|null
6438 6440
      * @since 4.9.74.p
6439 6441
      */
6440 6442
     public function getPasswordField()
Please login to merge, or discard this patch.
Indentation   +6545 added lines, -6545 removed lines patch added patch discarded remove patch
@@ -37,6551 +37,6551 @@
 block discarded – undo
37 37
 abstract class EEM_Base extends EE_Base implements ResettableInterface
38 38
 {
39 39
 
40
-    /**
41
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
42
-     */
43
-    const caps_read       = 'read';
44
-
45
-    const caps_read_admin = 'read_admin';
46
-
47
-    const caps_edit       = 'edit';
48
-
49
-    const caps_delete     = 'delete';
50
-
51
-
52
-    /**
53
-     * constant used to show EEM_Base has not yet verified the db on this http request
54
-     */
55
-    const db_verified_none = 0;
56
-
57
-    /**
58
-     * constant used to show EEM_Base has verified the EE core db on this http request,
59
-     * but not the addons' dbs
60
-     */
61
-    const db_verified_core = 1;
62
-
63
-    /**
64
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
65
-     * the EE core db too)
66
-     */
67
-    const db_verified_addons = 2;
68
-
69
-    /**
70
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
71
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
72
-     *        registrations for non-trashed tickets for non-trashed datetimes)
73
-     */
74
-    const default_where_conditions_all = 'all';
75
-
76
-    /**
77
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
78
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
79
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
80
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
81
-     *        models which share tables with other models, this can return data for the wrong model.
82
-     */
83
-    const default_where_conditions_this_only = 'this_model_only';
84
-
85
-    /**
86
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
87
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
88
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
89
-     */
90
-    const default_where_conditions_others_only = 'other_models_only';
91
-
92
-    /**
93
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
94
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
95
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
96
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
97
-     *        (regardless of whether those events and venues are trashed)
98
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
99
-     *        events.
100
-     */
101
-    const default_where_conditions_minimum_all = 'minimum';
102
-
103
-    /**
104
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
105
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
106
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
107
-     *        not)
108
-     */
109
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
110
-
111
-    /**
112
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
113
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
114
-     *        it's possible it will return table entries for other models. You should use
115
-     *        EEM_Base::default_where_conditions_minimum_all instead.
116
-     */
117
-    const default_where_conditions_none = 'none';
118
-
119
-    /**
120
-     * when $_values_already_prepared_by_model_object equals this, we assume
121
-     * the data is just like form input that needs to have the model fields'
122
-     * prepare_for_set and prepare_for_use_in_db called on it
123
-     */
124
-    const not_prepared_by_model_object = 0;
125
-
126
-    /**
127
-     * when $_values_already_prepared_by_model_object equals this, we
128
-     * assume this value is coming from a model object and doesn't need to have
129
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
130
-     */
131
-    const prepared_by_model_object = 1;
132
-
133
-    /**
134
-     * when $_values_already_prepared_by_model_object equals this, we assume
135
-     * the values are already to be used in the database (ie no processing is done
136
-     * on them by the model's fields)
137
-     */
138
-    const prepared_for_use_in_db = 2;
139
-
140
-    /**
141
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
142
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
143
-     * They almost always WILL NOT, but it's not necessarily a requirement.
144
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
145
-     *
146
-     * @var boolean
147
-     */
148
-    private $_values_already_prepared_by_model_object = 0;
149
-
150
-
151
-    /**
152
-     * @var string
153
-     */
154
-    protected $singular_item = 'Item';
155
-
156
-    /**
157
-     * @var string
158
-     */
159
-    protected $plural_item = 'Items';
160
-
161
-    /**
162
-     * array of EE_Table objects for defining which tables comprise this model.
163
-     *
164
-     * @type EE_Table_Base[] $_tables
165
-     */
166
-    protected $_tables;
167
-
168
-    /**
169
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
170
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
171
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
172
-     *
173
-     * @var EE_Model_Field_Base[][] $_fields
174
-     */
175
-    protected $_fields;
176
-
177
-    /**
178
-     * array of different kinds of relations
179
-     *
180
-     * @var EE_Model_Relation_Base[] $_model_relations
181
-     */
182
-    protected $_model_relations;
183
-
184
-    /**
185
-     * @var EE_Index[] $_indexes
186
-     */
187
-    protected $_indexes = [];
188
-
189
-    /**
190
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
191
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
192
-     * by setting the same columns as used in these queries in the query yourself.
193
-     *
194
-     * @var EE_Default_Where_Conditions
195
-     */
196
-    protected $_default_where_conditions_strategy;
197
-
198
-    /**
199
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
200
-     * This is particularly useful when you want something between 'none' and 'default'
201
-     *
202
-     * @var EE_Default_Where_Conditions
203
-     */
204
-    protected $_minimum_where_conditions_strategy;
205
-
206
-    /**
207
-     * String describing how to find the "owner" of this model's objects.
208
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
209
-     * But when there isn't, this indicates which related model, or transiently-related model,
210
-     * has the foreign key to the wp_users table.
211
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
212
-     * related to events, and events have a foreign key to wp_users.
213
-     * On EEM_Transaction, this would be 'Transaction.Event'
214
-     *
215
-     * @var string
216
-     */
217
-    protected $_model_chain_to_wp_user = '';
218
-
219
-    /**
220
-     * String describing how to find the model with a password controlling access to this model. This property has the
221
-     * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
222
-     * This value is the path of models to follow to arrive at the model with the password field.
223
-     * If it is an empty string, it means this model has the password field. If it is null, it means there is no
224
-     * model with a password that should affect reading this on the front-end.
225
-     * Eg this is an empty string for the Event model because it has a password.
226
-     * This is null for the Registration model, because its event's password has no bearing on whether
227
-     * you can read the registration or not on the front-end (it just depends on your capabilities.)
228
-     * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
229
-     * should hide tickets for datetimes for events that have a password set.
230
-     *
231
-     * @var string |null
232
-     */
233
-    protected $model_chain_to_password = null;
234
-
235
-    /**
236
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
237
-     * don't need it (particularly CPT models)
238
-     *
239
-     * @var bool
240
-     */
241
-    protected $_ignore_where_strategy = false;
242
-
243
-    /**
244
-     * String used in caps relating to this model. Eg, if the caps relating to this
245
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
246
-     *
247
-     * @var string. If null it hasn't been initialized yet. If false then we
248
-     * have indicated capabilities don't apply to this
249
-     */
250
-    protected $_caps_slug = null;
251
-
252
-    /**
253
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
254
-     * and next-level keys are capability names, and values are a
255
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
256
-     * they specify which context to use (ie, frontend, backend, edit or delete)
257
-     * and then each capability in the corresponding sub-array that they're missing
258
-     * adds the where conditions onto the query.
259
-     *
260
-     * @var array
261
-     */
262
-    protected $_cap_restrictions = [
263
-        self::caps_read       => [],
264
-        self::caps_read_admin => [],
265
-        self::caps_edit       => [],
266
-        self::caps_delete     => [],
267
-    ];
268
-
269
-    /**
270
-     * Array defining which cap restriction generators to use to create default
271
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
272
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
273
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
274
-     * automatically set this to false (not just null).
275
-     *
276
-     * @var EE_Restriction_Generator_Base[]
277
-     */
278
-    protected $_cap_restriction_generators = [];
279
-
280
-    /**
281
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
282
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
283
-     * maps to 'read' because when looking for relevant permissions we're going to use
284
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
285
-     *
286
-     * @var array
287
-     */
288
-    protected $_cap_contexts_to_cap_action_map = [
289
-        self::caps_read       => 'read',
290
-        self::caps_read_admin => 'read',
291
-        self::caps_edit       => 'edit',
292
-        self::caps_delete     => 'delete',
293
-    ];
294
-
295
-    /**
296
-     * Timezone
297
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
298
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
299
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
300
-     * EE_Datetime_Field data type will have access to it.
301
-     *
302
-     * @var string
303
-     */
304
-    protected $_timezone;
305
-
306
-
307
-    /**
308
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
309
-     * multisite.
310
-     *
311
-     * @var int
312
-     */
313
-    protected static $_model_query_blog_id;
314
-
315
-    /**
316
-     * A copy of _fields, except the array keys are the model names pointed to by
317
-     * the field
318
-     *
319
-     * @var EE_Model_Field_Base[]
320
-     */
321
-    private $_cache_foreign_key_to_fields = [];
322
-
323
-    /**
324
-     * Cached list of all the fields on the model, indexed by their name
325
-     *
326
-     * @var EE_Model_Field_Base[]
327
-     */
328
-    private $_cached_fields = null;
329
-
330
-    /**
331
-     * Cached list of all the fields on the model, except those that are
332
-     * marked as only pertinent to the database
333
-     *
334
-     * @var EE_Model_Field_Base[]
335
-     */
336
-    private $_cached_fields_non_db_only = null;
337
-
338
-    /**
339
-     * A cached reference to the primary key for quick lookup
340
-     *
341
-     * @var EE_Model_Field_Base
342
-     */
343
-    private $_primary_key_field = null;
344
-
345
-    /**
346
-     * Flag indicating whether this model has a primary key or not
347
-     *
348
-     * @var boolean
349
-     */
350
-    protected $_has_primary_key_field = null;
351
-
352
-    /**
353
-     * array in the format:  [ FK alias => full PK ]
354
-     * where keys are local column name aliases for foreign keys
355
-     * and values are the fully qualified column name for the primary key they represent
356
-     *  ex:
357
-     *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
358
-     *
359
-     * @var array $foreign_key_aliases
360
-     */
361
-    protected $foreign_key_aliases = [];
362
-
363
-    /**
364
-     * Whether or not this model is based off a table in WP core only (CPTs should set
365
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
366
-     * This should be true for models that deal with data that should exist independent of EE.
367
-     * For example, if the model can read and insert data that isn't used by EE, this should be true.
368
-     * It would be false, however, if you could guarantee the model would only interact with EE data,
369
-     * even if it uses a WP core table (eg event and venue models set this to false for that reason:
370
-     * they can only read and insert events and venues custom post types, not arbitrary post types)
371
-     *
372
-     * @var boolean
373
-     */
374
-    protected $_wp_core_model = false;
375
-
376
-    /**
377
-     * @var bool stores whether this model has a password field or not.
378
-     * null until initialized by hasPasswordField()
379
-     */
380
-    protected $has_password_field;
381
-
382
-    /**
383
-     * @var EE_Password_Field|null Automatically set when calling getPasswordField()
384
-     */
385
-    protected $password_field;
386
-
387
-    /**
388
-     *    List of valid operators that can be used for querying.
389
-     * The keys are all operators we'll accept, the values are the real SQL
390
-     * operators used
391
-     *
392
-     * @var array
393
-     */
394
-    protected $_valid_operators = [
395
-        '='           => '=',
396
-        '<='          => '<=',
397
-        '<'           => '<',
398
-        '>='          => '>=',
399
-        '>'           => '>',
400
-        '!='          => '!=',
401
-        'LIKE'        => 'LIKE',
402
-        'like'        => 'LIKE',
403
-        'NOT_LIKE'    => 'NOT LIKE',
404
-        'not_like'    => 'NOT LIKE',
405
-        'NOT LIKE'    => 'NOT LIKE',
406
-        'not like'    => 'NOT LIKE',
407
-        'IN'          => 'IN',
408
-        'in'          => 'IN',
409
-        'NOT_IN'      => 'NOT IN',
410
-        'not_in'      => 'NOT IN',
411
-        'NOT IN'      => 'NOT IN',
412
-        'not in'      => 'NOT IN',
413
-        'between'     => 'BETWEEN',
414
-        'BETWEEN'     => 'BETWEEN',
415
-        'IS_NOT_NULL' => 'IS NOT NULL',
416
-        'is_not_null' => 'IS NOT NULL',
417
-        'IS NOT NULL' => 'IS NOT NULL',
418
-        'is not null' => 'IS NOT NULL',
419
-        'IS_NULL'     => 'IS NULL',
420
-        'is_null'     => 'IS NULL',
421
-        'IS NULL'     => 'IS NULL',
422
-        'is null'     => 'IS NULL',
423
-        'REGEXP'      => 'REGEXP',
424
-        'regexp'      => 'REGEXP',
425
-        'NOT_REGEXP'  => 'NOT REGEXP',
426
-        'not_regexp'  => 'NOT REGEXP',
427
-        'NOT REGEXP'  => 'NOT REGEXP',
428
-        'not regexp'  => 'NOT REGEXP',
429
-    ];
430
-
431
-    /**
432
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
433
-     *
434
-     * @var array
435
-     */
436
-    protected $_in_style_operators = ['IN', 'NOT IN'];
437
-
438
-    /**
439
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
440
-     * '12-31-2012'"
441
-     *
442
-     * @var array
443
-     */
444
-    protected $_between_style_operators = ['BETWEEN'];
445
-
446
-    /**
447
-     * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
448
-     *
449
-     * @var array
450
-     */
451
-    protected $_like_style_operators = ['LIKE', 'NOT LIKE'];
452
-
453
-    /**
454
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
455
-     * on a join table.
456
-     *
457
-     * @var array
458
-     */
459
-    protected $_null_style_operators = ['IS NOT NULL', 'IS NULL'];
460
-
461
-    /**
462
-     * Allowed values for $query_params['order'] for ordering in queries
463
-     *
464
-     * @var array
465
-     */
466
-    protected $_allowed_order_values = ['asc', 'desc', 'ASC', 'DESC'];
467
-
468
-    /**
469
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
470
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
471
-     *
472
-     * @var array
473
-     */
474
-    private $_logic_query_param_keys = ['not', 'and', 'or', 'NOT', 'AND', 'OR'];
475
-
476
-    /**
477
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
478
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
479
-     *
480
-     * @var array
481
-     */
482
-    private $_allowed_query_params = [
483
-        0,
484
-        'limit',
485
-        'order_by',
486
-        'group_by',
487
-        'having',
488
-        'force_join',
489
-        'order',
490
-        'on_join_limit',
491
-        'default_where_conditions',
492
-        'caps',
493
-        'extra_selects',
494
-        'exclude_protected',
495
-    ];
496
-
497
-    /**
498
-     * All the data types that can be used in $wpdb->prepare statements.
499
-     *
500
-     * @var array
501
-     */
502
-    private $_valid_wpdb_data_types = ['%d', '%s', '%f'];
503
-
504
-    /**
505
-     * @var EE_Registry $EE
506
-     */
507
-    protected $EE = null;
508
-
509
-
510
-    /**
511
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
512
-     *
513
-     * @var int
514
-     */
515
-    protected $_show_next_x_db_queries = 0;
516
-
517
-    /**
518
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
519
-     * it gets saved on this property as an instance of CustomSelects so those selections can be used in
520
-     * WHERE, GROUP_BY, etc.
521
-     *
522
-     * @var CustomSelects
523
-     */
524
-    protected $_custom_selections = [];
525
-
526
-    /**
527
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
528
-     * caches every model object we've fetched from the DB on this request
529
-     *
530
-     * @var array
531
-     */
532
-    protected $_entity_map;
533
-
534
-    /**
535
-     * @var LoaderInterface $loader
536
-     */
537
-    private static $loader;
538
-
539
-    /**
540
-     * indicates whether an EEM_Base child has already re-verified the DB
541
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
542
-     * looking like EEM_Base::db_verified_*
543
-     *
544
-     * @var int - 0 = none, 1 = core, 2 = addons
545
-     */
546
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
547
-
548
-
549
-    /**
550
-     * About all child constructors:
551
-     * they should define the _tables, _fields and _model_relations arrays.
552
-     * Should ALWAYS be called after child constructor.
553
-     * In order to make the child constructors to be as simple as possible, this parent constructor
554
-     * finalizes constructing all the object's attributes.
555
-     * Generally, rather than requiring a child to code
556
-     * $this->_tables = array(
557
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
558
-     *        ...);
559
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
560
-     * each EE_Table has a function to set the table's alias after the constructor, using
561
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
562
-     * do something similar.
563
-     *
564
-     * @param string $timezone
565
-     * @throws EE_Error
566
-     */
567
-    protected function __construct($timezone = '')
568
-    {
569
-        // check that the model has not been loaded too soon
570
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
571
-            throw new EE_Error(
572
-                sprintf(
573
-                    esc_html__(
574
-                        'The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
575
-                        'event_espresso'
576
-                    ),
577
-                    get_class($this)
578
-                )
579
-            );
580
-        }
581
-        /**
582
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
583
-         */
584
-        if (empty(EEM_Base::$_model_query_blog_id)) {
585
-            EEM_Base::set_model_query_blog_id();
586
-        }
587
-        /**
588
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
589
-         * just use EE_Register_Model_Extension
590
-         *
591
-         * @var EE_Table_Base[] $_tables
592
-         */
593
-        $this->_tables = (array)apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
594
-        foreach ($this->_tables as $table_alias => $table_obj) {
595
-            /** @var $table_obj EE_Table_Base */
596
-            $table_obj->_construct_finalize_with_alias($table_alias);
597
-            if ($table_obj instanceof EE_Secondary_Table) {
598
-                /** @var $table_obj EE_Secondary_Table */
599
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
600
-            }
601
-        }
602
-        /**
603
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
604
-         * EE_Register_Model_Extension
605
-         *
606
-         * @param EE_Model_Field_Base[] $_fields
607
-         */
608
-        $this->_fields = (array)apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
609
-        $this->_invalidate_field_caches();
610
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
611
-            if (! array_key_exists($table_alias, $this->_tables)) {
612
-                throw new EE_Error(
613
-                    sprintf(
614
-                        esc_html__(
615
-                            "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
616
-                            'event_espresso'
617
-                        ),
618
-                        $table_alias,
619
-                        implode(",", $this->_fields)
620
-                    )
621
-                );
622
-            }
623
-            foreach ($fields_for_table as $field_name => $field_obj) {
624
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
625
-                // primary key field base has a slightly different _construct_finalize
626
-                /** @var $field_obj EE_Model_Field_Base */
627
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
628
-            }
629
-        }
630
-        // everything is related to Extra_Meta
631
-        if (get_class($this) !== 'EEM_Extra_Meta') {
632
-            // make extra meta related to everything, but don't block deleting things just
633
-            // because they have related extra meta info. For now just orphan those extra meta
634
-            // in the future we should automatically delete them
635
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
636
-        }
637
-        // and change logs
638
-        if (get_class($this) !== 'EEM_Change_Log') {
639
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
640
-        }
641
-        /**
642
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
643
-         * EE_Register_Model_Extension
644
-         *
645
-         * @param EE_Model_Relation_Base[] $_model_relations
646
-         */
647
-        $this->_model_relations = (array)apply_filters(
648
-            'FHEE__' . get_class($this) . '__construct__model_relations',
649
-            $this->_model_relations
650
-        );
651
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
652
-            /** @var $relation_obj EE_Model_Relation_Base */
653
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
654
-        }
655
-        foreach ($this->_indexes as $index_name => $index_obj) {
656
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
657
-        }
658
-        $this->set_timezone($timezone);
659
-        // finalize default where condition strategy, or set default
660
-        if (! $this->_default_where_conditions_strategy) {
661
-            // nothing was set during child constructor, so set default
662
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
663
-        }
664
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
665
-        if (! $this->_minimum_where_conditions_strategy) {
666
-            // nothing was set during child constructor, so set default
667
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
668
-        }
669
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
670
-        // if the cap slug hasn't been set, and we haven't set it to false on purpose
671
-        // to indicate to NOT set it, set it to the logical default
672
-        if ($this->_caps_slug === null) {
673
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
674
-        }
675
-        // initialize the standard cap restriction generators if none were specified by the child constructor
676
-        if ($this->_cap_restriction_generators !== false) {
677
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
678
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
679
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
680
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
681
-                        new EE_Restriction_Generator_Protected(),
682
-                        $cap_context,
683
-                        $this
684
-                    );
685
-                }
686
-            }
687
-        }
688
-        // if there are cap restriction generators, use them to make the default cap restrictions
689
-        if ($this->_cap_restriction_generators !== false) {
690
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
691
-                if (! $generator_object) {
692
-                    continue;
693
-                }
694
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
695
-                    throw new EE_Error(
696
-                        sprintf(
697
-                            esc_html__(
698
-                                '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.',
699
-                                'event_espresso'
700
-                            ),
701
-                            $context,
702
-                            $this->get_this_model_name()
703
-                        )
704
-                    );
705
-                }
706
-                $action = $this->cap_action_for_context($context);
707
-                if (! $generator_object->construction_finalized()) {
708
-                    $generator_object->_construct_finalize($this, $action);
709
-                }
710
-            }
711
-        }
712
-        do_action('AHEE__' . get_class($this) . '__construct__end');
713
-    }
714
-
715
-
716
-    /**
717
-     * Used to set the $_model_query_blog_id static property.
718
-     *
719
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
720
-     *                      value for get_current_blog_id() will be used.
721
-     */
722
-    public static function set_model_query_blog_id($blog_id = 0)
723
-    {
724
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
725
-    }
726
-
727
-
728
-    /**
729
-     * Returns whatever is set as the internal $model_query_blog_id.
730
-     *
731
-     * @return int
732
-     */
733
-    public static function get_model_query_blog_id()
734
-    {
735
-        return EEM_Base::$_model_query_blog_id;
736
-    }
737
-
738
-
739
-    /**
740
-     * This function is a singleton method used to instantiate the Espresso_model object
741
-     *
742
-     * @param string $timezone        string representing the timezone we want to set for returned Date Time Strings
743
-     *                                (and any incoming timezone data that gets saved).
744
-     *                                Note this just sends the timezone info to the date time model field objects.
745
-     *                                Default is NULL
746
-     *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
747
-     * @return EEM_Base (as in the concrete child class)
748
-     * @throws EE_Error
749
-     * @throws InvalidArgumentException
750
-     * @throws InvalidDataTypeException
751
-     * @throws InvalidInterfaceException
752
-     */
753
-    public static function instance($timezone = '')
754
-    {
755
-        // check if instance of Espresso_model already exists
756
-        if (! static::$_instance instanceof static) {
757
-            // instantiate Espresso_model
758
-            static::$_instance = new static(
759
-                $timezone,
760
-                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
761
-            );
762
-        }
763
-        // Espresso model object
764
-        return static::$_instance;
765
-    }
766
-
767
-
768
-    /**
769
-     * resets the model and returns it
770
-     *
771
-     * @param string $timezone
772
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
773
-     * all its properties reset; if it wasn't instantiated, returns null)
774
-     * @throws EE_Error
775
-     * @throws ReflectionException
776
-     * @throws InvalidArgumentException
777
-     * @throws InvalidDataTypeException
778
-     * @throws InvalidInterfaceException
779
-     */
780
-    public static function reset($timezone = '')
781
-    {
782
-        if (static::$_instance instanceof EEM_Base) {
783
-            // let's try to NOT swap out the current instance for a new one
784
-            // because if someone has a reference to it, we can't remove their reference
785
-            // so it's best to keep using the same reference, but change the original object
786
-            // reset all its properties to their original values as defined in the class
787
-            $r                 = new ReflectionClass(get_class(static::$_instance));
788
-            $static_properties = $r->getStaticProperties();
789
-            foreach ($r->getDefaultProperties() as $property => $value) {
790
-                // don't set instance to null like it was originally,
791
-                // but it's static anyways, and we're ignoring static properties (for now at least)
792
-                if (! isset($static_properties[ $property ])) {
793
-                    static::$_instance->{$property} = $value;
794
-                }
795
-            }
796
-            EEH_DTT_Helper::resetDefaultTimezoneString();
797
-            // and then directly call its constructor again, like we would if we were creating a new one
798
-            static::$_instance->__construct(
799
-                $timezone,
800
-                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
801
-            );
802
-            return static::instance();
803
-        }
804
-        return null;
805
-    }
806
-
807
-
808
-    /**
809
-     * @return LoaderInterface
810
-     * @throws InvalidArgumentException
811
-     * @throws InvalidDataTypeException
812
-     * @throws InvalidInterfaceException
813
-     */
814
-    private static function getLoader()
815
-    {
816
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
817
-            EEM_Base::$loader = LoaderFactory::getLoader();
818
-        }
819
-        return EEM_Base::$loader;
820
-    }
821
-
822
-
823
-    /**
824
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
825
-     *
826
-     * @param boolean $translated return localized strings or JUST the array.
827
-     * @return array
828
-     * @throws EE_Error
829
-     * @throws InvalidArgumentException
830
-     * @throws InvalidDataTypeException
831
-     * @throws InvalidInterfaceException
832
-     * @throws ReflectionException
833
-     */
834
-    public function status_array($translated = false)
835
-    {
836
-        if (! array_key_exists('Status', $this->_model_relations)) {
837
-            return [];
838
-        }
839
-        $model_name   = $this->get_this_model_name();
840
-        $status_type  = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
841
-        $stati        = EEM_Status::instance()->get_all([['STS_type' => $status_type]]);
842
-        $status_array = [];
843
-        foreach ($stati as $status) {
844
-            $status_array[ $status->ID() ] = $status->get('STS_code');
845
-        }
846
-        return $translated
847
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
848
-            : $status_array;
849
-    }
850
-
851
-
852
-    /**
853
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
854
-     *
855
-     * @param array $query_params             see github link below for more info
856
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
857
-     *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object
858
-     *                                        IDs (if there is a primary key on the model. if not, numerically indexed)
859
-     *                                        Some full examples: get 10 transactions which have Scottish attendees:
860
-     *                                        EEM_Transaction::instance()->get_all( array( array(
861
-     *                                        'OR'=>array(
862
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
863
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
864
-     *                                        )
865
-     *                                        ),
866
-     *                                        'limit'=>10,
867
-     *                                        'group_by'=>'TXN_ID'
868
-     *                                        ));
869
-     *                                        get all the answers to the question titled "shirt size" for event with id
870
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
871
-     *                                        'Question.QST_display_text'=>'shirt size',
872
-     *                                        'Registration.Event.EVT_ID'=>12
873
-     *                                        ),
874
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
875
-     *                                        ));
876
-     * @throws EE_Error
877
-     * @throws ReflectionException
878
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
879
-     *                                        or if you have the development copy of EE you can view this at the path:
880
-     *                                        /docs/G--Model-System/model-query-params.md
881
-     */
882
-    public function get_all($query_params = [])
883
-    {
884
-        if (
885
-            isset($query_params['limit'])
886
-            && ! isset($query_params['group_by'])
887
-        ) {
888
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
889
-        }
890
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params));
891
-    }
892
-
893
-
894
-    /**
895
-     * Modifies the query parameters so we only get back model objects
896
-     * that "belong" to the current user
897
-     *
898
-     * @param array $query_params see github link below for more info
899
-     * @return array
900
-     * @throws ReflectionException
901
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
902
-     */
903
-    public function alter_query_params_to_only_include_mine($query_params = [])
904
-    {
905
-        $wp_user_field_name = $this->wp_user_field_name();
906
-        if ($wp_user_field_name) {
907
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
908
-        }
909
-        return $query_params;
910
-    }
911
-
912
-
913
-    /**
914
-     * Returns the name of the field's name that points to the WP_User table
915
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
916
-     * foreign key to the WP_User table)
917
-     *
918
-     * @return string|boolean string on success, boolean false when there is no
919
-     * foreign key to the WP_User table
920
-     * @throws ReflectionException
921
-     */
922
-    public function wp_user_field_name()
923
-    {
924
-        try {
925
-            if (! empty($this->_model_chain_to_wp_user)) {
926
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
927
-                $last_model_name              = end($models_to_follow_to_wp_users);
928
-                $model_with_fk_to_wp_users    = EE_Registry::instance()->load_model($last_model_name);
929
-                $model_chain_to_wp_user       = $this->_model_chain_to_wp_user . '.';
930
-            } else {
931
-                $model_with_fk_to_wp_users = $this;
932
-                $model_chain_to_wp_user    = '';
933
-            }
934
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
935
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
936
-        } catch (EE_Error $e) {
937
-            return false;
938
-        }
939
-    }
940
-
941
-
942
-    /**
943
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
944
-     * (or transiently-related model) has a foreign key to the wp_users table;
945
-     * useful for finding if model objects of this type are 'owned' by the current user.
946
-     * This is an empty string when the foreign key is on this model and when it isn't,
947
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
948
-     * (or transiently-related model)
949
-     *
950
-     * @return string
951
-     */
952
-    public function model_chain_to_wp_user()
953
-    {
954
-        return $this->_model_chain_to_wp_user;
955
-    }
956
-
957
-
958
-    /**
959
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
960
-     * like how registrations don't have a foreign key to wp_users, but the
961
-     * events they are for are), or is unrelated to wp users.
962
-     * generally available
963
-     *
964
-     * @return boolean
965
-     */
966
-    public function is_owned()
967
-    {
968
-        if ($this->model_chain_to_wp_user()) {
969
-            return true;
970
-        }
971
-        try {
972
-            $this->get_foreign_key_to('WP_User');
973
-            return true;
974
-        } catch (EE_Error $e) {
975
-            return false;
976
-        }
977
-    }
978
-
979
-
980
-    /**
981
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
982
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
983
-     * the model)
984
-     *
985
-     * @param array  $query_params
986
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
987
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
988
-     *                                  fields on the model, and the models we joined to in the query. However, you can
989
-     *                                  override this and set the select to "*", or a specific column name, like
990
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
991
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
992
-     *                                  the aliases used to refer to this selection, and values are to be
993
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
994
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
995
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
996
-     * @throws EE_Error
997
-     * @throws InvalidArgumentException
998
-     * @throws ReflectionException
999
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1000
-     */
1001
-    protected function _get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1002
-    {
1003
-        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
1004
-        $model_query_info         = $this->_create_model_query_info_carrier($query_params);
1005
-        $select_expressions       = $columns_to_select === null
1006
-            ? $this->_construct_default_select_sql($model_query_info)
1007
-            : '';
1008
-        if ($this->_custom_selections instanceof CustomSelects) {
1009
-            $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1010
-            $select_expressions .= $select_expressions
1011
-                ? ', ' . $custom_expressions
1012
-                : $custom_expressions;
1013
-        }
1014
-
1015
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1016
-        return $this->_do_wpdb_query('get_results', [$SQL, $output]);
1017
-    }
1018
-
1019
-
1020
-    /**
1021
-     * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1022
-     * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1023
-     * method of including extra select information.
1024
-     *
1025
-     * @param array             $query_params
1026
-     * @param null|array|string $columns_to_select
1027
-     * @return null|CustomSelects
1028
-     * @throws InvalidArgumentException
1029
-     */
1030
-    protected function getCustomSelection(array $query_params, $columns_to_select = null)
1031
-    {
1032
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1033
-            return null;
1034
-        }
1035
-        $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1036
-        $selects = is_string($selects) ? explode(',', $selects) : $selects;
1037
-        return new CustomSelects($selects);
1038
-    }
1039
-
1040
-
1041
-    /**
1042
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1043
-     * but you can use the model query params to more easily
1044
-     * take care of joins, field preparation etc.
1045
-     *
1046
-     * @param array  $query_params
1047
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1048
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1049
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1050
-     *                                  override this and set the select to "*", or a specific column name, like
1051
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1052
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1053
-     *                                  the aliases used to refer to this selection, and values are to be
1054
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1055
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1056
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1057
-     * @throws EE_Error
1058
-     * @throws ReflectionException
1059
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1060
-     */
1061
-    public function get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1062
-    {
1063
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1064
-    }
1065
-
1066
-
1067
-    /**
1068
-     * For creating a custom select statement
1069
-     *
1070
-     * @param array|string $columns_to_select either a string to be inserted directly as the select statement,
1071
-     *                                        or an array where keys are aliases, and values are arrays where 0=>the
1072
-     *                                        selection SQL, and 1=>is the datatype
1073
-     * @return string
1074
-     * @throws EE_Error
1075
-     */
1076
-    private function _construct_select_from_input($columns_to_select)
1077
-    {
1078
-        if (is_array($columns_to_select)) {
1079
-            $select_sql_array = [];
1080
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1081
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1082
-                    throw new EE_Error(
1083
-                        sprintf(
1084
-                            esc_html__(
1085
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1086
-                                'event_espresso'
1087
-                            ),
1088
-                            $selection_and_datatype,
1089
-                            $alias
1090
-                        )
1091
-                    );
1092
-                }
1093
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1094
-                    throw new EE_Error(
1095
-                        sprintf(
1096
-                            esc_html__(
1097
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1098
-                                'event_espresso'
1099
-                            ),
1100
-                            $selection_and_datatype[1],
1101
-                            $selection_and_datatype[0],
1102
-                            $alias,
1103
-                            implode(', ', $this->_valid_wpdb_data_types)
1104
-                        )
1105
-                    );
1106
-                }
1107
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1108
-            }
1109
-            $columns_to_select_string = implode(', ', $select_sql_array);
1110
-        } else {
1111
-            $columns_to_select_string = $columns_to_select;
1112
-        }
1113
-        return $columns_to_select_string;
1114
-    }
1115
-
1116
-
1117
-    /**
1118
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1119
-     *
1120
-     * @return string
1121
-     * @throws EE_Error
1122
-     */
1123
-    public function primary_key_name()
1124
-    {
1125
-        return $this->get_primary_key_field()->get_name();
1126
-    }
1127
-
1128
-
1129
-    /**
1130
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1131
-     * If there is no primary key on this model, $id is treated as primary key string
1132
-     *
1133
-     * @param mixed $id int or string, depending on the type of the model's primary key
1134
-     * @return EE_Base_Class
1135
-     * @throws EE_Error
1136
-     * @throws ReflectionException
1137
-     */
1138
-    public function get_one_by_ID($id)
1139
-    {
1140
-        if ($this->get_from_entity_map($id)) {
1141
-            return $this->get_from_entity_map($id);
1142
-        }
1143
-        return $this->get_one(
1144
-            $this->alter_query_params_to_restrict_by_ID(
1145
-                $id,
1146
-                ['default_where_conditions' => EEM_Base::default_where_conditions_minimum_all]
1147
-            )
1148
-        );
1149
-    }
1150
-
1151
-
1152
-    /**
1153
-     * Alters query parameters to only get items with this ID are returned.
1154
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1155
-     * or could just be a simple primary key ID
1156
-     *
1157
-     * @param int   $id
1158
-     * @param array $query_params see github link below for more info
1159
-     * @return array of normal query params,
1160
-     * @throws EE_Error
1161
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1162
-     */
1163
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = [])
1164
-    {
1165
-        if (! isset($query_params[0])) {
1166
-            $query_params[0] = [];
1167
-        }
1168
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1169
-        if ($conditions_from_id === null) {
1170
-            $query_params[0][ $this->primary_key_name() ] = $id;
1171
-        } else {
1172
-            // no primary key, so the $id must be from the get_index_primary_key_string()
1173
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1174
-        }
1175
-        return $query_params;
1176
-    }
1177
-
1178
-
1179
-    /**
1180
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1181
-     * array. If no item is found, null is returned.
1182
-     *
1183
-     * @param array $query_params like EEM_Base's $query_params variable.
1184
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1185
-     * @throws EE_Error
1186
-     * @throws ReflectionException
1187
-     */
1188
-    public function get_one($query_params = [])
1189
-    {
1190
-        if (! is_array($query_params)) {
1191
-            EE_Error::doing_it_wrong(
1192
-                'EEM_Base::get_one',
1193
-                sprintf(
1194
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1195
-                    gettype($query_params)
1196
-                ),
1197
-                '4.6.0'
1198
-            );
1199
-            $query_params = [];
1200
-        }
1201
-        $query_params['limit'] = 1;
1202
-        $items                 = $this->get_all($query_params);
1203
-        if (empty($items)) {
1204
-            return null;
1205
-        }
1206
-        return array_shift($items);
1207
-    }
1208
-
1209
-
1210
-    /**
1211
-     * Returns the next x number of items in sequence from the given value as
1212
-     * found in the database matching the given query conditions.
1213
-     *
1214
-     * @param mixed $current_field_value    Value used for the reference point.
1215
-     * @param null  $field_to_order_by      What field is used for the
1216
-     *                                      reference point.
1217
-     * @param int   $limit                  How many to return.
1218
-     * @param array $query_params           Extra conditions on the query.
1219
-     * @param null  $columns_to_select      If left null, then an array of
1220
-     *                                      EE_Base_Class objects is returned,
1221
-     *                                      otherwise you can indicate just the
1222
-     *                                      columns you want returned.
1223
-     * @return EE_Base_Class[]|array
1224
-     * @throws EE_Error
1225
-     * @throws ReflectionException
1226
-     */
1227
-    public function next_x(
1228
-        $current_field_value,
1229
-        $field_to_order_by = null,
1230
-        $limit = 1,
1231
-        $query_params = [],
1232
-        $columns_to_select = null
1233
-    ) {
1234
-        return $this->_get_consecutive(
1235
-            $current_field_value,
1236
-            '>',
1237
-            $field_to_order_by,
1238
-            $limit,
1239
-            $query_params,
1240
-            $columns_to_select
1241
-        );
1242
-    }
1243
-
1244
-
1245
-    /**
1246
-     * Returns the previous x number of items in sequence from the given value
1247
-     * as found in the database matching the given query conditions.
1248
-     *
1249
-     * @param mixed $current_field_value    Value used for the reference point.
1250
-     * @param null  $field_to_order_by      What field is used for the
1251
-     *                                      reference point.
1252
-     * @param int   $limit                  How many to return.
1253
-     * @param array $query_params           Extra conditions on the query.
1254
-     * @param null  $columns_to_select      If left null, then an array of
1255
-     *                                      EE_Base_Class objects is returned,
1256
-     *                                      otherwise you can indicate just the
1257
-     *                                      columns you want returned.
1258
-     * @return EE_Base_Class[]|array
1259
-     * @throws EE_Error
1260
-     * @throws ReflectionException
1261
-     */
1262
-    public function previous_x(
1263
-        $current_field_value,
1264
-        $field_to_order_by = null,
1265
-        $limit = 1,
1266
-        $query_params = [],
1267
-        $columns_to_select = null
1268
-    ) {
1269
-        return $this->_get_consecutive(
1270
-            $current_field_value,
1271
-            '<',
1272
-            $field_to_order_by,
1273
-            $limit,
1274
-            $query_params,
1275
-            $columns_to_select
1276
-        );
1277
-    }
1278
-
1279
-
1280
-    /**
1281
-     * Returns the next item in sequence from the given value as found in the
1282
-     * database matching the given query conditions.
1283
-     *
1284
-     * @param mixed $current_field_value    Value used for the reference point.
1285
-     * @param null  $field_to_order_by      What field is used for the
1286
-     *                                      reference point.
1287
-     * @param array $query_params           Extra conditions on the query.
1288
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1289
-     *                                      object is returned, otherwise you
1290
-     *                                      can indicate just the columns you
1291
-     *                                      want and a single array indexed by
1292
-     *                                      the columns will be returned.
1293
-     * @return EE_Base_Class|null|array()
1294
-     * @throws EE_Error
1295
-     * @throws ReflectionException
1296
-     */
1297
-    public function next(
1298
-        $current_field_value,
1299
-        $field_to_order_by = null,
1300
-        $query_params = [],
1301
-        $columns_to_select = null
1302
-    ) {
1303
-        $results = $this->_get_consecutive(
1304
-            $current_field_value,
1305
-            '>',
1306
-            $field_to_order_by,
1307
-            1,
1308
-            $query_params,
1309
-            $columns_to_select
1310
-        );
1311
-        return empty($results) ? null : reset($results);
1312
-    }
1313
-
1314
-
1315
-    /**
1316
-     * Returns the previous item in sequence from the given value as found in
1317
-     * the database matching the given query conditions.
1318
-     *
1319
-     * @param mixed $current_field_value    Value used for the reference point.
1320
-     * @param null  $field_to_order_by      What field is used for the
1321
-     *                                      reference point.
1322
-     * @param array $query_params           Extra conditions on the query.
1323
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1324
-     *                                      object is returned, otherwise you
1325
-     *                                      can indicate just the columns you
1326
-     *                                      want and a single array indexed by
1327
-     *                                      the columns will be returned.
1328
-     * @return EE_Base_Class|null|array()
1329
-     * @throws EE_Error
1330
-     * @throws ReflectionException
1331
-     */
1332
-    public function previous(
1333
-        $current_field_value,
1334
-        $field_to_order_by = null,
1335
-        $query_params = [],
1336
-        $columns_to_select = null
1337
-    ) {
1338
-        $results = $this->_get_consecutive(
1339
-            $current_field_value,
1340
-            '<',
1341
-            $field_to_order_by,
1342
-            1,
1343
-            $query_params,
1344
-            $columns_to_select
1345
-        );
1346
-        return empty($results) ? null : reset($results);
1347
-    }
1348
-
1349
-
1350
-    /**
1351
-     * Returns the a consecutive number of items in sequence from the given
1352
-     * value as found in the database matching the given query conditions.
1353
-     *
1354
-     * @param mixed  $current_field_value   Value used for the reference point.
1355
-     * @param string $operand               What operand is used for the sequence.
1356
-     * @param string $field_to_order_by     What field is used for the reference point.
1357
-     * @param int    $limit                 How many to return.
1358
-     * @param array  $query_params          Extra conditions on the query.
1359
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1360
-     *                                      otherwise you can indicate just the columns you want returned.
1361
-     * @return EE_Base_Class[]|array
1362
-     * @throws EE_Error
1363
-     * @throws ReflectionException
1364
-     */
1365
-    protected function _get_consecutive(
1366
-        $current_field_value,
1367
-        $operand = '>',
1368
-        $field_to_order_by = null,
1369
-        $limit = 1,
1370
-        $query_params = [],
1371
-        $columns_to_select = null
1372
-    ) {
1373
-        // if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1374
-        if (empty($field_to_order_by)) {
1375
-            if ($this->has_primary_key_field()) {
1376
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1377
-            } else {
1378
-                if (WP_DEBUG) {
1379
-                    throw new EE_Error(
1380
-                        esc_html__(
1381
-                            '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).',
1382
-                            'event_espresso'
1383
-                        )
1384
-                    );
1385
-                }
1386
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1387
-                return [];
1388
-            }
1389
-        }
1390
-        if (! is_array($query_params)) {
1391
-            EE_Error::doing_it_wrong(
1392
-                'EEM_Base::_get_consecutive',
1393
-                sprintf(
1394
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1395
-                    gettype($query_params)
1396
-                ),
1397
-                '4.6.0'
1398
-            );
1399
-            $query_params = [];
1400
-        }
1401
-        // let's add the where query param for consecutive look up.
1402
-        $query_params[0][ $field_to_order_by ] = [$operand, $current_field_value];
1403
-        $query_params['limit']                 = $limit;
1404
-        // set direction
1405
-        $incoming_orderby         = isset($query_params['order_by']) ? (array)$query_params['order_by'] : [];
1406
-        $query_params['order_by'] = $operand === '>'
1407
-            ? [$field_to_order_by => 'ASC'] + $incoming_orderby
1408
-            : [$field_to_order_by => 'DESC'] + $incoming_orderby;
1409
-        // if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1410
-        if (empty($columns_to_select)) {
1411
-            return $this->get_all($query_params);
1412
-        }
1413
-        // getting just the fields
1414
-        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1415
-    }
1416
-
1417
-
1418
-    /**
1419
-     * This sets the _timezone property after model object has been instantiated.
1420
-     *
1421
-     * @param string|null $timezone valid PHP DateTimeZone timezone string
1422
-     */
1423
-    public function set_timezone($timezone = '')
1424
-    {
1425
-        static $set_in_progress = false;
1426
-        // if incoming timezone string is empty, then use the existing
1427
-        $valid_timezone = ! empty($timezone) && $timezone !== $this->_timezone
1428
-            ? EEH_DTT_Helper::get_valid_timezone_string($timezone)
1429
-            : $this->_timezone;
1430
-        // do NOT set the timezone if we are already in the process of setting the timezone
1431
-        // OR the existing timezone is already set and the incoming value is nothing (which gets set to default TZ)
1432
-        // OR the existing timezone is already set and the validated value is the same as the existing timezone
1433
-        if (
1434
-            $set_in_progress
1435
-            || (
1436
-                ! empty($this->_timezone)
1437
-                && (
1438
-                    empty($timezone) || $valid_timezone === $this->_timezone
1439
-                )
1440
-            )
1441
-        ) {
1442
-            return;
1443
-        }
1444
-        $set_in_progress = true;
1445
-        $this->_timezone = $valid_timezone ? $valid_timezone : EEH_DTT_Helper::get_valid_timezone_string();
1446
-        // note we need to loop through relations and set the timezone on those objects as well.
1447
-        foreach ($this->_model_relations as $relation) {
1448
-            $relation->set_timezone($this->_timezone);
1449
-        }
1450
-        // and finally we do the same for any datetime fields
1451
-        foreach ($this->_fields as $field) {
1452
-            if ($field instanceof EE_Datetime_Field) {
1453
-                $field->set_timezone($this->_timezone);
1454
-            }
1455
-        }
1456
-        $set_in_progress = false;
1457
-    }
1458
-
1459
-
1460
-    /**
1461
-     * This just returns whatever is set for the current timezone.
1462
-     *
1463
-     * @access public
1464
-     * @return string
1465
-     */
1466
-    public function get_timezone()
1467
-    {
1468
-        if (empty($this->_timezone)) {
1469
-            $this->set_timezone();
1470
-        }
1471
-        return $this->_timezone;
1472
-    }
1473
-
1474
-
1475
-    /**
1476
-     * This returns the date formats set for the given field name and also ensures that
1477
-     * $this->_timezone property is set correctly.
1478
-     *
1479
-     * @param string $field_name The name of the field the formats are being retrieved for.
1480
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1481
-     * @return array formats in an array with the date format first, and the time format last.
1482
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1483
-     * @since 4.6.x
1484
-     */
1485
-    public function get_formats_for($field_name, $pretty = false)
1486
-    {
1487
-        $field_settings = $this->field_settings_for($field_name);
1488
-        // if not a valid EE_Datetime_Field then throw error
1489
-        if (! $field_settings instanceof EE_Datetime_Field) {
1490
-            throw new EE_Error(
1491
-                sprintf(
1492
-                    esc_html__(
1493
-                        '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.',
1494
-                        'event_espresso'
1495
-                    ),
1496
-                    $field_name
1497
-                )
1498
-            );
1499
-        }
1500
-        // while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on the field.
1501
-        $field_timezone = $field_settings->get_timezone();
1502
-        if (empty($this->_timezone && $field_timezone)) {
1503
-            $this->set_timezone();
1504
-        } else {
1505
-            // or vice versa if the field TZ isn't set
1506
-            $model_timezone = $this->get_timezone();
1507
-            $field_settings->set_timezone($model_timezone);
1508
-        }
1509
-
1510
-        return [$field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty)];
1511
-    }
1512
-
1513
-
1514
-    /**
1515
-     * This returns the current time in a format setup for a query on this model.
1516
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1517
-     * it will return:
1518
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1519
-     *  NOW
1520
-     *  - or a unix timestamp (equivalent to time())
1521
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1522
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1523
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1524
-     *
1525
-     * @param string $field_name       The field the current time is needed for.
1526
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1527
-     *                                 formatted string matching the set format for the field in the set timezone will
1528
-     *                                 be returned.
1529
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1530
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1531
-     *                                 exception is triggered.
1532
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1533
-     * @throws Exception
1534
-     * @since 4.6.x
1535
-     */
1536
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1537
-    {
1538
-        $formats  = $this->get_formats_for($field_name);
1539
-        $DateTime = new DateTime("now", new DateTimeZone($this->get_timezone()));
1540
-        if ($timestamp) {
1541
-            return $DateTime->format('U');
1542
-        }
1543
-        // not returning timestamp, so return formatted string in timezone.
1544
-        switch ($what) {
1545
-            case 'time':
1546
-                return $DateTime->format($formats[1]);
1547
-            case 'date':
1548
-                return $DateTime->format($formats[0]);
1549
-            default:
1550
-                return $DateTime->format(implode(' ', $formats));
1551
-        }
1552
-    }
1553
-
1554
-
1555
-    /**
1556
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1557
-     * for the model are.  Returns a DateTime object.
1558
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1559
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1560
-     * ignored.
1561
-     *
1562
-     * @param string $field_name    The field being setup.
1563
-     * @param string $timestring    The date time string being used.
1564
-     * @param string $format        The format for the time string.
1565
-     * @param string $timezone      By default, it is assumed the incoming time string is in timezone for
1566
-     *                              the blog.  If this is not the case, then it can be specified here.
1567
-     *                              If incoming format is 'U', this is ignored.
1568
-     * @return DbSafeDateTime
1569
-     * @throws EE_Error
1570
-     * @throws Exception
1571
-     */
1572
-    public function convert_datetime_for_query($field_name, $timestring, $format, $timezone = '')
1573
-    {
1574
-        // just using this to ensure the timezone is set correctly internally
1575
-        $this->get_formats_for($field_name);
1576
-        $timezone         = ! empty($timezone) ? $timezone : EEH_DTT_Helper::get_timezone();
1577
-        $db_safe_datetime = DbSafeDateTime::createFromFormat($format, $timestring, new DateTimeZone($timezone));
1578
-        EEH_DTT_Helper::setTimezone($db_safe_datetime, new DateTimeZone($this->get_timezone()));
1579
-        return $db_safe_datetime;
1580
-    }
1581
-
1582
-
1583
-    /**
1584
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1585
-     *
1586
-     * @return EE_Table_Base[]
1587
-     */
1588
-    public function get_tables()
1589
-    {
1590
-        return $this->_tables;
1591
-    }
1592
-
1593
-
1594
-    /**
1595
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1596
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1597
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1598
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1599
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1600
-     * model object with EVT_ID = 1
1601
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1602
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1603
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1604
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1605
-     * are not specified)
1606
-     *
1607
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1608
-     *                                         columns!), values are strings, integers, floats, and maybe arrays if
1609
-     *                                         they
1610
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1611
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1612
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1613
-     *                                         ID=34, we'd use this method as follows:
1614
-     *                                         EEM_Transaction::instance()->update(
1615
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1616
-     *                                         array(array('TXN_ID'=>34)));
1617
-     * @param array   $query_params            Eg, consider updating Question's QST_admin_label field is of type
1618
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1619
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1620
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1621
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1622
-     *                                         TRUE, it is assumed that you've already called
1623
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1624
-     *                                         malicious javascript. However, if
1625
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1626
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1627
-     *                                         and every other field, before insertion. We provide this parameter
1628
-     *                                         because model objects perform their prepare_for_set function on all
1629
-     *                                         their values, and so don't need to be called again (and in many cases,
1630
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1631
-     *                                         prepare_for_set method...)
1632
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1633
-     *                                         in this model's entity map according to $fields_n_values that match
1634
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1635
-     *                                         by setting this to FALSE, but be aware that model objects being used
1636
-     *                                         could get out-of-sync with the database
1637
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1638
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1639
-     *                                         bad)
1640
-     * @throws EE_Error
1641
-     * @throws ReflectionException
1642
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1643
-     */
1644
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1645
-    {
1646
-        if (! is_array($query_params)) {
1647
-            EE_Error::doing_it_wrong(
1648
-                'EEM_Base::update',
1649
-                sprintf(
1650
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1651
-                    gettype($query_params)
1652
-                ),
1653
-                '4.6.0'
1654
-            );
1655
-            $query_params = [];
1656
-        }
1657
-        /**
1658
-         * Action called before a model update call has been made.
1659
-         *
1660
-         * @param EEM_Base $model
1661
-         * @param array    $fields_n_values the updated fields and their new values
1662
-         * @param array    $query_params
1663
-         * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1664
-         */
1665
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1666
-        /**
1667
-         * Filters the fields about to be updated given the query parameters. You can provide the
1668
-         * $query_params to $this->get_all() to find exactly which records will be updated
1669
-         *
1670
-         * @param array    $fields_n_values fields and their new values
1671
-         * @param EEM_Base $model           the model being queried
1672
-         * @param array    $query_params
1673
-         * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1674
-         */
1675
-        $fields_n_values = (array)apply_filters(
1676
-            'FHEE__EEM_Base__update__fields_n_values',
1677
-            $fields_n_values,
1678
-            $this,
1679
-            $query_params
1680
-        );
1681
-        // need to verify that, for any entry we want to update, there are entries in each secondary table.
1682
-        // to do that, for each table, verify that it's PK isn't null.
1683
-        $tables = $this->get_tables();
1684
-        // 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
1685
-        // NOTE: we should make this code more efficient by NOT querying twice
1686
-        // before the real update, but that needs to first go through ALPHA testing
1687
-        // as it's dangerous. says Mike August 8 2014
1688
-        // we want to make sure the default_where strategy is ignored
1689
-        $this->_ignore_where_strategy = true;
1690
-        $wpdb_select_results          = $this->_get_all_wpdb_results($query_params);
1691
-        foreach ($wpdb_select_results as $wpdb_result) {
1692
-            // type cast stdClass as array
1693
-            $wpdb_result = (array)$wpdb_result;
1694
-            // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1695
-            if ($this->has_primary_key_field()) {
1696
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1697
-            } else {
1698
-                // 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)
1699
-                $main_table_pk_value = null;
1700
-            }
1701
-            // 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
1702
-            // 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
1703
-            if (count($tables) > 1) {
1704
-                // foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1705
-                // in that table, and so we'll want to insert one
1706
-                foreach ($tables as $table_obj) {
1707
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1708
-                    // if there is no private key for this table on the results, it means there's no entry
1709
-                    // in this table, right? so insert a row in the current table, using any fields available
1710
-                    if (
1711
-                    ! (array_key_exists($this_table_pk_column, $wpdb_result)
1712
-                       && $wpdb_result[ $this_table_pk_column ])
1713
-                    ) {
1714
-                        $success = $this->_insert_into_specific_table(
1715
-                            $table_obj,
1716
-                            $fields_n_values,
1717
-                            $main_table_pk_value
1718
-                        );
1719
-                        // if we died here, report the error
1720
-                        if (! $success) {
1721
-                            return false;
1722
-                        }
1723
-                    }
1724
-                }
1725
-            }
1726
-            // let's make sure default_where strategy is followed now
1727
-            $this->_ignore_where_strategy = false;
1728
-        }
1729
-        // if we want to keep model objects in sync, AND
1730
-        // if this wasn't called from a model object (to update itself)
1731
-        // then we want to make sure we keep all the existing
1732
-        // model objects in sync with the db
1733
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1734
-            if ($this->has_primary_key_field()) {
1735
-                $model_objs_affected_ids = $this->get_col($query_params);
1736
-            } else {
1737
-                // we need to select a bunch of columns and then combine them into the the "index primary key string"s
1738
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params);
1739
-                $model_objs_affected_ids     = [];
1740
-                foreach ($models_affected_key_columns as $row) {
1741
-                    $combined_index_key                             = $this->get_index_primary_key_string($row);
1742
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1743
-                }
1744
-            }
1745
-            if (! $model_objs_affected_ids) {
1746
-                // wait wait wait- if nothing was affected let's stop here
1747
-                return 0;
1748
-            }
1749
-            foreach ($model_objs_affected_ids as $id) {
1750
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1751
-                if ($model_obj_in_entity_map) {
1752
-                    foreach ($fields_n_values as $field => $new_value) {
1753
-                        $model_obj_in_entity_map->set($field, $new_value);
1754
-                    }
1755
-                }
1756
-            }
1757
-            // if there is a primary key on this model, we can now do a slight optimization
1758
-            if ($this->has_primary_key_field()) {
1759
-                // we already know what we want to update. So let's make the query simpler so it's a little more efficient
1760
-                $query_params = [
1761
-                    [$this->primary_key_name() => ['IN', $model_objs_affected_ids]],
1762
-                    'limit'                    => count($model_objs_affected_ids),
1763
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1764
-                ];
1765
-            }
1766
-        }
1767
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1768
-        $SQL              = "UPDATE " . $model_query_info->get_full_join_sql()
1769
-                            . " SET " . $this->_construct_update_sql($fields_n_values)
1770
-                            . $model_query_info->get_where_sql();
1771
-        // note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1772
-        $rows_affected    = $this->_do_wpdb_query('query', [$SQL]);
1773
-        /**
1774
-         * Action called after a model update call has been made.
1775
-         *
1776
-         * @param EEM_Base $model
1777
-         * @param array    $fields_n_values the updated fields and their new values
1778
-         * @param array    $query_params
1779
-         * @param int      $rows_affected
1780
-         * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1781
-         */
1782
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1783
-        return $rows_affected;// how many supposedly got updated
1784
-    }
1785
-
1786
-
1787
-    /**
1788
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1789
-     * are teh values of the field specified (or by default the primary key field)
1790
-     * that matched the query params. Note that you should pass the name of the
1791
-     * model FIELD, not the database table's column name.
1792
-     *
1793
-     * @param array  $query_params
1794
-     * @param string $field_to_select
1795
-     * @return array just like $wpdb->get_col()
1796
-     * @throws EE_Error
1797
-     * @throws ReflectionException
1798
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1799
-     */
1800
-    public function get_col($query_params = [], $field_to_select = null)
1801
-    {
1802
-        if ($field_to_select) {
1803
-            $field = $this->field_settings_for($field_to_select);
1804
-        } elseif ($this->has_primary_key_field()) {
1805
-            $field = $this->get_primary_key_field();
1806
-        } else {
1807
-            $field_settings = $this->field_settings();
1808
-            // no primary key, just grab the first column
1809
-            $field = reset($field_settings);
1810
-        }
1811
-        $model_query_info   = $this->_create_model_query_info_carrier($query_params);
1812
-        $select_expressions = $field->get_qualified_column();
1813
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1814
-        return $this->_do_wpdb_query('get_col', [$SQL]);
1815
-    }
1816
-
1817
-
1818
-    /**
1819
-     * Returns a single column value for a single row from the database
1820
-     *
1821
-     * @param array  $query_params
1822
-     * @param string $field_to_select
1823
-     * @return string
1824
-     * @throws EE_Error
1825
-     * @throws ReflectionException
1826
-     * @see EEM_Base::get_col()
1827
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1828
-     */
1829
-    public function get_var($query_params = [], $field_to_select = null)
1830
-    {
1831
-        $query_params['limit'] = 1;
1832
-        $col                   = $this->get_col($query_params, $field_to_select);
1833
-        if (! empty($col)) {
1834
-            return reset($col);
1835
-        }
1836
-        return null;
1837
-    }
1838
-
1839
-
1840
-    /**
1841
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1842
-     * time?', Question.desc='what do you think?'..." Values are filtered through wpdb->prepare to avoid against SQL
1843
-     * injection, but currently no further filtering is done
1844
-     *
1845
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1846
-     *                               be updated to in the DB
1847
-     * @return string of SQL
1848
-     * @throws EE_Error
1849
-     * @global      $wpdb
1850
-     */
1851
-    public function _construct_update_sql($fields_n_values)
1852
-    {
1853
-        global $wpdb;
1854
-        $cols_n_values = [];
1855
-        foreach ($fields_n_values as $field_name => $value) {
1856
-            $field_obj = $this->field_settings_for($field_name);
1857
-            // if the value is NULL, we want to assign the value to that.
1858
-            // wpdb->prepare doesn't really handle that properly
1859
-            $prepared_value  = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1860
-            $value_sql       = $prepared_value === null
1861
-                ? 'NULL'
1862
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1863
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1864
-        }
1865
-        return implode(",", $cols_n_values);
1866
-    }
1867
-
1868
-
1869
-    /**
1870
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1871
-     * Performs a HARD delete, meaning the database row should always be removed,
1872
-     * not just have a flag field on it switched
1873
-     * Wrapper for EEM_Base::delete_permanently()
1874
-     *
1875
-     * @param mixed   $id
1876
-     * @param boolean $allow_blocking
1877
-     * @return int the number of rows deleted
1878
-     * @throws EE_Error
1879
-     * @throws ReflectionException
1880
-     */
1881
-    public function delete_permanently_by_ID($id, $allow_blocking = true)
1882
-    {
1883
-        return $this->delete_permanently(
1884
-            [
1885
-                [$this->get_primary_key_field()->get_name() => $id],
1886
-                'limit' => 1,
1887
-            ],
1888
-            $allow_blocking
1889
-        );
1890
-    }
1891
-
1892
-
1893
-    /**
1894
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1895
-     * Wrapper for EEM_Base::delete()
1896
-     *
1897
-     * @param mixed   $id
1898
-     * @param boolean $allow_blocking
1899
-     * @return int the number of rows deleted
1900
-     * @throws EE_Error
1901
-     * @throws ReflectionException
1902
-     */
1903
-    public function delete_by_ID($id, $allow_blocking = true)
1904
-    {
1905
-        return $this->delete(
1906
-            [
1907
-                [$this->get_primary_key_field()->get_name() => $id],
1908
-                'limit' => 1,
1909
-            ],
1910
-            $allow_blocking
1911
-        );
1912
-    }
1913
-
1914
-
1915
-    /**
1916
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1917
-     * meaning if the model has a field that indicates its been "trashed" or
1918
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1919
-     *
1920
-     * @param array   $query_params
1921
-     * @param boolean $allow_blocking
1922
-     * @return int how many rows got deleted
1923
-     * @throws EE_Error
1924
-     * @throws ReflectionException
1925
-     * @see EEM_Base::delete_permanently
1926
-     */
1927
-    public function delete($query_params, $allow_blocking = true)
1928
-    {
1929
-        return $this->delete_permanently($query_params, $allow_blocking);
1930
-    }
1931
-
1932
-
1933
-    /**
1934
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1935
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1936
-     * as archived, not actually deleted
1937
-     *
1938
-     * @param array   $query_params
1939
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1940
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1941
-     *                                deletes regardless of other objects which may depend on it. Its generally
1942
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1943
-     *                                DB
1944
-     * @return int how many rows got deleted
1945
-     * @throws EE_Error
1946
-     * @throws ReflectionException
1947
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1948
-     */
1949
-    public function delete_permanently($query_params, $allow_blocking = true)
1950
-    {
1951
-        /**
1952
-         * Action called just before performing a real deletion query. You can use the
1953
-         * model and its $query_params to find exactly which items will be deleted
1954
-         *
1955
-         * @param EEM_Base $model
1956
-         * @param array    $query_params
1957
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1958
-         *                                 to block (prevent) this deletion
1959
-         * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1960
-         */
1961
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1962
-        // some MySQL databases may be running safe mode, which may restrict
1963
-        // deletion if there is no KEY column used in the WHERE statement of a deletion.
1964
-        // to get around this, we first do a SELECT, get all the IDs, and then run another query
1965
-        // to delete them
1966
-        $items_for_deletion           = $this->_get_all_wpdb_results($query_params);
1967
-        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1968
-        $deletion_where_query_part    = $this->_build_query_part_for_deleting_from_columns_and_values(
1969
-            $columns_and_ids_for_deleting
1970
-        );
1971
-        /**
1972
-         * Allows client code to act on the items being deleted before the query is actually executed.
1973
-         *
1974
-         * @param EEM_Base $this                            The model instance being acted on.
1975
-         * @param array    $query_params                    The incoming array of query parameters influencing what gets deleted.
1976
-         * @param bool     $allow_blocking                  @see param description in method phpdoc block.
1977
-         * @param array    $columns_and_ids_for_deleting    An array indicating what entities will get removed as
1978
-         *                                                  derived from the incoming query parameters.
1979
-         * @see details on the structure of this array in the phpdocs
1980
-         *                                                  for the `_get_ids_for_delete_method`
1981
-         *
1982
-         */
1983
-        do_action(
1984
-            'AHEE__EEM_Base__delete__before_query',
1985
-            $this,
1986
-            $query_params,
1987
-            $allow_blocking,
1988
-            $columns_and_ids_for_deleting
1989
-        );
1990
-        if ($deletion_where_query_part) {
1991
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
1992
-            $table_aliases    = implode(', ', array_keys($this->_tables));
1993
-            $SQL              = "DELETE " . $table_aliases
1994
-                                . " FROM " . $model_query_info->get_full_join_sql()
1995
-                                . " WHERE " . $deletion_where_query_part;
1996
-            $rows_deleted     = $this->_do_wpdb_query('query', [$SQL]);
1997
-        } else {
1998
-            $rows_deleted = 0;
1999
-        }
2000
-
2001
-        // Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2002
-        // there was no error with the delete query.
2003
-        if (
2004
-            $this->has_primary_key_field()
2005
-            && $rows_deleted !== false
2006
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2007
-        ) {
2008
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2009
-            foreach ($ids_for_removal as $id) {
2010
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2011
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2012
-                }
2013
-            }
2014
-
2015
-            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2016
-            // `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2017
-            // unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2018
-            // (although it is possible).
2019
-            // Note this can be skipped by using the provided filter and returning false.
2020
-            if (
2021
-            apply_filters(
2022
-                'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2023
-                ! $this instanceof EEM_Extra_Meta,
2024
-                $this
2025
-            )
2026
-            ) {
2027
-                EEM_Extra_Meta::instance()->delete_permanently(
2028
-                    [
2029
-                        0 => [
2030
-                            'EXM_type' => $this->get_this_model_name(),
2031
-                            'OBJ_ID'   => [
2032
-                                'IN',
2033
-                                $ids_for_removal,
2034
-                            ],
2035
-                        ],
2036
-                    ]
2037
-                );
2038
-            }
2039
-        }
2040
-
2041
-        /**
2042
-         * Action called just after performing a real deletion query. Although at this point the
2043
-         * items should have been deleted
2044
-         *
2045
-         * @param EEM_Base $model
2046
-         * @param array    $query_params
2047
-         * @param int      $rows_deleted
2048
-         * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2049
-         */
2050
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2051
-        return $rows_deleted;// how many supposedly got deleted
2052
-    }
2053
-
2054
-
2055
-    /**
2056
-     * Checks all the relations that throw error messages when there are blocking related objects
2057
-     * for related model objects. If there are any related model objects on those relations,
2058
-     * adds an EE_Error, and return true
2059
-     *
2060
-     * @param EE_Base_Class|int $this_model_obj_or_id
2061
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2062
-     *                                                 should be ignored when determining whether there are related
2063
-     *                                                 model objects which block this model object's deletion. Useful
2064
-     *                                                 if you know A is related to B and are considering deleting A,
2065
-     *                                                 but want to see if A has any other objects blocking its deletion
2066
-     *                                                 before removing the relation between A and B
2067
-     * @return boolean
2068
-     * @throws EE_Error
2069
-     * @throws ReflectionException
2070
-     */
2071
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2072
-    {
2073
-        // first, if $ignore_this_model_obj was supplied, get its model
2074
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2075
-            $ignored_model = $ignore_this_model_obj->get_model();
2076
-        } else {
2077
-            $ignored_model = null;
2078
-        }
2079
-        // now check all the relations of $this_model_obj_or_id and see if there
2080
-        // are any related model objects blocking it?
2081
-        $is_blocked = false;
2082
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2083
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2084
-                // if $ignore_this_model_obj was supplied, then for the query
2085
-                // on that model needs to be told to ignore $ignore_this_model_obj
2086
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2087
-                    $related_model_objects = $relation_obj->get_all_related(
2088
-                        $this_model_obj_or_id,
2089
-                        [
2090
-                            [
2091
-                                $ignored_model->get_primary_key_field()->get_name() => [
2092
-                                    '!=',
2093
-                                    $ignore_this_model_obj->ID(),
2094
-                                ],
2095
-                            ],
2096
-                        ]
2097
-                    );
2098
-                } else {
2099
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2100
-                }
2101
-                if ($related_model_objects) {
2102
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2103
-                    $is_blocked = true;
2104
-                }
2105
-            }
2106
-        }
2107
-        return $is_blocked;
2108
-    }
2109
-
2110
-
2111
-    /**
2112
-     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2113
-     *
2114
-     * @param array $row_results_for_deleting
2115
-     * @param bool  $allow_blocking
2116
-     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2117
-     *                              model DOES have a primary_key_field, then the array will be a simple single
2118
-     *                              dimension array where the key is the fully qualified primary key column and the
2119
-     *                              value is an array of ids that will be deleted. Example: array('Event.EVT_ID' =>
2120
-     *                              array( 1,2,3)) If the model DOES NOT have a primary_key_field, then the array will
2121
-     *                              be a two dimensional array where each element is a group of columns and values that
2122
-     *                              get deleted. Example: array(
2123
-     *                              0 => array(
2124
-     *                              'Term_Relationship.object_id' => 1
2125
-     *                              'Term_Relationship.term_taxonomy_id' => 5
2126
-     *                              ),
2127
-     *                              1 => array(
2128
-     *                              'Term_Relationship.object_id' => 1
2129
-     *                              'Term_Relationship.term_taxonomy_id' => 6
2130
-     *                              )
2131
-     *                              )
2132
-     * @throws EE_Error
2133
-     * @throws ReflectionException
2134
-     */
2135
-    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2136
-    {
2137
-        $ids_to_delete_indexed_by_column = [];
2138
-        if ($this->has_primary_key_field()) {
2139
-            $primary_table                   = $this->_get_main_table();
2140
-            $ids_to_delete_indexed_by_column = $query = [];
2141
-            foreach ($row_results_for_deleting as $item_to_delete) {
2142
-                // before we mark this item for deletion,
2143
-                // make sure there's no related entities blocking its deletion (if we're checking)
2144
-                if (
2145
-                    $allow_blocking
2146
-                    && $this->delete_is_blocked_by_related_models(
2147
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2148
-                    )
2149
-                ) {
2150
-                    continue;
2151
-                }
2152
-                // primary table deletes
2153
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2154
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2155
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2156
-                }
2157
-            }
2158
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2159
-            $fields = $this->get_combined_primary_key_fields();
2160
-            foreach ($row_results_for_deleting as $item_to_delete) {
2161
-                $ids_to_delete_indexed_by_column_for_row = [];
2162
-                foreach ($fields as $cpk_field) {
2163
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2164
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2165
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2166
-                    }
2167
-                }
2168
-                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2169
-            }
2170
-        } else {
2171
-            // so there's no primary key and no combined key...
2172
-            // sorry, can't help you
2173
-            throw new EE_Error(
2174
-                sprintf(
2175
-                    esc_html__(
2176
-                        "Cannot delete objects of type %s because there is no primary key NOR combined key",
2177
-                        "event_espresso"
2178
-                    ),
2179
-                    get_class($this)
2180
-                )
2181
-            );
2182
-        }
2183
-        return $ids_to_delete_indexed_by_column;
2184
-    }
2185
-
2186
-
2187
-    /**
2188
-     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2189
-     * the corresponding query_part for the query performing the delete.
2190
-     *
2191
-     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2192
-     * @return string
2193
-     * @throws EE_Error
2194
-     */
2195
-    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2196
-    {
2197
-        $query_part = '';
2198
-        if (empty($ids_to_delete_indexed_by_column)) {
2199
-            return $query_part;
2200
-        } elseif ($this->has_primary_key_field()) {
2201
-            $query = [];
2202
-            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2203
-                // make sure we have unique $ids
2204
-                $ids     = array_unique($ids);
2205
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2206
-            }
2207
-            $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2208
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2209
-            $ways_to_identify_a_row = [];
2210
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2211
-                $values_for_each_combined_primary_key_for_a_row = [];
2212
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2213
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2214
-                }
2215
-                $value_and_value_and_value = implode(' AND ', $values_for_each_combined_primary_key_for_a_row);
2216
-                $ways_to_identify_a_row[]  = "({$value_and_value_and_value})";
2217
-            }
2218
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2219
-        }
2220
-        return $query_part;
2221
-    }
2222
-
2223
-
2224
-    /**
2225
-     * Gets the model field by the fully qualified name
2226
-     *
2227
-     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2228
-     * @return EE_Model_Field_Base
2229
-     * @throws EE_Error
2230
-     */
2231
-    public function get_field_by_column($qualified_column_name)
2232
-    {
2233
-        foreach ($this->field_settings(true) as $field_name => $field_obj) {
2234
-            if ($field_obj->get_qualified_column() === $qualified_column_name) {
2235
-                return $field_obj;
2236
-            }
2237
-        }
2238
-        throw new EE_Error(
2239
-            sprintf(
2240
-                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2241
-                $this->get_this_model_name(),
2242
-                $qualified_column_name
2243
-            )
2244
-        );
2245
-    }
2246
-
2247
-
2248
-    /**
2249
-     * Count all the rows that match criteria the model query params.
2250
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2251
-     * column
2252
-     *
2253
-     * @param array  $query_params
2254
-     * @param string $field_to_count field on model to count by (not column name)
2255
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2256
-     *                               that by the setting $distinct to TRUE;
2257
-     * @return int
2258
-     * @throws EE_Error
2259
-     * @throws ReflectionException
2260
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2261
-     */
2262
-    public function count($query_params = [], $field_to_count = null, $distinct = false)
2263
-    {
2264
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2265
-        if ($field_to_count) {
2266
-            $field_obj       = $this->field_settings_for($field_to_count);
2267
-            $column_to_count = $field_obj->get_qualified_column();
2268
-        } elseif ($this->has_primary_key_field()) {
2269
-            $pk_field_obj    = $this->get_primary_key_field();
2270
-            $column_to_count = $pk_field_obj->get_qualified_column();
2271
-        } else {
2272
-            // there's no primary key
2273
-            // if we're counting distinct items, and there's no primary key,
2274
-            // we need to list out the columns for distinction;
2275
-            // otherwise we can just use star
2276
-            if ($distinct) {
2277
-                $columns_to_use = [];
2278
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2279
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2280
-                }
2281
-                $column_to_count = implode(',', $columns_to_use);
2282
-            } else {
2283
-                $column_to_count = '*';
2284
-            }
2285
-        }
2286
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2287
-        $SQL             =
2288
-            "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2289
-        return (int)$this->_do_wpdb_query('get_var', [$SQL]);
2290
-    }
2291
-
2292
-
2293
-    /**
2294
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2295
-     *
2296
-     * @param array  $query_params
2297
-     * @param string $field_to_sum name of field (array key in $_fields array)
2298
-     * @return float
2299
-     * @throws EE_Error
2300
-     * @throws ReflectionException
2301
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2302
-     */
2303
-    public function sum($query_params, $field_to_sum = null)
2304
-    {
2305
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2306
-        if ($field_to_sum) {
2307
-            $field_obj = $this->field_settings_for($field_to_sum);
2308
-        } else {
2309
-            $field_obj = $this->get_primary_key_field();
2310
-        }
2311
-        $column_to_count = $field_obj->get_qualified_column();
2312
-        $SQL             = "SELECT SUM(" . $column_to_count . ")"
2313
-                           . $this->_construct_2nd_half_of_select_query($model_query_info);
2314
-        $return_value    = $this->_do_wpdb_query('get_var', [$SQL]);
2315
-        $data_type       = $field_obj->get_wpdb_data_type();
2316
-        if ($data_type === '%d' || $data_type === '%s') {
2317
-            return (float)$return_value;
2318
-        }
2319
-        // must be %f
2320
-        return (float)$return_value;
2321
-    }
2322
-
2323
-
2324
-    /**
2325
-     * Just calls the specified method on $wpdb with the given arguments
2326
-     * Consolidates a little extra error handling code
2327
-     *
2328
-     * @param string $wpdb_method
2329
-     * @param array  $arguments_to_provide
2330
-     * @return mixed
2331
-     * @throws EE_Error
2332
-     * @global wpdb  $wpdb
2333
-     */
2334
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2335
-    {
2336
-        // if we're in maintenance mode level 2, DON'T run any queries
2337
-        // because level 2 indicates the database needs updating and
2338
-        // is probably out of sync with the code
2339
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2340
-            throw new EE_Error(
2341
-                sprintf(
2342
-                    esc_html__(
2343
-                        "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.",
2344
-                        "event_espresso"
2345
-                    )
2346
-                )
2347
-            );
2348
-        }
2349
-        global $wpdb;
2350
-        if (! method_exists($wpdb, $wpdb_method)) {
2351
-            throw new EE_Error(
2352
-                sprintf(
2353
-                    esc_html__(
2354
-                        'There is no method named "%s" on Wordpress\' $wpdb object',
2355
-                        'event_espresso'
2356
-                    ),
2357
-                    $wpdb_method
2358
-                )
2359
-            );
2360
-        }
2361
-        $old_show_errors_value = $wpdb->show_errors;
2362
-        if (WP_DEBUG) {
2363
-            $wpdb->show_errors(false);
2364
-        }
2365
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2366
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2367
-        if (WP_DEBUG) {
2368
-            $wpdb->show_errors($old_show_errors_value);
2369
-            if (! empty($wpdb->last_error)) {
2370
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2371
-            }
2372
-            if ($result === false) {
2373
-                throw new EE_Error(
2374
-                    sprintf(
2375
-                        esc_html__(
2376
-                            'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2377
-                            'event_espresso'
2378
-                        ),
2379
-                        $wpdb_method,
2380
-                        var_export($arguments_to_provide, true)
2381
-                    )
2382
-                );
2383
-            }
2384
-        } elseif ($result === false) {
2385
-            EE_Error::add_error(
2386
-                sprintf(
2387
-                    esc_html__(
2388
-                        '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"',
2389
-                        'event_espresso'
2390
-                    ),
2391
-                    $wpdb_method,
2392
-                    var_export($arguments_to_provide, true),
2393
-                    $wpdb->last_error
2394
-                ),
2395
-                __FILE__,
2396
-                __FUNCTION__,
2397
-                __LINE__
2398
-            );
2399
-        }
2400
-        return $result;
2401
-    }
2402
-
2403
-
2404
-    /**
2405
-     * Attempts to run the indicated WPDB method with the provided arguments,
2406
-     * and if there's an error tries to verify the DB is correct. Uses
2407
-     * the static property EEM_Base::$_db_verification_level to determine whether
2408
-     * we should try to fix the EE core db, the addons, or just give up
2409
-     *
2410
-     * @param string $wpdb_method
2411
-     * @param array  $arguments_to_provide
2412
-     * @return mixed
2413
-     * @throws EE_Error
2414
-     */
2415
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2416
-    {
2417
-        global $wpdb;
2418
-        $wpdb->last_error = null;
2419
-        $result           = call_user_func_array([$wpdb, $wpdb_method], $arguments_to_provide);
2420
-        // was there an error running the query? but we don't care on new activations
2421
-        // (we're going to setup the DB anyway on new activations)
2422
-        if (
2423
-            ($result === false || ! empty($wpdb->last_error))
2424
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2425
-        ) {
2426
-            switch (EEM_Base::$_db_verification_level) {
2427
-                case EEM_Base::db_verified_none:
2428
-                    // let's double-check core's DB
2429
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2430
-                    break;
2431
-                case EEM_Base::db_verified_core:
2432
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2433
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2434
-                    break;
2435
-                case EEM_Base::db_verified_addons:
2436
-                    // ummmm... you in trouble
2437
-                    return $result;
2438
-            }
2439
-            if (! empty($error_message)) {
2440
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2441
-                trigger_error($error_message);
2442
-            }
2443
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2444
-        }
2445
-        return $result;
2446
-    }
2447
-
2448
-
2449
-    /**
2450
-     * Verifies the EE core database is up-to-date and records that we've done it on
2451
-     * EEM_Base::$_db_verification_level
2452
-     *
2453
-     * @param string $wpdb_method
2454
-     * @param array  $arguments_to_provide
2455
-     * @return string
2456
-     * @throws EE_Error
2457
-     */
2458
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2459
-    {
2460
-        global $wpdb;
2461
-        // ok remember that we've already attempted fixing the core db, in case the problem persists
2462
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2463
-        $error_message                    = sprintf(
2464
-            esc_html__(
2465
-                'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2466
-                'event_espresso'
2467
-            ),
2468
-            $wpdb->last_error,
2469
-            $wpdb_method,
2470
-            wp_json_encode($arguments_to_provide)
2471
-        );
2472
-        EE_System::instance()->initialize_db_if_no_migrations_required();
2473
-        return $error_message;
2474
-    }
2475
-
2476
-
2477
-    /**
2478
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2479
-     * EEM_Base::$_db_verification_level
2480
-     *
2481
-     * @param $wpdb_method
2482
-     * @param $arguments_to_provide
2483
-     * @return string
2484
-     * @throws EE_Error
2485
-     */
2486
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2487
-    {
2488
-        global $wpdb;
2489
-        // ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2490
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2491
-        $error_message                    = sprintf(
2492
-            esc_html__(
2493
-                'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2494
-                'event_espresso'
2495
-            ),
2496
-            $wpdb->last_error,
2497
-            $wpdb_method,
2498
-            wp_json_encode($arguments_to_provide)
2499
-        );
2500
-        EE_System::instance()->initialize_addons();
2501
-        return $error_message;
2502
-    }
2503
-
2504
-
2505
-    /**
2506
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2507
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2508
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2509
-     * ..."
2510
-     *
2511
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2512
-     * @return string
2513
-     */
2514
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2515
-    {
2516
-        return " FROM " . $model_query_info->get_full_join_sql() .
2517
-               $model_query_info->get_where_sql() .
2518
-               $model_query_info->get_group_by_sql() .
2519
-               $model_query_info->get_having_sql() .
2520
-               $model_query_info->get_order_by_sql() .
2521
-               $model_query_info->get_limit_sql();
2522
-    }
2523
-
2524
-
2525
-    /**
2526
-     * Set to easily debug the next X queries ran from this model.
2527
-     *
2528
-     * @param int $count
2529
-     */
2530
-    public function show_next_x_db_queries($count = 1)
2531
-    {
2532
-        $this->_show_next_x_db_queries = $count;
2533
-    }
2534
-
2535
-
2536
-    /**
2537
-     * @param $sql_query
2538
-     */
2539
-    public function show_db_query_if_previously_requested($sql_query)
2540
-    {
2541
-        if ($this->_show_next_x_db_queries > 0) {
2542
-            echo $sql_query;
2543
-            $this->_show_next_x_db_queries--;
2544
-        }
2545
-    }
2546
-
2547
-
2548
-    /**
2549
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2550
-     * There are the 3 cases:
2551
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2552
-     * $otherModelObject has no ID, it is first saved.
2553
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2554
-     * has no ID, it is first saved.
2555
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2556
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2557
-     * join table
2558
-     *
2559
-     * @param EE_Base_Class                     /int $thisModelObject
2560
-     * @param EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2561
-     * @param string $relationName                     , key in EEM_Base::_relations
2562
-     *                                                 an attendee to a group, you also want to specify which role they
2563
-     *                                                 will have in that group. So you would use this parameter to
2564
-     *                                                 specify array('role-column-name'=>'role-id')
2565
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2566
-     *                                                 to for relation to methods that allow you to further specify
2567
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2568
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2569
-     *                                                 because these will be inserted in any new rows created as well.
2570
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2571
-     * @throws EE_Error
2572
-     */
2573
-    public function add_relationship_to(
2574
-        $id_or_obj,
2575
-        $other_model_id_or_obj,
2576
-        $relationName,
2577
-        $extra_join_model_fields_n_values = []
2578
-    ) {
2579
-        $relation_obj = $this->related_settings_for($relationName);
2580
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2581
-    }
2582
-
2583
-
2584
-    /**
2585
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2586
-     * There are the 3 cases:
2587
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2588
-     * error
2589
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2590
-     * an error
2591
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2592
-     *
2593
-     * @param EE_Base_Class /int $id_or_obj
2594
-     * @param EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2595
-     * @param string $relationName key in EEM_Base::_relations
2596
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2597
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2598
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2599
-     *                             because these will be inserted in any new rows created as well.
2600
-     * @return boolean of success
2601
-     * @throws EE_Error
2602
-     */
2603
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = [])
2604
-    {
2605
-        $relation_obj = $this->related_settings_for($relationName);
2606
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2607
-    }
2608
-
2609
-
2610
-    /**
2611
-     * @param mixed  $id_or_obj
2612
-     * @param string $relationName
2613
-     * @param array  $where_query_params
2614
-     * @param EE_Base_Class[] objects to which relations were removed
2615
-     * @return EE_Base_Class[]
2616
-     * @throws EE_Error
2617
-     */
2618
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = [])
2619
-    {
2620
-        $relation_obj = $this->related_settings_for($relationName);
2621
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2622
-    }
2623
-
2624
-
2625
-    /**
2626
-     * Gets all the related items of the specified $model_name, using $query_params.
2627
-     * Note: by default, we remove the "default query params"
2628
-     * because we want to get even deleted items etc.
2629
-     *
2630
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2631
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2632
-     * @param array  $query_params see github link below for more info
2633
-     * @return EE_Base_Class[]
2634
-     * @throws EE_Error
2635
-     * @throws ReflectionException
2636
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2637
-     */
2638
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2639
-    {
2640
-        $model_obj         = $this->ensure_is_obj($id_or_obj);
2641
-        $relation_settings = $this->related_settings_for($model_name);
2642
-        return $relation_settings->get_all_related($model_obj, $query_params);
2643
-    }
2644
-
2645
-
2646
-    /**
2647
-     * Deletes all the model objects across the relation indicated by $model_name
2648
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2649
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2650
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2651
-     *
2652
-     * @param EE_Base_Class|int|string $id_or_obj
2653
-     * @param string                   $model_name
2654
-     * @param array                    $query_params
2655
-     * @return int how many deleted
2656
-     * @throws EE_Error
2657
-     * @throws ReflectionException
2658
-     */
2659
-    public function delete_related($id_or_obj, $model_name, $query_params = [])
2660
-    {
2661
-        $model_obj         = $this->ensure_is_obj($id_or_obj);
2662
-        $relation_settings = $this->related_settings_for($model_name);
2663
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2664
-    }
2665
-
2666
-
2667
-    /**
2668
-     * Hard deletes all the model objects across the relation indicated by $model_name
2669
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2670
-     * the model objects can't be hard deleted because of blocking related model objects,
2671
-     * just does a soft-delete on them instead.
2672
-     *
2673
-     * @param EE_Base_Class|int|string $id_or_obj
2674
-     * @param string                   $model_name
2675
-     * @param array                    $query_params
2676
-     * @return int how many deleted
2677
-     * @throws EE_Error
2678
-     * @throws ReflectionException
2679
-     */
2680
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = [])
2681
-    {
2682
-        $model_obj         = $this->ensure_is_obj($id_or_obj);
2683
-        $relation_settings = $this->related_settings_for($model_name);
2684
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2685
-    }
2686
-
2687
-
2688
-    /**
2689
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2690
-     * 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
2695
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2696
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2697
-     *                               that by the setting $distinct to TRUE;
2698
-     * @return int
2699
-     * @throws EE_Error
2700
-     * @throws ReflectionException
2701
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2702
-     */
2703
-    public function count_related(
2704
-        $id_or_obj,
2705
-        $model_name,
2706
-        $query_params = [],
2707
-        $field_to_count = null,
2708
-        $distinct = false
2709
-    ) {
2710
-        $related_model = $this->get_related_model_obj($model_name);
2711
-        // we're just going to use the query params on the related model's normal get_all query,
2712
-        // except add a condition to say to match the current mod
2713
-        if (! isset($query_params['default_where_conditions'])) {
2714
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2715
-        }
2716
-        $this_model_name                                                 = $this->get_this_model_name();
2717
-        $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2718
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2719
-        return $related_model->count($query_params, $field_to_count, $distinct);
2720
-    }
2721
-
2722
-
2723
-    /**
2724
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2725
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2726
-     *
2727
-     * @param int           /EE_Base_Class $id_or_obj
2728
-     * @param string $model_name   like 'Event', or 'Registration'
2729
-     * @param array  $query_params
2730
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2731
-     * @return float
2732
-     * @throws EE_Error
2733
-     * @throws ReflectionException
2734
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2735
-     */
2736
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2737
-    {
2738
-        $related_model = $this->get_related_model_obj($model_name);
2739
-        if (! is_array($query_params)) {
2740
-            EE_Error::doing_it_wrong(
2741
-                'EEM_Base::sum_related',
2742
-                sprintf(
2743
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2744
-                    gettype($query_params)
2745
-                ),
2746
-                '4.6.0'
2747
-            );
2748
-            $query_params = [];
2749
-        }
2750
-        // we're just going to use the query params on the related model's normal get_all query,
2751
-        // except add a condition to say to match the current mod
2752
-        if (! isset($query_params['default_where_conditions'])) {
2753
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2754
-        }
2755
-        $this_model_name                                                 = $this->get_this_model_name();
2756
-        $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2757
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2758
-        return $related_model->sum($query_params, $field_to_sum);
2759
-    }
2760
-
2761
-
2762
-    /**
2763
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2764
-     * $modelObject
2765
-     *
2766
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2767
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2768
-     * @param array               $query_params     see github link below for more info
2769
-     * @return EE_Base_Class
2770
-     * @throws EE_Error
2771
-     * @throws ReflectionException
2772
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2773
-     */
2774
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2775
-    {
2776
-        $query_params['limit'] = 1;
2777
-        $results               = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2778
-        if ($results) {
2779
-            return array_shift($results);
2780
-        }
2781
-        return null;
2782
-    }
2783
-
2784
-
2785
-    /**
2786
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2787
-     *
2788
-     * @return string
2789
-     */
2790
-    public function get_this_model_name()
2791
-    {
2792
-        return str_replace("EEM_", "", get_class($this));
2793
-    }
2794
-
2795
-
2796
-    /**
2797
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2798
-     *
2799
-     * @return EE_Any_Foreign_Model_Name_Field
2800
-     * @throws EE_Error
2801
-     */
2802
-    public function get_field_containing_related_model_name()
2803
-    {
2804
-        foreach ($this->field_settings(true) as $field) {
2805
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2806
-                $field_with_model_name = $field;
2807
-            }
2808
-        }
2809
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2810
-            throw new EE_Error(
2811
-                sprintf(
2812
-                    esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2813
-                    $this->get_this_model_name()
2814
-                )
2815
-            );
2816
-        }
2817
-        return $field_with_model_name;
2818
-    }
2819
-
2820
-
2821
-    /**
2822
-     * Inserts a new entry into the database, for each table.
2823
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2824
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2825
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2826
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2827
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2828
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2829
-     *
2830
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2831
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2832
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2833
-     *                              of EEM_Base)
2834
-     * @return int|string new primary key on main table that got inserted
2835
-     * @throws EE_Error
2836
-     * @throws ReflectionException
2837
-     */
2838
-    public function insert($field_n_values)
2839
-    {
2840
-        /**
2841
-         * Filters the fields and their values before inserting an item using the models
2842
-         *
2843
-         * @param array    $fields_n_values keys are the fields and values are their new values
2844
-         * @param EEM_Base $model           the model used
2845
-         */
2846
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2847
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2848
-            $main_table = $this->_get_main_table();
2849
-            $new_id     = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2850
-            if ($new_id !== false) {
2851
-                foreach ($this->_get_other_tables() as $other_table) {
2852
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2853
-                }
2854
-            }
2855
-            /**
2856
-             * Done just after attempting to insert a new model object
2857
-             *
2858
-             * @param EEM_Base $model           used
2859
-             * @param array    $fields_n_values fields and their values
2860
-             * @param int|string the              ID of the newly-inserted model object
2861
-             */
2862
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2863
-            return $new_id;
2864
-        }
2865
-        return false;
2866
-    }
2867
-
2868
-
2869
-    /**
2870
-     * Checks that the result would satisfy the unique indexes on this model
2871
-     *
2872
-     * @param array  $field_n_values
2873
-     * @param string $action
2874
-     * @return boolean
2875
-     * @throws EE_Error
2876
-     * @throws ReflectionException
2877
-     */
2878
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2879
-    {
2880
-        foreach ($this->unique_indexes() as $index_name => $index) {
2881
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2882
-            if ($this->exists([$uniqueness_where_params])) {
2883
-                EE_Error::add_error(
2884
-                    sprintf(
2885
-                        esc_html__(
2886
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2887
-                            "event_espresso"
2888
-                        ),
2889
-                        $action,
2890
-                        $this->_get_class_name(),
2891
-                        $index_name,
2892
-                        implode(",", $index->field_names()),
2893
-                        http_build_query($uniqueness_where_params)
2894
-                    ),
2895
-                    __FILE__,
2896
-                    __FUNCTION__,
2897
-                    __LINE__
2898
-                );
2899
-                return false;
2900
-            }
2901
-        }
2902
-        return true;
2903
-    }
2904
-
2905
-
2906
-    /**
2907
-     * Checks the database for an item that conflicts (ie, if this item were
2908
-     * saved to the DB would break some uniqueness requirement, like a primary key
2909
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2910
-     * can be either an EE_Base_Class or an array of fields n values
2911
-     *
2912
-     * @param EE_Base_Class|array $obj_or_fields_array
2913
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2914
-     *                                                 when looking for conflicts
2915
-     *                                                 (ie, if false, we ignore the model object's primary key
2916
-     *                                                 when finding "conflicts". If true, it's also considered).
2917
-     *                                                 Only works for INT primary key,
2918
-     *                                                 STRING primary keys cannot be ignored
2919
-     * @return EE_Base_Class|array
2920
-     * @throws EE_Error
2921
-     * @throws ReflectionException
2922
-     */
2923
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2924
-    {
2925
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2926
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2927
-        } elseif (is_array($obj_or_fields_array)) {
2928
-            $fields_n_values = $obj_or_fields_array;
2929
-        } else {
2930
-            throw new EE_Error(
2931
-                sprintf(
2932
-                    esc_html__(
2933
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2934
-                        "event_espresso"
2935
-                    ),
2936
-                    get_class($this),
2937
-                    $obj_or_fields_array
2938
-                )
2939
-            );
2940
-        }
2941
-        $query_params = [];
2942
-        if (
2943
-            $this->has_primary_key_field()
2944
-            && ($include_primary_key
2945
-                || $this->get_primary_key_field()
2946
-                   instanceof
2947
-                   EE_Primary_Key_String_Field)
2948
-            && isset($fields_n_values[ $this->primary_key_name() ])
2949
-        ) {
2950
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2951
-        }
2952
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2953
-            $uniqueness_where_params                              =
2954
-                array_intersect_key($fields_n_values, $unique_index->fields());
2955
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2956
-        }
2957
-        // if there is nothing to base this search on, then we shouldn't find anything
2958
-        if (empty($query_params)) {
2959
-            return [];
2960
-        }
2961
-        return $this->get_one($query_params);
2962
-    }
2963
-
2964
-
2965
-    /**
2966
-     * Like count, but is optimized and returns a boolean instead of an int
2967
-     *
2968
-     * @param array $query_params
2969
-     * @return boolean
2970
-     * @throws EE_Error
2971
-     * @throws ReflectionException
2972
-     */
2973
-    public function exists($query_params)
2974
-    {
2975
-        $query_params['limit'] = 1;
2976
-        return $this->count($query_params) > 0;
2977
-    }
2978
-
2979
-
2980
-    /**
2981
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2982
-     *
2983
-     * @param int|string $id
2984
-     * @return boolean
2985
-     * @throws EE_Error
2986
-     * @throws ReflectionException
2987
-     */
2988
-    public function exists_by_ID($id)
2989
-    {
2990
-        return $this->exists(
2991
-            [
2992
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2993
-                [
2994
-                    $this->primary_key_name() => $id,
2995
-                ],
2996
-            ]
2997
-        );
2998
-    }
2999
-
3000
-
3001
-    /**
3002
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
3003
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
3004
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
3005
-     * on the main table)
3006
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
3007
-     * cases where we want to call it directly rather than via insert().
3008
-     *
3009
-     * @access   protected
3010
-     * @param EE_Table_Base $table
3011
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
3012
-     *                                       float
3013
-     * @param int           $new_id          for now we assume only int keys
3014
-     * @return int ID of new row inserted, or FALSE on failure
3015
-     * @throws EE_Error
3016
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
3017
-     */
3018
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
3019
-    {
3020
-        global $wpdb;
3021
-        $insertion_col_n_values = [];
3022
-        $format_for_insertion   = [];
3023
-        $fields_on_table        = $this->_get_fields_for_table($table->get_table_alias());
3024
-        foreach ($fields_on_table as $field_name => $field_obj) {
3025
-            // check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
3026
-            if ($field_obj->is_auto_increment()) {
3027
-                continue;
3028
-            }
3029
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3030
-            // if the value we want to assign it to is NULL, just don't mention it for the insertion
3031
-            if ($prepared_value !== null) {
3032
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3033
-                $format_for_insertion[]                                   = $field_obj->get_wpdb_data_type();
3034
-            }
3035
-        }
3036
-        if ($table instanceof EE_Secondary_Table && $new_id) {
3037
-            // its not the main table, so we should have already saved the main table's PK which we just inserted
3038
-            // so add the fk to the main table as a column
3039
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3040
-            $format_for_insertion[]                              =
3041
-                '%d';// yes right now we're only allowing these foreign keys to be INTs
3042
-        }
3043
-        // insert the new entry
3044
-        $result = $this->_do_wpdb_query(
3045
-            'insert',
3046
-            [$table->get_table_name(), $insertion_col_n_values, $format_for_insertion]
3047
-        );
3048
-        if ($result === false) {
3049
-            return false;
3050
-        }
3051
-        // ok, now what do we return for the ID of the newly-inserted thing?
3052
-        if ($this->has_primary_key_field()) {
3053
-            if ($this->get_primary_key_field()->is_auto_increment()) {
3054
-                return $wpdb->insert_id;
3055
-            }
3056
-            // it's not an auto-increment primary key, so
3057
-            // it must have been supplied
3058
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3059
-        }
3060
-        // we can't return a  primary key because there is none. instead return
3061
-        // a unique string indicating this model
3062
-        return $this->get_index_primary_key_string($fields_n_values);
3063
-    }
3064
-
3065
-
3066
-    /**
3067
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3068
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3069
-     * and there is no default, we pass it along. WPDB will take care of it)
3070
-     *
3071
-     * @param EE_Model_Field_Base $field_obj
3072
-     * @param array               $fields_n_values
3073
-     * @return mixed string|int|float depending on what the table column will be expecting
3074
-     * @throws EE_Error
3075
-     */
3076
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3077
-    {
3078
-        // if this field doesn't allow nullable, don't allow it
3079
-        if (
3080
-            ! $field_obj->is_nullable()
3081
-            && (
3082
-                ! isset($fields_n_values[ $field_obj->get_name() ])
3083
-                || $fields_n_values[ $field_obj->get_name() ] === null
3084
-            )
3085
-        ) {
3086
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3087
-        }
3088
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3089
-            ? $fields_n_values[ $field_obj->get_name() ]
3090
-            : null;
3091
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3092
-    }
3093
-
3094
-
3095
-    /**
3096
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3097
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3098
-     * the field's prepare_for_set() method.
3099
-     *
3100
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3101
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3102
-     *                                   top of file)
3103
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3104
-     *                                   $value is a custom selection
3105
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3106
-     */
3107
-    private function _prepare_value_for_use_in_db($value, $field)
3108
-    {
3109
-        if ($field && $field instanceof EE_Model_Field_Base) {
3110
-            // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3111
-            switch ($this->_values_already_prepared_by_model_object) {
3112
-                /** @noinspection PhpMissingBreakStatementInspection */
3113
-                case self::not_prepared_by_model_object:
3114
-                    $value = $field->prepare_for_set($value);
3115
-                // purposefully left out "return"
3116
-                case self::prepared_by_model_object:
3117
-                    /** @noinspection SuspiciousAssignmentsInspection */
3118
-                    $value = $field->prepare_for_use_in_db($value);
3119
-                case self::prepared_for_use_in_db:
3120
-                    // leave the value alone
3121
-            }
3122
-            return $value;
3123
-            // phpcs:enable
3124
-        }
3125
-        return $value;
3126
-    }
3127
-
3128
-
3129
-    /**
3130
-     * Returns the main table on this model
3131
-     *
3132
-     * @return EE_Primary_Table
3133
-     * @throws EE_Error
3134
-     */
3135
-    protected function _get_main_table()
3136
-    {
3137
-        foreach ($this->_tables as $table) {
3138
-            if ($table instanceof EE_Primary_Table) {
3139
-                return $table;
3140
-            }
3141
-        }
3142
-        throw new EE_Error(
3143
-            sprintf(
3144
-                esc_html__(
3145
-                    'There are no main tables on %s. They should be added to _tables array in the constructor',
3146
-                    'event_espresso'
3147
-                ),
3148
-                get_class($this)
3149
-            )
3150
-        );
3151
-    }
3152
-
3153
-
3154
-    /**
3155
-     * table
3156
-     * returns EE_Primary_Table table name
3157
-     *
3158
-     * @return string
3159
-     * @throws EE_Error
3160
-     */
3161
-    public function table()
3162
-    {
3163
-        return $this->_get_main_table()->get_table_name();
3164
-    }
3165
-
3166
-
3167
-    /**
3168
-     * table
3169
-     * returns first EE_Secondary_Table table name
3170
-     *
3171
-     * @return string
3172
-     */
3173
-    public function second_table()
3174
-    {
3175
-        // grab second table from tables array
3176
-        $second_table = end($this->_tables);
3177
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3178
-    }
3179
-
3180
-
3181
-    /**
3182
-     * get_table_obj_by_alias
3183
-     * returns table name given it's alias
3184
-     *
3185
-     * @param string $table_alias
3186
-     * @return EE_Primary_Table | EE_Secondary_Table
3187
-     */
3188
-    public function get_table_obj_by_alias($table_alias = '')
3189
-    {
3190
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3191
-    }
3192
-
3193
-
3194
-    /**
3195
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3196
-     *
3197
-     * @return EE_Secondary_Table[]
3198
-     */
3199
-    protected function _get_other_tables()
3200
-    {
3201
-        $other_tables = [];
3202
-        foreach ($this->_tables as $table_alias => $table) {
3203
-            if ($table instanceof EE_Secondary_Table) {
3204
-                $other_tables[ $table_alias ] = $table;
3205
-            }
3206
-        }
3207
-        return $other_tables;
3208
-    }
3209
-
3210
-
3211
-    /**
3212
-     * Finds all the fields that correspond to the given table
3213
-     *
3214
-     * @param string $table_alias , array key in EEM_Base::_tables
3215
-     * @return EE_Model_Field_Base[]
3216
-     */
3217
-    public function _get_fields_for_table($table_alias)
3218
-    {
3219
-        return $this->_fields[ $table_alias ];
3220
-    }
3221
-
3222
-
3223
-    /**
3224
-     * Recurses through all the where parameters, and finds all the related models we'll need
3225
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3226
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3227
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3228
-     * related Registration, Transaction, and Payment models.
3229
-     *
3230
-     * @param array $query_params see github link below for more info
3231
-     * @return EE_Model_Query_Info_Carrier
3232
-     * @throws EE_Error
3233
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3234
-     */
3235
-    public function _extract_related_models_from_query($query_params)
3236
-    {
3237
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3238
-        if (array_key_exists(0, $query_params)) {
3239
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3240
-        }
3241
-        if (array_key_exists('group_by', $query_params)) {
3242
-            if (is_array($query_params['group_by'])) {
3243
-                $this->_extract_related_models_from_sub_params_array_values(
3244
-                    $query_params['group_by'],
3245
-                    $query_info_carrier,
3246
-                    'group_by'
3247
-                );
3248
-            } elseif (! empty($query_params['group_by'])) {
3249
-                $this->_extract_related_model_info_from_query_param(
3250
-                    $query_params['group_by'],
3251
-                    $query_info_carrier,
3252
-                    'group_by'
3253
-                );
3254
-            }
3255
-        }
3256
-        if (array_key_exists('having', $query_params)) {
3257
-            $this->_extract_related_models_from_sub_params_array_keys(
3258
-                $query_params[0],
3259
-                $query_info_carrier,
3260
-                'having'
3261
-            );
3262
-        }
3263
-        if (array_key_exists('order_by', $query_params)) {
3264
-            if (is_array($query_params['order_by'])) {
3265
-                $this->_extract_related_models_from_sub_params_array_keys(
3266
-                    $query_params['order_by'],
3267
-                    $query_info_carrier,
3268
-                    'order_by'
3269
-                );
3270
-            } elseif (! empty($query_params['order_by'])) {
3271
-                $this->_extract_related_model_info_from_query_param(
3272
-                    $query_params['order_by'],
3273
-                    $query_info_carrier,
3274
-                    'order_by'
3275
-                );
3276
-            }
3277
-        }
3278
-        if (array_key_exists('force_join', $query_params)) {
3279
-            $this->_extract_related_models_from_sub_params_array_values(
3280
-                $query_params['force_join'],
3281
-                $query_info_carrier,
3282
-                'force_join'
3283
-            );
3284
-        }
3285
-        $this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3286
-        return $query_info_carrier;
3287
-    }
3288
-
3289
-
3290
-    /**
3291
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3292
-     *
3293
-     * @param array                       $sub_query_params
3294
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3295
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3296
-     * @return EE_Model_Query_Info_Carrier
3297
-     * @throws EE_Error
3298
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3299
-     */
3300
-    private function _extract_related_models_from_sub_params_array_keys(
3301
-        $sub_query_params,
3302
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3303
-        $query_param_type
3304
-    ) {
3305
-        if (! empty($sub_query_params)) {
3306
-            $sub_query_params = (array)$sub_query_params;
3307
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3308
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3309
-                $this->_extract_related_model_info_from_query_param(
3310
-                    $param,
3311
-                    $model_query_info_carrier,
3312
-                    $query_param_type
3313
-                );
3314
-                // if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3315
-                // indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3316
-                // extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3317
-                // of array('Registration.TXN_ID'=>23)
3318
-                $query_param_sans_stars =
3319
-                    $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3320
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3321
-                    if (! is_array($possibly_array_of_params)) {
3322
-                        throw new EE_Error(
3323
-                            sprintf(
3324
-                                esc_html__(
3325
-                                    "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'))",
3326
-                                    "event_espresso"
3327
-                                ),
3328
-                                $param,
3329
-                                $possibly_array_of_params
3330
-                            )
3331
-                        );
3332
-                    }
3333
-                    $this->_extract_related_models_from_sub_params_array_keys(
3334
-                        $possibly_array_of_params,
3335
-                        $model_query_info_carrier,
3336
-                        $query_param_type
3337
-                    );
3338
-                } elseif (
3339
-                    $query_param_type === 0 // ie WHERE
3340
-                    && is_array($possibly_array_of_params)
3341
-                    && isset($possibly_array_of_params[2])
3342
-                    && $possibly_array_of_params[2] == true
3343
-                ) {
3344
-                    // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3345
-                    // indicating that $possible_array_of_params[1] is actually a field name,
3346
-                    // from which we should extract query parameters!
3347
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3348
-                        throw new EE_Error(
3349
-                            sprintf(
3350
-                                esc_html__(
3351
-                                    "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3352
-                                    "event_espresso"
3353
-                                ),
3354
-                                $query_param_type,
3355
-                                implode(",", $possibly_array_of_params)
3356
-                            )
3357
-                        );
3358
-                    }
3359
-                    $this->_extract_related_model_info_from_query_param(
3360
-                        $possibly_array_of_params[1],
3361
-                        $model_query_info_carrier,
3362
-                        $query_param_type
3363
-                    );
3364
-                }
3365
-            }
3366
-        }
3367
-        return $model_query_info_carrier;
3368
-    }
3369
-
3370
-
3371
-    /**
3372
-     * For extracting related models from forced_joins, where the array values contain the info about what
3373
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3374
-     *
3375
-     * @param array                       $sub_query_params
3376
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3377
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3378
-     * @return EE_Model_Query_Info_Carrier
3379
-     * @throws EE_Error
3380
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3381
-     */
3382
-    private function _extract_related_models_from_sub_params_array_values(
3383
-        $sub_query_params,
3384
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3385
-        $query_param_type
3386
-    ) {
3387
-        if (! empty($sub_query_params)) {
3388
-            if (! is_array($sub_query_params)) {
3389
-                throw new EE_Error(
3390
-                    sprintf(
3391
-                        esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3392
-                        $sub_query_params
3393
-                    )
3394
-                );
3395
-            }
3396
-            foreach ($sub_query_params as $param) {
3397
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3398
-                $this->_extract_related_model_info_from_query_param(
3399
-                    $param,
3400
-                    $model_query_info_carrier,
3401
-                    $query_param_type
3402
-                );
3403
-            }
3404
-        }
3405
-        return $model_query_info_carrier;
3406
-    }
3407
-
3408
-
3409
-    /**
3410
-     * Extract all the query parts from  model query params
3411
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3412
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3413
-     * but use them in a different order. Eg, we need to know what models we are querying
3414
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3415
-     * other models before we can finalize the where clause SQL.
3416
-     *
3417
-     * @param array $query_params see github link below for more info
3418
-     * @return EE_Model_Query_Info_Carrier
3419
-     * @throws EE_Error
3420
-     * @throws ModelConfigurationException
3421
-     * @throws ReflectionException
3422
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3423
-     */
3424
-    public function _create_model_query_info_carrier($query_params)
3425
-    {
3426
-        if (! is_array($query_params)) {
3427
-            EE_Error::doing_it_wrong(
3428
-                'EEM_Base::_create_model_query_info_carrier',
3429
-                sprintf(
3430
-                    esc_html__(
3431
-                        '$query_params should be an array, you passed a variable of type %s',
3432
-                        'event_espresso'
3433
-                    ),
3434
-                    gettype($query_params)
3435
-                ),
3436
-                '4.6.0'
3437
-            );
3438
-            $query_params = [];
3439
-        }
3440
-        $query_params[0] = isset($query_params[0]) ? $query_params[0] : [];
3441
-        // first check if we should alter the query to account for caps or not
3442
-        // because the caps might require us to do extra joins
3443
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3444
-            $query_params[0] = array_replace_recursive(
3445
-                $query_params[0],
3446
-                $this->caps_where_conditions(
3447
-                    $query_params['caps']
3448
-                )
3449
-            );
3450
-        }
3451
-
3452
-        // check if we should alter the query to remove data related to protected
3453
-        // custom post types
3454
-        if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3455
-            $where_param_key_for_password = $this->modelChainAndPassword();
3456
-            // only include if related to a cpt where no password has been set
3457
-            $query_params[0]['OR*nopassword'] = [
3458
-                $where_param_key_for_password       => '',
3459
-                $where_param_key_for_password . '*' => ['IS_NULL'],
3460
-            ];
3461
-        }
3462
-        $query_object = $this->_extract_related_models_from_query($query_params);
3463
-        // verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3464
-        foreach ($query_params[0] as $key => $value) {
3465
-            if (is_int($key)) {
3466
-                throw new EE_Error(
3467
-                    sprintf(
3468
-                        esc_html__(
3469
-                            "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.",
3470
-                            "event_espresso"
3471
-                        ),
3472
-                        $key,
3473
-                        var_export($value, true),
3474
-                        var_export($query_params, true),
3475
-                        get_class($this)
3476
-                    )
3477
-                );
3478
-            }
3479
-        }
3480
-        if (
3481
-            array_key_exists('default_where_conditions', $query_params)
3482
-            && ! empty($query_params['default_where_conditions'])
3483
-        ) {
3484
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3485
-        } else {
3486
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3487
-        }
3488
-        $query_params[0] = array_merge(
3489
-            $this->_get_default_where_conditions_for_models_in_query(
3490
-                $query_object,
3491
-                $use_default_where_conditions,
3492
-                $query_params[0]
3493
-            ),
3494
-            $query_params[0]
3495
-        );
3496
-        $query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3497
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3498
-        // So we need to setup a subquery and use that for the main join.
3499
-        // Note for now this only works on the primary table for the model.
3500
-        // So for instance, you could set the limit array like this:
3501
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3502
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3503
-            $query_object->set_main_model_join_sql(
3504
-                $this->_construct_limit_join_select(
3505
-                    $query_params['on_join_limit'][0],
3506
-                    $query_params['on_join_limit'][1]
3507
-                )
3508
-            );
3509
-        }
3510
-        // set limit
3511
-        if (array_key_exists('limit', $query_params)) {
3512
-            if (is_array($query_params['limit'])) {
3513
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3514
-                    $e = sprintf(
3515
-                        esc_html__(
3516
-                            "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)",
3517
-                            "event_espresso"
3518
-                        ),
3519
-                        http_build_query($query_params['limit'])
3520
-                    );
3521
-                    throw new EE_Error($e . "|" . $e);
3522
-                }
3523
-                // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3524
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3525
-            } elseif (! empty($query_params['limit'])) {
3526
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3527
-            }
3528
-        }
3529
-        // set order by
3530
-        if (array_key_exists('order_by', $query_params)) {
3531
-            if (is_array($query_params['order_by'])) {
3532
-                // if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3533
-                // specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3534
-                // including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3535
-                if (array_key_exists('order', $query_params)) {
3536
-                    throw new EE_Error(
3537
-                        sprintf(
3538
-                            esc_html__(
3539
-                                "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 ",
3540
-                                "event_espresso"
3541
-                            ),
3542
-                            get_class($this),
3543
-                            implode(", ", array_keys($query_params['order_by'])),
3544
-                            implode(", ", $query_params['order_by']),
3545
-                            $query_params['order']
3546
-                        )
3547
-                    );
3548
-                }
3549
-                $this->_extract_related_models_from_sub_params_array_keys(
3550
-                    $query_params['order_by'],
3551
-                    $query_object,
3552
-                    'order_by'
3553
-                );
3554
-                // assume it's an array of fields to order by
3555
-                $order_array = [];
3556
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3557
-                    $order         = $this->_extract_order($order);
3558
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3559
-                }
3560
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3561
-            } elseif (! empty($query_params['order_by'])) {
3562
-                $this->_extract_related_model_info_from_query_param(
3563
-                    $query_params['order_by'],
3564
-                    $query_object,
3565
-                    'order',
3566
-                    $query_params['order_by']
3567
-                );
3568
-                $order = isset($query_params['order'])
3569
-                    ? $this->_extract_order($query_params['order'])
3570
-                    : 'DESC';
3571
-                $query_object->set_order_by_sql(
3572
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3573
-                );
3574
-            }
3575
-        }
3576
-        // if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3577
-        if (
3578
-            ! array_key_exists('order_by', $query_params)
3579
-            && array_key_exists('order', $query_params)
3580
-            && ! empty($query_params['order'])
3581
-        ) {
3582
-            $pk_field = $this->get_primary_key_field();
3583
-            $order    = $this->_extract_order($query_params['order']);
3584
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3585
-        }
3586
-        // set group by
3587
-        if (array_key_exists('group_by', $query_params)) {
3588
-            if (is_array($query_params['group_by'])) {
3589
-                // it's an array, so assume we'll be grouping by a bunch of stuff
3590
-                $group_by_array = [];
3591
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3592
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3593
-                }
3594
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3595
-            } elseif (! empty($query_params['group_by'])) {
3596
-                $query_object->set_group_by_sql(
3597
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3598
-                );
3599
-            }
3600
-        }
3601
-        // set having
3602
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3603
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3604
-        }
3605
-        // now, just verify they didn't pass anything wack
3606
-        foreach ($query_params as $query_key => $query_value) {
3607
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3608
-                throw new EE_Error(
3609
-                    sprintf(
3610
-                        esc_html__(
3611
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3612
-                            'event_espresso'
3613
-                        ),
3614
-                        $query_key,
3615
-                        get_class($this),
3616
-                        //                      print_r( $this->_allowed_query_params, TRUE )
3617
-                        implode(',', $this->_allowed_query_params)
3618
-                    )
3619
-                );
3620
-            }
3621
-        }
3622
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3623
-        if (empty($main_model_join_sql)) {
3624
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3625
-        }
3626
-        return $query_object;
3627
-    }
3628
-
3629
-
3630
-    /**
3631
-     * Gets the where conditions that should be imposed on the query based on the
3632
-     * context (eg reading frontend, backend, edit or delete).
3633
-     *
3634
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3635
-     * @return array
3636
-     * @throws EE_Error
3637
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3638
-     */
3639
-    public function caps_where_conditions($context = self::caps_read)
3640
-    {
3641
-        EEM_Base::verify_is_valid_cap_context($context);
3642
-        $cap_where_conditions = [];
3643
-        $cap_restrictions     = $this->caps_missing($context);
3644
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3645
-            $cap_where_conditions = array_replace_recursive(
3646
-                $cap_where_conditions,
3647
-                $restriction_if_no_cap->get_default_where_conditions()
3648
-            );
3649
-        }
3650
-        return apply_filters(
3651
-            'FHEE__EEM_Base__caps_where_conditions__return',
3652
-            $cap_where_conditions,
3653
-            $this,
3654
-            $context,
3655
-            $cap_restrictions
3656
-        );
3657
-    }
3658
-
3659
-
3660
-    /**
3661
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3662
-     * otherwise throws an exception
3663
-     *
3664
-     * @param string $should_be_order_string
3665
-     * @return string either ASC, asc, DESC or desc
3666
-     * @throws EE_Error
3667
-     */
3668
-    private function _extract_order($should_be_order_string)
3669
-    {
3670
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3671
-            return $should_be_order_string;
3672
-        }
3673
-        throw new EE_Error(
3674
-            sprintf(
3675
-                esc_html__(
3676
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3677
-                    "event_espresso"
3678
-                ),
3679
-                get_class($this),
3680
-                $should_be_order_string
3681
-            )
3682
-        );
3683
-    }
3684
-
3685
-
3686
-    /**
3687
-     * Looks at all the models which are included in this query, and asks each
3688
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3689
-     * so they can be merged
3690
-     *
3691
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3692
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3693
-     *                                                                  'none' means NO default where conditions will
3694
-     *                                                                  be used AT ALL during this query.
3695
-     *                                                                  'other_models_only' means default where
3696
-     *                                                                  conditions from other models will be used, but
3697
-     *                                                                  not for this primary model. 'all', the default,
3698
-     *                                                                  means default where conditions will apply as
3699
-     *                                                                  normal
3700
-     * @param array                       $where_query_params
3701
-     * @return array
3702
-     * @throws EE_Error
3703
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3704
-     */
3705
-    private function _get_default_where_conditions_for_models_in_query(
3706
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3707
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3708
-        $where_query_params = []
3709
-    ) {
3710
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3711
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3712
-            throw new EE_Error(
3713
-                sprintf(
3714
-                    esc_html__(
3715
-                        "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3716
-                        "event_espresso"
3717
-                    ),
3718
-                    $use_default_where_conditions,
3719
-                    implode(", ", $allowed_used_default_where_conditions_values)
3720
-                )
3721
-            );
3722
-        }
3723
-        $universal_query_params = [];
3724
-        if ($this->_should_use_default_where_conditions($use_default_where_conditions)) {
3725
-            $universal_query_params = $this->_get_default_where_conditions();
3726
-        } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions)) {
3727
-            $universal_query_params = $this->_get_minimum_where_conditions();
3728
-        }
3729
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3730
-            $related_model = $this->get_related_model_obj($model_name);
3731
-            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3732
-                $related_model_universal_where_params =
3733
-                    $related_model->_get_default_where_conditions($model_relation_path);
3734
-            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3735
-                $related_model_universal_where_params =
3736
-                    $related_model->_get_minimum_where_conditions($model_relation_path);
3737
-            } else {
3738
-                // we don't want to add full or even minimum default where conditions from this model, so just continue
3739
-                continue;
3740
-            }
3741
-            $overrides              = $this->_override_defaults_or_make_null_friendly(
3742
-                $related_model_universal_where_params,
3743
-                $where_query_params,
3744
-                $related_model,
3745
-                $model_relation_path
3746
-            );
3747
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3748
-                $universal_query_params,
3749
-                $overrides
3750
-            );
3751
-        }
3752
-        return $universal_query_params;
3753
-    }
3754
-
3755
-
3756
-    /**
3757
-     * Determines whether or not we should use default where conditions for the model in question
3758
-     * (this model, or other related models).
3759
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3760
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3761
-     * We should use default where conditions on related models when they requested to use default where conditions
3762
-     * on all models, or specifically just on other related models
3763
-     *
3764
-     * @param      $default_where_conditions_value
3765
-     * @param bool $for_this_model false means this is for OTHER related models
3766
-     * @return bool
3767
-     */
3768
-    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3769
-    {
3770
-        return (
3771
-                   $for_this_model
3772
-                   && in_array(
3773
-                       $default_where_conditions_value,
3774
-                       [
3775
-                           EEM_Base::default_where_conditions_all,
3776
-                           EEM_Base::default_where_conditions_this_only,
3777
-                           EEM_Base::default_where_conditions_minimum_others,
3778
-                       ],
3779
-                       true
3780
-                   )
3781
-               )
3782
-               || (
3783
-                   ! $for_this_model
3784
-                   && in_array(
3785
-                       $default_where_conditions_value,
3786
-                       [
3787
-                           EEM_Base::default_where_conditions_all,
3788
-                           EEM_Base::default_where_conditions_others_only,
3789
-                       ],
3790
-                       true
3791
-                   )
3792
-               );
3793
-    }
3794
-
3795
-
3796
-    /**
3797
-     * Determines whether or not we should use default minimum conditions for the model in question
3798
-     * (this model, or other related models).
3799
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3800
-     * where conditions.
3801
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3802
-     * on this model or others
3803
-     *
3804
-     * @param      $default_where_conditions_value
3805
-     * @param bool $for_this_model false means this is for OTHER related models
3806
-     * @return bool
3807
-     */
3808
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3809
-    {
3810
-        return (
3811
-                   $for_this_model
3812
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3813
-               )
3814
-               || (
3815
-                   ! $for_this_model
3816
-                   && in_array(
3817
-                       $default_where_conditions_value,
3818
-                       [
3819
-                           EEM_Base::default_where_conditions_minimum_others,
3820
-                           EEM_Base::default_where_conditions_minimum_all,
3821
-                       ],
3822
-                       true
3823
-                   )
3824
-               );
3825
-    }
3826
-
3827
-
3828
-    /**
3829
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3830
-     * then we also add a special where condition which allows for that model's primary key
3831
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3832
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3833
-     *
3834
-     * @param array    $default_where_conditions
3835
-     * @param array    $provided_where_conditions
3836
-     * @param EEM_Base $model
3837
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3838
-     * @return array
3839
-     * @throws EE_Error
3840
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3841
-     */
3842
-    private function _override_defaults_or_make_null_friendly(
3843
-        $default_where_conditions,
3844
-        $provided_where_conditions,
3845
-        $model,
3846
-        $model_relation_path
3847
-    ) {
3848
-        $null_friendly_where_conditions = [];
3849
-        $none_overridden                = true;
3850
-        $or_condition_key_for_defaults  = 'OR*' . get_class($model);
3851
-        foreach ($default_where_conditions as $key => $val) {
3852
-            if (isset($provided_where_conditions[ $key ])) {
3853
-                $none_overridden = false;
3854
-            } else {
3855
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3856
-            }
3857
-        }
3858
-        if ($none_overridden && $default_where_conditions) {
3859
-            if ($model->has_primary_key_field()) {
3860
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3861
-                                                                                   . "."
3862
-                                                                                   . $model->primary_key_name() ] =
3863
-                    ['IS NULL'];
3864
-            }/*else{
40
+	/**
41
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
42
+	 */
43
+	const caps_read       = 'read';
44
+
45
+	const caps_read_admin = 'read_admin';
46
+
47
+	const caps_edit       = 'edit';
48
+
49
+	const caps_delete     = 'delete';
50
+
51
+
52
+	/**
53
+	 * constant used to show EEM_Base has not yet verified the db on this http request
54
+	 */
55
+	const db_verified_none = 0;
56
+
57
+	/**
58
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
59
+	 * but not the addons' dbs
60
+	 */
61
+	const db_verified_core = 1;
62
+
63
+	/**
64
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
65
+	 * the EE core db too)
66
+	 */
67
+	const db_verified_addons = 2;
68
+
69
+	/**
70
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
71
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
72
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
73
+	 */
74
+	const default_where_conditions_all = 'all';
75
+
76
+	/**
77
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
78
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
79
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
80
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
81
+	 *        models which share tables with other models, this can return data for the wrong model.
82
+	 */
83
+	const default_where_conditions_this_only = 'this_model_only';
84
+
85
+	/**
86
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
87
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
88
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
89
+	 */
90
+	const default_where_conditions_others_only = 'other_models_only';
91
+
92
+	/**
93
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
94
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
95
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
96
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
97
+	 *        (regardless of whether those events and venues are trashed)
98
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
99
+	 *        events.
100
+	 */
101
+	const default_where_conditions_minimum_all = 'minimum';
102
+
103
+	/**
104
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
105
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
106
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
107
+	 *        not)
108
+	 */
109
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
110
+
111
+	/**
112
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
113
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
114
+	 *        it's possible it will return table entries for other models. You should use
115
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
116
+	 */
117
+	const default_where_conditions_none = 'none';
118
+
119
+	/**
120
+	 * when $_values_already_prepared_by_model_object equals this, we assume
121
+	 * the data is just like form input that needs to have the model fields'
122
+	 * prepare_for_set and prepare_for_use_in_db called on it
123
+	 */
124
+	const not_prepared_by_model_object = 0;
125
+
126
+	/**
127
+	 * when $_values_already_prepared_by_model_object equals this, we
128
+	 * assume this value is coming from a model object and doesn't need to have
129
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
130
+	 */
131
+	const prepared_by_model_object = 1;
132
+
133
+	/**
134
+	 * when $_values_already_prepared_by_model_object equals this, we assume
135
+	 * the values are already to be used in the database (ie no processing is done
136
+	 * on them by the model's fields)
137
+	 */
138
+	const prepared_for_use_in_db = 2;
139
+
140
+	/**
141
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
142
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
143
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
144
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
145
+	 *
146
+	 * @var boolean
147
+	 */
148
+	private $_values_already_prepared_by_model_object = 0;
149
+
150
+
151
+	/**
152
+	 * @var string
153
+	 */
154
+	protected $singular_item = 'Item';
155
+
156
+	/**
157
+	 * @var string
158
+	 */
159
+	protected $plural_item = 'Items';
160
+
161
+	/**
162
+	 * array of EE_Table objects for defining which tables comprise this model.
163
+	 *
164
+	 * @type EE_Table_Base[] $_tables
165
+	 */
166
+	protected $_tables;
167
+
168
+	/**
169
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
170
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
171
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
172
+	 *
173
+	 * @var EE_Model_Field_Base[][] $_fields
174
+	 */
175
+	protected $_fields;
176
+
177
+	/**
178
+	 * array of different kinds of relations
179
+	 *
180
+	 * @var EE_Model_Relation_Base[] $_model_relations
181
+	 */
182
+	protected $_model_relations;
183
+
184
+	/**
185
+	 * @var EE_Index[] $_indexes
186
+	 */
187
+	protected $_indexes = [];
188
+
189
+	/**
190
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
191
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
192
+	 * by setting the same columns as used in these queries in the query yourself.
193
+	 *
194
+	 * @var EE_Default_Where_Conditions
195
+	 */
196
+	protected $_default_where_conditions_strategy;
197
+
198
+	/**
199
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
200
+	 * This is particularly useful when you want something between 'none' and 'default'
201
+	 *
202
+	 * @var EE_Default_Where_Conditions
203
+	 */
204
+	protected $_minimum_where_conditions_strategy;
205
+
206
+	/**
207
+	 * String describing how to find the "owner" of this model's objects.
208
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
209
+	 * But when there isn't, this indicates which related model, or transiently-related model,
210
+	 * has the foreign key to the wp_users table.
211
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
212
+	 * related to events, and events have a foreign key to wp_users.
213
+	 * On EEM_Transaction, this would be 'Transaction.Event'
214
+	 *
215
+	 * @var string
216
+	 */
217
+	protected $_model_chain_to_wp_user = '';
218
+
219
+	/**
220
+	 * String describing how to find the model with a password controlling access to this model. This property has the
221
+	 * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
222
+	 * This value is the path of models to follow to arrive at the model with the password field.
223
+	 * If it is an empty string, it means this model has the password field. If it is null, it means there is no
224
+	 * model with a password that should affect reading this on the front-end.
225
+	 * Eg this is an empty string for the Event model because it has a password.
226
+	 * This is null for the Registration model, because its event's password has no bearing on whether
227
+	 * you can read the registration or not on the front-end (it just depends on your capabilities.)
228
+	 * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
229
+	 * should hide tickets for datetimes for events that have a password set.
230
+	 *
231
+	 * @var string |null
232
+	 */
233
+	protected $model_chain_to_password = null;
234
+
235
+	/**
236
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
237
+	 * don't need it (particularly CPT models)
238
+	 *
239
+	 * @var bool
240
+	 */
241
+	protected $_ignore_where_strategy = false;
242
+
243
+	/**
244
+	 * String used in caps relating to this model. Eg, if the caps relating to this
245
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
246
+	 *
247
+	 * @var string. If null it hasn't been initialized yet. If false then we
248
+	 * have indicated capabilities don't apply to this
249
+	 */
250
+	protected $_caps_slug = null;
251
+
252
+	/**
253
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
254
+	 * and next-level keys are capability names, and values are a
255
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
256
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
257
+	 * and then each capability in the corresponding sub-array that they're missing
258
+	 * adds the where conditions onto the query.
259
+	 *
260
+	 * @var array
261
+	 */
262
+	protected $_cap_restrictions = [
263
+		self::caps_read       => [],
264
+		self::caps_read_admin => [],
265
+		self::caps_edit       => [],
266
+		self::caps_delete     => [],
267
+	];
268
+
269
+	/**
270
+	 * Array defining which cap restriction generators to use to create default
271
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
272
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
273
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
274
+	 * automatically set this to false (not just null).
275
+	 *
276
+	 * @var EE_Restriction_Generator_Base[]
277
+	 */
278
+	protected $_cap_restriction_generators = [];
279
+
280
+	/**
281
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
282
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
283
+	 * maps to 'read' because when looking for relevant permissions we're going to use
284
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
285
+	 *
286
+	 * @var array
287
+	 */
288
+	protected $_cap_contexts_to_cap_action_map = [
289
+		self::caps_read       => 'read',
290
+		self::caps_read_admin => 'read',
291
+		self::caps_edit       => 'edit',
292
+		self::caps_delete     => 'delete',
293
+	];
294
+
295
+	/**
296
+	 * Timezone
297
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
298
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
299
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
300
+	 * EE_Datetime_Field data type will have access to it.
301
+	 *
302
+	 * @var string
303
+	 */
304
+	protected $_timezone;
305
+
306
+
307
+	/**
308
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
309
+	 * multisite.
310
+	 *
311
+	 * @var int
312
+	 */
313
+	protected static $_model_query_blog_id;
314
+
315
+	/**
316
+	 * A copy of _fields, except the array keys are the model names pointed to by
317
+	 * the field
318
+	 *
319
+	 * @var EE_Model_Field_Base[]
320
+	 */
321
+	private $_cache_foreign_key_to_fields = [];
322
+
323
+	/**
324
+	 * Cached list of all the fields on the model, indexed by their name
325
+	 *
326
+	 * @var EE_Model_Field_Base[]
327
+	 */
328
+	private $_cached_fields = null;
329
+
330
+	/**
331
+	 * Cached list of all the fields on the model, except those that are
332
+	 * marked as only pertinent to the database
333
+	 *
334
+	 * @var EE_Model_Field_Base[]
335
+	 */
336
+	private $_cached_fields_non_db_only = null;
337
+
338
+	/**
339
+	 * A cached reference to the primary key for quick lookup
340
+	 *
341
+	 * @var EE_Model_Field_Base
342
+	 */
343
+	private $_primary_key_field = null;
344
+
345
+	/**
346
+	 * Flag indicating whether this model has a primary key or not
347
+	 *
348
+	 * @var boolean
349
+	 */
350
+	protected $_has_primary_key_field = null;
351
+
352
+	/**
353
+	 * array in the format:  [ FK alias => full PK ]
354
+	 * where keys are local column name aliases for foreign keys
355
+	 * and values are the fully qualified column name for the primary key they represent
356
+	 *  ex:
357
+	 *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
358
+	 *
359
+	 * @var array $foreign_key_aliases
360
+	 */
361
+	protected $foreign_key_aliases = [];
362
+
363
+	/**
364
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
365
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
366
+	 * This should be true for models that deal with data that should exist independent of EE.
367
+	 * For example, if the model can read and insert data that isn't used by EE, this should be true.
368
+	 * It would be false, however, if you could guarantee the model would only interact with EE data,
369
+	 * even if it uses a WP core table (eg event and venue models set this to false for that reason:
370
+	 * they can only read and insert events and venues custom post types, not arbitrary post types)
371
+	 *
372
+	 * @var boolean
373
+	 */
374
+	protected $_wp_core_model = false;
375
+
376
+	/**
377
+	 * @var bool stores whether this model has a password field or not.
378
+	 * null until initialized by hasPasswordField()
379
+	 */
380
+	protected $has_password_field;
381
+
382
+	/**
383
+	 * @var EE_Password_Field|null Automatically set when calling getPasswordField()
384
+	 */
385
+	protected $password_field;
386
+
387
+	/**
388
+	 *    List of valid operators that can be used for querying.
389
+	 * The keys are all operators we'll accept, the values are the real SQL
390
+	 * operators used
391
+	 *
392
+	 * @var array
393
+	 */
394
+	protected $_valid_operators = [
395
+		'='           => '=',
396
+		'<='          => '<=',
397
+		'<'           => '<',
398
+		'>='          => '>=',
399
+		'>'           => '>',
400
+		'!='          => '!=',
401
+		'LIKE'        => 'LIKE',
402
+		'like'        => 'LIKE',
403
+		'NOT_LIKE'    => 'NOT LIKE',
404
+		'not_like'    => 'NOT LIKE',
405
+		'NOT LIKE'    => 'NOT LIKE',
406
+		'not like'    => 'NOT LIKE',
407
+		'IN'          => 'IN',
408
+		'in'          => 'IN',
409
+		'NOT_IN'      => 'NOT IN',
410
+		'not_in'      => 'NOT IN',
411
+		'NOT IN'      => 'NOT IN',
412
+		'not in'      => 'NOT IN',
413
+		'between'     => 'BETWEEN',
414
+		'BETWEEN'     => 'BETWEEN',
415
+		'IS_NOT_NULL' => 'IS NOT NULL',
416
+		'is_not_null' => 'IS NOT NULL',
417
+		'IS NOT NULL' => 'IS NOT NULL',
418
+		'is not null' => 'IS NOT NULL',
419
+		'IS_NULL'     => 'IS NULL',
420
+		'is_null'     => 'IS NULL',
421
+		'IS NULL'     => 'IS NULL',
422
+		'is null'     => 'IS NULL',
423
+		'REGEXP'      => 'REGEXP',
424
+		'regexp'      => 'REGEXP',
425
+		'NOT_REGEXP'  => 'NOT REGEXP',
426
+		'not_regexp'  => 'NOT REGEXP',
427
+		'NOT REGEXP'  => 'NOT REGEXP',
428
+		'not regexp'  => 'NOT REGEXP',
429
+	];
430
+
431
+	/**
432
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
433
+	 *
434
+	 * @var array
435
+	 */
436
+	protected $_in_style_operators = ['IN', 'NOT IN'];
437
+
438
+	/**
439
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
440
+	 * '12-31-2012'"
441
+	 *
442
+	 * @var array
443
+	 */
444
+	protected $_between_style_operators = ['BETWEEN'];
445
+
446
+	/**
447
+	 * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
448
+	 *
449
+	 * @var array
450
+	 */
451
+	protected $_like_style_operators = ['LIKE', 'NOT LIKE'];
452
+
453
+	/**
454
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
455
+	 * on a join table.
456
+	 *
457
+	 * @var array
458
+	 */
459
+	protected $_null_style_operators = ['IS NOT NULL', 'IS NULL'];
460
+
461
+	/**
462
+	 * Allowed values for $query_params['order'] for ordering in queries
463
+	 *
464
+	 * @var array
465
+	 */
466
+	protected $_allowed_order_values = ['asc', 'desc', 'ASC', 'DESC'];
467
+
468
+	/**
469
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
470
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
471
+	 *
472
+	 * @var array
473
+	 */
474
+	private $_logic_query_param_keys = ['not', 'and', 'or', 'NOT', 'AND', 'OR'];
475
+
476
+	/**
477
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
478
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
479
+	 *
480
+	 * @var array
481
+	 */
482
+	private $_allowed_query_params = [
483
+		0,
484
+		'limit',
485
+		'order_by',
486
+		'group_by',
487
+		'having',
488
+		'force_join',
489
+		'order',
490
+		'on_join_limit',
491
+		'default_where_conditions',
492
+		'caps',
493
+		'extra_selects',
494
+		'exclude_protected',
495
+	];
496
+
497
+	/**
498
+	 * All the data types that can be used in $wpdb->prepare statements.
499
+	 *
500
+	 * @var array
501
+	 */
502
+	private $_valid_wpdb_data_types = ['%d', '%s', '%f'];
503
+
504
+	/**
505
+	 * @var EE_Registry $EE
506
+	 */
507
+	protected $EE = null;
508
+
509
+
510
+	/**
511
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
512
+	 *
513
+	 * @var int
514
+	 */
515
+	protected $_show_next_x_db_queries = 0;
516
+
517
+	/**
518
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
519
+	 * it gets saved on this property as an instance of CustomSelects so those selections can be used in
520
+	 * WHERE, GROUP_BY, etc.
521
+	 *
522
+	 * @var CustomSelects
523
+	 */
524
+	protected $_custom_selections = [];
525
+
526
+	/**
527
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
528
+	 * caches every model object we've fetched from the DB on this request
529
+	 *
530
+	 * @var array
531
+	 */
532
+	protected $_entity_map;
533
+
534
+	/**
535
+	 * @var LoaderInterface $loader
536
+	 */
537
+	private static $loader;
538
+
539
+	/**
540
+	 * indicates whether an EEM_Base child has already re-verified the DB
541
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
542
+	 * looking like EEM_Base::db_verified_*
543
+	 *
544
+	 * @var int - 0 = none, 1 = core, 2 = addons
545
+	 */
546
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
547
+
548
+
549
+	/**
550
+	 * About all child constructors:
551
+	 * they should define the _tables, _fields and _model_relations arrays.
552
+	 * Should ALWAYS be called after child constructor.
553
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
554
+	 * finalizes constructing all the object's attributes.
555
+	 * Generally, rather than requiring a child to code
556
+	 * $this->_tables = array(
557
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
558
+	 *        ...);
559
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
560
+	 * each EE_Table has a function to set the table's alias after the constructor, using
561
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
562
+	 * do something similar.
563
+	 *
564
+	 * @param string $timezone
565
+	 * @throws EE_Error
566
+	 */
567
+	protected function __construct($timezone = '')
568
+	{
569
+		// check that the model has not been loaded too soon
570
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
571
+			throw new EE_Error(
572
+				sprintf(
573
+					esc_html__(
574
+						'The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
575
+						'event_espresso'
576
+					),
577
+					get_class($this)
578
+				)
579
+			);
580
+		}
581
+		/**
582
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
583
+		 */
584
+		if (empty(EEM_Base::$_model_query_blog_id)) {
585
+			EEM_Base::set_model_query_blog_id();
586
+		}
587
+		/**
588
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
589
+		 * just use EE_Register_Model_Extension
590
+		 *
591
+		 * @var EE_Table_Base[] $_tables
592
+		 */
593
+		$this->_tables = (array)apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
594
+		foreach ($this->_tables as $table_alias => $table_obj) {
595
+			/** @var $table_obj EE_Table_Base */
596
+			$table_obj->_construct_finalize_with_alias($table_alias);
597
+			if ($table_obj instanceof EE_Secondary_Table) {
598
+				/** @var $table_obj EE_Secondary_Table */
599
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
600
+			}
601
+		}
602
+		/**
603
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
604
+		 * EE_Register_Model_Extension
605
+		 *
606
+		 * @param EE_Model_Field_Base[] $_fields
607
+		 */
608
+		$this->_fields = (array)apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
609
+		$this->_invalidate_field_caches();
610
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
611
+			if (! array_key_exists($table_alias, $this->_tables)) {
612
+				throw new EE_Error(
613
+					sprintf(
614
+						esc_html__(
615
+							"Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
616
+							'event_espresso'
617
+						),
618
+						$table_alias,
619
+						implode(",", $this->_fields)
620
+					)
621
+				);
622
+			}
623
+			foreach ($fields_for_table as $field_name => $field_obj) {
624
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
625
+				// primary key field base has a slightly different _construct_finalize
626
+				/** @var $field_obj EE_Model_Field_Base */
627
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
628
+			}
629
+		}
630
+		// everything is related to Extra_Meta
631
+		if (get_class($this) !== 'EEM_Extra_Meta') {
632
+			// make extra meta related to everything, but don't block deleting things just
633
+			// because they have related extra meta info. For now just orphan those extra meta
634
+			// in the future we should automatically delete them
635
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
636
+		}
637
+		// and change logs
638
+		if (get_class($this) !== 'EEM_Change_Log') {
639
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
640
+		}
641
+		/**
642
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
643
+		 * EE_Register_Model_Extension
644
+		 *
645
+		 * @param EE_Model_Relation_Base[] $_model_relations
646
+		 */
647
+		$this->_model_relations = (array)apply_filters(
648
+			'FHEE__' . get_class($this) . '__construct__model_relations',
649
+			$this->_model_relations
650
+		);
651
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
652
+			/** @var $relation_obj EE_Model_Relation_Base */
653
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
654
+		}
655
+		foreach ($this->_indexes as $index_name => $index_obj) {
656
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
657
+		}
658
+		$this->set_timezone($timezone);
659
+		// finalize default where condition strategy, or set default
660
+		if (! $this->_default_where_conditions_strategy) {
661
+			// nothing was set during child constructor, so set default
662
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
663
+		}
664
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
665
+		if (! $this->_minimum_where_conditions_strategy) {
666
+			// nothing was set during child constructor, so set default
667
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
668
+		}
669
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
670
+		// if the cap slug hasn't been set, and we haven't set it to false on purpose
671
+		// to indicate to NOT set it, set it to the logical default
672
+		if ($this->_caps_slug === null) {
673
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
674
+		}
675
+		// initialize the standard cap restriction generators if none were specified by the child constructor
676
+		if ($this->_cap_restriction_generators !== false) {
677
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
678
+				if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
679
+					$this->_cap_restriction_generators[ $cap_context ] = apply_filters(
680
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
681
+						new EE_Restriction_Generator_Protected(),
682
+						$cap_context,
683
+						$this
684
+					);
685
+				}
686
+			}
687
+		}
688
+		// if there are cap restriction generators, use them to make the default cap restrictions
689
+		if ($this->_cap_restriction_generators !== false) {
690
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
691
+				if (! $generator_object) {
692
+					continue;
693
+				}
694
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
695
+					throw new EE_Error(
696
+						sprintf(
697
+							esc_html__(
698
+								'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.',
699
+								'event_espresso'
700
+							),
701
+							$context,
702
+							$this->get_this_model_name()
703
+						)
704
+					);
705
+				}
706
+				$action = $this->cap_action_for_context($context);
707
+				if (! $generator_object->construction_finalized()) {
708
+					$generator_object->_construct_finalize($this, $action);
709
+				}
710
+			}
711
+		}
712
+		do_action('AHEE__' . get_class($this) . '__construct__end');
713
+	}
714
+
715
+
716
+	/**
717
+	 * Used to set the $_model_query_blog_id static property.
718
+	 *
719
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
720
+	 *                      value for get_current_blog_id() will be used.
721
+	 */
722
+	public static function set_model_query_blog_id($blog_id = 0)
723
+	{
724
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
725
+	}
726
+
727
+
728
+	/**
729
+	 * Returns whatever is set as the internal $model_query_blog_id.
730
+	 *
731
+	 * @return int
732
+	 */
733
+	public static function get_model_query_blog_id()
734
+	{
735
+		return EEM_Base::$_model_query_blog_id;
736
+	}
737
+
738
+
739
+	/**
740
+	 * This function is a singleton method used to instantiate the Espresso_model object
741
+	 *
742
+	 * @param string $timezone        string representing the timezone we want to set for returned Date Time Strings
743
+	 *                                (and any incoming timezone data that gets saved).
744
+	 *                                Note this just sends the timezone info to the date time model field objects.
745
+	 *                                Default is NULL
746
+	 *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
747
+	 * @return EEM_Base (as in the concrete child class)
748
+	 * @throws EE_Error
749
+	 * @throws InvalidArgumentException
750
+	 * @throws InvalidDataTypeException
751
+	 * @throws InvalidInterfaceException
752
+	 */
753
+	public static function instance($timezone = '')
754
+	{
755
+		// check if instance of Espresso_model already exists
756
+		if (! static::$_instance instanceof static) {
757
+			// instantiate Espresso_model
758
+			static::$_instance = new static(
759
+				$timezone,
760
+				LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
761
+			);
762
+		}
763
+		// Espresso model object
764
+		return static::$_instance;
765
+	}
766
+
767
+
768
+	/**
769
+	 * resets the model and returns it
770
+	 *
771
+	 * @param string $timezone
772
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
773
+	 * all its properties reset; if it wasn't instantiated, returns null)
774
+	 * @throws EE_Error
775
+	 * @throws ReflectionException
776
+	 * @throws InvalidArgumentException
777
+	 * @throws InvalidDataTypeException
778
+	 * @throws InvalidInterfaceException
779
+	 */
780
+	public static function reset($timezone = '')
781
+	{
782
+		if (static::$_instance instanceof EEM_Base) {
783
+			// let's try to NOT swap out the current instance for a new one
784
+			// because if someone has a reference to it, we can't remove their reference
785
+			// so it's best to keep using the same reference, but change the original object
786
+			// reset all its properties to their original values as defined in the class
787
+			$r                 = new ReflectionClass(get_class(static::$_instance));
788
+			$static_properties = $r->getStaticProperties();
789
+			foreach ($r->getDefaultProperties() as $property => $value) {
790
+				// don't set instance to null like it was originally,
791
+				// but it's static anyways, and we're ignoring static properties (for now at least)
792
+				if (! isset($static_properties[ $property ])) {
793
+					static::$_instance->{$property} = $value;
794
+				}
795
+			}
796
+			EEH_DTT_Helper::resetDefaultTimezoneString();
797
+			// and then directly call its constructor again, like we would if we were creating a new one
798
+			static::$_instance->__construct(
799
+				$timezone,
800
+				LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
801
+			);
802
+			return static::instance();
803
+		}
804
+		return null;
805
+	}
806
+
807
+
808
+	/**
809
+	 * @return LoaderInterface
810
+	 * @throws InvalidArgumentException
811
+	 * @throws InvalidDataTypeException
812
+	 * @throws InvalidInterfaceException
813
+	 */
814
+	private static function getLoader()
815
+	{
816
+		if (! EEM_Base::$loader instanceof LoaderInterface) {
817
+			EEM_Base::$loader = LoaderFactory::getLoader();
818
+		}
819
+		return EEM_Base::$loader;
820
+	}
821
+
822
+
823
+	/**
824
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
825
+	 *
826
+	 * @param boolean $translated return localized strings or JUST the array.
827
+	 * @return array
828
+	 * @throws EE_Error
829
+	 * @throws InvalidArgumentException
830
+	 * @throws InvalidDataTypeException
831
+	 * @throws InvalidInterfaceException
832
+	 * @throws ReflectionException
833
+	 */
834
+	public function status_array($translated = false)
835
+	{
836
+		if (! array_key_exists('Status', $this->_model_relations)) {
837
+			return [];
838
+		}
839
+		$model_name   = $this->get_this_model_name();
840
+		$status_type  = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
841
+		$stati        = EEM_Status::instance()->get_all([['STS_type' => $status_type]]);
842
+		$status_array = [];
843
+		foreach ($stati as $status) {
844
+			$status_array[ $status->ID() ] = $status->get('STS_code');
845
+		}
846
+		return $translated
847
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
848
+			: $status_array;
849
+	}
850
+
851
+
852
+	/**
853
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
854
+	 *
855
+	 * @param array $query_params             see github link below for more info
856
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
857
+	 *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object
858
+	 *                                        IDs (if there is a primary key on the model. if not, numerically indexed)
859
+	 *                                        Some full examples: get 10 transactions which have Scottish attendees:
860
+	 *                                        EEM_Transaction::instance()->get_all( array( array(
861
+	 *                                        'OR'=>array(
862
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
863
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
864
+	 *                                        )
865
+	 *                                        ),
866
+	 *                                        'limit'=>10,
867
+	 *                                        'group_by'=>'TXN_ID'
868
+	 *                                        ));
869
+	 *                                        get all the answers to the question titled "shirt size" for event with id
870
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
871
+	 *                                        'Question.QST_display_text'=>'shirt size',
872
+	 *                                        'Registration.Event.EVT_ID'=>12
873
+	 *                                        ),
874
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
875
+	 *                                        ));
876
+	 * @throws EE_Error
877
+	 * @throws ReflectionException
878
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
879
+	 *                                        or if you have the development copy of EE you can view this at the path:
880
+	 *                                        /docs/G--Model-System/model-query-params.md
881
+	 */
882
+	public function get_all($query_params = [])
883
+	{
884
+		if (
885
+			isset($query_params['limit'])
886
+			&& ! isset($query_params['group_by'])
887
+		) {
888
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
889
+		}
890
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params));
891
+	}
892
+
893
+
894
+	/**
895
+	 * Modifies the query parameters so we only get back model objects
896
+	 * that "belong" to the current user
897
+	 *
898
+	 * @param array $query_params see github link below for more info
899
+	 * @return array
900
+	 * @throws ReflectionException
901
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
902
+	 */
903
+	public function alter_query_params_to_only_include_mine($query_params = [])
904
+	{
905
+		$wp_user_field_name = $this->wp_user_field_name();
906
+		if ($wp_user_field_name) {
907
+			$query_params[0][ $wp_user_field_name ] = get_current_user_id();
908
+		}
909
+		return $query_params;
910
+	}
911
+
912
+
913
+	/**
914
+	 * Returns the name of the field's name that points to the WP_User table
915
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
916
+	 * foreign key to the WP_User table)
917
+	 *
918
+	 * @return string|boolean string on success, boolean false when there is no
919
+	 * foreign key to the WP_User table
920
+	 * @throws ReflectionException
921
+	 */
922
+	public function wp_user_field_name()
923
+	{
924
+		try {
925
+			if (! empty($this->_model_chain_to_wp_user)) {
926
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
927
+				$last_model_name              = end($models_to_follow_to_wp_users);
928
+				$model_with_fk_to_wp_users    = EE_Registry::instance()->load_model($last_model_name);
929
+				$model_chain_to_wp_user       = $this->_model_chain_to_wp_user . '.';
930
+			} else {
931
+				$model_with_fk_to_wp_users = $this;
932
+				$model_chain_to_wp_user    = '';
933
+			}
934
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
935
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
936
+		} catch (EE_Error $e) {
937
+			return false;
938
+		}
939
+	}
940
+
941
+
942
+	/**
943
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
944
+	 * (or transiently-related model) has a foreign key to the wp_users table;
945
+	 * useful for finding if model objects of this type are 'owned' by the current user.
946
+	 * This is an empty string when the foreign key is on this model and when it isn't,
947
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
948
+	 * (or transiently-related model)
949
+	 *
950
+	 * @return string
951
+	 */
952
+	public function model_chain_to_wp_user()
953
+	{
954
+		return $this->_model_chain_to_wp_user;
955
+	}
956
+
957
+
958
+	/**
959
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
960
+	 * like how registrations don't have a foreign key to wp_users, but the
961
+	 * events they are for are), or is unrelated to wp users.
962
+	 * generally available
963
+	 *
964
+	 * @return boolean
965
+	 */
966
+	public function is_owned()
967
+	{
968
+		if ($this->model_chain_to_wp_user()) {
969
+			return true;
970
+		}
971
+		try {
972
+			$this->get_foreign_key_to('WP_User');
973
+			return true;
974
+		} catch (EE_Error $e) {
975
+			return false;
976
+		}
977
+	}
978
+
979
+
980
+	/**
981
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
982
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
983
+	 * the model)
984
+	 *
985
+	 * @param array  $query_params
986
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
987
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
988
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
989
+	 *                                  override this and set the select to "*", or a specific column name, like
990
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
991
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
992
+	 *                                  the aliases used to refer to this selection, and values are to be
993
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
994
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
995
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
996
+	 * @throws EE_Error
997
+	 * @throws InvalidArgumentException
998
+	 * @throws ReflectionException
999
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1000
+	 */
1001
+	protected function _get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1002
+	{
1003
+		$this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
1004
+		$model_query_info         = $this->_create_model_query_info_carrier($query_params);
1005
+		$select_expressions       = $columns_to_select === null
1006
+			? $this->_construct_default_select_sql($model_query_info)
1007
+			: '';
1008
+		if ($this->_custom_selections instanceof CustomSelects) {
1009
+			$custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1010
+			$select_expressions .= $select_expressions
1011
+				? ', ' . $custom_expressions
1012
+				: $custom_expressions;
1013
+		}
1014
+
1015
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1016
+		return $this->_do_wpdb_query('get_results', [$SQL, $output]);
1017
+	}
1018
+
1019
+
1020
+	/**
1021
+	 * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1022
+	 * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1023
+	 * method of including extra select information.
1024
+	 *
1025
+	 * @param array             $query_params
1026
+	 * @param null|array|string $columns_to_select
1027
+	 * @return null|CustomSelects
1028
+	 * @throws InvalidArgumentException
1029
+	 */
1030
+	protected function getCustomSelection(array $query_params, $columns_to_select = null)
1031
+	{
1032
+		if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1033
+			return null;
1034
+		}
1035
+		$selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1036
+		$selects = is_string($selects) ? explode(',', $selects) : $selects;
1037
+		return new CustomSelects($selects);
1038
+	}
1039
+
1040
+
1041
+	/**
1042
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1043
+	 * but you can use the model query params to more easily
1044
+	 * take care of joins, field preparation etc.
1045
+	 *
1046
+	 * @param array  $query_params
1047
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1048
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1049
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1050
+	 *                                  override this and set the select to "*", or a specific column name, like
1051
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1052
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1053
+	 *                                  the aliases used to refer to this selection, and values are to be
1054
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1055
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1056
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1057
+	 * @throws EE_Error
1058
+	 * @throws ReflectionException
1059
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1060
+	 */
1061
+	public function get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1062
+	{
1063
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1064
+	}
1065
+
1066
+
1067
+	/**
1068
+	 * For creating a custom select statement
1069
+	 *
1070
+	 * @param array|string $columns_to_select either a string to be inserted directly as the select statement,
1071
+	 *                                        or an array where keys are aliases, and values are arrays where 0=>the
1072
+	 *                                        selection SQL, and 1=>is the datatype
1073
+	 * @return string
1074
+	 * @throws EE_Error
1075
+	 */
1076
+	private function _construct_select_from_input($columns_to_select)
1077
+	{
1078
+		if (is_array($columns_to_select)) {
1079
+			$select_sql_array = [];
1080
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1081
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1082
+					throw new EE_Error(
1083
+						sprintf(
1084
+							esc_html__(
1085
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1086
+								'event_espresso'
1087
+							),
1088
+							$selection_and_datatype,
1089
+							$alias
1090
+						)
1091
+					);
1092
+				}
1093
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1094
+					throw new EE_Error(
1095
+						sprintf(
1096
+							esc_html__(
1097
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1098
+								'event_espresso'
1099
+							),
1100
+							$selection_and_datatype[1],
1101
+							$selection_and_datatype[0],
1102
+							$alias,
1103
+							implode(', ', $this->_valid_wpdb_data_types)
1104
+						)
1105
+					);
1106
+				}
1107
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1108
+			}
1109
+			$columns_to_select_string = implode(', ', $select_sql_array);
1110
+		} else {
1111
+			$columns_to_select_string = $columns_to_select;
1112
+		}
1113
+		return $columns_to_select_string;
1114
+	}
1115
+
1116
+
1117
+	/**
1118
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1119
+	 *
1120
+	 * @return string
1121
+	 * @throws EE_Error
1122
+	 */
1123
+	public function primary_key_name()
1124
+	{
1125
+		return $this->get_primary_key_field()->get_name();
1126
+	}
1127
+
1128
+
1129
+	/**
1130
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1131
+	 * If there is no primary key on this model, $id is treated as primary key string
1132
+	 *
1133
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1134
+	 * @return EE_Base_Class
1135
+	 * @throws EE_Error
1136
+	 * @throws ReflectionException
1137
+	 */
1138
+	public function get_one_by_ID($id)
1139
+	{
1140
+		if ($this->get_from_entity_map($id)) {
1141
+			return $this->get_from_entity_map($id);
1142
+		}
1143
+		return $this->get_one(
1144
+			$this->alter_query_params_to_restrict_by_ID(
1145
+				$id,
1146
+				['default_where_conditions' => EEM_Base::default_where_conditions_minimum_all]
1147
+			)
1148
+		);
1149
+	}
1150
+
1151
+
1152
+	/**
1153
+	 * Alters query parameters to only get items with this ID are returned.
1154
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1155
+	 * or could just be a simple primary key ID
1156
+	 *
1157
+	 * @param int   $id
1158
+	 * @param array $query_params see github link below for more info
1159
+	 * @return array of normal query params,
1160
+	 * @throws EE_Error
1161
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1162
+	 */
1163
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = [])
1164
+	{
1165
+		if (! isset($query_params[0])) {
1166
+			$query_params[0] = [];
1167
+		}
1168
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1169
+		if ($conditions_from_id === null) {
1170
+			$query_params[0][ $this->primary_key_name() ] = $id;
1171
+		} else {
1172
+			// no primary key, so the $id must be from the get_index_primary_key_string()
1173
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1174
+		}
1175
+		return $query_params;
1176
+	}
1177
+
1178
+
1179
+	/**
1180
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1181
+	 * array. If no item is found, null is returned.
1182
+	 *
1183
+	 * @param array $query_params like EEM_Base's $query_params variable.
1184
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1185
+	 * @throws EE_Error
1186
+	 * @throws ReflectionException
1187
+	 */
1188
+	public function get_one($query_params = [])
1189
+	{
1190
+		if (! is_array($query_params)) {
1191
+			EE_Error::doing_it_wrong(
1192
+				'EEM_Base::get_one',
1193
+				sprintf(
1194
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1195
+					gettype($query_params)
1196
+				),
1197
+				'4.6.0'
1198
+			);
1199
+			$query_params = [];
1200
+		}
1201
+		$query_params['limit'] = 1;
1202
+		$items                 = $this->get_all($query_params);
1203
+		if (empty($items)) {
1204
+			return null;
1205
+		}
1206
+		return array_shift($items);
1207
+	}
1208
+
1209
+
1210
+	/**
1211
+	 * Returns the next x number of items in sequence from the given value as
1212
+	 * found in the database matching the given query conditions.
1213
+	 *
1214
+	 * @param mixed $current_field_value    Value used for the reference point.
1215
+	 * @param null  $field_to_order_by      What field is used for the
1216
+	 *                                      reference point.
1217
+	 * @param int   $limit                  How many to return.
1218
+	 * @param array $query_params           Extra conditions on the query.
1219
+	 * @param null  $columns_to_select      If left null, then an array of
1220
+	 *                                      EE_Base_Class objects is returned,
1221
+	 *                                      otherwise you can indicate just the
1222
+	 *                                      columns you want returned.
1223
+	 * @return EE_Base_Class[]|array
1224
+	 * @throws EE_Error
1225
+	 * @throws ReflectionException
1226
+	 */
1227
+	public function next_x(
1228
+		$current_field_value,
1229
+		$field_to_order_by = null,
1230
+		$limit = 1,
1231
+		$query_params = [],
1232
+		$columns_to_select = null
1233
+	) {
1234
+		return $this->_get_consecutive(
1235
+			$current_field_value,
1236
+			'>',
1237
+			$field_to_order_by,
1238
+			$limit,
1239
+			$query_params,
1240
+			$columns_to_select
1241
+		);
1242
+	}
1243
+
1244
+
1245
+	/**
1246
+	 * Returns the previous x number of items in sequence from the given value
1247
+	 * as found in the database matching the given query conditions.
1248
+	 *
1249
+	 * @param mixed $current_field_value    Value used for the reference point.
1250
+	 * @param null  $field_to_order_by      What field is used for the
1251
+	 *                                      reference point.
1252
+	 * @param int   $limit                  How many to return.
1253
+	 * @param array $query_params           Extra conditions on the query.
1254
+	 * @param null  $columns_to_select      If left null, then an array of
1255
+	 *                                      EE_Base_Class objects is returned,
1256
+	 *                                      otherwise you can indicate just the
1257
+	 *                                      columns you want returned.
1258
+	 * @return EE_Base_Class[]|array
1259
+	 * @throws EE_Error
1260
+	 * @throws ReflectionException
1261
+	 */
1262
+	public function previous_x(
1263
+		$current_field_value,
1264
+		$field_to_order_by = null,
1265
+		$limit = 1,
1266
+		$query_params = [],
1267
+		$columns_to_select = null
1268
+	) {
1269
+		return $this->_get_consecutive(
1270
+			$current_field_value,
1271
+			'<',
1272
+			$field_to_order_by,
1273
+			$limit,
1274
+			$query_params,
1275
+			$columns_to_select
1276
+		);
1277
+	}
1278
+
1279
+
1280
+	/**
1281
+	 * Returns the next item in sequence from the given value as found in the
1282
+	 * database matching the given query conditions.
1283
+	 *
1284
+	 * @param mixed $current_field_value    Value used for the reference point.
1285
+	 * @param null  $field_to_order_by      What field is used for the
1286
+	 *                                      reference point.
1287
+	 * @param array $query_params           Extra conditions on the query.
1288
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1289
+	 *                                      object is returned, otherwise you
1290
+	 *                                      can indicate just the columns you
1291
+	 *                                      want and a single array indexed by
1292
+	 *                                      the columns will be returned.
1293
+	 * @return EE_Base_Class|null|array()
1294
+	 * @throws EE_Error
1295
+	 * @throws ReflectionException
1296
+	 */
1297
+	public function next(
1298
+		$current_field_value,
1299
+		$field_to_order_by = null,
1300
+		$query_params = [],
1301
+		$columns_to_select = null
1302
+	) {
1303
+		$results = $this->_get_consecutive(
1304
+			$current_field_value,
1305
+			'>',
1306
+			$field_to_order_by,
1307
+			1,
1308
+			$query_params,
1309
+			$columns_to_select
1310
+		);
1311
+		return empty($results) ? null : reset($results);
1312
+	}
1313
+
1314
+
1315
+	/**
1316
+	 * Returns the previous item in sequence from the given value as found in
1317
+	 * the database matching the given query conditions.
1318
+	 *
1319
+	 * @param mixed $current_field_value    Value used for the reference point.
1320
+	 * @param null  $field_to_order_by      What field is used for the
1321
+	 *                                      reference point.
1322
+	 * @param array $query_params           Extra conditions on the query.
1323
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1324
+	 *                                      object is returned, otherwise you
1325
+	 *                                      can indicate just the columns you
1326
+	 *                                      want and a single array indexed by
1327
+	 *                                      the columns will be returned.
1328
+	 * @return EE_Base_Class|null|array()
1329
+	 * @throws EE_Error
1330
+	 * @throws ReflectionException
1331
+	 */
1332
+	public function previous(
1333
+		$current_field_value,
1334
+		$field_to_order_by = null,
1335
+		$query_params = [],
1336
+		$columns_to_select = null
1337
+	) {
1338
+		$results = $this->_get_consecutive(
1339
+			$current_field_value,
1340
+			'<',
1341
+			$field_to_order_by,
1342
+			1,
1343
+			$query_params,
1344
+			$columns_to_select
1345
+		);
1346
+		return empty($results) ? null : reset($results);
1347
+	}
1348
+
1349
+
1350
+	/**
1351
+	 * Returns the a consecutive number of items in sequence from the given
1352
+	 * value as found in the database matching the given query conditions.
1353
+	 *
1354
+	 * @param mixed  $current_field_value   Value used for the reference point.
1355
+	 * @param string $operand               What operand is used for the sequence.
1356
+	 * @param string $field_to_order_by     What field is used for the reference point.
1357
+	 * @param int    $limit                 How many to return.
1358
+	 * @param array  $query_params          Extra conditions on the query.
1359
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1360
+	 *                                      otherwise you can indicate just the columns you want returned.
1361
+	 * @return EE_Base_Class[]|array
1362
+	 * @throws EE_Error
1363
+	 * @throws ReflectionException
1364
+	 */
1365
+	protected function _get_consecutive(
1366
+		$current_field_value,
1367
+		$operand = '>',
1368
+		$field_to_order_by = null,
1369
+		$limit = 1,
1370
+		$query_params = [],
1371
+		$columns_to_select = null
1372
+	) {
1373
+		// if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1374
+		if (empty($field_to_order_by)) {
1375
+			if ($this->has_primary_key_field()) {
1376
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1377
+			} else {
1378
+				if (WP_DEBUG) {
1379
+					throw new EE_Error(
1380
+						esc_html__(
1381
+							'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).',
1382
+							'event_espresso'
1383
+						)
1384
+					);
1385
+				}
1386
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1387
+				return [];
1388
+			}
1389
+		}
1390
+		if (! is_array($query_params)) {
1391
+			EE_Error::doing_it_wrong(
1392
+				'EEM_Base::_get_consecutive',
1393
+				sprintf(
1394
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1395
+					gettype($query_params)
1396
+				),
1397
+				'4.6.0'
1398
+			);
1399
+			$query_params = [];
1400
+		}
1401
+		// let's add the where query param for consecutive look up.
1402
+		$query_params[0][ $field_to_order_by ] = [$operand, $current_field_value];
1403
+		$query_params['limit']                 = $limit;
1404
+		// set direction
1405
+		$incoming_orderby         = isset($query_params['order_by']) ? (array)$query_params['order_by'] : [];
1406
+		$query_params['order_by'] = $operand === '>'
1407
+			? [$field_to_order_by => 'ASC'] + $incoming_orderby
1408
+			: [$field_to_order_by => 'DESC'] + $incoming_orderby;
1409
+		// if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1410
+		if (empty($columns_to_select)) {
1411
+			return $this->get_all($query_params);
1412
+		}
1413
+		// getting just the fields
1414
+		return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1415
+	}
1416
+
1417
+
1418
+	/**
1419
+	 * This sets the _timezone property after model object has been instantiated.
1420
+	 *
1421
+	 * @param string|null $timezone valid PHP DateTimeZone timezone string
1422
+	 */
1423
+	public function set_timezone($timezone = '')
1424
+	{
1425
+		static $set_in_progress = false;
1426
+		// if incoming timezone string is empty, then use the existing
1427
+		$valid_timezone = ! empty($timezone) && $timezone !== $this->_timezone
1428
+			? EEH_DTT_Helper::get_valid_timezone_string($timezone)
1429
+			: $this->_timezone;
1430
+		// do NOT set the timezone if we are already in the process of setting the timezone
1431
+		// OR the existing timezone is already set and the incoming value is nothing (which gets set to default TZ)
1432
+		// OR the existing timezone is already set and the validated value is the same as the existing timezone
1433
+		if (
1434
+			$set_in_progress
1435
+			|| (
1436
+				! empty($this->_timezone)
1437
+				&& (
1438
+					empty($timezone) || $valid_timezone === $this->_timezone
1439
+				)
1440
+			)
1441
+		) {
1442
+			return;
1443
+		}
1444
+		$set_in_progress = true;
1445
+		$this->_timezone = $valid_timezone ? $valid_timezone : EEH_DTT_Helper::get_valid_timezone_string();
1446
+		// note we need to loop through relations and set the timezone on those objects as well.
1447
+		foreach ($this->_model_relations as $relation) {
1448
+			$relation->set_timezone($this->_timezone);
1449
+		}
1450
+		// and finally we do the same for any datetime fields
1451
+		foreach ($this->_fields as $field) {
1452
+			if ($field instanceof EE_Datetime_Field) {
1453
+				$field->set_timezone($this->_timezone);
1454
+			}
1455
+		}
1456
+		$set_in_progress = false;
1457
+	}
1458
+
1459
+
1460
+	/**
1461
+	 * This just returns whatever is set for the current timezone.
1462
+	 *
1463
+	 * @access public
1464
+	 * @return string
1465
+	 */
1466
+	public function get_timezone()
1467
+	{
1468
+		if (empty($this->_timezone)) {
1469
+			$this->set_timezone();
1470
+		}
1471
+		return $this->_timezone;
1472
+	}
1473
+
1474
+
1475
+	/**
1476
+	 * This returns the date formats set for the given field name and also ensures that
1477
+	 * $this->_timezone property is set correctly.
1478
+	 *
1479
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1480
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1481
+	 * @return array formats in an array with the date format first, and the time format last.
1482
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1483
+	 * @since 4.6.x
1484
+	 */
1485
+	public function get_formats_for($field_name, $pretty = false)
1486
+	{
1487
+		$field_settings = $this->field_settings_for($field_name);
1488
+		// if not a valid EE_Datetime_Field then throw error
1489
+		if (! $field_settings instanceof EE_Datetime_Field) {
1490
+			throw new EE_Error(
1491
+				sprintf(
1492
+					esc_html__(
1493
+						'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.',
1494
+						'event_espresso'
1495
+					),
1496
+					$field_name
1497
+				)
1498
+			);
1499
+		}
1500
+		// while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on the field.
1501
+		$field_timezone = $field_settings->get_timezone();
1502
+		if (empty($this->_timezone && $field_timezone)) {
1503
+			$this->set_timezone();
1504
+		} else {
1505
+			// or vice versa if the field TZ isn't set
1506
+			$model_timezone = $this->get_timezone();
1507
+			$field_settings->set_timezone($model_timezone);
1508
+		}
1509
+
1510
+		return [$field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty)];
1511
+	}
1512
+
1513
+
1514
+	/**
1515
+	 * This returns the current time in a format setup for a query on this model.
1516
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1517
+	 * it will return:
1518
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1519
+	 *  NOW
1520
+	 *  - or a unix timestamp (equivalent to time())
1521
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1522
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1523
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1524
+	 *
1525
+	 * @param string $field_name       The field the current time is needed for.
1526
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1527
+	 *                                 formatted string matching the set format for the field in the set timezone will
1528
+	 *                                 be returned.
1529
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1530
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1531
+	 *                                 exception is triggered.
1532
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1533
+	 * @throws Exception
1534
+	 * @since 4.6.x
1535
+	 */
1536
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1537
+	{
1538
+		$formats  = $this->get_formats_for($field_name);
1539
+		$DateTime = new DateTime("now", new DateTimeZone($this->get_timezone()));
1540
+		if ($timestamp) {
1541
+			return $DateTime->format('U');
1542
+		}
1543
+		// not returning timestamp, so return formatted string in timezone.
1544
+		switch ($what) {
1545
+			case 'time':
1546
+				return $DateTime->format($formats[1]);
1547
+			case 'date':
1548
+				return $DateTime->format($formats[0]);
1549
+			default:
1550
+				return $DateTime->format(implode(' ', $formats));
1551
+		}
1552
+	}
1553
+
1554
+
1555
+	/**
1556
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1557
+	 * for the model are.  Returns a DateTime object.
1558
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1559
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1560
+	 * ignored.
1561
+	 *
1562
+	 * @param string $field_name    The field being setup.
1563
+	 * @param string $timestring    The date time string being used.
1564
+	 * @param string $format        The format for the time string.
1565
+	 * @param string $timezone      By default, it is assumed the incoming time string is in timezone for
1566
+	 *                              the blog.  If this is not the case, then it can be specified here.
1567
+	 *                              If incoming format is 'U', this is ignored.
1568
+	 * @return DbSafeDateTime
1569
+	 * @throws EE_Error
1570
+	 * @throws Exception
1571
+	 */
1572
+	public function convert_datetime_for_query($field_name, $timestring, $format, $timezone = '')
1573
+	{
1574
+		// just using this to ensure the timezone is set correctly internally
1575
+		$this->get_formats_for($field_name);
1576
+		$timezone         = ! empty($timezone) ? $timezone : EEH_DTT_Helper::get_timezone();
1577
+		$db_safe_datetime = DbSafeDateTime::createFromFormat($format, $timestring, new DateTimeZone($timezone));
1578
+		EEH_DTT_Helper::setTimezone($db_safe_datetime, new DateTimeZone($this->get_timezone()));
1579
+		return $db_safe_datetime;
1580
+	}
1581
+
1582
+
1583
+	/**
1584
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1585
+	 *
1586
+	 * @return EE_Table_Base[]
1587
+	 */
1588
+	public function get_tables()
1589
+	{
1590
+		return $this->_tables;
1591
+	}
1592
+
1593
+
1594
+	/**
1595
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1596
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1597
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1598
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1599
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1600
+	 * model object with EVT_ID = 1
1601
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1602
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1603
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1604
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1605
+	 * are not specified)
1606
+	 *
1607
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1608
+	 *                                         columns!), values are strings, integers, floats, and maybe arrays if
1609
+	 *                                         they
1610
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1611
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1612
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1613
+	 *                                         ID=34, we'd use this method as follows:
1614
+	 *                                         EEM_Transaction::instance()->update(
1615
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1616
+	 *                                         array(array('TXN_ID'=>34)));
1617
+	 * @param array   $query_params            Eg, consider updating Question's QST_admin_label field is of type
1618
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1619
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1620
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1621
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1622
+	 *                                         TRUE, it is assumed that you've already called
1623
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1624
+	 *                                         malicious javascript. However, if
1625
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1626
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1627
+	 *                                         and every other field, before insertion. We provide this parameter
1628
+	 *                                         because model objects perform their prepare_for_set function on all
1629
+	 *                                         their values, and so don't need to be called again (and in many cases,
1630
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1631
+	 *                                         prepare_for_set method...)
1632
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1633
+	 *                                         in this model's entity map according to $fields_n_values that match
1634
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1635
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1636
+	 *                                         could get out-of-sync with the database
1637
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1638
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1639
+	 *                                         bad)
1640
+	 * @throws EE_Error
1641
+	 * @throws ReflectionException
1642
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1643
+	 */
1644
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1645
+	{
1646
+		if (! is_array($query_params)) {
1647
+			EE_Error::doing_it_wrong(
1648
+				'EEM_Base::update',
1649
+				sprintf(
1650
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1651
+					gettype($query_params)
1652
+				),
1653
+				'4.6.0'
1654
+			);
1655
+			$query_params = [];
1656
+		}
1657
+		/**
1658
+		 * Action called before a model update call has been made.
1659
+		 *
1660
+		 * @param EEM_Base $model
1661
+		 * @param array    $fields_n_values the updated fields and their new values
1662
+		 * @param array    $query_params
1663
+		 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1664
+		 */
1665
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1666
+		/**
1667
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1668
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1669
+		 *
1670
+		 * @param array    $fields_n_values fields and their new values
1671
+		 * @param EEM_Base $model           the model being queried
1672
+		 * @param array    $query_params
1673
+		 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1674
+		 */
1675
+		$fields_n_values = (array)apply_filters(
1676
+			'FHEE__EEM_Base__update__fields_n_values',
1677
+			$fields_n_values,
1678
+			$this,
1679
+			$query_params
1680
+		);
1681
+		// need to verify that, for any entry we want to update, there are entries in each secondary table.
1682
+		// to do that, for each table, verify that it's PK isn't null.
1683
+		$tables = $this->get_tables();
1684
+		// 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
1685
+		// NOTE: we should make this code more efficient by NOT querying twice
1686
+		// before the real update, but that needs to first go through ALPHA testing
1687
+		// as it's dangerous. says Mike August 8 2014
1688
+		// we want to make sure the default_where strategy is ignored
1689
+		$this->_ignore_where_strategy = true;
1690
+		$wpdb_select_results          = $this->_get_all_wpdb_results($query_params);
1691
+		foreach ($wpdb_select_results as $wpdb_result) {
1692
+			// type cast stdClass as array
1693
+			$wpdb_result = (array)$wpdb_result;
1694
+			// get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1695
+			if ($this->has_primary_key_field()) {
1696
+				$main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1697
+			} else {
1698
+				// 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)
1699
+				$main_table_pk_value = null;
1700
+			}
1701
+			// 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
1702
+			// 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
1703
+			if (count($tables) > 1) {
1704
+				// foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1705
+				// in that table, and so we'll want to insert one
1706
+				foreach ($tables as $table_obj) {
1707
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1708
+					// if there is no private key for this table on the results, it means there's no entry
1709
+					// in this table, right? so insert a row in the current table, using any fields available
1710
+					if (
1711
+					! (array_key_exists($this_table_pk_column, $wpdb_result)
1712
+					   && $wpdb_result[ $this_table_pk_column ])
1713
+					) {
1714
+						$success = $this->_insert_into_specific_table(
1715
+							$table_obj,
1716
+							$fields_n_values,
1717
+							$main_table_pk_value
1718
+						);
1719
+						// if we died here, report the error
1720
+						if (! $success) {
1721
+							return false;
1722
+						}
1723
+					}
1724
+				}
1725
+			}
1726
+			// let's make sure default_where strategy is followed now
1727
+			$this->_ignore_where_strategy = false;
1728
+		}
1729
+		// if we want to keep model objects in sync, AND
1730
+		// if this wasn't called from a model object (to update itself)
1731
+		// then we want to make sure we keep all the existing
1732
+		// model objects in sync with the db
1733
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1734
+			if ($this->has_primary_key_field()) {
1735
+				$model_objs_affected_ids = $this->get_col($query_params);
1736
+			} else {
1737
+				// we need to select a bunch of columns and then combine them into the the "index primary key string"s
1738
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params);
1739
+				$model_objs_affected_ids     = [];
1740
+				foreach ($models_affected_key_columns as $row) {
1741
+					$combined_index_key                             = $this->get_index_primary_key_string($row);
1742
+					$model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1743
+				}
1744
+			}
1745
+			if (! $model_objs_affected_ids) {
1746
+				// wait wait wait- if nothing was affected let's stop here
1747
+				return 0;
1748
+			}
1749
+			foreach ($model_objs_affected_ids as $id) {
1750
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1751
+				if ($model_obj_in_entity_map) {
1752
+					foreach ($fields_n_values as $field => $new_value) {
1753
+						$model_obj_in_entity_map->set($field, $new_value);
1754
+					}
1755
+				}
1756
+			}
1757
+			// if there is a primary key on this model, we can now do a slight optimization
1758
+			if ($this->has_primary_key_field()) {
1759
+				// we already know what we want to update. So let's make the query simpler so it's a little more efficient
1760
+				$query_params = [
1761
+					[$this->primary_key_name() => ['IN', $model_objs_affected_ids]],
1762
+					'limit'                    => count($model_objs_affected_ids),
1763
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1764
+				];
1765
+			}
1766
+		}
1767
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1768
+		$SQL              = "UPDATE " . $model_query_info->get_full_join_sql()
1769
+							. " SET " . $this->_construct_update_sql($fields_n_values)
1770
+							. $model_query_info->get_where_sql();
1771
+		// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1772
+		$rows_affected    = $this->_do_wpdb_query('query', [$SQL]);
1773
+		/**
1774
+		 * Action called after a model update call has been made.
1775
+		 *
1776
+		 * @param EEM_Base $model
1777
+		 * @param array    $fields_n_values the updated fields and their new values
1778
+		 * @param array    $query_params
1779
+		 * @param int      $rows_affected
1780
+		 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1781
+		 */
1782
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1783
+		return $rows_affected;// how many supposedly got updated
1784
+	}
1785
+
1786
+
1787
+	/**
1788
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1789
+	 * are teh values of the field specified (or by default the primary key field)
1790
+	 * that matched the query params. Note that you should pass the name of the
1791
+	 * model FIELD, not the database table's column name.
1792
+	 *
1793
+	 * @param array  $query_params
1794
+	 * @param string $field_to_select
1795
+	 * @return array just like $wpdb->get_col()
1796
+	 * @throws EE_Error
1797
+	 * @throws ReflectionException
1798
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1799
+	 */
1800
+	public function get_col($query_params = [], $field_to_select = null)
1801
+	{
1802
+		if ($field_to_select) {
1803
+			$field = $this->field_settings_for($field_to_select);
1804
+		} elseif ($this->has_primary_key_field()) {
1805
+			$field = $this->get_primary_key_field();
1806
+		} else {
1807
+			$field_settings = $this->field_settings();
1808
+			// no primary key, just grab the first column
1809
+			$field = reset($field_settings);
1810
+		}
1811
+		$model_query_info   = $this->_create_model_query_info_carrier($query_params);
1812
+		$select_expressions = $field->get_qualified_column();
1813
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1814
+		return $this->_do_wpdb_query('get_col', [$SQL]);
1815
+	}
1816
+
1817
+
1818
+	/**
1819
+	 * Returns a single column value for a single row from the database
1820
+	 *
1821
+	 * @param array  $query_params
1822
+	 * @param string $field_to_select
1823
+	 * @return string
1824
+	 * @throws EE_Error
1825
+	 * @throws ReflectionException
1826
+	 * @see EEM_Base::get_col()
1827
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1828
+	 */
1829
+	public function get_var($query_params = [], $field_to_select = null)
1830
+	{
1831
+		$query_params['limit'] = 1;
1832
+		$col                   = $this->get_col($query_params, $field_to_select);
1833
+		if (! empty($col)) {
1834
+			return reset($col);
1835
+		}
1836
+		return null;
1837
+	}
1838
+
1839
+
1840
+	/**
1841
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1842
+	 * time?', Question.desc='what do you think?'..." Values are filtered through wpdb->prepare to avoid against SQL
1843
+	 * injection, but currently no further filtering is done
1844
+	 *
1845
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1846
+	 *                               be updated to in the DB
1847
+	 * @return string of SQL
1848
+	 * @throws EE_Error
1849
+	 * @global      $wpdb
1850
+	 */
1851
+	public function _construct_update_sql($fields_n_values)
1852
+	{
1853
+		global $wpdb;
1854
+		$cols_n_values = [];
1855
+		foreach ($fields_n_values as $field_name => $value) {
1856
+			$field_obj = $this->field_settings_for($field_name);
1857
+			// if the value is NULL, we want to assign the value to that.
1858
+			// wpdb->prepare doesn't really handle that properly
1859
+			$prepared_value  = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1860
+			$value_sql       = $prepared_value === null
1861
+				? 'NULL'
1862
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1863
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1864
+		}
1865
+		return implode(",", $cols_n_values);
1866
+	}
1867
+
1868
+
1869
+	/**
1870
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1871
+	 * Performs a HARD delete, meaning the database row should always be removed,
1872
+	 * not just have a flag field on it switched
1873
+	 * Wrapper for EEM_Base::delete_permanently()
1874
+	 *
1875
+	 * @param mixed   $id
1876
+	 * @param boolean $allow_blocking
1877
+	 * @return int the number of rows deleted
1878
+	 * @throws EE_Error
1879
+	 * @throws ReflectionException
1880
+	 */
1881
+	public function delete_permanently_by_ID($id, $allow_blocking = true)
1882
+	{
1883
+		return $this->delete_permanently(
1884
+			[
1885
+				[$this->get_primary_key_field()->get_name() => $id],
1886
+				'limit' => 1,
1887
+			],
1888
+			$allow_blocking
1889
+		);
1890
+	}
1891
+
1892
+
1893
+	/**
1894
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1895
+	 * Wrapper for EEM_Base::delete()
1896
+	 *
1897
+	 * @param mixed   $id
1898
+	 * @param boolean $allow_blocking
1899
+	 * @return int the number of rows deleted
1900
+	 * @throws EE_Error
1901
+	 * @throws ReflectionException
1902
+	 */
1903
+	public function delete_by_ID($id, $allow_blocking = true)
1904
+	{
1905
+		return $this->delete(
1906
+			[
1907
+				[$this->get_primary_key_field()->get_name() => $id],
1908
+				'limit' => 1,
1909
+			],
1910
+			$allow_blocking
1911
+		);
1912
+	}
1913
+
1914
+
1915
+	/**
1916
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1917
+	 * meaning if the model has a field that indicates its been "trashed" or
1918
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1919
+	 *
1920
+	 * @param array   $query_params
1921
+	 * @param boolean $allow_blocking
1922
+	 * @return int how many rows got deleted
1923
+	 * @throws EE_Error
1924
+	 * @throws ReflectionException
1925
+	 * @see EEM_Base::delete_permanently
1926
+	 */
1927
+	public function delete($query_params, $allow_blocking = true)
1928
+	{
1929
+		return $this->delete_permanently($query_params, $allow_blocking);
1930
+	}
1931
+
1932
+
1933
+	/**
1934
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1935
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1936
+	 * as archived, not actually deleted
1937
+	 *
1938
+	 * @param array   $query_params
1939
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1940
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1941
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1942
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1943
+	 *                                DB
1944
+	 * @return int how many rows got deleted
1945
+	 * @throws EE_Error
1946
+	 * @throws ReflectionException
1947
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1948
+	 */
1949
+	public function delete_permanently($query_params, $allow_blocking = true)
1950
+	{
1951
+		/**
1952
+		 * Action called just before performing a real deletion query. You can use the
1953
+		 * model and its $query_params to find exactly which items will be deleted
1954
+		 *
1955
+		 * @param EEM_Base $model
1956
+		 * @param array    $query_params
1957
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1958
+		 *                                 to block (prevent) this deletion
1959
+		 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1960
+		 */
1961
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1962
+		// some MySQL databases may be running safe mode, which may restrict
1963
+		// deletion if there is no KEY column used in the WHERE statement of a deletion.
1964
+		// to get around this, we first do a SELECT, get all the IDs, and then run another query
1965
+		// to delete them
1966
+		$items_for_deletion           = $this->_get_all_wpdb_results($query_params);
1967
+		$columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1968
+		$deletion_where_query_part    = $this->_build_query_part_for_deleting_from_columns_and_values(
1969
+			$columns_and_ids_for_deleting
1970
+		);
1971
+		/**
1972
+		 * Allows client code to act on the items being deleted before the query is actually executed.
1973
+		 *
1974
+		 * @param EEM_Base $this                            The model instance being acted on.
1975
+		 * @param array    $query_params                    The incoming array of query parameters influencing what gets deleted.
1976
+		 * @param bool     $allow_blocking                  @see param description in method phpdoc block.
1977
+		 * @param array    $columns_and_ids_for_deleting    An array indicating what entities will get removed as
1978
+		 *                                                  derived from the incoming query parameters.
1979
+		 * @see details on the structure of this array in the phpdocs
1980
+		 *                                                  for the `_get_ids_for_delete_method`
1981
+		 *
1982
+		 */
1983
+		do_action(
1984
+			'AHEE__EEM_Base__delete__before_query',
1985
+			$this,
1986
+			$query_params,
1987
+			$allow_blocking,
1988
+			$columns_and_ids_for_deleting
1989
+		);
1990
+		if ($deletion_where_query_part) {
1991
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1992
+			$table_aliases    = implode(', ', array_keys($this->_tables));
1993
+			$SQL              = "DELETE " . $table_aliases
1994
+								. " FROM " . $model_query_info->get_full_join_sql()
1995
+								. " WHERE " . $deletion_where_query_part;
1996
+			$rows_deleted     = $this->_do_wpdb_query('query', [$SQL]);
1997
+		} else {
1998
+			$rows_deleted = 0;
1999
+		}
2000
+
2001
+		// Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2002
+		// there was no error with the delete query.
2003
+		if (
2004
+			$this->has_primary_key_field()
2005
+			&& $rows_deleted !== false
2006
+			&& isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2007
+		) {
2008
+			$ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2009
+			foreach ($ids_for_removal as $id) {
2010
+				if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2011
+					unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2012
+				}
2013
+			}
2014
+
2015
+			// delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2016
+			// `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2017
+			// unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2018
+			// (although it is possible).
2019
+			// Note this can be skipped by using the provided filter and returning false.
2020
+			if (
2021
+			apply_filters(
2022
+				'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2023
+				! $this instanceof EEM_Extra_Meta,
2024
+				$this
2025
+			)
2026
+			) {
2027
+				EEM_Extra_Meta::instance()->delete_permanently(
2028
+					[
2029
+						0 => [
2030
+							'EXM_type' => $this->get_this_model_name(),
2031
+							'OBJ_ID'   => [
2032
+								'IN',
2033
+								$ids_for_removal,
2034
+							],
2035
+						],
2036
+					]
2037
+				);
2038
+			}
2039
+		}
2040
+
2041
+		/**
2042
+		 * Action called just after performing a real deletion query. Although at this point the
2043
+		 * items should have been deleted
2044
+		 *
2045
+		 * @param EEM_Base $model
2046
+		 * @param array    $query_params
2047
+		 * @param int      $rows_deleted
2048
+		 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2049
+		 */
2050
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2051
+		return $rows_deleted;// how many supposedly got deleted
2052
+	}
2053
+
2054
+
2055
+	/**
2056
+	 * Checks all the relations that throw error messages when there are blocking related objects
2057
+	 * for related model objects. If there are any related model objects on those relations,
2058
+	 * adds an EE_Error, and return true
2059
+	 *
2060
+	 * @param EE_Base_Class|int $this_model_obj_or_id
2061
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2062
+	 *                                                 should be ignored when determining whether there are related
2063
+	 *                                                 model objects which block this model object's deletion. Useful
2064
+	 *                                                 if you know A is related to B and are considering deleting A,
2065
+	 *                                                 but want to see if A has any other objects blocking its deletion
2066
+	 *                                                 before removing the relation between A and B
2067
+	 * @return boolean
2068
+	 * @throws EE_Error
2069
+	 * @throws ReflectionException
2070
+	 */
2071
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2072
+	{
2073
+		// first, if $ignore_this_model_obj was supplied, get its model
2074
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2075
+			$ignored_model = $ignore_this_model_obj->get_model();
2076
+		} else {
2077
+			$ignored_model = null;
2078
+		}
2079
+		// now check all the relations of $this_model_obj_or_id and see if there
2080
+		// are any related model objects blocking it?
2081
+		$is_blocked = false;
2082
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2083
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2084
+				// if $ignore_this_model_obj was supplied, then for the query
2085
+				// on that model needs to be told to ignore $ignore_this_model_obj
2086
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2087
+					$related_model_objects = $relation_obj->get_all_related(
2088
+						$this_model_obj_or_id,
2089
+						[
2090
+							[
2091
+								$ignored_model->get_primary_key_field()->get_name() => [
2092
+									'!=',
2093
+									$ignore_this_model_obj->ID(),
2094
+								],
2095
+							],
2096
+						]
2097
+					);
2098
+				} else {
2099
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2100
+				}
2101
+				if ($related_model_objects) {
2102
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2103
+					$is_blocked = true;
2104
+				}
2105
+			}
2106
+		}
2107
+		return $is_blocked;
2108
+	}
2109
+
2110
+
2111
+	/**
2112
+	 * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2113
+	 *
2114
+	 * @param array $row_results_for_deleting
2115
+	 * @param bool  $allow_blocking
2116
+	 * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2117
+	 *                              model DOES have a primary_key_field, then the array will be a simple single
2118
+	 *                              dimension array where the key is the fully qualified primary key column and the
2119
+	 *                              value is an array of ids that will be deleted. Example: array('Event.EVT_ID' =>
2120
+	 *                              array( 1,2,3)) If the model DOES NOT have a primary_key_field, then the array will
2121
+	 *                              be a two dimensional array where each element is a group of columns and values that
2122
+	 *                              get deleted. Example: array(
2123
+	 *                              0 => array(
2124
+	 *                              'Term_Relationship.object_id' => 1
2125
+	 *                              'Term_Relationship.term_taxonomy_id' => 5
2126
+	 *                              ),
2127
+	 *                              1 => array(
2128
+	 *                              'Term_Relationship.object_id' => 1
2129
+	 *                              'Term_Relationship.term_taxonomy_id' => 6
2130
+	 *                              )
2131
+	 *                              )
2132
+	 * @throws EE_Error
2133
+	 * @throws ReflectionException
2134
+	 */
2135
+	protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2136
+	{
2137
+		$ids_to_delete_indexed_by_column = [];
2138
+		if ($this->has_primary_key_field()) {
2139
+			$primary_table                   = $this->_get_main_table();
2140
+			$ids_to_delete_indexed_by_column = $query = [];
2141
+			foreach ($row_results_for_deleting as $item_to_delete) {
2142
+				// before we mark this item for deletion,
2143
+				// make sure there's no related entities blocking its deletion (if we're checking)
2144
+				if (
2145
+					$allow_blocking
2146
+					&& $this->delete_is_blocked_by_related_models(
2147
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2148
+					)
2149
+				) {
2150
+					continue;
2151
+				}
2152
+				// primary table deletes
2153
+				if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2154
+					$ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2155
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2156
+				}
2157
+			}
2158
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2159
+			$fields = $this->get_combined_primary_key_fields();
2160
+			foreach ($row_results_for_deleting as $item_to_delete) {
2161
+				$ids_to_delete_indexed_by_column_for_row = [];
2162
+				foreach ($fields as $cpk_field) {
2163
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2164
+						$ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2165
+							$item_to_delete[ $cpk_field->get_qualified_column() ];
2166
+					}
2167
+				}
2168
+				$ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2169
+			}
2170
+		} else {
2171
+			// so there's no primary key and no combined key...
2172
+			// sorry, can't help you
2173
+			throw new EE_Error(
2174
+				sprintf(
2175
+					esc_html__(
2176
+						"Cannot delete objects of type %s because there is no primary key NOR combined key",
2177
+						"event_espresso"
2178
+					),
2179
+					get_class($this)
2180
+				)
2181
+			);
2182
+		}
2183
+		return $ids_to_delete_indexed_by_column;
2184
+	}
2185
+
2186
+
2187
+	/**
2188
+	 * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2189
+	 * the corresponding query_part for the query performing the delete.
2190
+	 *
2191
+	 * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2192
+	 * @return string
2193
+	 * @throws EE_Error
2194
+	 */
2195
+	protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2196
+	{
2197
+		$query_part = '';
2198
+		if (empty($ids_to_delete_indexed_by_column)) {
2199
+			return $query_part;
2200
+		} elseif ($this->has_primary_key_field()) {
2201
+			$query = [];
2202
+			foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2203
+				// make sure we have unique $ids
2204
+				$ids     = array_unique($ids);
2205
+				$query[] = $column . ' IN(' . implode(',', $ids) . ')';
2206
+			}
2207
+			$query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2208
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2209
+			$ways_to_identify_a_row = [];
2210
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2211
+				$values_for_each_combined_primary_key_for_a_row = [];
2212
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2213
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2214
+				}
2215
+				$value_and_value_and_value = implode(' AND ', $values_for_each_combined_primary_key_for_a_row);
2216
+				$ways_to_identify_a_row[]  = "({$value_and_value_and_value})";
2217
+			}
2218
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2219
+		}
2220
+		return $query_part;
2221
+	}
2222
+
2223
+
2224
+	/**
2225
+	 * Gets the model field by the fully qualified name
2226
+	 *
2227
+	 * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2228
+	 * @return EE_Model_Field_Base
2229
+	 * @throws EE_Error
2230
+	 */
2231
+	public function get_field_by_column($qualified_column_name)
2232
+	{
2233
+		foreach ($this->field_settings(true) as $field_name => $field_obj) {
2234
+			if ($field_obj->get_qualified_column() === $qualified_column_name) {
2235
+				return $field_obj;
2236
+			}
2237
+		}
2238
+		throw new EE_Error(
2239
+			sprintf(
2240
+				esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2241
+				$this->get_this_model_name(),
2242
+				$qualified_column_name
2243
+			)
2244
+		);
2245
+	}
2246
+
2247
+
2248
+	/**
2249
+	 * Count all the rows that match criteria the model query params.
2250
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2251
+	 * column
2252
+	 *
2253
+	 * @param array  $query_params
2254
+	 * @param string $field_to_count field on model to count by (not column name)
2255
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2256
+	 *                               that by the setting $distinct to TRUE;
2257
+	 * @return int
2258
+	 * @throws EE_Error
2259
+	 * @throws ReflectionException
2260
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2261
+	 */
2262
+	public function count($query_params = [], $field_to_count = null, $distinct = false)
2263
+	{
2264
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2265
+		if ($field_to_count) {
2266
+			$field_obj       = $this->field_settings_for($field_to_count);
2267
+			$column_to_count = $field_obj->get_qualified_column();
2268
+		} elseif ($this->has_primary_key_field()) {
2269
+			$pk_field_obj    = $this->get_primary_key_field();
2270
+			$column_to_count = $pk_field_obj->get_qualified_column();
2271
+		} else {
2272
+			// there's no primary key
2273
+			// if we're counting distinct items, and there's no primary key,
2274
+			// we need to list out the columns for distinction;
2275
+			// otherwise we can just use star
2276
+			if ($distinct) {
2277
+				$columns_to_use = [];
2278
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2279
+					$columns_to_use[] = $field_obj->get_qualified_column();
2280
+				}
2281
+				$column_to_count = implode(',', $columns_to_use);
2282
+			} else {
2283
+				$column_to_count = '*';
2284
+			}
2285
+		}
2286
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2287
+		$SQL             =
2288
+			"SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2289
+		return (int)$this->_do_wpdb_query('get_var', [$SQL]);
2290
+	}
2291
+
2292
+
2293
+	/**
2294
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2295
+	 *
2296
+	 * @param array  $query_params
2297
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2298
+	 * @return float
2299
+	 * @throws EE_Error
2300
+	 * @throws ReflectionException
2301
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2302
+	 */
2303
+	public function sum($query_params, $field_to_sum = null)
2304
+	{
2305
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2306
+		if ($field_to_sum) {
2307
+			$field_obj = $this->field_settings_for($field_to_sum);
2308
+		} else {
2309
+			$field_obj = $this->get_primary_key_field();
2310
+		}
2311
+		$column_to_count = $field_obj->get_qualified_column();
2312
+		$SQL             = "SELECT SUM(" . $column_to_count . ")"
2313
+						   . $this->_construct_2nd_half_of_select_query($model_query_info);
2314
+		$return_value    = $this->_do_wpdb_query('get_var', [$SQL]);
2315
+		$data_type       = $field_obj->get_wpdb_data_type();
2316
+		if ($data_type === '%d' || $data_type === '%s') {
2317
+			return (float)$return_value;
2318
+		}
2319
+		// must be %f
2320
+		return (float)$return_value;
2321
+	}
2322
+
2323
+
2324
+	/**
2325
+	 * Just calls the specified method on $wpdb with the given arguments
2326
+	 * Consolidates a little extra error handling code
2327
+	 *
2328
+	 * @param string $wpdb_method
2329
+	 * @param array  $arguments_to_provide
2330
+	 * @return mixed
2331
+	 * @throws EE_Error
2332
+	 * @global wpdb  $wpdb
2333
+	 */
2334
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2335
+	{
2336
+		// if we're in maintenance mode level 2, DON'T run any queries
2337
+		// because level 2 indicates the database needs updating and
2338
+		// is probably out of sync with the code
2339
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2340
+			throw new EE_Error(
2341
+				sprintf(
2342
+					esc_html__(
2343
+						"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.",
2344
+						"event_espresso"
2345
+					)
2346
+				)
2347
+			);
2348
+		}
2349
+		global $wpdb;
2350
+		if (! method_exists($wpdb, $wpdb_method)) {
2351
+			throw new EE_Error(
2352
+				sprintf(
2353
+					esc_html__(
2354
+						'There is no method named "%s" on Wordpress\' $wpdb object',
2355
+						'event_espresso'
2356
+					),
2357
+					$wpdb_method
2358
+				)
2359
+			);
2360
+		}
2361
+		$old_show_errors_value = $wpdb->show_errors;
2362
+		if (WP_DEBUG) {
2363
+			$wpdb->show_errors(false);
2364
+		}
2365
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2366
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2367
+		if (WP_DEBUG) {
2368
+			$wpdb->show_errors($old_show_errors_value);
2369
+			if (! empty($wpdb->last_error)) {
2370
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2371
+			}
2372
+			if ($result === false) {
2373
+				throw new EE_Error(
2374
+					sprintf(
2375
+						esc_html__(
2376
+							'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2377
+							'event_espresso'
2378
+						),
2379
+						$wpdb_method,
2380
+						var_export($arguments_to_provide, true)
2381
+					)
2382
+				);
2383
+			}
2384
+		} elseif ($result === false) {
2385
+			EE_Error::add_error(
2386
+				sprintf(
2387
+					esc_html__(
2388
+						'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"',
2389
+						'event_espresso'
2390
+					),
2391
+					$wpdb_method,
2392
+					var_export($arguments_to_provide, true),
2393
+					$wpdb->last_error
2394
+				),
2395
+				__FILE__,
2396
+				__FUNCTION__,
2397
+				__LINE__
2398
+			);
2399
+		}
2400
+		return $result;
2401
+	}
2402
+
2403
+
2404
+	/**
2405
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2406
+	 * and if there's an error tries to verify the DB is correct. Uses
2407
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2408
+	 * we should try to fix the EE core db, the addons, or just give up
2409
+	 *
2410
+	 * @param string $wpdb_method
2411
+	 * @param array  $arguments_to_provide
2412
+	 * @return mixed
2413
+	 * @throws EE_Error
2414
+	 */
2415
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2416
+	{
2417
+		global $wpdb;
2418
+		$wpdb->last_error = null;
2419
+		$result           = call_user_func_array([$wpdb, $wpdb_method], $arguments_to_provide);
2420
+		// was there an error running the query? but we don't care on new activations
2421
+		// (we're going to setup the DB anyway on new activations)
2422
+		if (
2423
+			($result === false || ! empty($wpdb->last_error))
2424
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2425
+		) {
2426
+			switch (EEM_Base::$_db_verification_level) {
2427
+				case EEM_Base::db_verified_none:
2428
+					// let's double-check core's DB
2429
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2430
+					break;
2431
+				case EEM_Base::db_verified_core:
2432
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2433
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2434
+					break;
2435
+				case EEM_Base::db_verified_addons:
2436
+					// ummmm... you in trouble
2437
+					return $result;
2438
+			}
2439
+			if (! empty($error_message)) {
2440
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2441
+				trigger_error($error_message);
2442
+			}
2443
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2444
+		}
2445
+		return $result;
2446
+	}
2447
+
2448
+
2449
+	/**
2450
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2451
+	 * EEM_Base::$_db_verification_level
2452
+	 *
2453
+	 * @param string $wpdb_method
2454
+	 * @param array  $arguments_to_provide
2455
+	 * @return string
2456
+	 * @throws EE_Error
2457
+	 */
2458
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2459
+	{
2460
+		global $wpdb;
2461
+		// ok remember that we've already attempted fixing the core db, in case the problem persists
2462
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2463
+		$error_message                    = sprintf(
2464
+			esc_html__(
2465
+				'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2466
+				'event_espresso'
2467
+			),
2468
+			$wpdb->last_error,
2469
+			$wpdb_method,
2470
+			wp_json_encode($arguments_to_provide)
2471
+		);
2472
+		EE_System::instance()->initialize_db_if_no_migrations_required();
2473
+		return $error_message;
2474
+	}
2475
+
2476
+
2477
+	/**
2478
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2479
+	 * EEM_Base::$_db_verification_level
2480
+	 *
2481
+	 * @param $wpdb_method
2482
+	 * @param $arguments_to_provide
2483
+	 * @return string
2484
+	 * @throws EE_Error
2485
+	 */
2486
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2487
+	{
2488
+		global $wpdb;
2489
+		// ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2490
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2491
+		$error_message                    = sprintf(
2492
+			esc_html__(
2493
+				'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2494
+				'event_espresso'
2495
+			),
2496
+			$wpdb->last_error,
2497
+			$wpdb_method,
2498
+			wp_json_encode($arguments_to_provide)
2499
+		);
2500
+		EE_System::instance()->initialize_addons();
2501
+		return $error_message;
2502
+	}
2503
+
2504
+
2505
+	/**
2506
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2507
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2508
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2509
+	 * ..."
2510
+	 *
2511
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2512
+	 * @return string
2513
+	 */
2514
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2515
+	{
2516
+		return " FROM " . $model_query_info->get_full_join_sql() .
2517
+			   $model_query_info->get_where_sql() .
2518
+			   $model_query_info->get_group_by_sql() .
2519
+			   $model_query_info->get_having_sql() .
2520
+			   $model_query_info->get_order_by_sql() .
2521
+			   $model_query_info->get_limit_sql();
2522
+	}
2523
+
2524
+
2525
+	/**
2526
+	 * Set to easily debug the next X queries ran from this model.
2527
+	 *
2528
+	 * @param int $count
2529
+	 */
2530
+	public function show_next_x_db_queries($count = 1)
2531
+	{
2532
+		$this->_show_next_x_db_queries = $count;
2533
+	}
2534
+
2535
+
2536
+	/**
2537
+	 * @param $sql_query
2538
+	 */
2539
+	public function show_db_query_if_previously_requested($sql_query)
2540
+	{
2541
+		if ($this->_show_next_x_db_queries > 0) {
2542
+			echo $sql_query;
2543
+			$this->_show_next_x_db_queries--;
2544
+		}
2545
+	}
2546
+
2547
+
2548
+	/**
2549
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2550
+	 * There are the 3 cases:
2551
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2552
+	 * $otherModelObject has no ID, it is first saved.
2553
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2554
+	 * has no ID, it is first saved.
2555
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2556
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2557
+	 * join table
2558
+	 *
2559
+	 * @param EE_Base_Class                     /int $thisModelObject
2560
+	 * @param EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2561
+	 * @param string $relationName                     , key in EEM_Base::_relations
2562
+	 *                                                 an attendee to a group, you also want to specify which role they
2563
+	 *                                                 will have in that group. So you would use this parameter to
2564
+	 *                                                 specify array('role-column-name'=>'role-id')
2565
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2566
+	 *                                                 to for relation to methods that allow you to further specify
2567
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2568
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2569
+	 *                                                 because these will be inserted in any new rows created as well.
2570
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2571
+	 * @throws EE_Error
2572
+	 */
2573
+	public function add_relationship_to(
2574
+		$id_or_obj,
2575
+		$other_model_id_or_obj,
2576
+		$relationName,
2577
+		$extra_join_model_fields_n_values = []
2578
+	) {
2579
+		$relation_obj = $this->related_settings_for($relationName);
2580
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2581
+	}
2582
+
2583
+
2584
+	/**
2585
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2586
+	 * There are the 3 cases:
2587
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2588
+	 * error
2589
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2590
+	 * an error
2591
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2592
+	 *
2593
+	 * @param EE_Base_Class /int $id_or_obj
2594
+	 * @param EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2595
+	 * @param string $relationName key in EEM_Base::_relations
2596
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2597
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2598
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2599
+	 *                             because these will be inserted in any new rows created as well.
2600
+	 * @return boolean of success
2601
+	 * @throws EE_Error
2602
+	 */
2603
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = [])
2604
+	{
2605
+		$relation_obj = $this->related_settings_for($relationName);
2606
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2607
+	}
2608
+
2609
+
2610
+	/**
2611
+	 * @param mixed  $id_or_obj
2612
+	 * @param string $relationName
2613
+	 * @param array  $where_query_params
2614
+	 * @param EE_Base_Class[] objects to which relations were removed
2615
+	 * @return EE_Base_Class[]
2616
+	 * @throws EE_Error
2617
+	 */
2618
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = [])
2619
+	{
2620
+		$relation_obj = $this->related_settings_for($relationName);
2621
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2622
+	}
2623
+
2624
+
2625
+	/**
2626
+	 * Gets all the related items of the specified $model_name, using $query_params.
2627
+	 * Note: by default, we remove the "default query params"
2628
+	 * because we want to get even deleted items etc.
2629
+	 *
2630
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2631
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2632
+	 * @param array  $query_params see github link below for more info
2633
+	 * @return EE_Base_Class[]
2634
+	 * @throws EE_Error
2635
+	 * @throws ReflectionException
2636
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2637
+	 */
2638
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2639
+	{
2640
+		$model_obj         = $this->ensure_is_obj($id_or_obj);
2641
+		$relation_settings = $this->related_settings_for($model_name);
2642
+		return $relation_settings->get_all_related($model_obj, $query_params);
2643
+	}
2644
+
2645
+
2646
+	/**
2647
+	 * Deletes all the model objects across the relation indicated by $model_name
2648
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2649
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2650
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2651
+	 *
2652
+	 * @param EE_Base_Class|int|string $id_or_obj
2653
+	 * @param string                   $model_name
2654
+	 * @param array                    $query_params
2655
+	 * @return int how many deleted
2656
+	 * @throws EE_Error
2657
+	 * @throws ReflectionException
2658
+	 */
2659
+	public function delete_related($id_or_obj, $model_name, $query_params = [])
2660
+	{
2661
+		$model_obj         = $this->ensure_is_obj($id_or_obj);
2662
+		$relation_settings = $this->related_settings_for($model_name);
2663
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2664
+	}
2665
+
2666
+
2667
+	/**
2668
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2669
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2670
+	 * the model objects can't be hard deleted because of blocking related model objects,
2671
+	 * just does a soft-delete on them instead.
2672
+	 *
2673
+	 * @param EE_Base_Class|int|string $id_or_obj
2674
+	 * @param string                   $model_name
2675
+	 * @param array                    $query_params
2676
+	 * @return int how many deleted
2677
+	 * @throws EE_Error
2678
+	 * @throws ReflectionException
2679
+	 */
2680
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = [])
2681
+	{
2682
+		$model_obj         = $this->ensure_is_obj($id_or_obj);
2683
+		$relation_settings = $this->related_settings_for($model_name);
2684
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2685
+	}
2686
+
2687
+
2688
+	/**
2689
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2690
+	 * 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
2695
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2696
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2697
+	 *                               that by the setting $distinct to TRUE;
2698
+	 * @return int
2699
+	 * @throws EE_Error
2700
+	 * @throws ReflectionException
2701
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2702
+	 */
2703
+	public function count_related(
2704
+		$id_or_obj,
2705
+		$model_name,
2706
+		$query_params = [],
2707
+		$field_to_count = null,
2708
+		$distinct = false
2709
+	) {
2710
+		$related_model = $this->get_related_model_obj($model_name);
2711
+		// we're just going to use the query params on the related model's normal get_all query,
2712
+		// except add a condition to say to match the current mod
2713
+		if (! isset($query_params['default_where_conditions'])) {
2714
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2715
+		}
2716
+		$this_model_name                                                 = $this->get_this_model_name();
2717
+		$this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2718
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2719
+		return $related_model->count($query_params, $field_to_count, $distinct);
2720
+	}
2721
+
2722
+
2723
+	/**
2724
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2725
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2726
+	 *
2727
+	 * @param int           /EE_Base_Class $id_or_obj
2728
+	 * @param string $model_name   like 'Event', or 'Registration'
2729
+	 * @param array  $query_params
2730
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2731
+	 * @return float
2732
+	 * @throws EE_Error
2733
+	 * @throws ReflectionException
2734
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2735
+	 */
2736
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2737
+	{
2738
+		$related_model = $this->get_related_model_obj($model_name);
2739
+		if (! is_array($query_params)) {
2740
+			EE_Error::doing_it_wrong(
2741
+				'EEM_Base::sum_related',
2742
+				sprintf(
2743
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2744
+					gettype($query_params)
2745
+				),
2746
+				'4.6.0'
2747
+			);
2748
+			$query_params = [];
2749
+		}
2750
+		// we're just going to use the query params on the related model's normal get_all query,
2751
+		// except add a condition to say to match the current mod
2752
+		if (! isset($query_params['default_where_conditions'])) {
2753
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2754
+		}
2755
+		$this_model_name                                                 = $this->get_this_model_name();
2756
+		$this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2757
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2758
+		return $related_model->sum($query_params, $field_to_sum);
2759
+	}
2760
+
2761
+
2762
+	/**
2763
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2764
+	 * $modelObject
2765
+	 *
2766
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2767
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2768
+	 * @param array               $query_params     see github link below for more info
2769
+	 * @return EE_Base_Class
2770
+	 * @throws EE_Error
2771
+	 * @throws ReflectionException
2772
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2773
+	 */
2774
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2775
+	{
2776
+		$query_params['limit'] = 1;
2777
+		$results               = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2778
+		if ($results) {
2779
+			return array_shift($results);
2780
+		}
2781
+		return null;
2782
+	}
2783
+
2784
+
2785
+	/**
2786
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2787
+	 *
2788
+	 * @return string
2789
+	 */
2790
+	public function get_this_model_name()
2791
+	{
2792
+		return str_replace("EEM_", "", get_class($this));
2793
+	}
2794
+
2795
+
2796
+	/**
2797
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2798
+	 *
2799
+	 * @return EE_Any_Foreign_Model_Name_Field
2800
+	 * @throws EE_Error
2801
+	 */
2802
+	public function get_field_containing_related_model_name()
2803
+	{
2804
+		foreach ($this->field_settings(true) as $field) {
2805
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2806
+				$field_with_model_name = $field;
2807
+			}
2808
+		}
2809
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2810
+			throw new EE_Error(
2811
+				sprintf(
2812
+					esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2813
+					$this->get_this_model_name()
2814
+				)
2815
+			);
2816
+		}
2817
+		return $field_with_model_name;
2818
+	}
2819
+
2820
+
2821
+	/**
2822
+	 * Inserts a new entry into the database, for each table.
2823
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2824
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2825
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2826
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2827
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2828
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2829
+	 *
2830
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2831
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2832
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2833
+	 *                              of EEM_Base)
2834
+	 * @return int|string new primary key on main table that got inserted
2835
+	 * @throws EE_Error
2836
+	 * @throws ReflectionException
2837
+	 */
2838
+	public function insert($field_n_values)
2839
+	{
2840
+		/**
2841
+		 * Filters the fields and their values before inserting an item using the models
2842
+		 *
2843
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2844
+		 * @param EEM_Base $model           the model used
2845
+		 */
2846
+		$field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2847
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2848
+			$main_table = $this->_get_main_table();
2849
+			$new_id     = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2850
+			if ($new_id !== false) {
2851
+				foreach ($this->_get_other_tables() as $other_table) {
2852
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2853
+				}
2854
+			}
2855
+			/**
2856
+			 * Done just after attempting to insert a new model object
2857
+			 *
2858
+			 * @param EEM_Base $model           used
2859
+			 * @param array    $fields_n_values fields and their values
2860
+			 * @param int|string the              ID of the newly-inserted model object
2861
+			 */
2862
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2863
+			return $new_id;
2864
+		}
2865
+		return false;
2866
+	}
2867
+
2868
+
2869
+	/**
2870
+	 * Checks that the result would satisfy the unique indexes on this model
2871
+	 *
2872
+	 * @param array  $field_n_values
2873
+	 * @param string $action
2874
+	 * @return boolean
2875
+	 * @throws EE_Error
2876
+	 * @throws ReflectionException
2877
+	 */
2878
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2879
+	{
2880
+		foreach ($this->unique_indexes() as $index_name => $index) {
2881
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2882
+			if ($this->exists([$uniqueness_where_params])) {
2883
+				EE_Error::add_error(
2884
+					sprintf(
2885
+						esc_html__(
2886
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2887
+							"event_espresso"
2888
+						),
2889
+						$action,
2890
+						$this->_get_class_name(),
2891
+						$index_name,
2892
+						implode(",", $index->field_names()),
2893
+						http_build_query($uniqueness_where_params)
2894
+					),
2895
+					__FILE__,
2896
+					__FUNCTION__,
2897
+					__LINE__
2898
+				);
2899
+				return false;
2900
+			}
2901
+		}
2902
+		return true;
2903
+	}
2904
+
2905
+
2906
+	/**
2907
+	 * Checks the database for an item that conflicts (ie, if this item were
2908
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2909
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2910
+	 * can be either an EE_Base_Class or an array of fields n values
2911
+	 *
2912
+	 * @param EE_Base_Class|array $obj_or_fields_array
2913
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2914
+	 *                                                 when looking for conflicts
2915
+	 *                                                 (ie, if false, we ignore the model object's primary key
2916
+	 *                                                 when finding "conflicts". If true, it's also considered).
2917
+	 *                                                 Only works for INT primary key,
2918
+	 *                                                 STRING primary keys cannot be ignored
2919
+	 * @return EE_Base_Class|array
2920
+	 * @throws EE_Error
2921
+	 * @throws ReflectionException
2922
+	 */
2923
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2924
+	{
2925
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2926
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2927
+		} elseif (is_array($obj_or_fields_array)) {
2928
+			$fields_n_values = $obj_or_fields_array;
2929
+		} else {
2930
+			throw new EE_Error(
2931
+				sprintf(
2932
+					esc_html__(
2933
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2934
+						"event_espresso"
2935
+					),
2936
+					get_class($this),
2937
+					$obj_or_fields_array
2938
+				)
2939
+			);
2940
+		}
2941
+		$query_params = [];
2942
+		if (
2943
+			$this->has_primary_key_field()
2944
+			&& ($include_primary_key
2945
+				|| $this->get_primary_key_field()
2946
+				   instanceof
2947
+				   EE_Primary_Key_String_Field)
2948
+			&& isset($fields_n_values[ $this->primary_key_name() ])
2949
+		) {
2950
+			$query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2951
+		}
2952
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2953
+			$uniqueness_where_params                              =
2954
+				array_intersect_key($fields_n_values, $unique_index->fields());
2955
+			$query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2956
+		}
2957
+		// if there is nothing to base this search on, then we shouldn't find anything
2958
+		if (empty($query_params)) {
2959
+			return [];
2960
+		}
2961
+		return $this->get_one($query_params);
2962
+	}
2963
+
2964
+
2965
+	/**
2966
+	 * Like count, but is optimized and returns a boolean instead of an int
2967
+	 *
2968
+	 * @param array $query_params
2969
+	 * @return boolean
2970
+	 * @throws EE_Error
2971
+	 * @throws ReflectionException
2972
+	 */
2973
+	public function exists($query_params)
2974
+	{
2975
+		$query_params['limit'] = 1;
2976
+		return $this->count($query_params) > 0;
2977
+	}
2978
+
2979
+
2980
+	/**
2981
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2982
+	 *
2983
+	 * @param int|string $id
2984
+	 * @return boolean
2985
+	 * @throws EE_Error
2986
+	 * @throws ReflectionException
2987
+	 */
2988
+	public function exists_by_ID($id)
2989
+	{
2990
+		return $this->exists(
2991
+			[
2992
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2993
+				[
2994
+					$this->primary_key_name() => $id,
2995
+				],
2996
+			]
2997
+		);
2998
+	}
2999
+
3000
+
3001
+	/**
3002
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
3003
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
3004
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
3005
+	 * on the main table)
3006
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
3007
+	 * cases where we want to call it directly rather than via insert().
3008
+	 *
3009
+	 * @access   protected
3010
+	 * @param EE_Table_Base $table
3011
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
3012
+	 *                                       float
3013
+	 * @param int           $new_id          for now we assume only int keys
3014
+	 * @return int ID of new row inserted, or FALSE on failure
3015
+	 * @throws EE_Error
3016
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
3017
+	 */
3018
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
3019
+	{
3020
+		global $wpdb;
3021
+		$insertion_col_n_values = [];
3022
+		$format_for_insertion   = [];
3023
+		$fields_on_table        = $this->_get_fields_for_table($table->get_table_alias());
3024
+		foreach ($fields_on_table as $field_name => $field_obj) {
3025
+			// check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
3026
+			if ($field_obj->is_auto_increment()) {
3027
+				continue;
3028
+			}
3029
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3030
+			// if the value we want to assign it to is NULL, just don't mention it for the insertion
3031
+			if ($prepared_value !== null) {
3032
+				$insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3033
+				$format_for_insertion[]                                   = $field_obj->get_wpdb_data_type();
3034
+			}
3035
+		}
3036
+		if ($table instanceof EE_Secondary_Table && $new_id) {
3037
+			// its not the main table, so we should have already saved the main table's PK which we just inserted
3038
+			// so add the fk to the main table as a column
3039
+			$insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3040
+			$format_for_insertion[]                              =
3041
+				'%d';// yes right now we're only allowing these foreign keys to be INTs
3042
+		}
3043
+		// insert the new entry
3044
+		$result = $this->_do_wpdb_query(
3045
+			'insert',
3046
+			[$table->get_table_name(), $insertion_col_n_values, $format_for_insertion]
3047
+		);
3048
+		if ($result === false) {
3049
+			return false;
3050
+		}
3051
+		// ok, now what do we return for the ID of the newly-inserted thing?
3052
+		if ($this->has_primary_key_field()) {
3053
+			if ($this->get_primary_key_field()->is_auto_increment()) {
3054
+				return $wpdb->insert_id;
3055
+			}
3056
+			// it's not an auto-increment primary key, so
3057
+			// it must have been supplied
3058
+			return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3059
+		}
3060
+		// we can't return a  primary key because there is none. instead return
3061
+		// a unique string indicating this model
3062
+		return $this->get_index_primary_key_string($fields_n_values);
3063
+	}
3064
+
3065
+
3066
+	/**
3067
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3068
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3069
+	 * and there is no default, we pass it along. WPDB will take care of it)
3070
+	 *
3071
+	 * @param EE_Model_Field_Base $field_obj
3072
+	 * @param array               $fields_n_values
3073
+	 * @return mixed string|int|float depending on what the table column will be expecting
3074
+	 * @throws EE_Error
3075
+	 */
3076
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3077
+	{
3078
+		// if this field doesn't allow nullable, don't allow it
3079
+		if (
3080
+			! $field_obj->is_nullable()
3081
+			&& (
3082
+				! isset($fields_n_values[ $field_obj->get_name() ])
3083
+				|| $fields_n_values[ $field_obj->get_name() ] === null
3084
+			)
3085
+		) {
3086
+			$fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3087
+		}
3088
+		$unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3089
+			? $fields_n_values[ $field_obj->get_name() ]
3090
+			: null;
3091
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3092
+	}
3093
+
3094
+
3095
+	/**
3096
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3097
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3098
+	 * the field's prepare_for_set() method.
3099
+	 *
3100
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3101
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3102
+	 *                                   top of file)
3103
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3104
+	 *                                   $value is a custom selection
3105
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3106
+	 */
3107
+	private function _prepare_value_for_use_in_db($value, $field)
3108
+	{
3109
+		if ($field && $field instanceof EE_Model_Field_Base) {
3110
+			// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3111
+			switch ($this->_values_already_prepared_by_model_object) {
3112
+				/** @noinspection PhpMissingBreakStatementInspection */
3113
+				case self::not_prepared_by_model_object:
3114
+					$value = $field->prepare_for_set($value);
3115
+				// purposefully left out "return"
3116
+				case self::prepared_by_model_object:
3117
+					/** @noinspection SuspiciousAssignmentsInspection */
3118
+					$value = $field->prepare_for_use_in_db($value);
3119
+				case self::prepared_for_use_in_db:
3120
+					// leave the value alone
3121
+			}
3122
+			return $value;
3123
+			// phpcs:enable
3124
+		}
3125
+		return $value;
3126
+	}
3127
+
3128
+
3129
+	/**
3130
+	 * Returns the main table on this model
3131
+	 *
3132
+	 * @return EE_Primary_Table
3133
+	 * @throws EE_Error
3134
+	 */
3135
+	protected function _get_main_table()
3136
+	{
3137
+		foreach ($this->_tables as $table) {
3138
+			if ($table instanceof EE_Primary_Table) {
3139
+				return $table;
3140
+			}
3141
+		}
3142
+		throw new EE_Error(
3143
+			sprintf(
3144
+				esc_html__(
3145
+					'There are no main tables on %s. They should be added to _tables array in the constructor',
3146
+					'event_espresso'
3147
+				),
3148
+				get_class($this)
3149
+			)
3150
+		);
3151
+	}
3152
+
3153
+
3154
+	/**
3155
+	 * table
3156
+	 * returns EE_Primary_Table table name
3157
+	 *
3158
+	 * @return string
3159
+	 * @throws EE_Error
3160
+	 */
3161
+	public function table()
3162
+	{
3163
+		return $this->_get_main_table()->get_table_name();
3164
+	}
3165
+
3166
+
3167
+	/**
3168
+	 * table
3169
+	 * returns first EE_Secondary_Table table name
3170
+	 *
3171
+	 * @return string
3172
+	 */
3173
+	public function second_table()
3174
+	{
3175
+		// grab second table from tables array
3176
+		$second_table = end($this->_tables);
3177
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3178
+	}
3179
+
3180
+
3181
+	/**
3182
+	 * get_table_obj_by_alias
3183
+	 * returns table name given it's alias
3184
+	 *
3185
+	 * @param string $table_alias
3186
+	 * @return EE_Primary_Table | EE_Secondary_Table
3187
+	 */
3188
+	public function get_table_obj_by_alias($table_alias = '')
3189
+	{
3190
+		return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3191
+	}
3192
+
3193
+
3194
+	/**
3195
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3196
+	 *
3197
+	 * @return EE_Secondary_Table[]
3198
+	 */
3199
+	protected function _get_other_tables()
3200
+	{
3201
+		$other_tables = [];
3202
+		foreach ($this->_tables as $table_alias => $table) {
3203
+			if ($table instanceof EE_Secondary_Table) {
3204
+				$other_tables[ $table_alias ] = $table;
3205
+			}
3206
+		}
3207
+		return $other_tables;
3208
+	}
3209
+
3210
+
3211
+	/**
3212
+	 * Finds all the fields that correspond to the given table
3213
+	 *
3214
+	 * @param string $table_alias , array key in EEM_Base::_tables
3215
+	 * @return EE_Model_Field_Base[]
3216
+	 */
3217
+	public function _get_fields_for_table($table_alias)
3218
+	{
3219
+		return $this->_fields[ $table_alias ];
3220
+	}
3221
+
3222
+
3223
+	/**
3224
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3225
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3226
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3227
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3228
+	 * related Registration, Transaction, and Payment models.
3229
+	 *
3230
+	 * @param array $query_params see github link below for more info
3231
+	 * @return EE_Model_Query_Info_Carrier
3232
+	 * @throws EE_Error
3233
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3234
+	 */
3235
+	public function _extract_related_models_from_query($query_params)
3236
+	{
3237
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3238
+		if (array_key_exists(0, $query_params)) {
3239
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3240
+		}
3241
+		if (array_key_exists('group_by', $query_params)) {
3242
+			if (is_array($query_params['group_by'])) {
3243
+				$this->_extract_related_models_from_sub_params_array_values(
3244
+					$query_params['group_by'],
3245
+					$query_info_carrier,
3246
+					'group_by'
3247
+				);
3248
+			} elseif (! empty($query_params['group_by'])) {
3249
+				$this->_extract_related_model_info_from_query_param(
3250
+					$query_params['group_by'],
3251
+					$query_info_carrier,
3252
+					'group_by'
3253
+				);
3254
+			}
3255
+		}
3256
+		if (array_key_exists('having', $query_params)) {
3257
+			$this->_extract_related_models_from_sub_params_array_keys(
3258
+				$query_params[0],
3259
+				$query_info_carrier,
3260
+				'having'
3261
+			);
3262
+		}
3263
+		if (array_key_exists('order_by', $query_params)) {
3264
+			if (is_array($query_params['order_by'])) {
3265
+				$this->_extract_related_models_from_sub_params_array_keys(
3266
+					$query_params['order_by'],
3267
+					$query_info_carrier,
3268
+					'order_by'
3269
+				);
3270
+			} elseif (! empty($query_params['order_by'])) {
3271
+				$this->_extract_related_model_info_from_query_param(
3272
+					$query_params['order_by'],
3273
+					$query_info_carrier,
3274
+					'order_by'
3275
+				);
3276
+			}
3277
+		}
3278
+		if (array_key_exists('force_join', $query_params)) {
3279
+			$this->_extract_related_models_from_sub_params_array_values(
3280
+				$query_params['force_join'],
3281
+				$query_info_carrier,
3282
+				'force_join'
3283
+			);
3284
+		}
3285
+		$this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3286
+		return $query_info_carrier;
3287
+	}
3288
+
3289
+
3290
+	/**
3291
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3292
+	 *
3293
+	 * @param array                       $sub_query_params
3294
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3295
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3296
+	 * @return EE_Model_Query_Info_Carrier
3297
+	 * @throws EE_Error
3298
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3299
+	 */
3300
+	private function _extract_related_models_from_sub_params_array_keys(
3301
+		$sub_query_params,
3302
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3303
+		$query_param_type
3304
+	) {
3305
+		if (! empty($sub_query_params)) {
3306
+			$sub_query_params = (array)$sub_query_params;
3307
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3308
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3309
+				$this->_extract_related_model_info_from_query_param(
3310
+					$param,
3311
+					$model_query_info_carrier,
3312
+					$query_param_type
3313
+				);
3314
+				// if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3315
+				// indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3316
+				// extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3317
+				// of array('Registration.TXN_ID'=>23)
3318
+				$query_param_sans_stars =
3319
+					$this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3320
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3321
+					if (! is_array($possibly_array_of_params)) {
3322
+						throw new EE_Error(
3323
+							sprintf(
3324
+								esc_html__(
3325
+									"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'))",
3326
+									"event_espresso"
3327
+								),
3328
+								$param,
3329
+								$possibly_array_of_params
3330
+							)
3331
+						);
3332
+					}
3333
+					$this->_extract_related_models_from_sub_params_array_keys(
3334
+						$possibly_array_of_params,
3335
+						$model_query_info_carrier,
3336
+						$query_param_type
3337
+					);
3338
+				} elseif (
3339
+					$query_param_type === 0 // ie WHERE
3340
+					&& is_array($possibly_array_of_params)
3341
+					&& isset($possibly_array_of_params[2])
3342
+					&& $possibly_array_of_params[2] == true
3343
+				) {
3344
+					// then $possible_array_of_params looks something like array('<','DTT_sold',true)
3345
+					// indicating that $possible_array_of_params[1] is actually a field name,
3346
+					// from which we should extract query parameters!
3347
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3348
+						throw new EE_Error(
3349
+							sprintf(
3350
+								esc_html__(
3351
+									"Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3352
+									"event_espresso"
3353
+								),
3354
+								$query_param_type,
3355
+								implode(",", $possibly_array_of_params)
3356
+							)
3357
+						);
3358
+					}
3359
+					$this->_extract_related_model_info_from_query_param(
3360
+						$possibly_array_of_params[1],
3361
+						$model_query_info_carrier,
3362
+						$query_param_type
3363
+					);
3364
+				}
3365
+			}
3366
+		}
3367
+		return $model_query_info_carrier;
3368
+	}
3369
+
3370
+
3371
+	/**
3372
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3373
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3374
+	 *
3375
+	 * @param array                       $sub_query_params
3376
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3377
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3378
+	 * @return EE_Model_Query_Info_Carrier
3379
+	 * @throws EE_Error
3380
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3381
+	 */
3382
+	private function _extract_related_models_from_sub_params_array_values(
3383
+		$sub_query_params,
3384
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3385
+		$query_param_type
3386
+	) {
3387
+		if (! empty($sub_query_params)) {
3388
+			if (! is_array($sub_query_params)) {
3389
+				throw new EE_Error(
3390
+					sprintf(
3391
+						esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3392
+						$sub_query_params
3393
+					)
3394
+				);
3395
+			}
3396
+			foreach ($sub_query_params as $param) {
3397
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3398
+				$this->_extract_related_model_info_from_query_param(
3399
+					$param,
3400
+					$model_query_info_carrier,
3401
+					$query_param_type
3402
+				);
3403
+			}
3404
+		}
3405
+		return $model_query_info_carrier;
3406
+	}
3407
+
3408
+
3409
+	/**
3410
+	 * Extract all the query parts from  model query params
3411
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3412
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3413
+	 * but use them in a different order. Eg, we need to know what models we are querying
3414
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3415
+	 * other models before we can finalize the where clause SQL.
3416
+	 *
3417
+	 * @param array $query_params see github link below for more info
3418
+	 * @return EE_Model_Query_Info_Carrier
3419
+	 * @throws EE_Error
3420
+	 * @throws ModelConfigurationException
3421
+	 * @throws ReflectionException
3422
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3423
+	 */
3424
+	public function _create_model_query_info_carrier($query_params)
3425
+	{
3426
+		if (! is_array($query_params)) {
3427
+			EE_Error::doing_it_wrong(
3428
+				'EEM_Base::_create_model_query_info_carrier',
3429
+				sprintf(
3430
+					esc_html__(
3431
+						'$query_params should be an array, you passed a variable of type %s',
3432
+						'event_espresso'
3433
+					),
3434
+					gettype($query_params)
3435
+				),
3436
+				'4.6.0'
3437
+			);
3438
+			$query_params = [];
3439
+		}
3440
+		$query_params[0] = isset($query_params[0]) ? $query_params[0] : [];
3441
+		// first check if we should alter the query to account for caps or not
3442
+		// because the caps might require us to do extra joins
3443
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3444
+			$query_params[0] = array_replace_recursive(
3445
+				$query_params[0],
3446
+				$this->caps_where_conditions(
3447
+					$query_params['caps']
3448
+				)
3449
+			);
3450
+		}
3451
+
3452
+		// check if we should alter the query to remove data related to protected
3453
+		// custom post types
3454
+		if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3455
+			$where_param_key_for_password = $this->modelChainAndPassword();
3456
+			// only include if related to a cpt where no password has been set
3457
+			$query_params[0]['OR*nopassword'] = [
3458
+				$where_param_key_for_password       => '',
3459
+				$where_param_key_for_password . '*' => ['IS_NULL'],
3460
+			];
3461
+		}
3462
+		$query_object = $this->_extract_related_models_from_query($query_params);
3463
+		// verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3464
+		foreach ($query_params[0] as $key => $value) {
3465
+			if (is_int($key)) {
3466
+				throw new EE_Error(
3467
+					sprintf(
3468
+						esc_html__(
3469
+							"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.",
3470
+							"event_espresso"
3471
+						),
3472
+						$key,
3473
+						var_export($value, true),
3474
+						var_export($query_params, true),
3475
+						get_class($this)
3476
+					)
3477
+				);
3478
+			}
3479
+		}
3480
+		if (
3481
+			array_key_exists('default_where_conditions', $query_params)
3482
+			&& ! empty($query_params['default_where_conditions'])
3483
+		) {
3484
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3485
+		} else {
3486
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3487
+		}
3488
+		$query_params[0] = array_merge(
3489
+			$this->_get_default_where_conditions_for_models_in_query(
3490
+				$query_object,
3491
+				$use_default_where_conditions,
3492
+				$query_params[0]
3493
+			),
3494
+			$query_params[0]
3495
+		);
3496
+		$query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3497
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3498
+		// So we need to setup a subquery and use that for the main join.
3499
+		// Note for now this only works on the primary table for the model.
3500
+		// So for instance, you could set the limit array like this:
3501
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3502
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3503
+			$query_object->set_main_model_join_sql(
3504
+				$this->_construct_limit_join_select(
3505
+					$query_params['on_join_limit'][0],
3506
+					$query_params['on_join_limit'][1]
3507
+				)
3508
+			);
3509
+		}
3510
+		// set limit
3511
+		if (array_key_exists('limit', $query_params)) {
3512
+			if (is_array($query_params['limit'])) {
3513
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3514
+					$e = sprintf(
3515
+						esc_html__(
3516
+							"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)",
3517
+							"event_espresso"
3518
+						),
3519
+						http_build_query($query_params['limit'])
3520
+					);
3521
+					throw new EE_Error($e . "|" . $e);
3522
+				}
3523
+				// they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3524
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3525
+			} elseif (! empty($query_params['limit'])) {
3526
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3527
+			}
3528
+		}
3529
+		// set order by
3530
+		if (array_key_exists('order_by', $query_params)) {
3531
+			if (is_array($query_params['order_by'])) {
3532
+				// if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3533
+				// specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3534
+				// including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3535
+				if (array_key_exists('order', $query_params)) {
3536
+					throw new EE_Error(
3537
+						sprintf(
3538
+							esc_html__(
3539
+								"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 ",
3540
+								"event_espresso"
3541
+							),
3542
+							get_class($this),
3543
+							implode(", ", array_keys($query_params['order_by'])),
3544
+							implode(", ", $query_params['order_by']),
3545
+							$query_params['order']
3546
+						)
3547
+					);
3548
+				}
3549
+				$this->_extract_related_models_from_sub_params_array_keys(
3550
+					$query_params['order_by'],
3551
+					$query_object,
3552
+					'order_by'
3553
+				);
3554
+				// assume it's an array of fields to order by
3555
+				$order_array = [];
3556
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3557
+					$order         = $this->_extract_order($order);
3558
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3559
+				}
3560
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3561
+			} elseif (! empty($query_params['order_by'])) {
3562
+				$this->_extract_related_model_info_from_query_param(
3563
+					$query_params['order_by'],
3564
+					$query_object,
3565
+					'order',
3566
+					$query_params['order_by']
3567
+				);
3568
+				$order = isset($query_params['order'])
3569
+					? $this->_extract_order($query_params['order'])
3570
+					: 'DESC';
3571
+				$query_object->set_order_by_sql(
3572
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3573
+				);
3574
+			}
3575
+		}
3576
+		// if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3577
+		if (
3578
+			! array_key_exists('order_by', $query_params)
3579
+			&& array_key_exists('order', $query_params)
3580
+			&& ! empty($query_params['order'])
3581
+		) {
3582
+			$pk_field = $this->get_primary_key_field();
3583
+			$order    = $this->_extract_order($query_params['order']);
3584
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3585
+		}
3586
+		// set group by
3587
+		if (array_key_exists('group_by', $query_params)) {
3588
+			if (is_array($query_params['group_by'])) {
3589
+				// it's an array, so assume we'll be grouping by a bunch of stuff
3590
+				$group_by_array = [];
3591
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3592
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3593
+				}
3594
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3595
+			} elseif (! empty($query_params['group_by'])) {
3596
+				$query_object->set_group_by_sql(
3597
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3598
+				);
3599
+			}
3600
+		}
3601
+		// set having
3602
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3603
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3604
+		}
3605
+		// now, just verify they didn't pass anything wack
3606
+		foreach ($query_params as $query_key => $query_value) {
3607
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3608
+				throw new EE_Error(
3609
+					sprintf(
3610
+						esc_html__(
3611
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3612
+							'event_espresso'
3613
+						),
3614
+						$query_key,
3615
+						get_class($this),
3616
+						//                      print_r( $this->_allowed_query_params, TRUE )
3617
+						implode(',', $this->_allowed_query_params)
3618
+					)
3619
+				);
3620
+			}
3621
+		}
3622
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3623
+		if (empty($main_model_join_sql)) {
3624
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3625
+		}
3626
+		return $query_object;
3627
+	}
3628
+
3629
+
3630
+	/**
3631
+	 * Gets the where conditions that should be imposed on the query based on the
3632
+	 * context (eg reading frontend, backend, edit or delete).
3633
+	 *
3634
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3635
+	 * @return array
3636
+	 * @throws EE_Error
3637
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3638
+	 */
3639
+	public function caps_where_conditions($context = self::caps_read)
3640
+	{
3641
+		EEM_Base::verify_is_valid_cap_context($context);
3642
+		$cap_where_conditions = [];
3643
+		$cap_restrictions     = $this->caps_missing($context);
3644
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3645
+			$cap_where_conditions = array_replace_recursive(
3646
+				$cap_where_conditions,
3647
+				$restriction_if_no_cap->get_default_where_conditions()
3648
+			);
3649
+		}
3650
+		return apply_filters(
3651
+			'FHEE__EEM_Base__caps_where_conditions__return',
3652
+			$cap_where_conditions,
3653
+			$this,
3654
+			$context,
3655
+			$cap_restrictions
3656
+		);
3657
+	}
3658
+
3659
+
3660
+	/**
3661
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3662
+	 * otherwise throws an exception
3663
+	 *
3664
+	 * @param string $should_be_order_string
3665
+	 * @return string either ASC, asc, DESC or desc
3666
+	 * @throws EE_Error
3667
+	 */
3668
+	private function _extract_order($should_be_order_string)
3669
+	{
3670
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3671
+			return $should_be_order_string;
3672
+		}
3673
+		throw new EE_Error(
3674
+			sprintf(
3675
+				esc_html__(
3676
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3677
+					"event_espresso"
3678
+				),
3679
+				get_class($this),
3680
+				$should_be_order_string
3681
+			)
3682
+		);
3683
+	}
3684
+
3685
+
3686
+	/**
3687
+	 * Looks at all the models which are included in this query, and asks each
3688
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3689
+	 * so they can be merged
3690
+	 *
3691
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3692
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3693
+	 *                                                                  'none' means NO default where conditions will
3694
+	 *                                                                  be used AT ALL during this query.
3695
+	 *                                                                  'other_models_only' means default where
3696
+	 *                                                                  conditions from other models will be used, but
3697
+	 *                                                                  not for this primary model. 'all', the default,
3698
+	 *                                                                  means default where conditions will apply as
3699
+	 *                                                                  normal
3700
+	 * @param array                       $where_query_params
3701
+	 * @return array
3702
+	 * @throws EE_Error
3703
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3704
+	 */
3705
+	private function _get_default_where_conditions_for_models_in_query(
3706
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3707
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3708
+		$where_query_params = []
3709
+	) {
3710
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3711
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3712
+			throw new EE_Error(
3713
+				sprintf(
3714
+					esc_html__(
3715
+						"You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3716
+						"event_espresso"
3717
+					),
3718
+					$use_default_where_conditions,
3719
+					implode(", ", $allowed_used_default_where_conditions_values)
3720
+				)
3721
+			);
3722
+		}
3723
+		$universal_query_params = [];
3724
+		if ($this->_should_use_default_where_conditions($use_default_where_conditions)) {
3725
+			$universal_query_params = $this->_get_default_where_conditions();
3726
+		} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions)) {
3727
+			$universal_query_params = $this->_get_minimum_where_conditions();
3728
+		}
3729
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3730
+			$related_model = $this->get_related_model_obj($model_name);
3731
+			if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3732
+				$related_model_universal_where_params =
3733
+					$related_model->_get_default_where_conditions($model_relation_path);
3734
+			} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3735
+				$related_model_universal_where_params =
3736
+					$related_model->_get_minimum_where_conditions($model_relation_path);
3737
+			} else {
3738
+				// we don't want to add full or even minimum default where conditions from this model, so just continue
3739
+				continue;
3740
+			}
3741
+			$overrides              = $this->_override_defaults_or_make_null_friendly(
3742
+				$related_model_universal_where_params,
3743
+				$where_query_params,
3744
+				$related_model,
3745
+				$model_relation_path
3746
+			);
3747
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3748
+				$universal_query_params,
3749
+				$overrides
3750
+			);
3751
+		}
3752
+		return $universal_query_params;
3753
+	}
3754
+
3755
+
3756
+	/**
3757
+	 * Determines whether or not we should use default where conditions for the model in question
3758
+	 * (this model, or other related models).
3759
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3760
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3761
+	 * We should use default where conditions on related models when they requested to use default where conditions
3762
+	 * on all models, or specifically just on other related models
3763
+	 *
3764
+	 * @param      $default_where_conditions_value
3765
+	 * @param bool $for_this_model false means this is for OTHER related models
3766
+	 * @return bool
3767
+	 */
3768
+	private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3769
+	{
3770
+		return (
3771
+				   $for_this_model
3772
+				   && in_array(
3773
+					   $default_where_conditions_value,
3774
+					   [
3775
+						   EEM_Base::default_where_conditions_all,
3776
+						   EEM_Base::default_where_conditions_this_only,
3777
+						   EEM_Base::default_where_conditions_minimum_others,
3778
+					   ],
3779
+					   true
3780
+				   )
3781
+			   )
3782
+			   || (
3783
+				   ! $for_this_model
3784
+				   && in_array(
3785
+					   $default_where_conditions_value,
3786
+					   [
3787
+						   EEM_Base::default_where_conditions_all,
3788
+						   EEM_Base::default_where_conditions_others_only,
3789
+					   ],
3790
+					   true
3791
+				   )
3792
+			   );
3793
+	}
3794
+
3795
+
3796
+	/**
3797
+	 * Determines whether or not we should use default minimum conditions for the model in question
3798
+	 * (this model, or other related models).
3799
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3800
+	 * where conditions.
3801
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3802
+	 * on this model or others
3803
+	 *
3804
+	 * @param      $default_where_conditions_value
3805
+	 * @param bool $for_this_model false means this is for OTHER related models
3806
+	 * @return bool
3807
+	 */
3808
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3809
+	{
3810
+		return (
3811
+				   $for_this_model
3812
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3813
+			   )
3814
+			   || (
3815
+				   ! $for_this_model
3816
+				   && in_array(
3817
+					   $default_where_conditions_value,
3818
+					   [
3819
+						   EEM_Base::default_where_conditions_minimum_others,
3820
+						   EEM_Base::default_where_conditions_minimum_all,
3821
+					   ],
3822
+					   true
3823
+				   )
3824
+			   );
3825
+	}
3826
+
3827
+
3828
+	/**
3829
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3830
+	 * then we also add a special where condition which allows for that model's primary key
3831
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3832
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3833
+	 *
3834
+	 * @param array    $default_where_conditions
3835
+	 * @param array    $provided_where_conditions
3836
+	 * @param EEM_Base $model
3837
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3838
+	 * @return array
3839
+	 * @throws EE_Error
3840
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3841
+	 */
3842
+	private function _override_defaults_or_make_null_friendly(
3843
+		$default_where_conditions,
3844
+		$provided_where_conditions,
3845
+		$model,
3846
+		$model_relation_path
3847
+	) {
3848
+		$null_friendly_where_conditions = [];
3849
+		$none_overridden                = true;
3850
+		$or_condition_key_for_defaults  = 'OR*' . get_class($model);
3851
+		foreach ($default_where_conditions as $key => $val) {
3852
+			if (isset($provided_where_conditions[ $key ])) {
3853
+				$none_overridden = false;
3854
+			} else {
3855
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3856
+			}
3857
+		}
3858
+		if ($none_overridden && $default_where_conditions) {
3859
+			if ($model->has_primary_key_field()) {
3860
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3861
+																				   . "."
3862
+																				   . $model->primary_key_name() ] =
3863
+					['IS NULL'];
3864
+			}/*else{
3865 3865
                 //@todo NO PK, use other defaults
3866 3866
             }*/
3867
-        }
3868
-        return $null_friendly_where_conditions;
3869
-    }
3870
-
3871
-
3872
-    /**
3873
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3874
-     * default where conditions on all get_all, update, and delete queries done by this model.
3875
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3876
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3877
-     *
3878
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3879
-     * @return array
3880
-     * @throws EE_Error
3881
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3882
-     */
3883
-    private function _get_default_where_conditions($model_relation_path = '')
3884
-    {
3885
-        if ($this->_ignore_where_strategy) {
3886
-            return [];
3887
-        }
3888
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3889
-    }
3890
-
3891
-
3892
-    /**
3893
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3894
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3895
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3896
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3897
-     * Similar to _get_default_where_conditions
3898
-     *
3899
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3900
-     * @return array
3901
-     * @throws EE_Error
3902
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3903
-     */
3904
-    protected function _get_minimum_where_conditions($model_relation_path = '')
3905
-    {
3906
-        if ($this->_ignore_where_strategy) {
3907
-            return [];
3908
-        }
3909
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3910
-    }
3911
-
3912
-
3913
-    /**
3914
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3915
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3916
-     *
3917
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3918
-     * @return string
3919
-     * @throws EE_Error
3920
-     */
3921
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3922
-    {
3923
-        $selects = $this->_get_columns_to_select_for_this_model();
3924
-        foreach (
3925
-            $model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included
3926
-        ) {
3927
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3928
-            $other_model_selects  = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3929
-            foreach ($other_model_selects as $key => $value) {
3930
-                $selects[] = $value;
3931
-            }
3932
-        }
3933
-        return implode(", ", $selects);
3934
-    }
3935
-
3936
-
3937
-    /**
3938
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3939
-     * So that's going to be the columns for all the fields on the model
3940
-     *
3941
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3942
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3943
-     */
3944
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3945
-    {
3946
-        $fields                                       = $this->field_settings();
3947
-        $selects                                      = [];
3948
-        $table_alias_with_model_relation_chain_prefix =
3949
-            EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3950
-                $model_relation_chain,
3951
-                $this->get_this_model_name()
3952
-            );
3953
-        foreach ($fields as $field_obj) {
3954
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3955
-                         . $field_obj->get_table_alias()
3956
-                         . "."
3957
-                         . $field_obj->get_table_column()
3958
-                         . " AS '"
3959
-                         . $table_alias_with_model_relation_chain_prefix
3960
-                         . $field_obj->get_table_alias()
3961
-                         . "."
3962
-                         . $field_obj->get_table_column()
3963
-                         . "'";
3964
-        }
3965
-        // make sure we are also getting the PKs of each table
3966
-        $tables = $this->get_tables();
3967
-        if (count($tables) > 1) {
3968
-            foreach ($tables as $table_obj) {
3969
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3970
-                                       . $table_obj->get_fully_qualified_pk_column();
3971
-                if (! in_array($qualified_pk_column, $selects)) {
3972
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3973
-                }
3974
-            }
3975
-        }
3976
-        return $selects;
3977
-    }
3978
-
3979
-
3980
-    /**
3981
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3982
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3983
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3984
-     * SQL for joining, and the data types
3985
-     *
3986
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3987
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3988
-     * @param string                      $query_param_type     like Registration.Transaction.TXN_ID
3989
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3990
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3991
-     *                                                          or 'Registration's
3992
-     * @param string|null                 $original_query_param what it originally was (eg
3993
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3994
-     *                                                          matches $query_param
3995
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3996
-     * @throws EE_Error
3997
-     */
3998
-    private function _extract_related_model_info_from_query_param(
3999
-        $query_param,
4000
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4001
-        $query_param_type,
4002
-        $original_query_param = null
4003
-    ) {
4004
-        if ($original_query_param === null) {
4005
-            $original_query_param = $query_param;
4006
-        }
4007
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4008
-        // whether or not to allow logic_query_params like 'NOT','OR', or 'AND'
4009
-        $allow_logic_query_params = in_array($query_param_type, ['where', 'having', 0, 'custom_selects'], true);
4010
-        $allow_fields             = in_array(
4011
-            $query_param_type,
4012
-            ['where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0],
4013
-            true
4014
-        );
4015
-        // check to see if we have a field on this model
4016
-        $this_model_fields = $this->field_settings(true);
4017
-        if (array_key_exists($query_param, $this_model_fields)) {
4018
-            if ($allow_fields) {
4019
-                return;
4020
-            }
4021
-            throw new EE_Error(
4022
-                sprintf(
4023
-                    esc_html__(
4024
-                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
4025
-                        "event_espresso"
4026
-                    ),
4027
-                    $query_param,
4028
-                    get_class($this),
4029
-                    $query_param_type,
4030
-                    $original_query_param
4031
-                )
4032
-            );
4033
-        }
4034
-        // check if this is a special logic query param
4035
-        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4036
-            if ($allow_logic_query_params) {
4037
-                return;
4038
-            }
4039
-            throw new EE_Error(
4040
-                sprintf(
4041
-                    esc_html__(
4042
-                        'Logic query params ("%1$s") are being used incorrectly with the following query param ("%2$s") on model %3$s. %4$sAdditional Info:%4$s%5$s',
4043
-                        'event_espresso'
4044
-                    ),
4045
-                    implode('", "', $this->_logic_query_param_keys),
4046
-                    $query_param,
4047
-                    get_class($this),
4048
-                    '<br />',
4049
-                    "\t"
4050
-                    . ' $passed_in_query_info = <pre>'
4051
-                    . print_r($passed_in_query_info, true)
4052
-                    . '</pre>'
4053
-                    . "\n\t"
4054
-                    . ' $query_param_type = '
4055
-                    . $query_param_type
4056
-                    . "\n\t"
4057
-                    . ' $original_query_param = '
4058
-                    . $original_query_param
4059
-                )
4060
-            );
4061
-        }
4062
-        // check if it's a custom selection
4063
-        if (
4064
-            $this->_custom_selections instanceof CustomSelects
4065
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4066
-        ) {
4067
-            return;
4068
-        }
4069
-        // check if has a model name at the beginning
4070
-        // and
4071
-        // check if it's a field on a related model
4072
-        if (
4073
-        $this->extractJoinModelFromQueryParams(
4074
-            $passed_in_query_info,
4075
-            $query_param,
4076
-            $original_query_param,
4077
-            $query_param_type
4078
-        )
4079
-        ) {
4080
-            return;
4081
-        }
4082
-
4083
-        // ok so $query_param didn't start with a model name
4084
-        // and we previously confirmed it wasn't a logic query param or field on the current model
4085
-        // it's wack, that's what it is
4086
-        throw new EE_Error(
4087
-            sprintf(
4088
-                esc_html__(
4089
-                    "There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4090
-                    "event_espresso"
4091
-                ),
4092
-                $query_param,
4093
-                get_class($this),
4094
-                $query_param_type,
4095
-                $original_query_param
4096
-            )
4097
-        );
4098
-    }
4099
-
4100
-
4101
-    /**
4102
-     * Extracts any possible join model information from the provided possible_join_string.
4103
-     * This method will read the provided $possible_join_string value and determine if there are any possible model
4104
-     * join
4105
-     * parts that should be added to the query.
4106
-     *
4107
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4108
-     * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4109
-     * @param null|string                 $original_query_param
4110
-     * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4111
-     *                                                           ('where', 'order_by', 'group_by', 'custom_selects'
4112
-     *                                                           etc.)
4113
-     * @return bool  returns true if a join was added and false if not.
4114
-     * @throws EE_Error
4115
-     */
4116
-    private function extractJoinModelFromQueryParams(
4117
-        EE_Model_Query_Info_Carrier $query_info_carrier,
4118
-        $possible_join_string,
4119
-        $original_query_param,
4120
-        $query_parameter_type
4121
-    ) {
4122
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4123
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4124
-                $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4125
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4126
-                if ($possible_join_string === '') {
4127
-                    // nothing left to $query_param
4128
-                    // we should actually end in a field name, not a model like this!
4129
-                    throw new EE_Error(
4130
-                        sprintf(
4131
-                            esc_html__(
4132
-                                "Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4133
-                                "event_espresso"
4134
-                            ),
4135
-                            $possible_join_string,
4136
-                            $query_parameter_type,
4137
-                            get_class($this),
4138
-                            $valid_related_model_name
4139
-                        )
4140
-                    );
4141
-                }
4142
-                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4143
-                $related_model_obj->_extract_related_model_info_from_query_param(
4144
-                    $possible_join_string,
4145
-                    $query_info_carrier,
4146
-                    $query_parameter_type,
4147
-                    $original_query_param
4148
-                );
4149
-                return true;
4150
-            }
4151
-            if ($possible_join_string === $valid_related_model_name) {
4152
-                $this->_add_join_to_model(
4153
-                    $valid_related_model_name,
4154
-                    $query_info_carrier,
4155
-                    $original_query_param
4156
-                );
4157
-                return true;
4158
-            }
4159
-        }
4160
-        return false;
4161
-    }
4162
-
4163
-
4164
-    /**
4165
-     * Extracts related models from Custom Selects and sets up any joins for those related models.
4166
-     *
4167
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4168
-     * @throws EE_Error
4169
-     */
4170
-    private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4171
-    {
4172
-        if (
4173
-            $this->_custom_selections instanceof CustomSelects
4174
-            && ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4175
-                || $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4176
-            )
4177
-        ) {
4178
-            $original_selects = $this->_custom_selections->originalSelects();
4179
-            foreach ($original_selects as $alias => $select_configuration) {
4180
-                $this->extractJoinModelFromQueryParams(
4181
-                    $query_info_carrier,
4182
-                    $select_configuration[0],
4183
-                    $select_configuration[0],
4184
-                    'custom_selects'
4185
-                );
4186
-            }
4187
-        }
4188
-    }
4189
-
4190
-
4191
-    /**
4192
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4193
-     * and store it on $passed_in_query_info
4194
-     *
4195
-     * @param string                      $model_name
4196
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4197
-     * @param string                      $original_query_param used to extract the relation chain between the queried
4198
-     *                                                          model and $model_name. Eg, if we are querying Event,
4199
-     *                                                          and are adding a join to 'Payment' with the original
4200
-     *                                                          query param key
4201
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4202
-     *                                                          to extract 'Registration.Transaction.Payment', in case
4203
-     *                                                          Payment wants to add default query params so that it
4204
-     *                                                          will know what models to prepend onto its default query
4205
-     *                                                          params or in case it wants to rename tables (in case
4206
-     *                                                          there are multiple joins to the same table)
4207
-     * @return void
4208
-     * @throws EE_Error
4209
-     */
4210
-    private function _add_join_to_model(
4211
-        $model_name,
4212
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4213
-        $original_query_param
4214
-    ) {
4215
-        $relation_obj         = $this->related_settings_for($model_name);
4216
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4217
-        // check if the relation is HABTM, because then we're essentially doing two joins
4218
-        // If so, join first to the JOIN table, and add its data types, and then continue as normal
4219
-        if ($relation_obj instanceof EE_HABTM_Relation) {
4220
-            $join_model_obj = $relation_obj->get_join_model();
4221
-            // replace the model specified with the join model for this relation chain, whi
4222
-            $relation_chain_to_join_model =
4223
-                EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4224
-                    $model_name,
4225
-                    $join_model_obj->get_this_model_name(),
4226
-                    $model_relation_chain
4227
-                );
4228
-            $passed_in_query_info->merge(
4229
-                new EE_Model_Query_Info_Carrier(
4230
-                    [$relation_chain_to_join_model => $join_model_obj->get_this_model_name()],
4231
-                    $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4232
-                )
4233
-            );
4234
-        }
4235
-        // now just join to the other table pointed to by the relation object, and add its data types
4236
-        $passed_in_query_info->merge(
4237
-            new EE_Model_Query_Info_Carrier(
4238
-                [$model_relation_chain => $model_name],
4239
-                $relation_obj->get_join_statement($model_relation_chain)
4240
-            )
4241
-        );
4242
-    }
4243
-
4244
-
4245
-    /**
4246
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4247
-     *
4248
-     * @param array $where_params
4249
-     * @return string of SQL
4250
-     * @throws EE_Error
4251
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4252
-     */
4253
-    private function _construct_where_clause($where_params)
4254
-    {
4255
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4256
-        if ($SQL) {
4257
-            return " WHERE " . $SQL;
4258
-        }
4259
-        return '';
4260
-    }
4261
-
4262
-
4263
-    /**
4264
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4265
-     * and should be passed HAVING parameters, not WHERE parameters
4266
-     *
4267
-     * @param array $having_params
4268
-     * @return string
4269
-     * @throws EE_Error
4270
-     */
4271
-    private function _construct_having_clause($having_params)
4272
-    {
4273
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4274
-        if ($SQL) {
4275
-            return " HAVING " . $SQL;
4276
-        }
4277
-        return '';
4278
-    }
4279
-
4280
-
4281
-    /**
4282
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4283
-     * Event_Meta.meta_value = 'foo'))"
4284
-     *
4285
-     * @param array  $where_params
4286
-     * @param string $glue joins each sub-clause together. Should really only be " AND " or " OR "...
4287
-     * @return string of SQL
4288
-     * @throws EE_Error
4289
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4290
-     */
4291
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4292
-    {
4293
-        $where_clauses = [];
4294
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4295
-            $query_param =
4296
-                $this->_remove_stars_and_anything_after_from_condition_query_param_key(
4297
-                    $query_param
4298
-                );// str_replace("*",'',$query_param);
4299
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
4300
-                switch ($query_param) {
4301
-                    case 'not':
4302
-                    case 'NOT':
4303
-                        $where_clauses[] = "! ("
4304
-                                           . $this->_construct_condition_clause_recursive(
4305
-                                $op_and_value_or_sub_condition,
4306
-                                $glue
4307
-                            )
4308
-                                           . ")";
4309
-                        break;
4310
-                    case 'and':
4311
-                    case 'AND':
4312
-                        $where_clauses[] = " ("
4313
-                                           . $this->_construct_condition_clause_recursive(
4314
-                                $op_and_value_or_sub_condition,
4315
-                                ' AND '
4316
-                            )
4317
-                                           . ")";
4318
-                        break;
4319
-                    case 'or':
4320
-                    case 'OR':
4321
-                        $where_clauses[] = " ("
4322
-                                           . $this->_construct_condition_clause_recursive(
4323
-                                $op_and_value_or_sub_condition,
4324
-                                ' OR '
4325
-                            )
4326
-                                           . ")";
4327
-                        break;
4328
-                }
4329
-            } else {
4330
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4331
-                // if it's not a normal field, maybe it's a custom selection?
4332
-                if (! $field_obj) {
4333
-                    if ($this->_custom_selections instanceof CustomSelects) {
4334
-                        $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4335
-                    } else {
4336
-                        throw new EE_Error(
4337
-                            sprintf(
4338
-                                esc_html__(
4339
-                                    "%s is neither a valid model field name, nor a custom selection",
4340
-                                    "event_espresso"
4341
-                                ),
4342
-                                $query_param
4343
-                            )
4344
-                        );
4345
-                    }
4346
-                }
4347
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4348
-                $where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4349
-            }
4350
-        }
4351
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4352
-    }
4353
-
4354
-
4355
-    /**
4356
-     * Takes the input parameter and extract the table name (alias) and column name
4357
-     *
4358
-     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4359
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4360
-     * @throws EE_Error
4361
-     */
4362
-    private function _deduce_column_name_from_query_param($query_param)
4363
-    {
4364
-        $field = $this->_deduce_field_from_query_param($query_param);
4365
-        if ($field) {
4366
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4367
-                $field->get_model_name(),
4368
-                $query_param
4369
-            );
4370
-            return $table_alias_prefix . $field->get_qualified_column();
4371
-        }
4372
-        if (
4373
-            $this->_custom_selections instanceof CustomSelects
4374
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4375
-        ) {
4376
-            // maybe it's custom selection item?
4377
-            // if so, just use it as the "column name"
4378
-            return $query_param;
4379
-        }
4380
-        $custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4381
-            ? implode(',', $this->_custom_selections->columnAliases())
4382
-            : '';
4383
-        throw new EE_Error(
4384
-            sprintf(
4385
-                esc_html__(
4386
-                    "%s is not a valid field on this model, nor a custom selection (%s)",
4387
-                    "event_espresso"
4388
-                ),
4389
-                $query_param,
4390
-                $custom_select_aliases
4391
-            )
4392
-        );
4393
-    }
4394
-
4395
-
4396
-    /**
4397
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4398
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4399
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4400
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4401
-     *
4402
-     * @param string $condition_query_param_key
4403
-     * @return string
4404
-     */
4405
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4406
-    {
4407
-        $pos_of_star = strpos($condition_query_param_key, '*');
4408
-        if ($pos_of_star === false) {
4409
-            return $condition_query_param_key;
4410
-        }
4411
-        return substr($condition_query_param_key, 0, $pos_of_star);
4412
-    }
4413
-
4414
-
4415
-    /**
4416
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4417
-     *
4418
-     * @param mixed      array | string    $op_and_value
4419
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4420
-     * @return string
4421
-     * @throws EE_Error
4422
-     */
4423
-    private function _construct_op_and_value($op_and_value, $field_obj)
4424
-    {
4425
-        if (is_array($op_and_value)) {
4426
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4427
-            if (! $operator) {
4428
-                $php_array_like_string = [];
4429
-                foreach ($op_and_value as $key => $value) {
4430
-                    $php_array_like_string[] = "$key=>$value";
4431
-                }
4432
-                throw new EE_Error(
4433
-                    sprintf(
4434
-                        esc_html__(
4435
-                            "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))",
4436
-                            "event_espresso"
4437
-                        ),
4438
-                        implode(",", $php_array_like_string)
4439
-                    )
4440
-                );
4441
-            }
4442
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4443
-        } else {
4444
-            $operator = '=';
4445
-            $value    = $op_and_value;
4446
-        }
4447
-        // check to see if the value is actually another field
4448
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4449
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4450
-        }
4451
-        if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4452
-            // in this case, the value should be an array, or at least a comma-separated list
4453
-            // it will need to handle a little differently
4454
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4455
-            // note: $cleaned_value has already been run through $wpdb->prepare()
4456
-            return $operator . SP . $cleaned_value;
4457
-        }
4458
-        if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4459
-            // the value should be an array with count of two.
4460
-            if (count($value) !== 2) {
4461
-                throw new EE_Error(
4462
-                    sprintf(
4463
-                        esc_html__(
4464
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4465
-                            'event_espresso'
4466
-                        ),
4467
-                        "BETWEEN"
4468
-                    )
4469
-                );
4470
-            }
4471
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4472
-            return $operator . SP . $cleaned_value;
4473
-        }
4474
-        if (in_array($operator, $this->valid_null_style_operators())) {
4475
-            if ($value !== null) {
4476
-                throw new EE_Error(
4477
-                    sprintf(
4478
-                        esc_html__(
4479
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4480
-                            "event_espresso"
4481
-                        ),
4482
-                        $value,
4483
-                        $operator
4484
-                    )
4485
-                );
4486
-            }
4487
-            return $operator;
4488
-        }
4489
-        if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4490
-            // if the operator is 'LIKE', we want to allow percent signs (%) and not
4491
-            // remove other junk. So just treat it as a string.
4492
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4493
-        }
4494
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4495
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4496
-        }
4497
-        if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4498
-            throw new EE_Error(
4499
-                sprintf(
4500
-                    esc_html__(
4501
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4502
-                        'event_espresso'
4503
-                    ),
4504
-                    $operator,
4505
-                    $operator
4506
-                )
4507
-            );
4508
-        }
4509
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4510
-            throw new EE_Error(
4511
-                sprintf(
4512
-                    esc_html__(
4513
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4514
-                        'event_espresso'
4515
-                    ),
4516
-                    $operator,
4517
-                    $operator
4518
-                )
4519
-            );
4520
-        }
4521
-        throw new EE_Error(
4522
-            sprintf(
4523
-                esc_html__(
4524
-                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4525
-                    "event_espresso"
4526
-                ),
4527
-                http_build_query($op_and_value)
4528
-            )
4529
-        );
4530
-    }
4531
-
4532
-
4533
-    /**
4534
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4535
-     *
4536
-     * @param array                      $values
4537
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4538
-     *                                              '%s'
4539
-     * @return string
4540
-     * @throws EE_Error
4541
-     */
4542
-    public function _construct_between_value($values, $field_obj)
4543
-    {
4544
-        $cleaned_values = [];
4545
-        foreach ($values as $value) {
4546
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4547
-        }
4548
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4549
-    }
4550
-
4551
-
4552
-    /**
4553
-     * Takes an array or a comma-separated list of $values and cleans them
4554
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4555
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4556
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4557
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4558
-     *
4559
-     * @param mixed                      $values    array or comma-separated string
4560
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4561
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4562
-     * @throws EE_Error
4563
-     */
4564
-    public function _construct_in_value($values, $field_obj)
4565
-    {
4566
-        // check if the value is a CSV list
4567
-        if (is_string($values)) {
4568
-            // in which case, turn it into an array
4569
-            $values = explode(",", $values);
4570
-        }
4571
-        $cleaned_values = [];
4572
-        foreach ($values as $value) {
4573
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4574
-        }
4575
-        // we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4576
-        // but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4577
-        // which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4578
-        if (empty($cleaned_values)) {
4579
-            $all_fields       = $this->field_settings();
4580
-            $a_field          = array_shift($all_fields);
4581
-            $main_table       = $this->_get_main_table();
4582
-            $cleaned_values[] = "SELECT "
4583
-                                . $a_field->get_table_column()
4584
-                                . " FROM "
4585
-                                . $main_table->get_table_name()
4586
-                                . " WHERE FALSE";
4587
-        }
4588
-        return "(" . implode(",", $cleaned_values) . ")";
4589
-    }
4590
-
4591
-
4592
-    /**
4593
-     * @param mixed                      $value
4594
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4595
-     * @return false|null|string
4596
-     * @throws EE_Error
4597
-     */
4598
-    private function _wpdb_prepare_using_field($value, $field_obj)
4599
-    {
4600
-        global $wpdb;
4601
-        if ($field_obj instanceof EE_Model_Field_Base) {
4602
-            return $wpdb->prepare(
4603
-                $field_obj->get_wpdb_data_type(),
4604
-                $this->_prepare_value_for_use_in_db($value, $field_obj)
4605
-            );
4606
-        } //$field_obj should really just be a data type
4607
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4608
-            throw new EE_Error(
4609
-                sprintf(
4610
-                    esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4611
-                    $field_obj,
4612
-                    implode(",", $this->_valid_wpdb_data_types)
4613
-                )
4614
-            );
4615
-        }
4616
-        return $wpdb->prepare($field_obj, $value);
4617
-    }
4618
-
4619
-
4620
-    /**
4621
-     * Takes the input parameter and finds the model field that it indicates.
4622
-     *
4623
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4624
-     * @return EE_Model_Field_Base
4625
-     * @throws EE_Error
4626
-     */
4627
-    protected function _deduce_field_from_query_param($query_param_name)
4628
-    {
4629
-        // ok, now proceed with deducing which part is the model's name, and which is the field's name
4630
-        // which will help us find the database table and column
4631
-        $query_param_parts = explode(".", $query_param_name);
4632
-        if (empty($query_param_parts)) {
4633
-            throw new EE_Error(
4634
-                sprintf(
4635
-                    esc_html__(
4636
-                        "_extract_column_name is empty when trying to extract column and table name from %s",
4637
-                        'event_espresso'
4638
-                    ),
4639
-                    $query_param_name
4640
-                )
4641
-            );
4642
-        }
4643
-        $number_of_parts       = count($query_param_parts);
4644
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4645
-        if ($number_of_parts === 1) {
4646
-            $field_name = $last_query_param_part;
4647
-            $model_obj  = $this;
4648
-        } else {// $number_of_parts >= 2
4649
-            // the last part is the column name, and there are only 2parts. therefore...
4650
-            $field_name = $last_query_param_part;
4651
-            $model_obj  = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4652
-        }
4653
-        try {
4654
-            return $model_obj->field_settings_for($field_name);
4655
-        } catch (EE_Error $e) {
4656
-            return null;
4657
-        }
4658
-    }
4659
-
4660
-
4661
-    /**
4662
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4663
-     * alias and column which corresponds to it
4664
-     *
4665
-     * @param string $field_name
4666
-     * @return string
4667
-     * @throws EE_Error
4668
-     */
4669
-    public function _get_qualified_column_for_field($field_name)
4670
-    {
4671
-        $all_fields = $this->field_settings();
4672
-        $field      = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4673
-        if ($field) {
4674
-            return $field->get_qualified_column();
4675
-        }
4676
-        throw new EE_Error(
4677
-            sprintf(
4678
-                esc_html__(
4679
-                    "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.",
4680
-                    'event_espresso'
4681
-                ),
4682
-                $field_name,
4683
-                get_class($this)
4684
-            )
4685
-        );
4686
-    }
4687
-
4688
-
4689
-    /**
4690
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4691
-     * Example usage:
4692
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4693
-     *      array(),
4694
-     *      ARRAY_A,
4695
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4696
-     *  );
4697
-     * is equivalent to
4698
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4699
-     * and
4700
-     *  EEM_Event::instance()->get_all_wpdb_results(
4701
-     *      array(
4702
-     *          array(
4703
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4704
-     *          ),
4705
-     *          ARRAY_A,
4706
-     *          implode(
4707
-     *              ', ',
4708
-     *              array_merge(
4709
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4710
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4711
-     *              )
4712
-     *          )
4713
-     *      )
4714
-     *  );
4715
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4716
-     *
4717
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4718
-     *                                            and the one whose fields you are selecting for example: when querying
4719
-     *                                            tickets model and selecting fields from the tickets model you would
4720
-     *                                            leave this parameter empty, because no models are needed to join
4721
-     *                                            between the queried model and the selected one. Likewise when
4722
-     *                                            querying the datetime model and selecting fields from the tickets
4723
-     *                                            model, it would also be left empty, because there is a direct
4724
-     *                                            relation from datetimes to tickets, so no model is needed to join
4725
-     *                                            them together. However, when querying from the event model and
4726
-     *                                            selecting fields from the ticket model, you should provide the string
4727
-     *                                            'Datetime', indicating that the event model must first join to the
4728
-     *                                            datetime model in order to find its relation to ticket model.
4729
-     *                                            Also, when querying from the venue model and selecting fields from
4730
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4731
-     *                                            indicating you need to join the venue model to the event model,
4732
-     *                                            to the datetime model, in order to find its relation to the ticket
4733
-     *                                            model. This string is used to deduce the prefix that gets added onto
4734
-     *                                            the models' tables qualified columns
4735
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4736
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4737
-     *                                            qualified column names
4738
-     * @return array|string
4739
-     */
4740
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4741
-    {
4742
-        $table_prefix      = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4743
-        $qualified_columns = [];
4744
-        foreach ($this->field_settings() as $field_name => $field) {
4745
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4746
-        }
4747
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4748
-    }
4749
-
4750
-
4751
-    /**
4752
-     * constructs the select use on special limit joins
4753
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4754
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4755
-     * (as that is typically where the limits would be set).
4756
-     *
4757
-     * @param string       $table_alias The table the select is being built for
4758
-     * @param mixed|string $limit       The limit for this select
4759
-     * @return string                The final select join element for the query.
4760
-     * @throws EE_Error
4761
-     */
4762
-    public function _construct_limit_join_select($table_alias, $limit)
4763
-    {
4764
-        $SQL = '';
4765
-        foreach ($this->_tables as $table_obj) {
4766
-            if ($table_obj instanceof EE_Primary_Table) {
4767
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4768
-                    ? $table_obj->get_select_join_limit($limit)
4769
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4770
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4771
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4772
-                    ? $table_obj->get_select_join_limit_join($limit)
4773
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4774
-            }
4775
-        }
4776
-        return $SQL;
4777
-    }
4778
-
4779
-
4780
-    /**
4781
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4782
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4783
-     *
4784
-     * @return string SQL
4785
-     * @throws EE_Error
4786
-     */
4787
-    public function _construct_internal_join()
4788
-    {
4789
-        $SQL = $this->_get_main_table()->get_table_sql();
4790
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4791
-        return $SQL;
4792
-    }
4793
-
4794
-
4795
-    /**
4796
-     * Constructs the SQL for joining all the tables on this model.
4797
-     * Normally $alias should be the primary table's alias, but in cases where
4798
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4799
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4800
-     * alias, this will construct SQL like:
4801
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4802
-     * With $alias being a secondary table's alias, this will construct SQL like:
4803
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4804
-     *
4805
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4806
-     * @return string
4807
-     * @throws EE_Error
4808
-     */
4809
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4810
-    {
4811
-        $SQL               = '';
4812
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4813
-        foreach ($this->_tables as $table_obj) {
4814
-            if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4815
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4816
-                    // so we're joining to this table, meaning the table is already in
4817
-                    // the FROM statement, BUT the primary table isn't. So we want
4818
-                    // to add the inverse join sql
4819
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4820
-                } else {
4821
-                    // just add a regular JOIN to this table from the primary table
4822
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4823
-                }
4824
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4825
-        }
4826
-        return $SQL;
4827
-    }
4828
-
4829
-
4830
-    /**
4831
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4832
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4833
-     * their data type (eg, '%s', '%d', etc)
4834
-     *
4835
-     * @return array
4836
-     */
4837
-    public function _get_data_types()
4838
-    {
4839
-        $data_types = [];
4840
-        foreach ($this->field_settings() as $field_obj) {
4841
-            // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4842
-            /** @var $field_obj EE_Model_Field_Base */
4843
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4844
-        }
4845
-        return $data_types;
4846
-    }
4847
-
4848
-
4849
-    /**
4850
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4851
-     *
4852
-     * @param string $model_name
4853
-     * @return EEM_Base
4854
-     * @throws EE_Error
4855
-     */
4856
-    public function get_related_model_obj($model_name)
4857
-    {
4858
-        $model_classname = "EEM_" . $model_name;
4859
-        if (! class_exists($model_classname)) {
4860
-            throw new EE_Error(
4861
-                sprintf(
4862
-                    esc_html__(
4863
-                        "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4864
-                        'event_espresso'
4865
-                    ),
4866
-                    $model_name,
4867
-                    $model_classname
4868
-                )
4869
-            );
4870
-        }
4871
-        return call_user_func($model_classname . "::instance");
4872
-    }
4873
-
4874
-
4875
-    /**
4876
-     * Returns the array of EE_ModelRelations for this model.
4877
-     *
4878
-     * @return EE_Model_Relation_Base[]
4879
-     */
4880
-    public function relation_settings()
4881
-    {
4882
-        return $this->_model_relations;
4883
-    }
4884
-
4885
-
4886
-    /**
4887
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4888
-     * because without THOSE models, this model probably doesn't have much purpose.
4889
-     * (Eg, without an event, datetimes have little purpose.)
4890
-     *
4891
-     * @return EE_Belongs_To_Relation[]
4892
-     */
4893
-    public function belongs_to_relations()
4894
-    {
4895
-        $belongs_to_relations = [];
4896
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4897
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4898
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4899
-            }
4900
-        }
4901
-        return $belongs_to_relations;
4902
-    }
4903
-
4904
-
4905
-    /**
4906
-     * Returns the specified EE_Model_Relation, or throws an exception
4907
-     *
4908
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4909
-     * @return EE_Model_Relation_Base
4910
-     * @throws EE_Error
4911
-     */
4912
-    public function related_settings_for($relation_name)
4913
-    {
4914
-        $relatedModels = $this->relation_settings();
4915
-        if (! array_key_exists($relation_name, $relatedModels)) {
4916
-            throw new EE_Error(
4917
-                sprintf(
4918
-                    esc_html__(
4919
-                        'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4920
-                        'event_espresso'
4921
-                    ),
4922
-                    $relation_name,
4923
-                    $this->_get_class_name(),
4924
-                    implode(', ', array_keys($relatedModels))
4925
-                )
4926
-            );
4927
-        }
4928
-        return $relatedModels[ $relation_name ];
4929
-    }
4930
-
4931
-
4932
-    /**
4933
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4934
-     * fields
4935
-     *
4936
-     * @param string  $fieldName
4937
-     * @param boolean $include_db_only_fields
4938
-     * @return EE_Model_Field_Base
4939
-     * @throws EE_Error
4940
-     */
4941
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
4942
-    {
4943
-        $fieldSettings = $this->field_settings($include_db_only_fields);
4944
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4945
-            throw new EE_Error(
4946
-                sprintf(
4947
-                    esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
4948
-                    $fieldName,
4949
-                    get_class($this)
4950
-                )
4951
-            );
4952
-        }
4953
-        return $fieldSettings[ $fieldName ];
4954
-    }
4955
-
4956
-
4957
-    /**
4958
-     * Checks if this field exists on this model
4959
-     *
4960
-     * @param string $fieldName a key in the model's _field_settings array
4961
-     * @return boolean
4962
-     */
4963
-    public function has_field($fieldName)
4964
-    {
4965
-        $fieldSettings = $this->field_settings(true);
4966
-        if (isset($fieldSettings[ $fieldName ])) {
4967
-            return true;
4968
-        }
4969
-        return false;
4970
-    }
4971
-
4972
-
4973
-    /**
4974
-     * Returns whether or not this model has a relation to the specified model
4975
-     *
4976
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4977
-     * @return boolean
4978
-     */
4979
-    public function has_relation($relation_name)
4980
-    {
4981
-        $relations = $this->relation_settings();
4982
-        if (isset($relations[ $relation_name ])) {
4983
-            return true;
4984
-        }
4985
-        return false;
4986
-    }
4987
-
4988
-
4989
-    /**
4990
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4991
-     * Eg, on EE_Answer that would be ANS_ID field object
4992
-     *
4993
-     * @param $field_obj
4994
-     * @return boolean
4995
-     */
4996
-    public function is_primary_key_field($field_obj)
4997
-    {
4998
-        return $field_obj instanceof EE_Primary_Key_Field_Base;
4999
-    }
5000
-
5001
-
5002
-    /**
5003
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
5004
-     * Eg, on EE_Answer that would be ANS_ID field object
5005
-     *
5006
-     * @return EE_Model_Field_Base
5007
-     * @throws EE_Error
5008
-     */
5009
-    public function get_primary_key_field()
5010
-    {
5011
-        if ($this->_primary_key_field === null) {
5012
-            foreach ($this->field_settings(true) as $field_obj) {
5013
-                if ($this->is_primary_key_field($field_obj)) {
5014
-                    $this->_primary_key_field = $field_obj;
5015
-                    break;
5016
-                }
5017
-            }
5018
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5019
-                throw new EE_Error(
5020
-                    sprintf(
5021
-                        esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
5022
-                        get_class($this)
5023
-                    )
5024
-                );
5025
-            }
5026
-        }
5027
-        return $this->_primary_key_field;
5028
-    }
5029
-
5030
-
5031
-    /**
5032
-     * Returns whether or not not there is a primary key on this model.
5033
-     * Internally does some caching.
5034
-     *
5035
-     * @return boolean
5036
-     */
5037
-    public function has_primary_key_field()
5038
-    {
5039
-        if ($this->_has_primary_key_field === null) {
5040
-            try {
5041
-                $this->get_primary_key_field();
5042
-                $this->_has_primary_key_field = true;
5043
-            } catch (EE_Error $e) {
5044
-                $this->_has_primary_key_field = false;
5045
-            }
5046
-        }
5047
-        return $this->_has_primary_key_field;
5048
-    }
5049
-
5050
-
5051
-    /**
5052
-     * Finds the first field of type $field_class_name.
5053
-     *
5054
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5055
-     *                                 EE_Foreign_Key_Field, etc
5056
-     * @return EE_Model_Field_Base or null if none is found
5057
-     */
5058
-    public function get_a_field_of_type($field_class_name)
5059
-    {
5060
-        foreach ($this->field_settings() as $field) {
5061
-            if ($field instanceof $field_class_name) {
5062
-                return $field;
5063
-            }
5064
-        }
5065
-        return null;
5066
-    }
5067
-
5068
-
5069
-    /**
5070
-     * Gets a foreign key field pointing to model.
5071
-     *
5072
-     * @param string $model_name eg Event, Registration, not EEM_Event
5073
-     * @return EE_Foreign_Key_Field_Base
5074
-     * @throws EE_Error
5075
-     */
5076
-    public function get_foreign_key_to($model_name)
5077
-    {
5078
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5079
-            foreach ($this->field_settings() as $field) {
5080
-                if (
5081
-                    $field instanceof EE_Foreign_Key_Field_Base
5082
-                    && in_array($model_name, $field->get_model_names_pointed_to())
5083
-                ) {
5084
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5085
-                    break;
5086
-                }
5087
-            }
5088
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5089
-                throw new EE_Error(
5090
-                    sprintf(
5091
-                        esc_html__(
5092
-                            "There is no foreign key field pointing to model %s on model %s",
5093
-                            'event_espresso'
5094
-                        ),
5095
-                        $model_name,
5096
-                        get_class($this)
5097
-                    )
5098
-                );
5099
-            }
5100
-        }
5101
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5102
-    }
5103
-
5104
-
5105
-    /**
5106
-     * Gets the table name (including $wpdb->prefix) for the table alias
5107
-     *
5108
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5109
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5110
-     *                            Either one works
5111
-     * @return string
5112
-     */
5113
-    public function get_table_for_alias($table_alias)
5114
-    {
5115
-        $table_alias_sans_model_relation_chain_prefix =
5116
-            EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5117
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5118
-    }
5119
-
5120
-
5121
-    /**
5122
-     * Returns a flat array of all field son this model, instead of organizing them
5123
-     * by table_alias as they are in the constructor.
5124
-     *
5125
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5126
-     * @return EE_Model_Field_Base[] where the keys are the field's name
5127
-     */
5128
-    public function field_settings($include_db_only_fields = false)
5129
-    {
5130
-        if ($include_db_only_fields) {
5131
-            if ($this->_cached_fields === null) {
5132
-                $this->_cached_fields = [];
5133
-                foreach ($this->_fields as $fields_corresponding_to_table) {
5134
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5135
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5136
-                    }
5137
-                }
5138
-            }
5139
-            return $this->_cached_fields;
5140
-        }
5141
-        if ($this->_cached_fields_non_db_only === null) {
5142
-            $this->_cached_fields_non_db_only = [];
5143
-            foreach ($this->_fields as $fields_corresponding_to_table) {
5144
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5145
-                    /** @var $field_obj EE_Model_Field_Base */
5146
-                    if (! $field_obj->is_db_only_field()) {
5147
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5148
-                    }
5149
-                }
5150
-            }
5151
-        }
5152
-        return $this->_cached_fields_non_db_only;
5153
-    }
5154
-
5155
-
5156
-    /**
5157
-     *        cycle though array of attendees and create objects out of each item
5158
-     *
5159
-     * @access        private
5160
-     * @param array $rows        of results of $wpdb->get_results($query,ARRAY_A)
5161
-     * @return EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5162
-     *                           numerically indexed)
5163
-     * @throws EE_Error
5164
-     * @throws ReflectionException
5165
-     */
5166
-    protected function _create_objects($rows = [])
5167
-    {
5168
-        $array_of_objects = [];
5169
-        if (empty($rows)) {
5170
-            return [];
5171
-        }
5172
-        $count_if_model_has_no_primary_key = 0;
5173
-        $has_primary_key                   = $this->has_primary_key_field();
5174
-        $primary_key_field                 = $has_primary_key ? $this->get_primary_key_field() : null;
5175
-        foreach ((array)$rows as $row) {
5176
-            if (empty($row)) {
5177
-                // wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5178
-                return [];
5179
-            }
5180
-            // check if we've already set this object in the results array,
5181
-            // in which case there's no need to process it further (again)
5182
-            if ($has_primary_key) {
5183
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5184
-                    $row,
5185
-                    $primary_key_field->get_qualified_column(),
5186
-                    $primary_key_field->get_table_column()
5187
-                );
5188
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5189
-                    continue;
5190
-                }
5191
-            }
5192
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
5193
-            if (! $classInstance) {
5194
-                throw new EE_Error(
5195
-                    sprintf(
5196
-                        esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
5197
-                        $this->get_this_model_name(),
5198
-                        http_build_query($row)
5199
-                    )
5200
-                );
5201
-            }
5202
-            // set the timezone on the instantiated objects
5203
-            $classInstance->set_timezone($this->get_timezone(), true);
5204
-            // make sure if there is any timezone setting present that we set the timezone for the object
5205
-            $key                      = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5206
-            $array_of_objects[ $key ] = $classInstance;
5207
-            // also, for all the relations of type BelongsTo, see if we can cache
5208
-            // those related models
5209
-            // (we could do this for other relations too, but if there are conditions
5210
-            // that filtered out some fo the results, then we'd be caching an incomplete set
5211
-            // so it requires a little more thought than just caching them immediately...)
5212
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
5213
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
5214
-                    // check if this model's INFO is present. If so, cache it on the model
5215
-                    $other_model           = $relation_obj->get_other_model();
5216
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5217
-                    // if we managed to make a model object from the results, cache it on the main model object
5218
-                    if ($other_model_obj_maybe) {
5219
-                        // set timezone on these other model objects if they are present
5220
-                        $other_model_obj_maybe->set_timezone($this->get_timezone(), true);
5221
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
5222
-                    }
5223
-                }
5224
-            }
5225
-            // also, if this was a custom select query, let's see if there are any results for the custom select fields
5226
-            // and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5227
-            // the field in the CustomSelects object
5228
-            if ($this->_custom_selections instanceof CustomSelects) {
5229
-                $classInstance->setCustomSelectsValues(
5230
-                    $this->getValuesForCustomSelectAliasesFromResults($row)
5231
-                );
5232
-            }
5233
-        }
5234
-        return $array_of_objects;
5235
-    }
5236
-
5237
-
5238
-    /**
5239
-     * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5240
-     * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5241
-     *
5242
-     * @param array $db_results_row
5243
-     * @return array
5244
-     */
5245
-    protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5246
-    {
5247
-        $results = [];
5248
-        if ($this->_custom_selections instanceof CustomSelects) {
5249
-            foreach ($this->_custom_selections->columnAliases() as $alias) {
5250
-                if (isset($db_results_row[ $alias ])) {
5251
-                    $results[ $alias ] = $this->convertValueToDataType(
5252
-                        $db_results_row[ $alias ],
5253
-                        $this->_custom_selections->getDataTypeForAlias($alias)
5254
-                    );
5255
-                }
5256
-            }
5257
-        }
5258
-        return $results;
5259
-    }
5260
-
5261
-
5262
-    /**
5263
-     * This will set the value for the given alias
5264
-     *
5265
-     * @param string $value
5266
-     * @param string $datatype (one of %d, %s, %f)
5267
-     * @return int|string|float (int for %d, string for %s, float for %f)
5268
-     */
5269
-    protected function convertValueToDataType($value, $datatype)
5270
-    {
5271
-        switch ($datatype) {
5272
-            case '%f':
5273
-                return (float)$value;
5274
-            case '%d':
5275
-                return (int)$value;
5276
-            default:
5277
-                return (string)$value;
5278
-        }
5279
-    }
5280
-
5281
-
5282
-    /**
5283
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5284
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5285
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5286
-     * object (as set in the model_field!).
5287
-     *
5288
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5289
-     * @throws EE_Error
5290
-     * @throws ReflectionException
5291
-     */
5292
-    public function create_default_object()
5293
-    {
5294
-        $this_model_fields_and_values = [];
5295
-        // setup the row using default values;
5296
-        foreach ($this->field_settings() as $field_name => $field_obj) {
5297
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5298
-        }
5299
-        $className = $this->_get_class_name();
5300
-        return EE_Registry::instance()->load_class(
5301
-            $className,
5302
-            [$this_model_fields_and_values],
5303
-            false,
5304
-            false
5305
-        );
5306
-    }
5307
-
5308
-
5309
-    /**
5310
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5311
-     *                             or an stdClass where each property is the name of a column,
5312
-     * @return EE_Base_Class
5313
-     * @throws EE_Error
5314
-     * @throws ReflectionException
5315
-     */
5316
-    public function instantiate_class_from_array_or_object($cols_n_values)
5317
-    {
5318
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5319
-            $cols_n_values = get_object_vars($cols_n_values);
5320
-        }
5321
-        $primary_key = null;
5322
-        // make sure the array only has keys that are fields/columns on this model
5323
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5324
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5325
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5326
-        }
5327
-        $className = $this->_get_class_name();
5328
-        // check we actually found results that we can use to build our model object
5329
-        // if not, return null
5330
-        if ($this->has_primary_key_field()) {
5331
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5332
-                return null;
5333
-            }
5334
-        } elseif ($this->unique_indexes()) {
5335
-            $first_column = reset($this_model_fields_n_values);
5336
-            if (empty($first_column)) {
5337
-                return null;
5338
-            }
5339
-        }
5340
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5341
-        if ($primary_key) {
5342
-            $classInstance = $this->get_from_entity_map($primary_key);
5343
-            if (! $classInstance) {
5344
-                $classInstance = EE_Registry::instance()->load_class(
5345
-                    $className,
5346
-                    [$this_model_fields_n_values, $this->get_timezone()],
5347
-                    true,
5348
-                    false
5349
-                );
5350
-                // add this new object to the entity map
5351
-                $classInstance = $this->add_to_entity_map($classInstance);
5352
-            }
5353
-        } else {
5354
-            $classInstance = EE_Registry::instance()->load_class(
5355
-                $className,
5356
-                [$this_model_fields_n_values, $this->get_timezone()],
5357
-                true,
5358
-                false
5359
-            );
5360
-        }
5361
-        return $classInstance;
5362
-    }
5363
-
5364
-
5365
-    /**
5366
-     * Gets the model object from the  entity map if it exists
5367
-     *
5368
-     * @param int|string $id the ID of the model object
5369
-     * @return EE_Base_Class
5370
-     */
5371
-    public function get_from_entity_map($id)
5372
-    {
5373
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5374
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]
5375
-            : null;
5376
-    }
5377
-
5378
-
5379
-    /**
5380
-     * add_to_entity_map
5381
-     * Adds the object to the model's entity mappings
5382
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5383
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5384
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5385
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5386
-     *        then this method should be called immediately after the update query
5387
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5388
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5389
-     *
5390
-     * @param EE_Base_Class $object
5391
-     * @return EE_Base_Class
5392
-     * @throws EE_Error
5393
-     */
5394
-    public function add_to_entity_map(EE_Base_Class $object)
5395
-    {
5396
-        $className = $this->_get_class_name();
5397
-        if (! $object instanceof $className) {
5398
-            throw new EE_Error(
5399
-                sprintf(
5400
-                    esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5401
-                    is_object($object) ? get_class($object) : $object,
5402
-                    $className
5403
-                )
5404
-            );
5405
-        }
5406
-        if (! $object->ID()) {
5407
-            throw new EE_Error(
5408
-                sprintf(
5409
-                    esc_html__(
5410
-                        "You tried storing a model object with NO ID in the %s entity mapper.",
5411
-                        "event_espresso"
5412
-                    ),
5413
-                    get_class($this)
5414
-                )
5415
-            );
5416
-        }
5417
-        // double check it's not already there
5418
-        $classInstance = $this->get_from_entity_map($object->ID());
5419
-        if ($classInstance) {
5420
-            return $classInstance;
5421
-        }
5422
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5423
-        return $object;
5424
-    }
5425
-
5426
-
5427
-    /**
5428
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5429
-     * if no identifier is provided, then the entire entity map is emptied
5430
-     *
5431
-     * @param int|string $id the ID of the model object
5432
-     * @return boolean
5433
-     */
5434
-    public function clear_entity_map($id = null)
5435
-    {
5436
-        if (empty($id)) {
5437
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = [];
5438
-            return true;
5439
-        }
5440
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5441
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5442
-            return true;
5443
-        }
5444
-        return false;
5445
-    }
5446
-
5447
-
5448
-    /**
5449
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5450
-     * Given an array where keys are column (or column alias) names and values,
5451
-     * returns an array of their corresponding field names and database values
5452
-     *
5453
-     * @param array $cols_n_values
5454
-     * @return array
5455
-     */
5456
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5457
-    {
5458
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5459
-    }
5460
-
5461
-
5462
-    /**
5463
-     * _deduce_fields_n_values_from_cols_n_values
5464
-     * Given an array where keys are column (or column alias) names and values,
5465
-     * returns an array of their corresponding field names and database values
5466
-     *
5467
-     * @param array $cols_n_values
5468
-     * @return array
5469
-     */
5470
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5471
-    {
5472
-        $this_model_fields_n_values = [];
5473
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5474
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5475
-                $cols_n_values,
5476
-                $table_obj->get_fully_qualified_pk_column(),
5477
-                $table_obj->get_pk_column()
5478
-            );
5479
-            // there is a primary key on this table and its not set. Use defaults for all its columns
5480
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5481
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5482
-                    if (! $field_obj->is_db_only_field()) {
5483
-                        // prepare field as if its coming from db
5484
-                        $prepared_value                            =
5485
-                            $field_obj->prepare_for_set($field_obj->get_default_value());
5486
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5487
-                    }
5488
-                }
5489
-            } else {
5490
-                // the table's rows existed. Use their values
5491
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5492
-                    if (! $field_obj->is_db_only_field()) {
5493
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5494
-                            $cols_n_values,
5495
-                            $field_obj->get_qualified_column(),
5496
-                            $field_obj->get_table_column()
5497
-                        );
5498
-                    }
5499
-                }
5500
-            }
5501
-        }
5502
-        return $this_model_fields_n_values;
5503
-    }
5504
-
5505
-
5506
-    /**
5507
-     * @param array  $cols_n_values
5508
-     * @param string $qualified_column
5509
-     * @param string $regular_column
5510
-     * @return null
5511
-     */
5512
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5513
-    {
5514
-        $value = null;
5515
-        // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5516
-        // does the field on the model relate to this column retrieved from the db?
5517
-        // or is it a db-only field? (not relating to the model)
5518
-        if (isset($cols_n_values[ $qualified_column ])) {
5519
-            $value = $cols_n_values[ $qualified_column ];
5520
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5521
-            $value = $cols_n_values[ $regular_column ];
5522
-        } elseif (! empty($this->foreign_key_aliases)) {
5523
-            // no PK?  ok check if there is a foreign key alias set for this table
5524
-            // then check if that alias exists in the incoming data
5525
-            // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5526
-            foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5527
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5528
-                    $value = $cols_n_values[ $FK_alias ];
5529
-                    break;
5530
-                }
5531
-            }
5532
-        }
5533
-        return $value;
5534
-    }
5535
-
5536
-
5537
-    /**
5538
-     * refresh_entity_map_from_db
5539
-     * Makes sure the model object in the entity map at $id assumes the values
5540
-     * of the database (opposite of EE_base_Class::save())
5541
-     *
5542
-     * @param int|string $id
5543
-     * @return EE_Base_Class
5544
-     * @throws EE_Error
5545
-     * @throws ReflectionException
5546
-     */
5547
-    public function refresh_entity_map_from_db($id)
5548
-    {
5549
-        $obj_in_map = $this->get_from_entity_map($id);
5550
-        if ($obj_in_map) {
5551
-            $wpdb_results = $this->_get_all_wpdb_results(
5552
-                [[$this->get_primary_key_field()->get_name() => $id], 'limit' => 1]
5553
-            );
5554
-            if ($wpdb_results && is_array($wpdb_results)) {
5555
-                $one_row = reset($wpdb_results);
5556
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5557
-                    $obj_in_map->set_from_db($field_name, $db_value);
5558
-                }
5559
-                // clear the cache of related model objects
5560
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5561
-                    $obj_in_map->clear_cache($relation_name, null, true);
5562
-                }
5563
-            }
5564
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5565
-            return $obj_in_map;
5566
-        }
5567
-        return $this->get_one_by_ID($id);
5568
-    }
5569
-
5570
-
5571
-    /**
5572
-     * refresh_entity_map_with
5573
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5574
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5575
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5576
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5577
-     *
5578
-     * @param int|string    $id
5579
-     * @param EE_Base_Class $replacing_model_obj
5580
-     * @return EE_Base_Class
5581
-     * @throws EE_Error
5582
-     * @throws ReflectionException
5583
-     */
5584
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5585
-    {
5586
-        $obj_in_map = $this->get_from_entity_map($id);
5587
-        if ($obj_in_map) {
5588
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5589
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5590
-                    $obj_in_map->set($field_name, $value);
5591
-                }
5592
-                // make the model object in the entity map's cache match the $replacing_model_obj
5593
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5594
-                    $obj_in_map->clear_cache($relation_name, null, true);
5595
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5596
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5597
-                    }
5598
-                }
5599
-            }
5600
-            return $obj_in_map;
5601
-        }
5602
-        $this->add_to_entity_map($replacing_model_obj);
5603
-        return $replacing_model_obj;
5604
-    }
5605
-
5606
-
5607
-    /**
5608
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5609
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5610
-     * require_once($this->_getClassName().".class.php");
5611
-     *
5612
-     * @return string
5613
-     */
5614
-    private function _get_class_name()
5615
-    {
5616
-        return "EE_" . $this->get_this_model_name();
5617
-    }
5618
-
5619
-
5620
-    /**
5621
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5622
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5623
-     * it would be 'Events'.
5624
-     *
5625
-     * @param int $quantity
5626
-     * @return string
5627
-     */
5628
-    public function item_name($quantity = 1)
5629
-    {
5630
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5631
-    }
5632
-
5633
-
5634
-    /**
5635
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5636
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5637
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5638
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5639
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5640
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5641
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5642
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5643
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5644
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5645
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5646
-     *        return $previousReturnValue.$returnString;
5647
-     * }
5648
-     * require('EEM_Answer.model.php');
5649
-     * $answer=EEM_Answer::instance();
5650
-     * echo $answer->my_callback('monkeys',100);
5651
-     * //will output "you called my_callback! and passed args:monkeys,100"
5652
-     *
5653
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5654
-     * @param array  $args       array of original arguments passed to the function
5655
-     * @return mixed whatever the plugin which calls add_filter decides
5656
-     * @throws EE_Error
5657
-     */
5658
-    public function __call($methodName, $args)
5659
-    {
5660
-        $className = get_class($this);
5661
-        $tagName   = "FHEE__{$className}__{$methodName}";
5662
-        if (! has_filter($tagName)) {
5663
-            throw new EE_Error(
5664
-                sprintf(
5665
-                    esc_html__(
5666
-                        '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 );',
5667
-                        'event_espresso'
5668
-                    ),
5669
-                    $methodName,
5670
-                    $className,
5671
-                    $tagName,
5672
-                    '<br />'
5673
-                )
5674
-            );
5675
-        }
5676
-        return apply_filters($tagName, null, $this, $args);
5677
-    }
5678
-
5679
-
5680
-    /**
5681
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5682
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5683
-     *
5684
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5685
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5686
-     *                                                       the object's class name
5687
-     *                                                       or object's ID
5688
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5689
-     *                                                       exists in the database. If it does not, we add it
5690
-     * @return EE_Base_Class
5691
-     * @throws EE_Error
5692
-     * @throws ReflectionException
5693
-     */
5694
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5695
-    {
5696
-        $className = $this->_get_class_name();
5697
-        if ($base_class_obj_or_id instanceof $className) {
5698
-            $model_object = $base_class_obj_or_id;
5699
-        } else {
5700
-            $primary_key_field = $this->get_primary_key_field();
5701
-            if (
5702
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5703
-                && (
5704
-                    is_int($base_class_obj_or_id)
5705
-                    || is_string($base_class_obj_or_id)
5706
-                )
5707
-            ) {
5708
-                // assume it's an ID.
5709
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5710
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5711
-            } elseif (
5712
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5713
-                && is_string($base_class_obj_or_id)
5714
-            ) {
5715
-                // assume its a string representation of the object
5716
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5717
-            } else {
5718
-                throw new EE_Error(
5719
-                    sprintf(
5720
-                        esc_html__(
5721
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5722
-                            'event_espresso'
5723
-                        ),
5724
-                        $base_class_obj_or_id,
5725
-                        $this->_get_class_name(),
5726
-                        print_r($base_class_obj_or_id, true)
5727
-                    )
5728
-                );
5729
-            }
5730
-        }
5731
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5732
-            $model_object->save();
5733
-        }
5734
-        return $model_object;
5735
-    }
5736
-
5737
-
5738
-    /**
5739
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5740
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5741
-     * returns it ID.
5742
-     *
5743
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5744
-     * @return int|string depending on the type of this model object's ID
5745
-     * @throws EE_Error
5746
-     */
5747
-    public function ensure_is_ID($base_class_obj_or_id)
5748
-    {
5749
-        $className = $this->_get_class_name();
5750
-        if ($base_class_obj_or_id instanceof $className) {
5751
-            $id = $base_class_obj_or_id->ID();
5752
-        } elseif (is_int($base_class_obj_or_id)) {
5753
-            // assume it's an ID
5754
-            $id = $base_class_obj_or_id;
5755
-        } elseif (is_string($base_class_obj_or_id)) {
5756
-            // assume its a string representation of the object
5757
-            $id = $base_class_obj_or_id;
5758
-        } else {
5759
-            throw new EE_Error(
5760
-                sprintf(
5761
-                    esc_html__(
5762
-                        "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5763
-                        'event_espresso'
5764
-                    ),
5765
-                    $base_class_obj_or_id,
5766
-                    $this->_get_class_name(),
5767
-                    print_r($base_class_obj_or_id, true)
5768
-                )
5769
-            );
5770
-        }
5771
-        return $id;
5772
-    }
5773
-
5774
-
5775
-    /**
5776
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5777
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5778
-     * been sanitized and converted into the appropriate domain.
5779
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5780
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5781
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5782
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5783
-     * $EVT = EEM_Event::instance(); $old_setting =
5784
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5785
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5786
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5787
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5788
-     *
5789
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5790
-     * @return void
5791
-     */
5792
-    public function assume_values_already_prepared_by_model_object(
5793
-        $values_already_prepared = self::not_prepared_by_model_object
5794
-    ) {
5795
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5796
-    }
5797
-
5798
-
5799
-    /**
5800
-     * Read comments for assume_values_already_prepared_by_model_object()
5801
-     *
5802
-     * @return int
5803
-     */
5804
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5805
-    {
5806
-        return $this->_values_already_prepared_by_model_object;
5807
-    }
5808
-
5809
-
5810
-    /**
5811
-     * Gets all the indexes on this model
5812
-     *
5813
-     * @return EE_Index[]
5814
-     */
5815
-    public function indexes()
5816
-    {
5817
-        return $this->_indexes;
5818
-    }
5819
-
5820
-
5821
-    /**
5822
-     * Gets all the Unique Indexes on this model
5823
-     *
5824
-     * @return EE_Unique_Index[]
5825
-     */
5826
-    public function unique_indexes()
5827
-    {
5828
-        $unique_indexes = [];
5829
-        foreach ($this->_indexes as $name => $index) {
5830
-            if ($index instanceof EE_Unique_Index) {
5831
-                $unique_indexes [ $name ] = $index;
5832
-            }
5833
-        }
5834
-        return $unique_indexes;
5835
-    }
5836
-
5837
-
5838
-    /**
5839
-     * Gets all the fields which, when combined, make the primary key.
5840
-     * This is usually just an array with 1 element (the primary key), but in cases
5841
-     * where there is no primary key, it's a combination of fields as defined
5842
-     * on a primary index
5843
-     *
5844
-     * @return EE_Model_Field_Base[] indexed by the field's name
5845
-     * @throws EE_Error
5846
-     */
5847
-    public function get_combined_primary_key_fields()
5848
-    {
5849
-        foreach ($this->indexes() as $index) {
5850
-            if ($index instanceof EE_Primary_Key_Index) {
5851
-                return $index->fields();
5852
-            }
5853
-        }
5854
-        return [$this->primary_key_name() => $this->get_primary_key_field()];
5855
-    }
5856
-
5857
-
5858
-    /**
5859
-     * Used to build a primary key string (when the model has no primary key),
5860
-     * which can be used a unique string to identify this model object.
5861
-     *
5862
-     * @param array $fields_n_values keys are field names, values are their values.
5863
-     *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5864
-     *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5865
-     *                               before passing it to this function (that will convert it from columns-n-values
5866
-     *                               to field-names-n-values).
5867
-     * @return string
5868
-     * @throws EE_Error
5869
-     */
5870
-    public function get_index_primary_key_string($fields_n_values)
5871
-    {
5872
-        $cols_n_values_for_primary_key_index = array_intersect_key(
5873
-            $fields_n_values,
5874
-            $this->get_combined_primary_key_fields()
5875
-        );
5876
-        return http_build_query($cols_n_values_for_primary_key_index);
5877
-    }
5878
-
5879
-
5880
-    /**
5881
-     * Gets the field values from the primary key string
5882
-     *
5883
-     * @param string $index_primary_key_string
5884
-     * @return null|array
5885
-     * @throws EE_Error
5886
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5887
-     */
5888
-    public function parse_index_primary_key_string($index_primary_key_string)
5889
-    {
5890
-        $key_fields = $this->get_combined_primary_key_fields();
5891
-        // check all of them are in the $id
5892
-        $key_values_in_combined_pk = [];
5893
-        parse_str($index_primary_key_string, $key_values_in_combined_pk);
5894
-        foreach ($key_fields as $key_field_name => $field_obj) {
5895
-            if (! isset($key_values_in_combined_pk[ $key_field_name ])) {
5896
-                return null;
5897
-            }
5898
-        }
5899
-        return $key_values_in_combined_pk;
5900
-    }
5901
-
5902
-
5903
-    /**
5904
-     * verifies that an array of key-value pairs for model fields has a key
5905
-     * for each field comprising the primary key index
5906
-     *
5907
-     * @param array $key_values
5908
-     * @return boolean
5909
-     * @throws EE_Error
5910
-     */
5911
-    public function has_all_combined_primary_key_fields($key_values)
5912
-    {
5913
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5914
-        foreach ($keys_it_should_have as $key) {
5915
-            if (! isset($key_values[ $key ])) {
5916
-                return false;
5917
-            }
5918
-        }
5919
-        return true;
5920
-    }
5921
-
5922
-
5923
-    /**
5924
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5925
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5926
-     *
5927
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5928
-     * @param array               $query_params                     see github link below for more info
5929
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5930
-     * @throws EE_Error
5931
-     * @throws ReflectionException
5932
-     * @return EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5933
-     *                                                              indexed)
5934
-     */
5935
-    public function get_all_copies($model_object_or_attributes_array, $query_params = [])
5936
-    {
5937
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5938
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5939
-        } elseif (is_array($model_object_or_attributes_array)) {
5940
-            $attributes_array = $model_object_or_attributes_array;
5941
-        } else {
5942
-            throw new EE_Error(
5943
-                sprintf(
5944
-                    esc_html__(
5945
-                        "get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5946
-                        "event_espresso"
5947
-                    ),
5948
-                    $model_object_or_attributes_array
5949
-                )
5950
-            );
5951
-        }
5952
-        // even copies obviously won't have the same ID, so remove the primary key
5953
-        // from the WHERE conditions for finding copies (if there is a primary key, of course)
5954
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5955
-            unset($attributes_array[ $this->primary_key_name() ]);
5956
-        }
5957
-        if (isset($query_params[0])) {
5958
-            $query_params[0] = array_merge($attributes_array, $query_params);
5959
-        } else {
5960
-            $query_params[0] = $attributes_array;
5961
-        }
5962
-        return $this->get_all($query_params);
5963
-    }
5964
-
5965
-
5966
-    /**
5967
-     * Gets the first copy we find. See get_all_copies for more details
5968
-     *
5969
-     * @param mixed EE_Base_Class | array        $model_object_or_attributes_array
5970
-     * @param array $query_params
5971
-     * @return EE_Base_Class
5972
-     * @throws EE_Error
5973
-     * @throws ReflectionException
5974
-     */
5975
-    public function get_one_copy($model_object_or_attributes_array, $query_params = [])
5976
-    {
5977
-        if (! is_array($query_params)) {
5978
-            EE_Error::doing_it_wrong(
5979
-                'EEM_Base::get_one_copy',
5980
-                sprintf(
5981
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5982
-                    gettype($query_params)
5983
-                ),
5984
-                '4.6.0'
5985
-            );
5986
-            $query_params = [];
5987
-        }
5988
-        $query_params['limit'] = 1;
5989
-        $copies                = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5990
-        if (is_array($copies)) {
5991
-            return array_shift($copies);
5992
-        }
5993
-        return null;
5994
-    }
5995
-
5996
-
5997
-    /**
5998
-     * Updates the item with the specified id. Ignores default query parameters because
5999
-     * we have specified the ID, and its assumed we KNOW what we're doing
6000
-     *
6001
-     * @param array      $fields_n_values keys are field names, values are their new values
6002
-     * @param int|string $id              the value of the primary key to update
6003
-     * @return int number of rows updated
6004
-     * @throws EE_Error
6005
-     * @throws ReflectionException
6006
-     */
6007
-    public function update_by_ID($fields_n_values, $id)
6008
-    {
6009
-        $query_params = [
6010
-            0                          => [$this->get_primary_key_field()->get_name() => $id],
6011
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
6012
-        ];
6013
-        return $this->update($fields_n_values, $query_params);
6014
-    }
6015
-
6016
-
6017
-    /**
6018
-     * Changes an operator which was supplied to the models into one usable in SQL
6019
-     *
6020
-     * @param string $operator_supplied
6021
-     * @return string an operator which can be used in SQL
6022
-     * @throws EE_Error
6023
-     */
6024
-    private function _prepare_operator_for_sql($operator_supplied)
6025
-    {
6026
-        $sql_operator =
6027
-            isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
6028
-                : null;
6029
-        if ($sql_operator) {
6030
-            return $sql_operator;
6031
-        }
6032
-        throw new EE_Error(
6033
-            sprintf(
6034
-                esc_html__(
6035
-                    "The operator '%s' is not in the list of valid operators: %s",
6036
-                    "event_espresso"
6037
-                ),
6038
-                $operator_supplied,
6039
-                implode(",", array_keys($this->_valid_operators))
6040
-            )
6041
-        );
6042
-    }
6043
-
6044
-
6045
-    /**
6046
-     * Gets the valid operators
6047
-     *
6048
-     * @return array keys are accepted strings, values are the SQL they are converted to
6049
-     */
6050
-    public function valid_operators()
6051
-    {
6052
-        return $this->_valid_operators;
6053
-    }
6054
-
6055
-
6056
-    /**
6057
-     * Gets the between-style operators (take 2 arguments).
6058
-     *
6059
-     * @return array keys are accepted strings, values are the SQL they are converted to
6060
-     */
6061
-    public function valid_between_style_operators()
6062
-    {
6063
-        return array_intersect(
6064
-            $this->valid_operators(),
6065
-            $this->_between_style_operators
6066
-        );
6067
-    }
6068
-
6069
-
6070
-    /**
6071
-     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6072
-     *
6073
-     * @return array keys are accepted strings, values are the SQL they are converted to
6074
-     */
6075
-    public function valid_like_style_operators()
6076
-    {
6077
-        return array_intersect(
6078
-            $this->valid_operators(),
6079
-            $this->_like_style_operators
6080
-        );
6081
-    }
6082
-
6083
-
6084
-    /**
6085
-     * Gets the "in"-style operators
6086
-     *
6087
-     * @return array keys are accepted strings, values are the SQL they are converted to
6088
-     */
6089
-    public function valid_in_style_operators()
6090
-    {
6091
-        return array_intersect(
6092
-            $this->valid_operators(),
6093
-            $this->_in_style_operators
6094
-        );
6095
-    }
6096
-
6097
-
6098
-    /**
6099
-     * Gets the "null"-style operators (accept no arguments)
6100
-     *
6101
-     * @return array keys are accepted strings, values are the SQL they are converted to
6102
-     */
6103
-    public function valid_null_style_operators()
6104
-    {
6105
-        return array_intersect(
6106
-            $this->valid_operators(),
6107
-            $this->_null_style_operators
6108
-        );
6109
-    }
6110
-
6111
-
6112
-    /**
6113
-     * Gets an array where keys are the primary keys and values are their 'names'
6114
-     * (as determined by the model object's name() function, which is often overridden)
6115
-     *
6116
-     * @param array $query_params like get_all's
6117
-     * @return string[]
6118
-     * @throws EE_Error
6119
-     * @throws ReflectionException
6120
-     */
6121
-    public function get_all_names($query_params = [])
6122
-    {
6123
-        $objs  = $this->get_all($query_params);
6124
-        $names = [];
6125
-        foreach ($objs as $obj) {
6126
-            $names[ $obj->ID() ] = $obj->name();
6127
-        }
6128
-        return $names;
6129
-    }
6130
-
6131
-
6132
-    /**
6133
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
6134
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6135
-     * this is duplicated effort and reduces efficiency) you would be better to use
6136
-     * array_keys() on $model_objects.
6137
-     *
6138
-     * @param EE_Base_Class[] $model_objects
6139
-     * @param boolean         $filter_out_empty_ids  if a model object has an ID of '' or 0, don't bother including it
6140
-     *                                               in the returned array
6141
-     * @return array
6142
-     * @throws EE_Error
6143
-     */
6144
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
6145
-    {
6146
-        if (! $this->has_primary_key_field()) {
6147
-            if (WP_DEBUG) {
6148
-                EE_Error::add_error(
6149
-                    esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6150
-                    __FILE__,
6151
-                    __FUNCTION__,
6152
-                    __LINE__
6153
-                );
6154
-            }
6155
-        }
6156
-        $IDs = [];
6157
-        foreach ($model_objects as $model_object) {
6158
-            $id = $model_object->ID();
6159
-            if (! $id) {
6160
-                if ($filter_out_empty_ids) {
6161
-                    continue;
6162
-                }
6163
-                if (WP_DEBUG) {
6164
-                    EE_Error::add_error(
6165
-                        esc_html__(
6166
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6167
-                            'event_espresso'
6168
-                        ),
6169
-                        __FILE__,
6170
-                        __FUNCTION__,
6171
-                        __LINE__
6172
-                    );
6173
-                }
6174
-            }
6175
-            $IDs[] = $id;
6176
-        }
6177
-        return $IDs;
6178
-    }
6179
-
6180
-
6181
-    /**
6182
-     * Returns the string used in capabilities relating to this model. If there
6183
-     * are no capabilities that relate to this model returns false
6184
-     *
6185
-     * @return string|false
6186
-     */
6187
-    public function cap_slug()
6188
-    {
6189
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6190
-    }
6191
-
6192
-
6193
-    /**
6194
-     * Returns the capability-restrictions array (@param string $context
6195
-     *
6196
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
6197
-     * @throws EE_Error
6198
-     * @see EEM_Base::_cap_restrictions).
6199
-     *      If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6200
-     *      only returns the cap restrictions array in that context (ie, the array
6201
-     *      at that key)
6202
-     *
6203
-     */
6204
-    public function cap_restrictions($context = EEM_Base::caps_read)
6205
-    {
6206
-        EEM_Base::verify_is_valid_cap_context($context);
6207
-        // check if we ought to run the restriction generator first
6208
-        if (
6209
-            isset($this->_cap_restriction_generators[ $context ])
6210
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6211
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6212
-        ) {
6213
-            $this->_cap_restrictions[ $context ] = array_merge(
6214
-                $this->_cap_restrictions[ $context ],
6215
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6216
-            );
6217
-        }
6218
-        // and make sure we've finalized the construction of each restriction
6219
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6220
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6221
-                $where_conditions_obj->_finalize_construct($this);
6222
-            }
6223
-        }
6224
-        return $this->_cap_restrictions[ $context ];
6225
-    }
6226
-
6227
-
6228
-    /**
6229
-     * Indicating whether or not this model thinks its a wp core model
6230
-     *
6231
-     * @return boolean
6232
-     */
6233
-    public function is_wp_core_model()
6234
-    {
6235
-        return $this->_wp_core_model;
6236
-    }
6237
-
6238
-
6239
-    /**
6240
-     * Gets all the caps that are missing which impose a restriction on
6241
-     * queries made in this context
6242
-     *
6243
-     * @param string $context one of EEM_Base::caps_ constants
6244
-     * @return EE_Default_Where_Conditions[] indexed by capability name
6245
-     * @throws EE_Error
6246
-     */
6247
-    public function caps_missing($context = EEM_Base::caps_read)
6248
-    {
6249
-        $missing_caps     = [];
6250
-        $cap_restrictions = $this->cap_restrictions($context);
6251
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6252
-            if (
6253
-            ! EE_Capabilities::instance()
6254
-                             ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6255
-            ) {
6256
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6257
-            }
6258
-        }
6259
-        return $missing_caps;
6260
-    }
6261
-
6262
-
6263
-    /**
6264
-     * Gets the mapping from capability contexts to action strings used in capability names
6265
-     *
6266
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6267
-     * one of 'read', 'edit', or 'delete'
6268
-     */
6269
-    public function cap_contexts_to_cap_action_map()
6270
-    {
6271
-        return apply_filters(
6272
-            'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6273
-            $this->_cap_contexts_to_cap_action_map,
6274
-            $this
6275
-        );
6276
-    }
6277
-
6278
-
6279
-    /**
6280
-     * Gets the action string for the specified capability context
6281
-     *
6282
-     * @param string $context
6283
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6284
-     * @throws EE_Error
6285
-     */
6286
-    public function cap_action_for_context($context)
6287
-    {
6288
-        $mapping = $this->cap_contexts_to_cap_action_map();
6289
-        if (isset($mapping[ $context ])) {
6290
-            return $mapping[ $context ];
6291
-        }
6292
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6293
-            return $action;
6294
-        }
6295
-        throw new EE_Error(
6296
-            sprintf(
6297
-                esc_html__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6298
-                $context,
6299
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6300
-            )
6301
-        );
6302
-    }
6303
-
6304
-
6305
-    /**
6306
-     * Returns all the capability contexts which are valid when querying models
6307
-     *
6308
-     * @return array
6309
-     */
6310
-    public static function valid_cap_contexts()
6311
-    {
6312
-        return apply_filters(
6313
-            'FHEE__EEM_Base__valid_cap_contexts',
6314
-            [
6315
-                self::caps_read,
6316
-                self::caps_read_admin,
6317
-                self::caps_edit,
6318
-                self::caps_delete,
6319
-            ]
6320
-        );
6321
-    }
6322
-
6323
-
6324
-    /**
6325
-     * Returns all valid options for 'default_where_conditions'
6326
-     *
6327
-     * @return array
6328
-     */
6329
-    public static function valid_default_where_conditions()
6330
-    {
6331
-        return [
6332
-            EEM_Base::default_where_conditions_all,
6333
-            EEM_Base::default_where_conditions_this_only,
6334
-            EEM_Base::default_where_conditions_others_only,
6335
-            EEM_Base::default_where_conditions_minimum_all,
6336
-            EEM_Base::default_where_conditions_minimum_others,
6337
-            EEM_Base::default_where_conditions_none,
6338
-        ];
6339
-    }
6340
-
6341
-    // public static function default_where_conditions_full
6342
-
6343
-
6344
-    /**
6345
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6346
-     *
6347
-     * @param string $context
6348
-     * @return bool
6349
-     * @throws EE_Error
6350
-     */
6351
-    public static function verify_is_valid_cap_context($context)
6352
-    {
6353
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
6354
-        if (in_array($context, $valid_cap_contexts)) {
6355
-            return true;
6356
-        }
6357
-        throw new EE_Error(
6358
-            sprintf(
6359
-                esc_html__(
6360
-                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6361
-                    'event_espresso'
6362
-                ),
6363
-                $context,
6364
-                'EEM_Base',
6365
-                implode(',', $valid_cap_contexts)
6366
-            )
6367
-        );
6368
-    }
6369
-
6370
-
6371
-    /**
6372
-     * Clears all the models field caches. This is only useful when a sub-class
6373
-     * might have added a field or something and these caches might be invalidated
6374
-     */
6375
-    protected function _invalidate_field_caches()
6376
-    {
6377
-        $this->_cache_foreign_key_to_fields = [];
6378
-        $this->_cached_fields               = null;
6379
-        $this->_cached_fields_non_db_only   = null;
6380
-    }
6381
-
6382
-
6383
-    /**
6384
-     * Gets the list of all the where query param keys that relate to logic instead of field names
6385
-     * (eg "and", "or", "not").
6386
-     *
6387
-     * @return array
6388
-     */
6389
-    public function logic_query_param_keys()
6390
-    {
6391
-        return $this->_logic_query_param_keys;
6392
-    }
6393
-
6394
-
6395
-    /**
6396
-     * Determines whether or not the where query param array key is for a logic query param.
6397
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6398
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6399
-     *
6400
-     * @param $query_param_key
6401
-     * @return bool
6402
-     */
6403
-    public function is_logic_query_param_key($query_param_key)
6404
-    {
6405
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6406
-            if (
6407
-                $query_param_key === $logic_query_param_key
6408
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6409
-            ) {
6410
-                return true;
6411
-            }
6412
-        }
6413
-        return false;
6414
-    }
6415
-
6416
-
6417
-    /**
6418
-     * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6419
-     *
6420
-     * @return boolean
6421
-     * @since 4.9.74.p
6422
-     */
6423
-    public function hasPassword()
6424
-    {
6425
-        // if we don't yet know if there's a password field, find out and remember it for next time.
6426
-        if ($this->has_password_field === null) {
6427
-            $password_field           = $this->getPasswordField();
6428
-            $this->has_password_field = $password_field instanceof EE_Password_Field;
6429
-        }
6430
-        return $this->has_password_field;
6431
-    }
6432
-
6433
-
6434
-    /**
6435
-     * Returns the password field on this model, if there is one
6436
-     *
6437
-     * @return EE_Password_Field|null
6438
-     * @since 4.9.74.p
6439
-     */
6440
-    public function getPasswordField()
6441
-    {
6442
-        // if we definitely already know there is a password field or not (because has_password_field is true or false)
6443
-        // there's no need to search for it. If we don't know yet, then find out
6444
-        if ($this->has_password_field === null && $this->password_field === null) {
6445
-            $this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6446
-        }
6447
-        // don't bother setting has_password_field because that's hasPassword()'s job.
6448
-        return $this->password_field;
6449
-    }
6450
-
6451
-
6452
-    /**
6453
-     * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6454
-     *
6455
-     * @return EE_Model_Field_Base[]
6456
-     * @throws EE_Error
6457
-     * @since 4.9.74.p
6458
-     */
6459
-    public function getPasswordProtectedFields()
6460
-    {
6461
-        $password_field = $this->getPasswordField();
6462
-        $fields         = [];
6463
-        if ($password_field instanceof EE_Password_Field) {
6464
-            $field_names = $password_field->protectedFields();
6465
-            foreach ($field_names as $field_name) {
6466
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6467
-            }
6468
-        }
6469
-        return $fields;
6470
-    }
6471
-
6472
-
6473
-    /**
6474
-     * Checks if the current user can perform the requested action on this model
6475
-     *
6476
-     * @param string              $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6477
-     * @param EE_Base_Class|array $model_obj_or_fields_n_values
6478
-     * @return bool
6479
-     * @throws EE_Error
6480
-     * @throws InvalidArgumentException
6481
-     * @throws InvalidDataTypeException
6482
-     * @throws InvalidInterfaceException
6483
-     * @throws ReflectionException
6484
-     * @throws UnexpectedEntityException
6485
-     * @since 4.9.74.p
6486
-     */
6487
-    public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6488
-    {
6489
-        if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6490
-            $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6491
-        }
6492
-        if (! is_array($model_obj_or_fields_n_values)) {
6493
-            throw new UnexpectedEntityException(
6494
-                $model_obj_or_fields_n_values,
6495
-                'EE_Base_Class',
6496
-                sprintf(
6497
-                    esc_html__(
6498
-                        '%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.',
6499
-                        'event_espresso'
6500
-                    ),
6501
-                    __FUNCTION__
6502
-                )
6503
-            );
6504
-        }
6505
-        return $this->exists(
6506
-            $this->alter_query_params_to_restrict_by_ID(
6507
-                $this->get_index_primary_key_string($model_obj_or_fields_n_values),
6508
-                [
6509
-                    'default_where_conditions' => 'none',
6510
-                    'caps'                     => $cap_to_check,
6511
-                ]
6512
-            )
6513
-        );
6514
-    }
6515
-
6516
-
6517
-    /**
6518
-     * Returns the query param where conditions key to the password affecting this model.
6519
-     * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6520
-     *
6521
-     * @return null|string
6522
-     * @throws EE_Error
6523
-     * @throws InvalidArgumentException
6524
-     * @throws InvalidDataTypeException
6525
-     * @throws InvalidInterfaceException
6526
-     * @throws ModelConfigurationException
6527
-     * @throws ReflectionException
6528
-     * @since 4.9.74.p
6529
-     */
6530
-    public function modelChainAndPassword()
6531
-    {
6532
-        if ($this->model_chain_to_password === null) {
6533
-            throw new ModelConfigurationException(
6534
-                $this,
6535
-                esc_html_x(
6536
-                // @codingStandardsIgnoreStart
6537
-                    'Cannot exclude protected data because the model has not specified which model has the password.',
6538
-                    // @codingStandardsIgnoreEnd
6539
-                    '1: model name',
6540
-                    'event_espresso'
6541
-                )
6542
-            );
6543
-        }
6544
-        if ($this->model_chain_to_password === '') {
6545
-            $model_with_password = $this;
6546
-        } else {
6547
-            if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6548
-                $last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6549
-            } else {
6550
-                $last_model_in_chain = $this->model_chain_to_password;
6551
-            }
6552
-            $model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6553
-        }
6554
-
6555
-        $password_field = $model_with_password->getPasswordField();
6556
-        if ($password_field instanceof EE_Password_Field) {
6557
-            $password_field_name = $password_field->get_name();
6558
-        } else {
6559
-            throw new ModelConfigurationException(
6560
-                $this,
6561
-                sprintf(
6562
-                    esc_html_x(
6563
-                        '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"',
6564
-                        '1: model name, 2: special string',
6565
-                        'event_espresso'
6566
-                    ),
6567
-                    $model_with_password->get_this_model_name(),
6568
-                    $this->model_chain_to_password
6569
-                )
6570
-            );
6571
-        }
6572
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6573
-    }
6574
-
6575
-
6576
-    /**
6577
-     * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6578
-     * or if this model itself has a password affecting access to some of its other fields.
6579
-     *
6580
-     * @return boolean
6581
-     * @since 4.9.74.p
6582
-     */
6583
-    public function restrictedByRelatedModelPassword()
6584
-    {
6585
-        return $this->model_chain_to_password !== null;
6586
-    }
3867
+		}
3868
+		return $null_friendly_where_conditions;
3869
+	}
3870
+
3871
+
3872
+	/**
3873
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3874
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3875
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3876
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3877
+	 *
3878
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3879
+	 * @return array
3880
+	 * @throws EE_Error
3881
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3882
+	 */
3883
+	private function _get_default_where_conditions($model_relation_path = '')
3884
+	{
3885
+		if ($this->_ignore_where_strategy) {
3886
+			return [];
3887
+		}
3888
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3889
+	}
3890
+
3891
+
3892
+	/**
3893
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3894
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3895
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3896
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3897
+	 * Similar to _get_default_where_conditions
3898
+	 *
3899
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3900
+	 * @return array
3901
+	 * @throws EE_Error
3902
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3903
+	 */
3904
+	protected function _get_minimum_where_conditions($model_relation_path = '')
3905
+	{
3906
+		if ($this->_ignore_where_strategy) {
3907
+			return [];
3908
+		}
3909
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3910
+	}
3911
+
3912
+
3913
+	/**
3914
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3915
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3916
+	 *
3917
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3918
+	 * @return string
3919
+	 * @throws EE_Error
3920
+	 */
3921
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3922
+	{
3923
+		$selects = $this->_get_columns_to_select_for_this_model();
3924
+		foreach (
3925
+			$model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included
3926
+		) {
3927
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3928
+			$other_model_selects  = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3929
+			foreach ($other_model_selects as $key => $value) {
3930
+				$selects[] = $value;
3931
+			}
3932
+		}
3933
+		return implode(", ", $selects);
3934
+	}
3935
+
3936
+
3937
+	/**
3938
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3939
+	 * So that's going to be the columns for all the fields on the model
3940
+	 *
3941
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3942
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3943
+	 */
3944
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3945
+	{
3946
+		$fields                                       = $this->field_settings();
3947
+		$selects                                      = [];
3948
+		$table_alias_with_model_relation_chain_prefix =
3949
+			EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3950
+				$model_relation_chain,
3951
+				$this->get_this_model_name()
3952
+			);
3953
+		foreach ($fields as $field_obj) {
3954
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3955
+						 . $field_obj->get_table_alias()
3956
+						 . "."
3957
+						 . $field_obj->get_table_column()
3958
+						 . " AS '"
3959
+						 . $table_alias_with_model_relation_chain_prefix
3960
+						 . $field_obj->get_table_alias()
3961
+						 . "."
3962
+						 . $field_obj->get_table_column()
3963
+						 . "'";
3964
+		}
3965
+		// make sure we are also getting the PKs of each table
3966
+		$tables = $this->get_tables();
3967
+		if (count($tables) > 1) {
3968
+			foreach ($tables as $table_obj) {
3969
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3970
+									   . $table_obj->get_fully_qualified_pk_column();
3971
+				if (! in_array($qualified_pk_column, $selects)) {
3972
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3973
+				}
3974
+			}
3975
+		}
3976
+		return $selects;
3977
+	}
3978
+
3979
+
3980
+	/**
3981
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3982
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3983
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3984
+	 * SQL for joining, and the data types
3985
+	 *
3986
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3987
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3988
+	 * @param string                      $query_param_type     like Registration.Transaction.TXN_ID
3989
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3990
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3991
+	 *                                                          or 'Registration's
3992
+	 * @param string|null                 $original_query_param what it originally was (eg
3993
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3994
+	 *                                                          matches $query_param
3995
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3996
+	 * @throws EE_Error
3997
+	 */
3998
+	private function _extract_related_model_info_from_query_param(
3999
+		$query_param,
4000
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4001
+		$query_param_type,
4002
+		$original_query_param = null
4003
+	) {
4004
+		if ($original_query_param === null) {
4005
+			$original_query_param = $query_param;
4006
+		}
4007
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4008
+		// whether or not to allow logic_query_params like 'NOT','OR', or 'AND'
4009
+		$allow_logic_query_params = in_array($query_param_type, ['where', 'having', 0, 'custom_selects'], true);
4010
+		$allow_fields             = in_array(
4011
+			$query_param_type,
4012
+			['where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0],
4013
+			true
4014
+		);
4015
+		// check to see if we have a field on this model
4016
+		$this_model_fields = $this->field_settings(true);
4017
+		if (array_key_exists($query_param, $this_model_fields)) {
4018
+			if ($allow_fields) {
4019
+				return;
4020
+			}
4021
+			throw new EE_Error(
4022
+				sprintf(
4023
+					esc_html__(
4024
+						"Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
4025
+						"event_espresso"
4026
+					),
4027
+					$query_param,
4028
+					get_class($this),
4029
+					$query_param_type,
4030
+					$original_query_param
4031
+				)
4032
+			);
4033
+		}
4034
+		// check if this is a special logic query param
4035
+		if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4036
+			if ($allow_logic_query_params) {
4037
+				return;
4038
+			}
4039
+			throw new EE_Error(
4040
+				sprintf(
4041
+					esc_html__(
4042
+						'Logic query params ("%1$s") are being used incorrectly with the following query param ("%2$s") on model %3$s. %4$sAdditional Info:%4$s%5$s',
4043
+						'event_espresso'
4044
+					),
4045
+					implode('", "', $this->_logic_query_param_keys),
4046
+					$query_param,
4047
+					get_class($this),
4048
+					'<br />',
4049
+					"\t"
4050
+					. ' $passed_in_query_info = <pre>'
4051
+					. print_r($passed_in_query_info, true)
4052
+					. '</pre>'
4053
+					. "\n\t"
4054
+					. ' $query_param_type = '
4055
+					. $query_param_type
4056
+					. "\n\t"
4057
+					. ' $original_query_param = '
4058
+					. $original_query_param
4059
+				)
4060
+			);
4061
+		}
4062
+		// check if it's a custom selection
4063
+		if (
4064
+			$this->_custom_selections instanceof CustomSelects
4065
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4066
+		) {
4067
+			return;
4068
+		}
4069
+		// check if has a model name at the beginning
4070
+		// and
4071
+		// check if it's a field on a related model
4072
+		if (
4073
+		$this->extractJoinModelFromQueryParams(
4074
+			$passed_in_query_info,
4075
+			$query_param,
4076
+			$original_query_param,
4077
+			$query_param_type
4078
+		)
4079
+		) {
4080
+			return;
4081
+		}
4082
+
4083
+		// ok so $query_param didn't start with a model name
4084
+		// and we previously confirmed it wasn't a logic query param or field on the current model
4085
+		// it's wack, that's what it is
4086
+		throw new EE_Error(
4087
+			sprintf(
4088
+				esc_html__(
4089
+					"There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4090
+					"event_espresso"
4091
+				),
4092
+				$query_param,
4093
+				get_class($this),
4094
+				$query_param_type,
4095
+				$original_query_param
4096
+			)
4097
+		);
4098
+	}
4099
+
4100
+
4101
+	/**
4102
+	 * Extracts any possible join model information from the provided possible_join_string.
4103
+	 * This method will read the provided $possible_join_string value and determine if there are any possible model
4104
+	 * join
4105
+	 * parts that should be added to the query.
4106
+	 *
4107
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4108
+	 * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4109
+	 * @param null|string                 $original_query_param
4110
+	 * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4111
+	 *                                                           ('where', 'order_by', 'group_by', 'custom_selects'
4112
+	 *                                                           etc.)
4113
+	 * @return bool  returns true if a join was added and false if not.
4114
+	 * @throws EE_Error
4115
+	 */
4116
+	private function extractJoinModelFromQueryParams(
4117
+		EE_Model_Query_Info_Carrier $query_info_carrier,
4118
+		$possible_join_string,
4119
+		$original_query_param,
4120
+		$query_parameter_type
4121
+	) {
4122
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4123
+			if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4124
+				$this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4125
+				$possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4126
+				if ($possible_join_string === '') {
4127
+					// nothing left to $query_param
4128
+					// we should actually end in a field name, not a model like this!
4129
+					throw new EE_Error(
4130
+						sprintf(
4131
+							esc_html__(
4132
+								"Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4133
+								"event_espresso"
4134
+							),
4135
+							$possible_join_string,
4136
+							$query_parameter_type,
4137
+							get_class($this),
4138
+							$valid_related_model_name
4139
+						)
4140
+					);
4141
+				}
4142
+				$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4143
+				$related_model_obj->_extract_related_model_info_from_query_param(
4144
+					$possible_join_string,
4145
+					$query_info_carrier,
4146
+					$query_parameter_type,
4147
+					$original_query_param
4148
+				);
4149
+				return true;
4150
+			}
4151
+			if ($possible_join_string === $valid_related_model_name) {
4152
+				$this->_add_join_to_model(
4153
+					$valid_related_model_name,
4154
+					$query_info_carrier,
4155
+					$original_query_param
4156
+				);
4157
+				return true;
4158
+			}
4159
+		}
4160
+		return false;
4161
+	}
4162
+
4163
+
4164
+	/**
4165
+	 * Extracts related models from Custom Selects and sets up any joins for those related models.
4166
+	 *
4167
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4168
+	 * @throws EE_Error
4169
+	 */
4170
+	private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4171
+	{
4172
+		if (
4173
+			$this->_custom_selections instanceof CustomSelects
4174
+			&& ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4175
+				|| $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4176
+			)
4177
+		) {
4178
+			$original_selects = $this->_custom_selections->originalSelects();
4179
+			foreach ($original_selects as $alias => $select_configuration) {
4180
+				$this->extractJoinModelFromQueryParams(
4181
+					$query_info_carrier,
4182
+					$select_configuration[0],
4183
+					$select_configuration[0],
4184
+					'custom_selects'
4185
+				);
4186
+			}
4187
+		}
4188
+	}
4189
+
4190
+
4191
+	/**
4192
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4193
+	 * and store it on $passed_in_query_info
4194
+	 *
4195
+	 * @param string                      $model_name
4196
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4197
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
4198
+	 *                                                          model and $model_name. Eg, if we are querying Event,
4199
+	 *                                                          and are adding a join to 'Payment' with the original
4200
+	 *                                                          query param key
4201
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4202
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
4203
+	 *                                                          Payment wants to add default query params so that it
4204
+	 *                                                          will know what models to prepend onto its default query
4205
+	 *                                                          params or in case it wants to rename tables (in case
4206
+	 *                                                          there are multiple joins to the same table)
4207
+	 * @return void
4208
+	 * @throws EE_Error
4209
+	 */
4210
+	private function _add_join_to_model(
4211
+		$model_name,
4212
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4213
+		$original_query_param
4214
+	) {
4215
+		$relation_obj         = $this->related_settings_for($model_name);
4216
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4217
+		// check if the relation is HABTM, because then we're essentially doing two joins
4218
+		// If so, join first to the JOIN table, and add its data types, and then continue as normal
4219
+		if ($relation_obj instanceof EE_HABTM_Relation) {
4220
+			$join_model_obj = $relation_obj->get_join_model();
4221
+			// replace the model specified with the join model for this relation chain, whi
4222
+			$relation_chain_to_join_model =
4223
+				EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4224
+					$model_name,
4225
+					$join_model_obj->get_this_model_name(),
4226
+					$model_relation_chain
4227
+				);
4228
+			$passed_in_query_info->merge(
4229
+				new EE_Model_Query_Info_Carrier(
4230
+					[$relation_chain_to_join_model => $join_model_obj->get_this_model_name()],
4231
+					$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4232
+				)
4233
+			);
4234
+		}
4235
+		// now just join to the other table pointed to by the relation object, and add its data types
4236
+		$passed_in_query_info->merge(
4237
+			new EE_Model_Query_Info_Carrier(
4238
+				[$model_relation_chain => $model_name],
4239
+				$relation_obj->get_join_statement($model_relation_chain)
4240
+			)
4241
+		);
4242
+	}
4243
+
4244
+
4245
+	/**
4246
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4247
+	 *
4248
+	 * @param array $where_params
4249
+	 * @return string of SQL
4250
+	 * @throws EE_Error
4251
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4252
+	 */
4253
+	private function _construct_where_clause($where_params)
4254
+	{
4255
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4256
+		if ($SQL) {
4257
+			return " WHERE " . $SQL;
4258
+		}
4259
+		return '';
4260
+	}
4261
+
4262
+
4263
+	/**
4264
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4265
+	 * and should be passed HAVING parameters, not WHERE parameters
4266
+	 *
4267
+	 * @param array $having_params
4268
+	 * @return string
4269
+	 * @throws EE_Error
4270
+	 */
4271
+	private function _construct_having_clause($having_params)
4272
+	{
4273
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4274
+		if ($SQL) {
4275
+			return " HAVING " . $SQL;
4276
+		}
4277
+		return '';
4278
+	}
4279
+
4280
+
4281
+	/**
4282
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4283
+	 * Event_Meta.meta_value = 'foo'))"
4284
+	 *
4285
+	 * @param array  $where_params
4286
+	 * @param string $glue joins each sub-clause together. Should really only be " AND " or " OR "...
4287
+	 * @return string of SQL
4288
+	 * @throws EE_Error
4289
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4290
+	 */
4291
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4292
+	{
4293
+		$where_clauses = [];
4294
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4295
+			$query_param =
4296
+				$this->_remove_stars_and_anything_after_from_condition_query_param_key(
4297
+					$query_param
4298
+				);// str_replace("*",'',$query_param);
4299
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
4300
+				switch ($query_param) {
4301
+					case 'not':
4302
+					case 'NOT':
4303
+						$where_clauses[] = "! ("
4304
+										   . $this->_construct_condition_clause_recursive(
4305
+								$op_and_value_or_sub_condition,
4306
+								$glue
4307
+							)
4308
+										   . ")";
4309
+						break;
4310
+					case 'and':
4311
+					case 'AND':
4312
+						$where_clauses[] = " ("
4313
+										   . $this->_construct_condition_clause_recursive(
4314
+								$op_and_value_or_sub_condition,
4315
+								' AND '
4316
+							)
4317
+										   . ")";
4318
+						break;
4319
+					case 'or':
4320
+					case 'OR':
4321
+						$where_clauses[] = " ("
4322
+										   . $this->_construct_condition_clause_recursive(
4323
+								$op_and_value_or_sub_condition,
4324
+								' OR '
4325
+							)
4326
+										   . ")";
4327
+						break;
4328
+				}
4329
+			} else {
4330
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4331
+				// if it's not a normal field, maybe it's a custom selection?
4332
+				if (! $field_obj) {
4333
+					if ($this->_custom_selections instanceof CustomSelects) {
4334
+						$field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4335
+					} else {
4336
+						throw new EE_Error(
4337
+							sprintf(
4338
+								esc_html__(
4339
+									"%s is neither a valid model field name, nor a custom selection",
4340
+									"event_espresso"
4341
+								),
4342
+								$query_param
4343
+							)
4344
+						);
4345
+					}
4346
+				}
4347
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4348
+				$where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4349
+			}
4350
+		}
4351
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4352
+	}
4353
+
4354
+
4355
+	/**
4356
+	 * Takes the input parameter and extract the table name (alias) and column name
4357
+	 *
4358
+	 * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4359
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4360
+	 * @throws EE_Error
4361
+	 */
4362
+	private function _deduce_column_name_from_query_param($query_param)
4363
+	{
4364
+		$field = $this->_deduce_field_from_query_param($query_param);
4365
+		if ($field) {
4366
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4367
+				$field->get_model_name(),
4368
+				$query_param
4369
+			);
4370
+			return $table_alias_prefix . $field->get_qualified_column();
4371
+		}
4372
+		if (
4373
+			$this->_custom_selections instanceof CustomSelects
4374
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4375
+		) {
4376
+			// maybe it's custom selection item?
4377
+			// if so, just use it as the "column name"
4378
+			return $query_param;
4379
+		}
4380
+		$custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4381
+			? implode(',', $this->_custom_selections->columnAliases())
4382
+			: '';
4383
+		throw new EE_Error(
4384
+			sprintf(
4385
+				esc_html__(
4386
+					"%s is not a valid field on this model, nor a custom selection (%s)",
4387
+					"event_espresso"
4388
+				),
4389
+				$query_param,
4390
+				$custom_select_aliases
4391
+			)
4392
+		);
4393
+	}
4394
+
4395
+
4396
+	/**
4397
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4398
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4399
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4400
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4401
+	 *
4402
+	 * @param string $condition_query_param_key
4403
+	 * @return string
4404
+	 */
4405
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4406
+	{
4407
+		$pos_of_star = strpos($condition_query_param_key, '*');
4408
+		if ($pos_of_star === false) {
4409
+			return $condition_query_param_key;
4410
+		}
4411
+		return substr($condition_query_param_key, 0, $pos_of_star);
4412
+	}
4413
+
4414
+
4415
+	/**
4416
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4417
+	 *
4418
+	 * @param mixed      array | string    $op_and_value
4419
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4420
+	 * @return string
4421
+	 * @throws EE_Error
4422
+	 */
4423
+	private function _construct_op_and_value($op_and_value, $field_obj)
4424
+	{
4425
+		if (is_array($op_and_value)) {
4426
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4427
+			if (! $operator) {
4428
+				$php_array_like_string = [];
4429
+				foreach ($op_and_value as $key => $value) {
4430
+					$php_array_like_string[] = "$key=>$value";
4431
+				}
4432
+				throw new EE_Error(
4433
+					sprintf(
4434
+						esc_html__(
4435
+							"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))",
4436
+							"event_espresso"
4437
+						),
4438
+						implode(",", $php_array_like_string)
4439
+					)
4440
+				);
4441
+			}
4442
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4443
+		} else {
4444
+			$operator = '=';
4445
+			$value    = $op_and_value;
4446
+		}
4447
+		// check to see if the value is actually another field
4448
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4449
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4450
+		}
4451
+		if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4452
+			// in this case, the value should be an array, or at least a comma-separated list
4453
+			// it will need to handle a little differently
4454
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4455
+			// note: $cleaned_value has already been run through $wpdb->prepare()
4456
+			return $operator . SP . $cleaned_value;
4457
+		}
4458
+		if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4459
+			// the value should be an array with count of two.
4460
+			if (count($value) !== 2) {
4461
+				throw new EE_Error(
4462
+					sprintf(
4463
+						esc_html__(
4464
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4465
+							'event_espresso'
4466
+						),
4467
+						"BETWEEN"
4468
+					)
4469
+				);
4470
+			}
4471
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4472
+			return $operator . SP . $cleaned_value;
4473
+		}
4474
+		if (in_array($operator, $this->valid_null_style_operators())) {
4475
+			if ($value !== null) {
4476
+				throw new EE_Error(
4477
+					sprintf(
4478
+						esc_html__(
4479
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4480
+							"event_espresso"
4481
+						),
4482
+						$value,
4483
+						$operator
4484
+					)
4485
+				);
4486
+			}
4487
+			return $operator;
4488
+		}
4489
+		if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4490
+			// if the operator is 'LIKE', we want to allow percent signs (%) and not
4491
+			// remove other junk. So just treat it as a string.
4492
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4493
+		}
4494
+		if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4495
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4496
+		}
4497
+		if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4498
+			throw new EE_Error(
4499
+				sprintf(
4500
+					esc_html__(
4501
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4502
+						'event_espresso'
4503
+					),
4504
+					$operator,
4505
+					$operator
4506
+				)
4507
+			);
4508
+		}
4509
+		if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4510
+			throw new EE_Error(
4511
+				sprintf(
4512
+					esc_html__(
4513
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4514
+						'event_espresso'
4515
+					),
4516
+					$operator,
4517
+					$operator
4518
+				)
4519
+			);
4520
+		}
4521
+		throw new EE_Error(
4522
+			sprintf(
4523
+				esc_html__(
4524
+					"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4525
+					"event_espresso"
4526
+				),
4527
+				http_build_query($op_and_value)
4528
+			)
4529
+		);
4530
+	}
4531
+
4532
+
4533
+	/**
4534
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4535
+	 *
4536
+	 * @param array                      $values
4537
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4538
+	 *                                              '%s'
4539
+	 * @return string
4540
+	 * @throws EE_Error
4541
+	 */
4542
+	public function _construct_between_value($values, $field_obj)
4543
+	{
4544
+		$cleaned_values = [];
4545
+		foreach ($values as $value) {
4546
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4547
+		}
4548
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4549
+	}
4550
+
4551
+
4552
+	/**
4553
+	 * Takes an array or a comma-separated list of $values and cleans them
4554
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4555
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4556
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4557
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4558
+	 *
4559
+	 * @param mixed                      $values    array or comma-separated string
4560
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4561
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4562
+	 * @throws EE_Error
4563
+	 */
4564
+	public function _construct_in_value($values, $field_obj)
4565
+	{
4566
+		// check if the value is a CSV list
4567
+		if (is_string($values)) {
4568
+			// in which case, turn it into an array
4569
+			$values = explode(",", $values);
4570
+		}
4571
+		$cleaned_values = [];
4572
+		foreach ($values as $value) {
4573
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4574
+		}
4575
+		// we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4576
+		// but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4577
+		// which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4578
+		if (empty($cleaned_values)) {
4579
+			$all_fields       = $this->field_settings();
4580
+			$a_field          = array_shift($all_fields);
4581
+			$main_table       = $this->_get_main_table();
4582
+			$cleaned_values[] = "SELECT "
4583
+								. $a_field->get_table_column()
4584
+								. " FROM "
4585
+								. $main_table->get_table_name()
4586
+								. " WHERE FALSE";
4587
+		}
4588
+		return "(" . implode(",", $cleaned_values) . ")";
4589
+	}
4590
+
4591
+
4592
+	/**
4593
+	 * @param mixed                      $value
4594
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4595
+	 * @return false|null|string
4596
+	 * @throws EE_Error
4597
+	 */
4598
+	private function _wpdb_prepare_using_field($value, $field_obj)
4599
+	{
4600
+		global $wpdb;
4601
+		if ($field_obj instanceof EE_Model_Field_Base) {
4602
+			return $wpdb->prepare(
4603
+				$field_obj->get_wpdb_data_type(),
4604
+				$this->_prepare_value_for_use_in_db($value, $field_obj)
4605
+			);
4606
+		} //$field_obj should really just be a data type
4607
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4608
+			throw new EE_Error(
4609
+				sprintf(
4610
+					esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4611
+					$field_obj,
4612
+					implode(",", $this->_valid_wpdb_data_types)
4613
+				)
4614
+			);
4615
+		}
4616
+		return $wpdb->prepare($field_obj, $value);
4617
+	}
4618
+
4619
+
4620
+	/**
4621
+	 * Takes the input parameter and finds the model field that it indicates.
4622
+	 *
4623
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4624
+	 * @return EE_Model_Field_Base
4625
+	 * @throws EE_Error
4626
+	 */
4627
+	protected function _deduce_field_from_query_param($query_param_name)
4628
+	{
4629
+		// ok, now proceed with deducing which part is the model's name, and which is the field's name
4630
+		// which will help us find the database table and column
4631
+		$query_param_parts = explode(".", $query_param_name);
4632
+		if (empty($query_param_parts)) {
4633
+			throw new EE_Error(
4634
+				sprintf(
4635
+					esc_html__(
4636
+						"_extract_column_name is empty when trying to extract column and table name from %s",
4637
+						'event_espresso'
4638
+					),
4639
+					$query_param_name
4640
+				)
4641
+			);
4642
+		}
4643
+		$number_of_parts       = count($query_param_parts);
4644
+		$last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4645
+		if ($number_of_parts === 1) {
4646
+			$field_name = $last_query_param_part;
4647
+			$model_obj  = $this;
4648
+		} else {// $number_of_parts >= 2
4649
+			// the last part is the column name, and there are only 2parts. therefore...
4650
+			$field_name = $last_query_param_part;
4651
+			$model_obj  = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4652
+		}
4653
+		try {
4654
+			return $model_obj->field_settings_for($field_name);
4655
+		} catch (EE_Error $e) {
4656
+			return null;
4657
+		}
4658
+	}
4659
+
4660
+
4661
+	/**
4662
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4663
+	 * alias and column which corresponds to it
4664
+	 *
4665
+	 * @param string $field_name
4666
+	 * @return string
4667
+	 * @throws EE_Error
4668
+	 */
4669
+	public function _get_qualified_column_for_field($field_name)
4670
+	{
4671
+		$all_fields = $this->field_settings();
4672
+		$field      = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4673
+		if ($field) {
4674
+			return $field->get_qualified_column();
4675
+		}
4676
+		throw new EE_Error(
4677
+			sprintf(
4678
+				esc_html__(
4679
+					"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.",
4680
+					'event_espresso'
4681
+				),
4682
+				$field_name,
4683
+				get_class($this)
4684
+			)
4685
+		);
4686
+	}
4687
+
4688
+
4689
+	/**
4690
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4691
+	 * Example usage:
4692
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4693
+	 *      array(),
4694
+	 *      ARRAY_A,
4695
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4696
+	 *  );
4697
+	 * is equivalent to
4698
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4699
+	 * and
4700
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4701
+	 *      array(
4702
+	 *          array(
4703
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4704
+	 *          ),
4705
+	 *          ARRAY_A,
4706
+	 *          implode(
4707
+	 *              ', ',
4708
+	 *              array_merge(
4709
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4710
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4711
+	 *              )
4712
+	 *          )
4713
+	 *      )
4714
+	 *  );
4715
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4716
+	 *
4717
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4718
+	 *                                            and the one whose fields you are selecting for example: when querying
4719
+	 *                                            tickets model and selecting fields from the tickets model you would
4720
+	 *                                            leave this parameter empty, because no models are needed to join
4721
+	 *                                            between the queried model and the selected one. Likewise when
4722
+	 *                                            querying the datetime model and selecting fields from the tickets
4723
+	 *                                            model, it would also be left empty, because there is a direct
4724
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4725
+	 *                                            them together. However, when querying from the event model and
4726
+	 *                                            selecting fields from the ticket model, you should provide the string
4727
+	 *                                            'Datetime', indicating that the event model must first join to the
4728
+	 *                                            datetime model in order to find its relation to ticket model.
4729
+	 *                                            Also, when querying from the venue model and selecting fields from
4730
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4731
+	 *                                            indicating you need to join the venue model to the event model,
4732
+	 *                                            to the datetime model, in order to find its relation to the ticket
4733
+	 *                                            model. This string is used to deduce the prefix that gets added onto
4734
+	 *                                            the models' tables qualified columns
4735
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4736
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4737
+	 *                                            qualified column names
4738
+	 * @return array|string
4739
+	 */
4740
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4741
+	{
4742
+		$table_prefix      = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4743
+		$qualified_columns = [];
4744
+		foreach ($this->field_settings() as $field_name => $field) {
4745
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4746
+		}
4747
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4748
+	}
4749
+
4750
+
4751
+	/**
4752
+	 * constructs the select use on special limit joins
4753
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4754
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4755
+	 * (as that is typically where the limits would be set).
4756
+	 *
4757
+	 * @param string       $table_alias The table the select is being built for
4758
+	 * @param mixed|string $limit       The limit for this select
4759
+	 * @return string                The final select join element for the query.
4760
+	 * @throws EE_Error
4761
+	 */
4762
+	public function _construct_limit_join_select($table_alias, $limit)
4763
+	{
4764
+		$SQL = '';
4765
+		foreach ($this->_tables as $table_obj) {
4766
+			if ($table_obj instanceof EE_Primary_Table) {
4767
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4768
+					? $table_obj->get_select_join_limit($limit)
4769
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4770
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4771
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4772
+					? $table_obj->get_select_join_limit_join($limit)
4773
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4774
+			}
4775
+		}
4776
+		return $SQL;
4777
+	}
4778
+
4779
+
4780
+	/**
4781
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4782
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4783
+	 *
4784
+	 * @return string SQL
4785
+	 * @throws EE_Error
4786
+	 */
4787
+	public function _construct_internal_join()
4788
+	{
4789
+		$SQL = $this->_get_main_table()->get_table_sql();
4790
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4791
+		return $SQL;
4792
+	}
4793
+
4794
+
4795
+	/**
4796
+	 * Constructs the SQL for joining all the tables on this model.
4797
+	 * Normally $alias should be the primary table's alias, but in cases where
4798
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4799
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4800
+	 * alias, this will construct SQL like:
4801
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4802
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4803
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4804
+	 *
4805
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4806
+	 * @return string
4807
+	 * @throws EE_Error
4808
+	 */
4809
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4810
+	{
4811
+		$SQL               = '';
4812
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4813
+		foreach ($this->_tables as $table_obj) {
4814
+			if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4815
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4816
+					// so we're joining to this table, meaning the table is already in
4817
+					// the FROM statement, BUT the primary table isn't. So we want
4818
+					// to add the inverse join sql
4819
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4820
+				} else {
4821
+					// just add a regular JOIN to this table from the primary table
4822
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4823
+				}
4824
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4825
+		}
4826
+		return $SQL;
4827
+	}
4828
+
4829
+
4830
+	/**
4831
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4832
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4833
+	 * their data type (eg, '%s', '%d', etc)
4834
+	 *
4835
+	 * @return array
4836
+	 */
4837
+	public function _get_data_types()
4838
+	{
4839
+		$data_types = [];
4840
+		foreach ($this->field_settings() as $field_obj) {
4841
+			// $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4842
+			/** @var $field_obj EE_Model_Field_Base */
4843
+			$data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4844
+		}
4845
+		return $data_types;
4846
+	}
4847
+
4848
+
4849
+	/**
4850
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4851
+	 *
4852
+	 * @param string $model_name
4853
+	 * @return EEM_Base
4854
+	 * @throws EE_Error
4855
+	 */
4856
+	public function get_related_model_obj($model_name)
4857
+	{
4858
+		$model_classname = "EEM_" . $model_name;
4859
+		if (! class_exists($model_classname)) {
4860
+			throw new EE_Error(
4861
+				sprintf(
4862
+					esc_html__(
4863
+						"You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4864
+						'event_espresso'
4865
+					),
4866
+					$model_name,
4867
+					$model_classname
4868
+				)
4869
+			);
4870
+		}
4871
+		return call_user_func($model_classname . "::instance");
4872
+	}
4873
+
4874
+
4875
+	/**
4876
+	 * Returns the array of EE_ModelRelations for this model.
4877
+	 *
4878
+	 * @return EE_Model_Relation_Base[]
4879
+	 */
4880
+	public function relation_settings()
4881
+	{
4882
+		return $this->_model_relations;
4883
+	}
4884
+
4885
+
4886
+	/**
4887
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4888
+	 * because without THOSE models, this model probably doesn't have much purpose.
4889
+	 * (Eg, without an event, datetimes have little purpose.)
4890
+	 *
4891
+	 * @return EE_Belongs_To_Relation[]
4892
+	 */
4893
+	public function belongs_to_relations()
4894
+	{
4895
+		$belongs_to_relations = [];
4896
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4897
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4898
+				$belongs_to_relations[ $model_name ] = $relation_obj;
4899
+			}
4900
+		}
4901
+		return $belongs_to_relations;
4902
+	}
4903
+
4904
+
4905
+	/**
4906
+	 * Returns the specified EE_Model_Relation, or throws an exception
4907
+	 *
4908
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4909
+	 * @return EE_Model_Relation_Base
4910
+	 * @throws EE_Error
4911
+	 */
4912
+	public function related_settings_for($relation_name)
4913
+	{
4914
+		$relatedModels = $this->relation_settings();
4915
+		if (! array_key_exists($relation_name, $relatedModels)) {
4916
+			throw new EE_Error(
4917
+				sprintf(
4918
+					esc_html__(
4919
+						'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4920
+						'event_espresso'
4921
+					),
4922
+					$relation_name,
4923
+					$this->_get_class_name(),
4924
+					implode(', ', array_keys($relatedModels))
4925
+				)
4926
+			);
4927
+		}
4928
+		return $relatedModels[ $relation_name ];
4929
+	}
4930
+
4931
+
4932
+	/**
4933
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4934
+	 * fields
4935
+	 *
4936
+	 * @param string  $fieldName
4937
+	 * @param boolean $include_db_only_fields
4938
+	 * @return EE_Model_Field_Base
4939
+	 * @throws EE_Error
4940
+	 */
4941
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
4942
+	{
4943
+		$fieldSettings = $this->field_settings($include_db_only_fields);
4944
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4945
+			throw new EE_Error(
4946
+				sprintf(
4947
+					esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
4948
+					$fieldName,
4949
+					get_class($this)
4950
+				)
4951
+			);
4952
+		}
4953
+		return $fieldSettings[ $fieldName ];
4954
+	}
4955
+
4956
+
4957
+	/**
4958
+	 * Checks if this field exists on this model
4959
+	 *
4960
+	 * @param string $fieldName a key in the model's _field_settings array
4961
+	 * @return boolean
4962
+	 */
4963
+	public function has_field($fieldName)
4964
+	{
4965
+		$fieldSettings = $this->field_settings(true);
4966
+		if (isset($fieldSettings[ $fieldName ])) {
4967
+			return true;
4968
+		}
4969
+		return false;
4970
+	}
4971
+
4972
+
4973
+	/**
4974
+	 * Returns whether or not this model has a relation to the specified model
4975
+	 *
4976
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4977
+	 * @return boolean
4978
+	 */
4979
+	public function has_relation($relation_name)
4980
+	{
4981
+		$relations = $this->relation_settings();
4982
+		if (isset($relations[ $relation_name ])) {
4983
+			return true;
4984
+		}
4985
+		return false;
4986
+	}
4987
+
4988
+
4989
+	/**
4990
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4991
+	 * Eg, on EE_Answer that would be ANS_ID field object
4992
+	 *
4993
+	 * @param $field_obj
4994
+	 * @return boolean
4995
+	 */
4996
+	public function is_primary_key_field($field_obj)
4997
+	{
4998
+		return $field_obj instanceof EE_Primary_Key_Field_Base;
4999
+	}
5000
+
5001
+
5002
+	/**
5003
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
5004
+	 * Eg, on EE_Answer that would be ANS_ID field object
5005
+	 *
5006
+	 * @return EE_Model_Field_Base
5007
+	 * @throws EE_Error
5008
+	 */
5009
+	public function get_primary_key_field()
5010
+	{
5011
+		if ($this->_primary_key_field === null) {
5012
+			foreach ($this->field_settings(true) as $field_obj) {
5013
+				if ($this->is_primary_key_field($field_obj)) {
5014
+					$this->_primary_key_field = $field_obj;
5015
+					break;
5016
+				}
5017
+			}
5018
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5019
+				throw new EE_Error(
5020
+					sprintf(
5021
+						esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
5022
+						get_class($this)
5023
+					)
5024
+				);
5025
+			}
5026
+		}
5027
+		return $this->_primary_key_field;
5028
+	}
5029
+
5030
+
5031
+	/**
5032
+	 * Returns whether or not not there is a primary key on this model.
5033
+	 * Internally does some caching.
5034
+	 *
5035
+	 * @return boolean
5036
+	 */
5037
+	public function has_primary_key_field()
5038
+	{
5039
+		if ($this->_has_primary_key_field === null) {
5040
+			try {
5041
+				$this->get_primary_key_field();
5042
+				$this->_has_primary_key_field = true;
5043
+			} catch (EE_Error $e) {
5044
+				$this->_has_primary_key_field = false;
5045
+			}
5046
+		}
5047
+		return $this->_has_primary_key_field;
5048
+	}
5049
+
5050
+
5051
+	/**
5052
+	 * Finds the first field of type $field_class_name.
5053
+	 *
5054
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5055
+	 *                                 EE_Foreign_Key_Field, etc
5056
+	 * @return EE_Model_Field_Base or null if none is found
5057
+	 */
5058
+	public function get_a_field_of_type($field_class_name)
5059
+	{
5060
+		foreach ($this->field_settings() as $field) {
5061
+			if ($field instanceof $field_class_name) {
5062
+				return $field;
5063
+			}
5064
+		}
5065
+		return null;
5066
+	}
5067
+
5068
+
5069
+	/**
5070
+	 * Gets a foreign key field pointing to model.
5071
+	 *
5072
+	 * @param string $model_name eg Event, Registration, not EEM_Event
5073
+	 * @return EE_Foreign_Key_Field_Base
5074
+	 * @throws EE_Error
5075
+	 */
5076
+	public function get_foreign_key_to($model_name)
5077
+	{
5078
+		if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5079
+			foreach ($this->field_settings() as $field) {
5080
+				if (
5081
+					$field instanceof EE_Foreign_Key_Field_Base
5082
+					&& in_array($model_name, $field->get_model_names_pointed_to())
5083
+				) {
5084
+					$this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5085
+					break;
5086
+				}
5087
+			}
5088
+			if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5089
+				throw new EE_Error(
5090
+					sprintf(
5091
+						esc_html__(
5092
+							"There is no foreign key field pointing to model %s on model %s",
5093
+							'event_espresso'
5094
+						),
5095
+						$model_name,
5096
+						get_class($this)
5097
+					)
5098
+				);
5099
+			}
5100
+		}
5101
+		return $this->_cache_foreign_key_to_fields[ $model_name ];
5102
+	}
5103
+
5104
+
5105
+	/**
5106
+	 * Gets the table name (including $wpdb->prefix) for the table alias
5107
+	 *
5108
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5109
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5110
+	 *                            Either one works
5111
+	 * @return string
5112
+	 */
5113
+	public function get_table_for_alias($table_alias)
5114
+	{
5115
+		$table_alias_sans_model_relation_chain_prefix =
5116
+			EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5117
+		return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5118
+	}
5119
+
5120
+
5121
+	/**
5122
+	 * Returns a flat array of all field son this model, instead of organizing them
5123
+	 * by table_alias as they are in the constructor.
5124
+	 *
5125
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5126
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
5127
+	 */
5128
+	public function field_settings($include_db_only_fields = false)
5129
+	{
5130
+		if ($include_db_only_fields) {
5131
+			if ($this->_cached_fields === null) {
5132
+				$this->_cached_fields = [];
5133
+				foreach ($this->_fields as $fields_corresponding_to_table) {
5134
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5135
+						$this->_cached_fields[ $field_name ] = $field_obj;
5136
+					}
5137
+				}
5138
+			}
5139
+			return $this->_cached_fields;
5140
+		}
5141
+		if ($this->_cached_fields_non_db_only === null) {
5142
+			$this->_cached_fields_non_db_only = [];
5143
+			foreach ($this->_fields as $fields_corresponding_to_table) {
5144
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5145
+					/** @var $field_obj EE_Model_Field_Base */
5146
+					if (! $field_obj->is_db_only_field()) {
5147
+						$this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5148
+					}
5149
+				}
5150
+			}
5151
+		}
5152
+		return $this->_cached_fields_non_db_only;
5153
+	}
5154
+
5155
+
5156
+	/**
5157
+	 *        cycle though array of attendees and create objects out of each item
5158
+	 *
5159
+	 * @access        private
5160
+	 * @param array $rows        of results of $wpdb->get_results($query,ARRAY_A)
5161
+	 * @return EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5162
+	 *                           numerically indexed)
5163
+	 * @throws EE_Error
5164
+	 * @throws ReflectionException
5165
+	 */
5166
+	protected function _create_objects($rows = [])
5167
+	{
5168
+		$array_of_objects = [];
5169
+		if (empty($rows)) {
5170
+			return [];
5171
+		}
5172
+		$count_if_model_has_no_primary_key = 0;
5173
+		$has_primary_key                   = $this->has_primary_key_field();
5174
+		$primary_key_field                 = $has_primary_key ? $this->get_primary_key_field() : null;
5175
+		foreach ((array)$rows as $row) {
5176
+			if (empty($row)) {
5177
+				// wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5178
+				return [];
5179
+			}
5180
+			// check if we've already set this object in the results array,
5181
+			// in which case there's no need to process it further (again)
5182
+			if ($has_primary_key) {
5183
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5184
+					$row,
5185
+					$primary_key_field->get_qualified_column(),
5186
+					$primary_key_field->get_table_column()
5187
+				);
5188
+				if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5189
+					continue;
5190
+				}
5191
+			}
5192
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
5193
+			if (! $classInstance) {
5194
+				throw new EE_Error(
5195
+					sprintf(
5196
+						esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
5197
+						$this->get_this_model_name(),
5198
+						http_build_query($row)
5199
+					)
5200
+				);
5201
+			}
5202
+			// set the timezone on the instantiated objects
5203
+			$classInstance->set_timezone($this->get_timezone(), true);
5204
+			// make sure if there is any timezone setting present that we set the timezone for the object
5205
+			$key                      = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5206
+			$array_of_objects[ $key ] = $classInstance;
5207
+			// also, for all the relations of type BelongsTo, see if we can cache
5208
+			// those related models
5209
+			// (we could do this for other relations too, but if there are conditions
5210
+			// that filtered out some fo the results, then we'd be caching an incomplete set
5211
+			// so it requires a little more thought than just caching them immediately...)
5212
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
5213
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
5214
+					// check if this model's INFO is present. If so, cache it on the model
5215
+					$other_model           = $relation_obj->get_other_model();
5216
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5217
+					// if we managed to make a model object from the results, cache it on the main model object
5218
+					if ($other_model_obj_maybe) {
5219
+						// set timezone on these other model objects if they are present
5220
+						$other_model_obj_maybe->set_timezone($this->get_timezone(), true);
5221
+						$classInstance->cache($modelName, $other_model_obj_maybe);
5222
+					}
5223
+				}
5224
+			}
5225
+			// also, if this was a custom select query, let's see if there are any results for the custom select fields
5226
+			// and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5227
+			// the field in the CustomSelects object
5228
+			if ($this->_custom_selections instanceof CustomSelects) {
5229
+				$classInstance->setCustomSelectsValues(
5230
+					$this->getValuesForCustomSelectAliasesFromResults($row)
5231
+				);
5232
+			}
5233
+		}
5234
+		return $array_of_objects;
5235
+	}
5236
+
5237
+
5238
+	/**
5239
+	 * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5240
+	 * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5241
+	 *
5242
+	 * @param array $db_results_row
5243
+	 * @return array
5244
+	 */
5245
+	protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5246
+	{
5247
+		$results = [];
5248
+		if ($this->_custom_selections instanceof CustomSelects) {
5249
+			foreach ($this->_custom_selections->columnAliases() as $alias) {
5250
+				if (isset($db_results_row[ $alias ])) {
5251
+					$results[ $alias ] = $this->convertValueToDataType(
5252
+						$db_results_row[ $alias ],
5253
+						$this->_custom_selections->getDataTypeForAlias($alias)
5254
+					);
5255
+				}
5256
+			}
5257
+		}
5258
+		return $results;
5259
+	}
5260
+
5261
+
5262
+	/**
5263
+	 * This will set the value for the given alias
5264
+	 *
5265
+	 * @param string $value
5266
+	 * @param string $datatype (one of %d, %s, %f)
5267
+	 * @return int|string|float (int for %d, string for %s, float for %f)
5268
+	 */
5269
+	protected function convertValueToDataType($value, $datatype)
5270
+	{
5271
+		switch ($datatype) {
5272
+			case '%f':
5273
+				return (float)$value;
5274
+			case '%d':
5275
+				return (int)$value;
5276
+			default:
5277
+				return (string)$value;
5278
+		}
5279
+	}
5280
+
5281
+
5282
+	/**
5283
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5284
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5285
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5286
+	 * object (as set in the model_field!).
5287
+	 *
5288
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5289
+	 * @throws EE_Error
5290
+	 * @throws ReflectionException
5291
+	 */
5292
+	public function create_default_object()
5293
+	{
5294
+		$this_model_fields_and_values = [];
5295
+		// setup the row using default values;
5296
+		foreach ($this->field_settings() as $field_name => $field_obj) {
5297
+			$this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5298
+		}
5299
+		$className = $this->_get_class_name();
5300
+		return EE_Registry::instance()->load_class(
5301
+			$className,
5302
+			[$this_model_fields_and_values],
5303
+			false,
5304
+			false
5305
+		);
5306
+	}
5307
+
5308
+
5309
+	/**
5310
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5311
+	 *                             or an stdClass where each property is the name of a column,
5312
+	 * @return EE_Base_Class
5313
+	 * @throws EE_Error
5314
+	 * @throws ReflectionException
5315
+	 */
5316
+	public function instantiate_class_from_array_or_object($cols_n_values)
5317
+	{
5318
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5319
+			$cols_n_values = get_object_vars($cols_n_values);
5320
+		}
5321
+		$primary_key = null;
5322
+		// make sure the array only has keys that are fields/columns on this model
5323
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5324
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5325
+			$primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5326
+		}
5327
+		$className = $this->_get_class_name();
5328
+		// check we actually found results that we can use to build our model object
5329
+		// if not, return null
5330
+		if ($this->has_primary_key_field()) {
5331
+			if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5332
+				return null;
5333
+			}
5334
+		} elseif ($this->unique_indexes()) {
5335
+			$first_column = reset($this_model_fields_n_values);
5336
+			if (empty($first_column)) {
5337
+				return null;
5338
+			}
5339
+		}
5340
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5341
+		if ($primary_key) {
5342
+			$classInstance = $this->get_from_entity_map($primary_key);
5343
+			if (! $classInstance) {
5344
+				$classInstance = EE_Registry::instance()->load_class(
5345
+					$className,
5346
+					[$this_model_fields_n_values, $this->get_timezone()],
5347
+					true,
5348
+					false
5349
+				);
5350
+				// add this new object to the entity map
5351
+				$classInstance = $this->add_to_entity_map($classInstance);
5352
+			}
5353
+		} else {
5354
+			$classInstance = EE_Registry::instance()->load_class(
5355
+				$className,
5356
+				[$this_model_fields_n_values, $this->get_timezone()],
5357
+				true,
5358
+				false
5359
+			);
5360
+		}
5361
+		return $classInstance;
5362
+	}
5363
+
5364
+
5365
+	/**
5366
+	 * Gets the model object from the  entity map if it exists
5367
+	 *
5368
+	 * @param int|string $id the ID of the model object
5369
+	 * @return EE_Base_Class
5370
+	 */
5371
+	public function get_from_entity_map($id)
5372
+	{
5373
+		return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5374
+			? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]
5375
+			: null;
5376
+	}
5377
+
5378
+
5379
+	/**
5380
+	 * add_to_entity_map
5381
+	 * Adds the object to the model's entity mappings
5382
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5383
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5384
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5385
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5386
+	 *        then this method should be called immediately after the update query
5387
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5388
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5389
+	 *
5390
+	 * @param EE_Base_Class $object
5391
+	 * @return EE_Base_Class
5392
+	 * @throws EE_Error
5393
+	 */
5394
+	public function add_to_entity_map(EE_Base_Class $object)
5395
+	{
5396
+		$className = $this->_get_class_name();
5397
+		if (! $object instanceof $className) {
5398
+			throw new EE_Error(
5399
+				sprintf(
5400
+					esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5401
+					is_object($object) ? get_class($object) : $object,
5402
+					$className
5403
+				)
5404
+			);
5405
+		}
5406
+		if (! $object->ID()) {
5407
+			throw new EE_Error(
5408
+				sprintf(
5409
+					esc_html__(
5410
+						"You tried storing a model object with NO ID in the %s entity mapper.",
5411
+						"event_espresso"
5412
+					),
5413
+					get_class($this)
5414
+				)
5415
+			);
5416
+		}
5417
+		// double check it's not already there
5418
+		$classInstance = $this->get_from_entity_map($object->ID());
5419
+		if ($classInstance) {
5420
+			return $classInstance;
5421
+		}
5422
+		$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5423
+		return $object;
5424
+	}
5425
+
5426
+
5427
+	/**
5428
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5429
+	 * if no identifier is provided, then the entire entity map is emptied
5430
+	 *
5431
+	 * @param int|string $id the ID of the model object
5432
+	 * @return boolean
5433
+	 */
5434
+	public function clear_entity_map($id = null)
5435
+	{
5436
+		if (empty($id)) {
5437
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ] = [];
5438
+			return true;
5439
+		}
5440
+		if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5441
+			unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5442
+			return true;
5443
+		}
5444
+		return false;
5445
+	}
5446
+
5447
+
5448
+	/**
5449
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5450
+	 * Given an array where keys are column (or column alias) names and values,
5451
+	 * returns an array of their corresponding field names and database values
5452
+	 *
5453
+	 * @param array $cols_n_values
5454
+	 * @return array
5455
+	 */
5456
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5457
+	{
5458
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5459
+	}
5460
+
5461
+
5462
+	/**
5463
+	 * _deduce_fields_n_values_from_cols_n_values
5464
+	 * Given an array where keys are column (or column alias) names and values,
5465
+	 * returns an array of their corresponding field names and database values
5466
+	 *
5467
+	 * @param array $cols_n_values
5468
+	 * @return array
5469
+	 */
5470
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5471
+	{
5472
+		$this_model_fields_n_values = [];
5473
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5474
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5475
+				$cols_n_values,
5476
+				$table_obj->get_fully_qualified_pk_column(),
5477
+				$table_obj->get_pk_column()
5478
+			);
5479
+			// there is a primary key on this table and its not set. Use defaults for all its columns
5480
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5481
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5482
+					if (! $field_obj->is_db_only_field()) {
5483
+						// prepare field as if its coming from db
5484
+						$prepared_value                            =
5485
+							$field_obj->prepare_for_set($field_obj->get_default_value());
5486
+						$this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5487
+					}
5488
+				}
5489
+			} else {
5490
+				// the table's rows existed. Use their values
5491
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5492
+					if (! $field_obj->is_db_only_field()) {
5493
+						$this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5494
+							$cols_n_values,
5495
+							$field_obj->get_qualified_column(),
5496
+							$field_obj->get_table_column()
5497
+						);
5498
+					}
5499
+				}
5500
+			}
5501
+		}
5502
+		return $this_model_fields_n_values;
5503
+	}
5504
+
5505
+
5506
+	/**
5507
+	 * @param array  $cols_n_values
5508
+	 * @param string $qualified_column
5509
+	 * @param string $regular_column
5510
+	 * @return null
5511
+	 */
5512
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5513
+	{
5514
+		$value = null;
5515
+		// ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5516
+		// does the field on the model relate to this column retrieved from the db?
5517
+		// or is it a db-only field? (not relating to the model)
5518
+		if (isset($cols_n_values[ $qualified_column ])) {
5519
+			$value = $cols_n_values[ $qualified_column ];
5520
+		} elseif (isset($cols_n_values[ $regular_column ])) {
5521
+			$value = $cols_n_values[ $regular_column ];
5522
+		} elseif (! empty($this->foreign_key_aliases)) {
5523
+			// no PK?  ok check if there is a foreign key alias set for this table
5524
+			// then check if that alias exists in the incoming data
5525
+			// AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5526
+			foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5527
+				if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5528
+					$value = $cols_n_values[ $FK_alias ];
5529
+					break;
5530
+				}
5531
+			}
5532
+		}
5533
+		return $value;
5534
+	}
5535
+
5536
+
5537
+	/**
5538
+	 * refresh_entity_map_from_db
5539
+	 * Makes sure the model object in the entity map at $id assumes the values
5540
+	 * of the database (opposite of EE_base_Class::save())
5541
+	 *
5542
+	 * @param int|string $id
5543
+	 * @return EE_Base_Class
5544
+	 * @throws EE_Error
5545
+	 * @throws ReflectionException
5546
+	 */
5547
+	public function refresh_entity_map_from_db($id)
5548
+	{
5549
+		$obj_in_map = $this->get_from_entity_map($id);
5550
+		if ($obj_in_map) {
5551
+			$wpdb_results = $this->_get_all_wpdb_results(
5552
+				[[$this->get_primary_key_field()->get_name() => $id], 'limit' => 1]
5553
+			);
5554
+			if ($wpdb_results && is_array($wpdb_results)) {
5555
+				$one_row = reset($wpdb_results);
5556
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5557
+					$obj_in_map->set_from_db($field_name, $db_value);
5558
+				}
5559
+				// clear the cache of related model objects
5560
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5561
+					$obj_in_map->clear_cache($relation_name, null, true);
5562
+				}
5563
+			}
5564
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5565
+			return $obj_in_map;
5566
+		}
5567
+		return $this->get_one_by_ID($id);
5568
+	}
5569
+
5570
+
5571
+	/**
5572
+	 * refresh_entity_map_with
5573
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5574
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5575
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5576
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5577
+	 *
5578
+	 * @param int|string    $id
5579
+	 * @param EE_Base_Class $replacing_model_obj
5580
+	 * @return EE_Base_Class
5581
+	 * @throws EE_Error
5582
+	 * @throws ReflectionException
5583
+	 */
5584
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5585
+	{
5586
+		$obj_in_map = $this->get_from_entity_map($id);
5587
+		if ($obj_in_map) {
5588
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5589
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5590
+					$obj_in_map->set($field_name, $value);
5591
+				}
5592
+				// make the model object in the entity map's cache match the $replacing_model_obj
5593
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5594
+					$obj_in_map->clear_cache($relation_name, null, true);
5595
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5596
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5597
+					}
5598
+				}
5599
+			}
5600
+			return $obj_in_map;
5601
+		}
5602
+		$this->add_to_entity_map($replacing_model_obj);
5603
+		return $replacing_model_obj;
5604
+	}
5605
+
5606
+
5607
+	/**
5608
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5609
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5610
+	 * require_once($this->_getClassName().".class.php");
5611
+	 *
5612
+	 * @return string
5613
+	 */
5614
+	private function _get_class_name()
5615
+	{
5616
+		return "EE_" . $this->get_this_model_name();
5617
+	}
5618
+
5619
+
5620
+	/**
5621
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5622
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5623
+	 * it would be 'Events'.
5624
+	 *
5625
+	 * @param int $quantity
5626
+	 * @return string
5627
+	 */
5628
+	public function item_name($quantity = 1)
5629
+	{
5630
+		return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5631
+	}
5632
+
5633
+
5634
+	/**
5635
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5636
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5637
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5638
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5639
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5640
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5641
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5642
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5643
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5644
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5645
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5646
+	 *        return $previousReturnValue.$returnString;
5647
+	 * }
5648
+	 * require('EEM_Answer.model.php');
5649
+	 * $answer=EEM_Answer::instance();
5650
+	 * echo $answer->my_callback('monkeys',100);
5651
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5652
+	 *
5653
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5654
+	 * @param array  $args       array of original arguments passed to the function
5655
+	 * @return mixed whatever the plugin which calls add_filter decides
5656
+	 * @throws EE_Error
5657
+	 */
5658
+	public function __call($methodName, $args)
5659
+	{
5660
+		$className = get_class($this);
5661
+		$tagName   = "FHEE__{$className}__{$methodName}";
5662
+		if (! has_filter($tagName)) {
5663
+			throw new EE_Error(
5664
+				sprintf(
5665
+					esc_html__(
5666
+						'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 );',
5667
+						'event_espresso'
5668
+					),
5669
+					$methodName,
5670
+					$className,
5671
+					$tagName,
5672
+					'<br />'
5673
+				)
5674
+			);
5675
+		}
5676
+		return apply_filters($tagName, null, $this, $args);
5677
+	}
5678
+
5679
+
5680
+	/**
5681
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5682
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5683
+	 *
5684
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5685
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5686
+	 *                                                       the object's class name
5687
+	 *                                                       or object's ID
5688
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5689
+	 *                                                       exists in the database. If it does not, we add it
5690
+	 * @return EE_Base_Class
5691
+	 * @throws EE_Error
5692
+	 * @throws ReflectionException
5693
+	 */
5694
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5695
+	{
5696
+		$className = $this->_get_class_name();
5697
+		if ($base_class_obj_or_id instanceof $className) {
5698
+			$model_object = $base_class_obj_or_id;
5699
+		} else {
5700
+			$primary_key_field = $this->get_primary_key_field();
5701
+			if (
5702
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5703
+				&& (
5704
+					is_int($base_class_obj_or_id)
5705
+					|| is_string($base_class_obj_or_id)
5706
+				)
5707
+			) {
5708
+				// assume it's an ID.
5709
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5710
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5711
+			} elseif (
5712
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5713
+				&& is_string($base_class_obj_or_id)
5714
+			) {
5715
+				// assume its a string representation of the object
5716
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5717
+			} else {
5718
+				throw new EE_Error(
5719
+					sprintf(
5720
+						esc_html__(
5721
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5722
+							'event_espresso'
5723
+						),
5724
+						$base_class_obj_or_id,
5725
+						$this->_get_class_name(),
5726
+						print_r($base_class_obj_or_id, true)
5727
+					)
5728
+				);
5729
+			}
5730
+		}
5731
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5732
+			$model_object->save();
5733
+		}
5734
+		return $model_object;
5735
+	}
5736
+
5737
+
5738
+	/**
5739
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5740
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5741
+	 * returns it ID.
5742
+	 *
5743
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5744
+	 * @return int|string depending on the type of this model object's ID
5745
+	 * @throws EE_Error
5746
+	 */
5747
+	public function ensure_is_ID($base_class_obj_or_id)
5748
+	{
5749
+		$className = $this->_get_class_name();
5750
+		if ($base_class_obj_or_id instanceof $className) {
5751
+			$id = $base_class_obj_or_id->ID();
5752
+		} elseif (is_int($base_class_obj_or_id)) {
5753
+			// assume it's an ID
5754
+			$id = $base_class_obj_or_id;
5755
+		} elseif (is_string($base_class_obj_or_id)) {
5756
+			// assume its a string representation of the object
5757
+			$id = $base_class_obj_or_id;
5758
+		} else {
5759
+			throw new EE_Error(
5760
+				sprintf(
5761
+					esc_html__(
5762
+						"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5763
+						'event_espresso'
5764
+					),
5765
+					$base_class_obj_or_id,
5766
+					$this->_get_class_name(),
5767
+					print_r($base_class_obj_or_id, true)
5768
+				)
5769
+			);
5770
+		}
5771
+		return $id;
5772
+	}
5773
+
5774
+
5775
+	/**
5776
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5777
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5778
+	 * been sanitized and converted into the appropriate domain.
5779
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5780
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5781
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5782
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5783
+	 * $EVT = EEM_Event::instance(); $old_setting =
5784
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5785
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5786
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5787
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5788
+	 *
5789
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5790
+	 * @return void
5791
+	 */
5792
+	public function assume_values_already_prepared_by_model_object(
5793
+		$values_already_prepared = self::not_prepared_by_model_object
5794
+	) {
5795
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5796
+	}
5797
+
5798
+
5799
+	/**
5800
+	 * Read comments for assume_values_already_prepared_by_model_object()
5801
+	 *
5802
+	 * @return int
5803
+	 */
5804
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5805
+	{
5806
+		return $this->_values_already_prepared_by_model_object;
5807
+	}
5808
+
5809
+
5810
+	/**
5811
+	 * Gets all the indexes on this model
5812
+	 *
5813
+	 * @return EE_Index[]
5814
+	 */
5815
+	public function indexes()
5816
+	{
5817
+		return $this->_indexes;
5818
+	}
5819
+
5820
+
5821
+	/**
5822
+	 * Gets all the Unique Indexes on this model
5823
+	 *
5824
+	 * @return EE_Unique_Index[]
5825
+	 */
5826
+	public function unique_indexes()
5827
+	{
5828
+		$unique_indexes = [];
5829
+		foreach ($this->_indexes as $name => $index) {
5830
+			if ($index instanceof EE_Unique_Index) {
5831
+				$unique_indexes [ $name ] = $index;
5832
+			}
5833
+		}
5834
+		return $unique_indexes;
5835
+	}
5836
+
5837
+
5838
+	/**
5839
+	 * Gets all the fields which, when combined, make the primary key.
5840
+	 * This is usually just an array with 1 element (the primary key), but in cases
5841
+	 * where there is no primary key, it's a combination of fields as defined
5842
+	 * on a primary index
5843
+	 *
5844
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5845
+	 * @throws EE_Error
5846
+	 */
5847
+	public function get_combined_primary_key_fields()
5848
+	{
5849
+		foreach ($this->indexes() as $index) {
5850
+			if ($index instanceof EE_Primary_Key_Index) {
5851
+				return $index->fields();
5852
+			}
5853
+		}
5854
+		return [$this->primary_key_name() => $this->get_primary_key_field()];
5855
+	}
5856
+
5857
+
5858
+	/**
5859
+	 * Used to build a primary key string (when the model has no primary key),
5860
+	 * which can be used a unique string to identify this model object.
5861
+	 *
5862
+	 * @param array $fields_n_values keys are field names, values are their values.
5863
+	 *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5864
+	 *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5865
+	 *                               before passing it to this function (that will convert it from columns-n-values
5866
+	 *                               to field-names-n-values).
5867
+	 * @return string
5868
+	 * @throws EE_Error
5869
+	 */
5870
+	public function get_index_primary_key_string($fields_n_values)
5871
+	{
5872
+		$cols_n_values_for_primary_key_index = array_intersect_key(
5873
+			$fields_n_values,
5874
+			$this->get_combined_primary_key_fields()
5875
+		);
5876
+		return http_build_query($cols_n_values_for_primary_key_index);
5877
+	}
5878
+
5879
+
5880
+	/**
5881
+	 * Gets the field values from the primary key string
5882
+	 *
5883
+	 * @param string $index_primary_key_string
5884
+	 * @return null|array
5885
+	 * @throws EE_Error
5886
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5887
+	 */
5888
+	public function parse_index_primary_key_string($index_primary_key_string)
5889
+	{
5890
+		$key_fields = $this->get_combined_primary_key_fields();
5891
+		// check all of them are in the $id
5892
+		$key_values_in_combined_pk = [];
5893
+		parse_str($index_primary_key_string, $key_values_in_combined_pk);
5894
+		foreach ($key_fields as $key_field_name => $field_obj) {
5895
+			if (! isset($key_values_in_combined_pk[ $key_field_name ])) {
5896
+				return null;
5897
+			}
5898
+		}
5899
+		return $key_values_in_combined_pk;
5900
+	}
5901
+
5902
+
5903
+	/**
5904
+	 * verifies that an array of key-value pairs for model fields has a key
5905
+	 * for each field comprising the primary key index
5906
+	 *
5907
+	 * @param array $key_values
5908
+	 * @return boolean
5909
+	 * @throws EE_Error
5910
+	 */
5911
+	public function has_all_combined_primary_key_fields($key_values)
5912
+	{
5913
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5914
+		foreach ($keys_it_should_have as $key) {
5915
+			if (! isset($key_values[ $key ])) {
5916
+				return false;
5917
+			}
5918
+		}
5919
+		return true;
5920
+	}
5921
+
5922
+
5923
+	/**
5924
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5925
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5926
+	 *
5927
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5928
+	 * @param array               $query_params                     see github link below for more info
5929
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5930
+	 * @throws EE_Error
5931
+	 * @throws ReflectionException
5932
+	 * @return EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5933
+	 *                                                              indexed)
5934
+	 */
5935
+	public function get_all_copies($model_object_or_attributes_array, $query_params = [])
5936
+	{
5937
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5938
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5939
+		} elseif (is_array($model_object_or_attributes_array)) {
5940
+			$attributes_array = $model_object_or_attributes_array;
5941
+		} else {
5942
+			throw new EE_Error(
5943
+				sprintf(
5944
+					esc_html__(
5945
+						"get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5946
+						"event_espresso"
5947
+					),
5948
+					$model_object_or_attributes_array
5949
+				)
5950
+			);
5951
+		}
5952
+		// even copies obviously won't have the same ID, so remove the primary key
5953
+		// from the WHERE conditions for finding copies (if there is a primary key, of course)
5954
+		if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5955
+			unset($attributes_array[ $this->primary_key_name() ]);
5956
+		}
5957
+		if (isset($query_params[0])) {
5958
+			$query_params[0] = array_merge($attributes_array, $query_params);
5959
+		} else {
5960
+			$query_params[0] = $attributes_array;
5961
+		}
5962
+		return $this->get_all($query_params);
5963
+	}
5964
+
5965
+
5966
+	/**
5967
+	 * Gets the first copy we find. See get_all_copies for more details
5968
+	 *
5969
+	 * @param mixed EE_Base_Class | array        $model_object_or_attributes_array
5970
+	 * @param array $query_params
5971
+	 * @return EE_Base_Class
5972
+	 * @throws EE_Error
5973
+	 * @throws ReflectionException
5974
+	 */
5975
+	public function get_one_copy($model_object_or_attributes_array, $query_params = [])
5976
+	{
5977
+		if (! is_array($query_params)) {
5978
+			EE_Error::doing_it_wrong(
5979
+				'EEM_Base::get_one_copy',
5980
+				sprintf(
5981
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5982
+					gettype($query_params)
5983
+				),
5984
+				'4.6.0'
5985
+			);
5986
+			$query_params = [];
5987
+		}
5988
+		$query_params['limit'] = 1;
5989
+		$copies                = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5990
+		if (is_array($copies)) {
5991
+			return array_shift($copies);
5992
+		}
5993
+		return null;
5994
+	}
5995
+
5996
+
5997
+	/**
5998
+	 * Updates the item with the specified id. Ignores default query parameters because
5999
+	 * we have specified the ID, and its assumed we KNOW what we're doing
6000
+	 *
6001
+	 * @param array      $fields_n_values keys are field names, values are their new values
6002
+	 * @param int|string $id              the value of the primary key to update
6003
+	 * @return int number of rows updated
6004
+	 * @throws EE_Error
6005
+	 * @throws ReflectionException
6006
+	 */
6007
+	public function update_by_ID($fields_n_values, $id)
6008
+	{
6009
+		$query_params = [
6010
+			0                          => [$this->get_primary_key_field()->get_name() => $id],
6011
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
6012
+		];
6013
+		return $this->update($fields_n_values, $query_params);
6014
+	}
6015
+
6016
+
6017
+	/**
6018
+	 * Changes an operator which was supplied to the models into one usable in SQL
6019
+	 *
6020
+	 * @param string $operator_supplied
6021
+	 * @return string an operator which can be used in SQL
6022
+	 * @throws EE_Error
6023
+	 */
6024
+	private function _prepare_operator_for_sql($operator_supplied)
6025
+	{
6026
+		$sql_operator =
6027
+			isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
6028
+				: null;
6029
+		if ($sql_operator) {
6030
+			return $sql_operator;
6031
+		}
6032
+		throw new EE_Error(
6033
+			sprintf(
6034
+				esc_html__(
6035
+					"The operator '%s' is not in the list of valid operators: %s",
6036
+					"event_espresso"
6037
+				),
6038
+				$operator_supplied,
6039
+				implode(",", array_keys($this->_valid_operators))
6040
+			)
6041
+		);
6042
+	}
6043
+
6044
+
6045
+	/**
6046
+	 * Gets the valid operators
6047
+	 *
6048
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6049
+	 */
6050
+	public function valid_operators()
6051
+	{
6052
+		return $this->_valid_operators;
6053
+	}
6054
+
6055
+
6056
+	/**
6057
+	 * Gets the between-style operators (take 2 arguments).
6058
+	 *
6059
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6060
+	 */
6061
+	public function valid_between_style_operators()
6062
+	{
6063
+		return array_intersect(
6064
+			$this->valid_operators(),
6065
+			$this->_between_style_operators
6066
+		);
6067
+	}
6068
+
6069
+
6070
+	/**
6071
+	 * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6072
+	 *
6073
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6074
+	 */
6075
+	public function valid_like_style_operators()
6076
+	{
6077
+		return array_intersect(
6078
+			$this->valid_operators(),
6079
+			$this->_like_style_operators
6080
+		);
6081
+	}
6082
+
6083
+
6084
+	/**
6085
+	 * Gets the "in"-style operators
6086
+	 *
6087
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6088
+	 */
6089
+	public function valid_in_style_operators()
6090
+	{
6091
+		return array_intersect(
6092
+			$this->valid_operators(),
6093
+			$this->_in_style_operators
6094
+		);
6095
+	}
6096
+
6097
+
6098
+	/**
6099
+	 * Gets the "null"-style operators (accept no arguments)
6100
+	 *
6101
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6102
+	 */
6103
+	public function valid_null_style_operators()
6104
+	{
6105
+		return array_intersect(
6106
+			$this->valid_operators(),
6107
+			$this->_null_style_operators
6108
+		);
6109
+	}
6110
+
6111
+
6112
+	/**
6113
+	 * Gets an array where keys are the primary keys and values are their 'names'
6114
+	 * (as determined by the model object's name() function, which is often overridden)
6115
+	 *
6116
+	 * @param array $query_params like get_all's
6117
+	 * @return string[]
6118
+	 * @throws EE_Error
6119
+	 * @throws ReflectionException
6120
+	 */
6121
+	public function get_all_names($query_params = [])
6122
+	{
6123
+		$objs  = $this->get_all($query_params);
6124
+		$names = [];
6125
+		foreach ($objs as $obj) {
6126
+			$names[ $obj->ID() ] = $obj->name();
6127
+		}
6128
+		return $names;
6129
+	}
6130
+
6131
+
6132
+	/**
6133
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
6134
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6135
+	 * this is duplicated effort and reduces efficiency) you would be better to use
6136
+	 * array_keys() on $model_objects.
6137
+	 *
6138
+	 * @param EE_Base_Class[] $model_objects
6139
+	 * @param boolean         $filter_out_empty_ids  if a model object has an ID of '' or 0, don't bother including it
6140
+	 *                                               in the returned array
6141
+	 * @return array
6142
+	 * @throws EE_Error
6143
+	 */
6144
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
6145
+	{
6146
+		if (! $this->has_primary_key_field()) {
6147
+			if (WP_DEBUG) {
6148
+				EE_Error::add_error(
6149
+					esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6150
+					__FILE__,
6151
+					__FUNCTION__,
6152
+					__LINE__
6153
+				);
6154
+			}
6155
+		}
6156
+		$IDs = [];
6157
+		foreach ($model_objects as $model_object) {
6158
+			$id = $model_object->ID();
6159
+			if (! $id) {
6160
+				if ($filter_out_empty_ids) {
6161
+					continue;
6162
+				}
6163
+				if (WP_DEBUG) {
6164
+					EE_Error::add_error(
6165
+						esc_html__(
6166
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6167
+							'event_espresso'
6168
+						),
6169
+						__FILE__,
6170
+						__FUNCTION__,
6171
+						__LINE__
6172
+					);
6173
+				}
6174
+			}
6175
+			$IDs[] = $id;
6176
+		}
6177
+		return $IDs;
6178
+	}
6179
+
6180
+
6181
+	/**
6182
+	 * Returns the string used in capabilities relating to this model. If there
6183
+	 * are no capabilities that relate to this model returns false
6184
+	 *
6185
+	 * @return string|false
6186
+	 */
6187
+	public function cap_slug()
6188
+	{
6189
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6190
+	}
6191
+
6192
+
6193
+	/**
6194
+	 * Returns the capability-restrictions array (@param string $context
6195
+	 *
6196
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
6197
+	 * @throws EE_Error
6198
+	 * @see EEM_Base::_cap_restrictions).
6199
+	 *      If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6200
+	 *      only returns the cap restrictions array in that context (ie, the array
6201
+	 *      at that key)
6202
+	 *
6203
+	 */
6204
+	public function cap_restrictions($context = EEM_Base::caps_read)
6205
+	{
6206
+		EEM_Base::verify_is_valid_cap_context($context);
6207
+		// check if we ought to run the restriction generator first
6208
+		if (
6209
+			isset($this->_cap_restriction_generators[ $context ])
6210
+			&& $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6211
+			&& ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6212
+		) {
6213
+			$this->_cap_restrictions[ $context ] = array_merge(
6214
+				$this->_cap_restrictions[ $context ],
6215
+				$this->_cap_restriction_generators[ $context ]->generate_restrictions()
6216
+			);
6217
+		}
6218
+		// and make sure we've finalized the construction of each restriction
6219
+		foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6220
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6221
+				$where_conditions_obj->_finalize_construct($this);
6222
+			}
6223
+		}
6224
+		return $this->_cap_restrictions[ $context ];
6225
+	}
6226
+
6227
+
6228
+	/**
6229
+	 * Indicating whether or not this model thinks its a wp core model
6230
+	 *
6231
+	 * @return boolean
6232
+	 */
6233
+	public function is_wp_core_model()
6234
+	{
6235
+		return $this->_wp_core_model;
6236
+	}
6237
+
6238
+
6239
+	/**
6240
+	 * Gets all the caps that are missing which impose a restriction on
6241
+	 * queries made in this context
6242
+	 *
6243
+	 * @param string $context one of EEM_Base::caps_ constants
6244
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
6245
+	 * @throws EE_Error
6246
+	 */
6247
+	public function caps_missing($context = EEM_Base::caps_read)
6248
+	{
6249
+		$missing_caps     = [];
6250
+		$cap_restrictions = $this->cap_restrictions($context);
6251
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6252
+			if (
6253
+			! EE_Capabilities::instance()
6254
+							 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6255
+			) {
6256
+				$missing_caps[ $cap ] = $restriction_if_no_cap;
6257
+			}
6258
+		}
6259
+		return $missing_caps;
6260
+	}
6261
+
6262
+
6263
+	/**
6264
+	 * Gets the mapping from capability contexts to action strings used in capability names
6265
+	 *
6266
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6267
+	 * one of 'read', 'edit', or 'delete'
6268
+	 */
6269
+	public function cap_contexts_to_cap_action_map()
6270
+	{
6271
+		return apply_filters(
6272
+			'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6273
+			$this->_cap_contexts_to_cap_action_map,
6274
+			$this
6275
+		);
6276
+	}
6277
+
6278
+
6279
+	/**
6280
+	 * Gets the action string for the specified capability context
6281
+	 *
6282
+	 * @param string $context
6283
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6284
+	 * @throws EE_Error
6285
+	 */
6286
+	public function cap_action_for_context($context)
6287
+	{
6288
+		$mapping = $this->cap_contexts_to_cap_action_map();
6289
+		if (isset($mapping[ $context ])) {
6290
+			return $mapping[ $context ];
6291
+		}
6292
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6293
+			return $action;
6294
+		}
6295
+		throw new EE_Error(
6296
+			sprintf(
6297
+				esc_html__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6298
+				$context,
6299
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6300
+			)
6301
+		);
6302
+	}
6303
+
6304
+
6305
+	/**
6306
+	 * Returns all the capability contexts which are valid when querying models
6307
+	 *
6308
+	 * @return array
6309
+	 */
6310
+	public static function valid_cap_contexts()
6311
+	{
6312
+		return apply_filters(
6313
+			'FHEE__EEM_Base__valid_cap_contexts',
6314
+			[
6315
+				self::caps_read,
6316
+				self::caps_read_admin,
6317
+				self::caps_edit,
6318
+				self::caps_delete,
6319
+			]
6320
+		);
6321
+	}
6322
+
6323
+
6324
+	/**
6325
+	 * Returns all valid options for 'default_where_conditions'
6326
+	 *
6327
+	 * @return array
6328
+	 */
6329
+	public static function valid_default_where_conditions()
6330
+	{
6331
+		return [
6332
+			EEM_Base::default_where_conditions_all,
6333
+			EEM_Base::default_where_conditions_this_only,
6334
+			EEM_Base::default_where_conditions_others_only,
6335
+			EEM_Base::default_where_conditions_minimum_all,
6336
+			EEM_Base::default_where_conditions_minimum_others,
6337
+			EEM_Base::default_where_conditions_none,
6338
+		];
6339
+	}
6340
+
6341
+	// public static function default_where_conditions_full
6342
+
6343
+
6344
+	/**
6345
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6346
+	 *
6347
+	 * @param string $context
6348
+	 * @return bool
6349
+	 * @throws EE_Error
6350
+	 */
6351
+	public static function verify_is_valid_cap_context($context)
6352
+	{
6353
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
6354
+		if (in_array($context, $valid_cap_contexts)) {
6355
+			return true;
6356
+		}
6357
+		throw new EE_Error(
6358
+			sprintf(
6359
+				esc_html__(
6360
+					'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6361
+					'event_espresso'
6362
+				),
6363
+				$context,
6364
+				'EEM_Base',
6365
+				implode(',', $valid_cap_contexts)
6366
+			)
6367
+		);
6368
+	}
6369
+
6370
+
6371
+	/**
6372
+	 * Clears all the models field caches. This is only useful when a sub-class
6373
+	 * might have added a field or something and these caches might be invalidated
6374
+	 */
6375
+	protected function _invalidate_field_caches()
6376
+	{
6377
+		$this->_cache_foreign_key_to_fields = [];
6378
+		$this->_cached_fields               = null;
6379
+		$this->_cached_fields_non_db_only   = null;
6380
+	}
6381
+
6382
+
6383
+	/**
6384
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
6385
+	 * (eg "and", "or", "not").
6386
+	 *
6387
+	 * @return array
6388
+	 */
6389
+	public function logic_query_param_keys()
6390
+	{
6391
+		return $this->_logic_query_param_keys;
6392
+	}
6393
+
6394
+
6395
+	/**
6396
+	 * Determines whether or not the where query param array key is for a logic query param.
6397
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6398
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6399
+	 *
6400
+	 * @param $query_param_key
6401
+	 * @return bool
6402
+	 */
6403
+	public function is_logic_query_param_key($query_param_key)
6404
+	{
6405
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6406
+			if (
6407
+				$query_param_key === $logic_query_param_key
6408
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
6409
+			) {
6410
+				return true;
6411
+			}
6412
+		}
6413
+		return false;
6414
+	}
6415
+
6416
+
6417
+	/**
6418
+	 * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6419
+	 *
6420
+	 * @return boolean
6421
+	 * @since 4.9.74.p
6422
+	 */
6423
+	public function hasPassword()
6424
+	{
6425
+		// if we don't yet know if there's a password field, find out and remember it for next time.
6426
+		if ($this->has_password_field === null) {
6427
+			$password_field           = $this->getPasswordField();
6428
+			$this->has_password_field = $password_field instanceof EE_Password_Field;
6429
+		}
6430
+		return $this->has_password_field;
6431
+	}
6432
+
6433
+
6434
+	/**
6435
+	 * Returns the password field on this model, if there is one
6436
+	 *
6437
+	 * @return EE_Password_Field|null
6438
+	 * @since 4.9.74.p
6439
+	 */
6440
+	public function getPasswordField()
6441
+	{
6442
+		// if we definitely already know there is a password field or not (because has_password_field is true or false)
6443
+		// there's no need to search for it. If we don't know yet, then find out
6444
+		if ($this->has_password_field === null && $this->password_field === null) {
6445
+			$this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6446
+		}
6447
+		// don't bother setting has_password_field because that's hasPassword()'s job.
6448
+		return $this->password_field;
6449
+	}
6450
+
6451
+
6452
+	/**
6453
+	 * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6454
+	 *
6455
+	 * @return EE_Model_Field_Base[]
6456
+	 * @throws EE_Error
6457
+	 * @since 4.9.74.p
6458
+	 */
6459
+	public function getPasswordProtectedFields()
6460
+	{
6461
+		$password_field = $this->getPasswordField();
6462
+		$fields         = [];
6463
+		if ($password_field instanceof EE_Password_Field) {
6464
+			$field_names = $password_field->protectedFields();
6465
+			foreach ($field_names as $field_name) {
6466
+				$fields[ $field_name ] = $this->field_settings_for($field_name);
6467
+			}
6468
+		}
6469
+		return $fields;
6470
+	}
6471
+
6472
+
6473
+	/**
6474
+	 * Checks if the current user can perform the requested action on this model
6475
+	 *
6476
+	 * @param string              $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6477
+	 * @param EE_Base_Class|array $model_obj_or_fields_n_values
6478
+	 * @return bool
6479
+	 * @throws EE_Error
6480
+	 * @throws InvalidArgumentException
6481
+	 * @throws InvalidDataTypeException
6482
+	 * @throws InvalidInterfaceException
6483
+	 * @throws ReflectionException
6484
+	 * @throws UnexpectedEntityException
6485
+	 * @since 4.9.74.p
6486
+	 */
6487
+	public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6488
+	{
6489
+		if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6490
+			$model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6491
+		}
6492
+		if (! is_array($model_obj_or_fields_n_values)) {
6493
+			throw new UnexpectedEntityException(
6494
+				$model_obj_or_fields_n_values,
6495
+				'EE_Base_Class',
6496
+				sprintf(
6497
+					esc_html__(
6498
+						'%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.',
6499
+						'event_espresso'
6500
+					),
6501
+					__FUNCTION__
6502
+				)
6503
+			);
6504
+		}
6505
+		return $this->exists(
6506
+			$this->alter_query_params_to_restrict_by_ID(
6507
+				$this->get_index_primary_key_string($model_obj_or_fields_n_values),
6508
+				[
6509
+					'default_where_conditions' => 'none',
6510
+					'caps'                     => $cap_to_check,
6511
+				]
6512
+			)
6513
+		);
6514
+	}
6515
+
6516
+
6517
+	/**
6518
+	 * Returns the query param where conditions key to the password affecting this model.
6519
+	 * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6520
+	 *
6521
+	 * @return null|string
6522
+	 * @throws EE_Error
6523
+	 * @throws InvalidArgumentException
6524
+	 * @throws InvalidDataTypeException
6525
+	 * @throws InvalidInterfaceException
6526
+	 * @throws ModelConfigurationException
6527
+	 * @throws ReflectionException
6528
+	 * @since 4.9.74.p
6529
+	 */
6530
+	public function modelChainAndPassword()
6531
+	{
6532
+		if ($this->model_chain_to_password === null) {
6533
+			throw new ModelConfigurationException(
6534
+				$this,
6535
+				esc_html_x(
6536
+				// @codingStandardsIgnoreStart
6537
+					'Cannot exclude protected data because the model has not specified which model has the password.',
6538
+					// @codingStandardsIgnoreEnd
6539
+					'1: model name',
6540
+					'event_espresso'
6541
+				)
6542
+			);
6543
+		}
6544
+		if ($this->model_chain_to_password === '') {
6545
+			$model_with_password = $this;
6546
+		} else {
6547
+			if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6548
+				$last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6549
+			} else {
6550
+				$last_model_in_chain = $this->model_chain_to_password;
6551
+			}
6552
+			$model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6553
+		}
6554
+
6555
+		$password_field = $model_with_password->getPasswordField();
6556
+		if ($password_field instanceof EE_Password_Field) {
6557
+			$password_field_name = $password_field->get_name();
6558
+		} else {
6559
+			throw new ModelConfigurationException(
6560
+				$this,
6561
+				sprintf(
6562
+					esc_html_x(
6563
+						'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"',
6564
+						'1: model name, 2: special string',
6565
+						'event_espresso'
6566
+					),
6567
+					$model_with_password->get_this_model_name(),
6568
+					$this->model_chain_to_password
6569
+				)
6570
+			);
6571
+		}
6572
+		return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6573
+	}
6574
+
6575
+
6576
+	/**
6577
+	 * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6578
+	 * or if this model itself has a password affecting access to some of its other fields.
6579
+	 *
6580
+	 * @return boolean
6581
+	 * @since 4.9.74.p
6582
+	 */
6583
+	public function restrictedByRelatedModelPassword()
6584
+	{
6585
+		return $this->model_chain_to_password !== null;
6586
+	}
6587 6587
 }
Please login to merge, or discard this patch.
Spacing   +247 added lines, -247 removed lines patch added patch discarded remove patch
@@ -567,7 +567,7 @@  discard block
 block discarded – undo
567 567
     protected function __construct($timezone = '')
568 568
     {
569 569
         // check that the model has not been loaded too soon
570
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
570
+        if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
571 571
             throw new EE_Error(
572 572
                 sprintf(
573 573
                     esc_html__(
@@ -590,7 +590,7 @@  discard block
 block discarded – undo
590 590
          *
591 591
          * @var EE_Table_Base[] $_tables
592 592
          */
593
-        $this->_tables = (array)apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
593
+        $this->_tables = (array) apply_filters('FHEE__'.get_class($this).'__construct__tables', $this->_tables);
594 594
         foreach ($this->_tables as $table_alias => $table_obj) {
595 595
             /** @var $table_obj EE_Table_Base */
596 596
             $table_obj->_construct_finalize_with_alias($table_alias);
@@ -605,10 +605,10 @@  discard block
 block discarded – undo
605 605
          *
606 606
          * @param EE_Model_Field_Base[] $_fields
607 607
          */
608
-        $this->_fields = (array)apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
608
+        $this->_fields = (array) apply_filters('FHEE__'.get_class($this).'__construct__fields', $this->_fields);
609 609
         $this->_invalidate_field_caches();
610 610
         foreach ($this->_fields as $table_alias => $fields_for_table) {
611
-            if (! array_key_exists($table_alias, $this->_tables)) {
611
+            if ( ! array_key_exists($table_alias, $this->_tables)) {
612 612
                 throw new EE_Error(
613 613
                     sprintf(
614 614
                         esc_html__(
@@ -644,8 +644,8 @@  discard block
 block discarded – undo
644 644
          *
645 645
          * @param EE_Model_Relation_Base[] $_model_relations
646 646
          */
647
-        $this->_model_relations = (array)apply_filters(
648
-            'FHEE__' . get_class($this) . '__construct__model_relations',
647
+        $this->_model_relations = (array) apply_filters(
648
+            'FHEE__'.get_class($this).'__construct__model_relations',
649 649
             $this->_model_relations
650 650
         );
651 651
         foreach ($this->_model_relations as $model_name => $relation_obj) {
@@ -657,12 +657,12 @@  discard block
 block discarded – undo
657 657
         }
658 658
         $this->set_timezone($timezone);
659 659
         // finalize default where condition strategy, or set default
660
-        if (! $this->_default_where_conditions_strategy) {
660
+        if ( ! $this->_default_where_conditions_strategy) {
661 661
             // nothing was set during child constructor, so set default
662 662
             $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
663 663
         }
664 664
         $this->_default_where_conditions_strategy->_finalize_construct($this);
665
-        if (! $this->_minimum_where_conditions_strategy) {
665
+        if ( ! $this->_minimum_where_conditions_strategy) {
666 666
             // nothing was set during child constructor, so set default
667 667
             $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
668 668
         }
@@ -675,8 +675,8 @@  discard block
 block discarded – undo
675 675
         // initialize the standard cap restriction generators if none were specified by the child constructor
676 676
         if ($this->_cap_restriction_generators !== false) {
677 677
             foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
678
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
679
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
678
+                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
679
+                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
680 680
                         'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
681 681
                         new EE_Restriction_Generator_Protected(),
682 682
                         $cap_context,
@@ -688,10 +688,10 @@  discard block
 block discarded – undo
688 688
         // if there are cap restriction generators, use them to make the default cap restrictions
689 689
         if ($this->_cap_restriction_generators !== false) {
690 690
             foreach ($this->_cap_restriction_generators as $context => $generator_object) {
691
-                if (! $generator_object) {
691
+                if ( ! $generator_object) {
692 692
                     continue;
693 693
                 }
694
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
694
+                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
695 695
                     throw new EE_Error(
696 696
                         sprintf(
697 697
                             esc_html__(
@@ -704,12 +704,12 @@  discard block
 block discarded – undo
704 704
                     );
705 705
                 }
706 706
                 $action = $this->cap_action_for_context($context);
707
-                if (! $generator_object->construction_finalized()) {
707
+                if ( ! $generator_object->construction_finalized()) {
708 708
                     $generator_object->_construct_finalize($this, $action);
709 709
                 }
710 710
             }
711 711
         }
712
-        do_action('AHEE__' . get_class($this) . '__construct__end');
712
+        do_action('AHEE__'.get_class($this).'__construct__end');
713 713
     }
714 714
 
715 715
 
@@ -721,7 +721,7 @@  discard block
 block discarded – undo
721 721
      */
722 722
     public static function set_model_query_blog_id($blog_id = 0)
723 723
     {
724
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
724
+        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
725 725
     }
726 726
 
727 727
 
@@ -753,7 +753,7 @@  discard block
 block discarded – undo
753 753
     public static function instance($timezone = '')
754 754
     {
755 755
         // check if instance of Espresso_model already exists
756
-        if (! static::$_instance instanceof static) {
756
+        if ( ! static::$_instance instanceof static) {
757 757
             // instantiate Espresso_model
758 758
             static::$_instance = new static(
759 759
                 $timezone,
@@ -789,7 +789,7 @@  discard block
 block discarded – undo
789 789
             foreach ($r->getDefaultProperties() as $property => $value) {
790 790
                 // don't set instance to null like it was originally,
791 791
                 // but it's static anyways, and we're ignoring static properties (for now at least)
792
-                if (! isset($static_properties[ $property ])) {
792
+                if ( ! isset($static_properties[$property])) {
793 793
                     static::$_instance->{$property} = $value;
794 794
                 }
795 795
             }
@@ -813,7 +813,7 @@  discard block
 block discarded – undo
813 813
      */
814 814
     private static function getLoader()
815 815
     {
816
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
816
+        if ( ! EEM_Base::$loader instanceof LoaderInterface) {
817 817
             EEM_Base::$loader = LoaderFactory::getLoader();
818 818
         }
819 819
         return EEM_Base::$loader;
@@ -833,7 +833,7 @@  discard block
 block discarded – undo
833 833
      */
834 834
     public function status_array($translated = false)
835 835
     {
836
-        if (! array_key_exists('Status', $this->_model_relations)) {
836
+        if ( ! array_key_exists('Status', $this->_model_relations)) {
837 837
             return [];
838 838
         }
839 839
         $model_name   = $this->get_this_model_name();
@@ -841,7 +841,7 @@  discard block
 block discarded – undo
841 841
         $stati        = EEM_Status::instance()->get_all([['STS_type' => $status_type]]);
842 842
         $status_array = [];
843 843
         foreach ($stati as $status) {
844
-            $status_array[ $status->ID() ] = $status->get('STS_code');
844
+            $status_array[$status->ID()] = $status->get('STS_code');
845 845
         }
846 846
         return $translated
847 847
             ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
@@ -904,7 +904,7 @@  discard block
 block discarded – undo
904 904
     {
905 905
         $wp_user_field_name = $this->wp_user_field_name();
906 906
         if ($wp_user_field_name) {
907
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
907
+            $query_params[0][$wp_user_field_name] = get_current_user_id();
908 908
         }
909 909
         return $query_params;
910 910
     }
@@ -922,17 +922,17 @@  discard block
 block discarded – undo
922 922
     public function wp_user_field_name()
923 923
     {
924 924
         try {
925
-            if (! empty($this->_model_chain_to_wp_user)) {
925
+            if ( ! empty($this->_model_chain_to_wp_user)) {
926 926
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
927 927
                 $last_model_name              = end($models_to_follow_to_wp_users);
928 928
                 $model_with_fk_to_wp_users    = EE_Registry::instance()->load_model($last_model_name);
929
-                $model_chain_to_wp_user       = $this->_model_chain_to_wp_user . '.';
929
+                $model_chain_to_wp_user       = $this->_model_chain_to_wp_user.'.';
930 930
             } else {
931 931
                 $model_with_fk_to_wp_users = $this;
932 932
                 $model_chain_to_wp_user    = '';
933 933
             }
934 934
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
935
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
935
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
936 936
         } catch (EE_Error $e) {
937 937
             return false;
938 938
         }
@@ -1008,11 +1008,11 @@  discard block
 block discarded – undo
1008 1008
         if ($this->_custom_selections instanceof CustomSelects) {
1009 1009
             $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1010 1010
             $select_expressions .= $select_expressions
1011
-                ? ', ' . $custom_expressions
1011
+                ? ', '.$custom_expressions
1012 1012
                 : $custom_expressions;
1013 1013
         }
1014 1014
 
1015
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1015
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1016 1016
         return $this->_do_wpdb_query('get_results', [$SQL, $output]);
1017 1017
     }
1018 1018
 
@@ -1029,7 +1029,7 @@  discard block
 block discarded – undo
1029 1029
      */
1030 1030
     protected function getCustomSelection(array $query_params, $columns_to_select = null)
1031 1031
     {
1032
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1032
+        if ( ! isset($query_params['extra_selects']) && $columns_to_select === null) {
1033 1033
             return null;
1034 1034
         }
1035 1035
         $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
@@ -1078,7 +1078,7 @@  discard block
 block discarded – undo
1078 1078
         if (is_array($columns_to_select)) {
1079 1079
             $select_sql_array = [];
1080 1080
             foreach ($columns_to_select as $alias => $selection_and_datatype) {
1081
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1081
+                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1082 1082
                     throw new EE_Error(
1083 1083
                         sprintf(
1084 1084
                             esc_html__(
@@ -1090,7 +1090,7 @@  discard block
 block discarded – undo
1090 1090
                         )
1091 1091
                     );
1092 1092
                 }
1093
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1093
+                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1094 1094
                     throw new EE_Error(
1095 1095
                         sprintf(
1096 1096
                             esc_html__(
@@ -1162,12 +1162,12 @@  discard block
 block discarded – undo
1162 1162
      */
1163 1163
     public function alter_query_params_to_restrict_by_ID($id, $query_params = [])
1164 1164
     {
1165
-        if (! isset($query_params[0])) {
1165
+        if ( ! isset($query_params[0])) {
1166 1166
             $query_params[0] = [];
1167 1167
         }
1168 1168
         $conditions_from_id = $this->parse_index_primary_key_string($id);
1169 1169
         if ($conditions_from_id === null) {
1170
-            $query_params[0][ $this->primary_key_name() ] = $id;
1170
+            $query_params[0][$this->primary_key_name()] = $id;
1171 1171
         } else {
1172 1172
             // no primary key, so the $id must be from the get_index_primary_key_string()
1173 1173
             $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
@@ -1187,7 +1187,7 @@  discard block
 block discarded – undo
1187 1187
      */
1188 1188
     public function get_one($query_params = [])
1189 1189
     {
1190
-        if (! is_array($query_params)) {
1190
+        if ( ! is_array($query_params)) {
1191 1191
             EE_Error::doing_it_wrong(
1192 1192
                 'EEM_Base::get_one',
1193 1193
                 sprintf(
@@ -1387,7 +1387,7 @@  discard block
 block discarded – undo
1387 1387
                 return [];
1388 1388
             }
1389 1389
         }
1390
-        if (! is_array($query_params)) {
1390
+        if ( ! is_array($query_params)) {
1391 1391
             EE_Error::doing_it_wrong(
1392 1392
                 'EEM_Base::_get_consecutive',
1393 1393
                 sprintf(
@@ -1399,10 +1399,10 @@  discard block
 block discarded – undo
1399 1399
             $query_params = [];
1400 1400
         }
1401 1401
         // let's add the where query param for consecutive look up.
1402
-        $query_params[0][ $field_to_order_by ] = [$operand, $current_field_value];
1402
+        $query_params[0][$field_to_order_by] = [$operand, $current_field_value];
1403 1403
         $query_params['limit']                 = $limit;
1404 1404
         // set direction
1405
-        $incoming_orderby         = isset($query_params['order_by']) ? (array)$query_params['order_by'] : [];
1405
+        $incoming_orderby         = isset($query_params['order_by']) ? (array) $query_params['order_by'] : [];
1406 1406
         $query_params['order_by'] = $operand === '>'
1407 1407
             ? [$field_to_order_by => 'ASC'] + $incoming_orderby
1408 1408
             : [$field_to_order_by => 'DESC'] + $incoming_orderby;
@@ -1486,7 +1486,7 @@  discard block
 block discarded – undo
1486 1486
     {
1487 1487
         $field_settings = $this->field_settings_for($field_name);
1488 1488
         // if not a valid EE_Datetime_Field then throw error
1489
-        if (! $field_settings instanceof EE_Datetime_Field) {
1489
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1490 1490
             throw new EE_Error(
1491 1491
                 sprintf(
1492 1492
                     esc_html__(
@@ -1643,7 +1643,7 @@  discard block
 block discarded – undo
1643 1643
      */
1644 1644
     public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1645 1645
     {
1646
-        if (! is_array($query_params)) {
1646
+        if ( ! is_array($query_params)) {
1647 1647
             EE_Error::doing_it_wrong(
1648 1648
                 'EEM_Base::update',
1649 1649
                 sprintf(
@@ -1672,7 +1672,7 @@  discard block
 block discarded – undo
1672 1672
          * @param array    $query_params
1673 1673
          * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1674 1674
          */
1675
-        $fields_n_values = (array)apply_filters(
1675
+        $fields_n_values = (array) apply_filters(
1676 1676
             'FHEE__EEM_Base__update__fields_n_values',
1677 1677
             $fields_n_values,
1678 1678
             $this,
@@ -1690,10 +1690,10 @@  discard block
 block discarded – undo
1690 1690
         $wpdb_select_results          = $this->_get_all_wpdb_results($query_params);
1691 1691
         foreach ($wpdb_select_results as $wpdb_result) {
1692 1692
             // type cast stdClass as array
1693
-            $wpdb_result = (array)$wpdb_result;
1693
+            $wpdb_result = (array) $wpdb_result;
1694 1694
             // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1695 1695
             if ($this->has_primary_key_field()) {
1696
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1696
+                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1697 1697
             } else {
1698 1698
                 // 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)
1699 1699
                 $main_table_pk_value = null;
@@ -1709,7 +1709,7 @@  discard block
 block discarded – undo
1709 1709
                     // in this table, right? so insert a row in the current table, using any fields available
1710 1710
                     if (
1711 1711
                     ! (array_key_exists($this_table_pk_column, $wpdb_result)
1712
-                       && $wpdb_result[ $this_table_pk_column ])
1712
+                       && $wpdb_result[$this_table_pk_column])
1713 1713
                     ) {
1714 1714
                         $success = $this->_insert_into_specific_table(
1715 1715
                             $table_obj,
@@ -1717,7 +1717,7 @@  discard block
 block discarded – undo
1717 1717
                             $main_table_pk_value
1718 1718
                         );
1719 1719
                         // if we died here, report the error
1720
-                        if (! $success) {
1720
+                        if ( ! $success) {
1721 1721
                             return false;
1722 1722
                         }
1723 1723
                     }
@@ -1739,10 +1739,10 @@  discard block
 block discarded – undo
1739 1739
                 $model_objs_affected_ids     = [];
1740 1740
                 foreach ($models_affected_key_columns as $row) {
1741 1741
                     $combined_index_key                             = $this->get_index_primary_key_string($row);
1742
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1742
+                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1743 1743
                 }
1744 1744
             }
1745
-            if (! $model_objs_affected_ids) {
1745
+            if ( ! $model_objs_affected_ids) {
1746 1746
                 // wait wait wait- if nothing was affected let's stop here
1747 1747
                 return 0;
1748 1748
             }
@@ -1765,11 +1765,11 @@  discard block
 block discarded – undo
1765 1765
             }
1766 1766
         }
1767 1767
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1768
-        $SQL              = "UPDATE " . $model_query_info->get_full_join_sql()
1769
-                            . " SET " . $this->_construct_update_sql($fields_n_values)
1768
+        $SQL              = "UPDATE ".$model_query_info->get_full_join_sql()
1769
+                            . " SET ".$this->_construct_update_sql($fields_n_values)
1770 1770
                             . $model_query_info->get_where_sql();
1771 1771
         // note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1772
-        $rows_affected    = $this->_do_wpdb_query('query', [$SQL]);
1772
+        $rows_affected = $this->_do_wpdb_query('query', [$SQL]);
1773 1773
         /**
1774 1774
          * Action called after a model update call has been made.
1775 1775
          *
@@ -1780,7 +1780,7 @@  discard block
 block discarded – undo
1780 1780
          * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1781 1781
          */
1782 1782
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1783
-        return $rows_affected;// how many supposedly got updated
1783
+        return $rows_affected; // how many supposedly got updated
1784 1784
     }
1785 1785
 
1786 1786
 
@@ -1810,7 +1810,7 @@  discard block
 block discarded – undo
1810 1810
         }
1811 1811
         $model_query_info   = $this->_create_model_query_info_carrier($query_params);
1812 1812
         $select_expressions = $field->get_qualified_column();
1813
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1813
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1814 1814
         return $this->_do_wpdb_query('get_col', [$SQL]);
1815 1815
     }
1816 1816
 
@@ -1830,7 +1830,7 @@  discard block
 block discarded – undo
1830 1830
     {
1831 1831
         $query_params['limit'] = 1;
1832 1832
         $col                   = $this->get_col($query_params, $field_to_select);
1833
-        if (! empty($col)) {
1833
+        if ( ! empty($col)) {
1834 1834
             return reset($col);
1835 1835
         }
1836 1836
         return null;
@@ -1860,7 +1860,7 @@  discard block
 block discarded – undo
1860 1860
             $value_sql       = $prepared_value === null
1861 1861
                 ? 'NULL'
1862 1862
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1863
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1863
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1864 1864
         }
1865 1865
         return implode(",", $cols_n_values);
1866 1866
     }
@@ -1990,9 +1990,9 @@  discard block
 block discarded – undo
1990 1990
         if ($deletion_where_query_part) {
1991 1991
             $model_query_info = $this->_create_model_query_info_carrier($query_params);
1992 1992
             $table_aliases    = implode(', ', array_keys($this->_tables));
1993
-            $SQL              = "DELETE " . $table_aliases
1994
-                                . " FROM " . $model_query_info->get_full_join_sql()
1995
-                                . " WHERE " . $deletion_where_query_part;
1993
+            $SQL              = "DELETE ".$table_aliases
1994
+                                . " FROM ".$model_query_info->get_full_join_sql()
1995
+                                . " WHERE ".$deletion_where_query_part;
1996 1996
             $rows_deleted     = $this->_do_wpdb_query('query', [$SQL]);
1997 1997
         } else {
1998 1998
             $rows_deleted = 0;
@@ -2003,12 +2003,12 @@  discard block
 block discarded – undo
2003 2003
         if (
2004 2004
             $this->has_primary_key_field()
2005 2005
             && $rows_deleted !== false
2006
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2006
+            && isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
2007 2007
         ) {
2008
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2008
+            $ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
2009 2009
             foreach ($ids_for_removal as $id) {
2010
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2011
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2010
+                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
2011
+                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
2012 2012
                 }
2013 2013
             }
2014 2014
 
@@ -2048,7 +2048,7 @@  discard block
 block discarded – undo
2048 2048
          * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2049 2049
          */
2050 2050
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2051
-        return $rows_deleted;// how many supposedly got deleted
2051
+        return $rows_deleted; // how many supposedly got deleted
2052 2052
     }
2053 2053
 
2054 2054
 
@@ -2144,15 +2144,15 @@  discard block
 block discarded – undo
2144 2144
                 if (
2145 2145
                     $allow_blocking
2146 2146
                     && $this->delete_is_blocked_by_related_models(
2147
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2147
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2148 2148
                     )
2149 2149
                 ) {
2150 2150
                     continue;
2151 2151
                 }
2152 2152
                 // primary table deletes
2153
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2154
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2155
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2153
+                if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2154
+                    $ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2155
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2156 2156
                 }
2157 2157
             }
2158 2158
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2161,8 +2161,8 @@  discard block
 block discarded – undo
2161 2161
                 $ids_to_delete_indexed_by_column_for_row = [];
2162 2162
                 foreach ($fields as $cpk_field) {
2163 2163
                     if ($cpk_field instanceof EE_Model_Field_Base) {
2164
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2165
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2164
+                        $ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2165
+                            $item_to_delete[$cpk_field->get_qualified_column()];
2166 2166
                     }
2167 2167
                 }
2168 2168
                 $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
@@ -2202,7 +2202,7 @@  discard block
 block discarded – undo
2202 2202
             foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2203 2203
                 // make sure we have unique $ids
2204 2204
                 $ids     = array_unique($ids);
2205
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2205
+                $query[] = $column.' IN('.implode(',', $ids).')';
2206 2206
             }
2207 2207
             $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2208 2208
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2210,7 +2210,7 @@  discard block
 block discarded – undo
2210 2210
             foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2211 2211
                 $values_for_each_combined_primary_key_for_a_row = [];
2212 2212
                 foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2213
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2213
+                    $values_for_each_combined_primary_key_for_a_row[] = $column.'='.$id;
2214 2214
                 }
2215 2215
                 $value_and_value_and_value = implode(' AND ', $values_for_each_combined_primary_key_for_a_row);
2216 2216
                 $ways_to_identify_a_row[]  = "({$value_and_value_and_value})";
@@ -2283,10 +2283,10 @@  discard block
 block discarded – undo
2283 2283
                 $column_to_count = '*';
2284 2284
             }
2285 2285
         }
2286
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2286
+        $column_to_count = $distinct ? "DISTINCT ".$column_to_count : $column_to_count;
2287 2287
         $SQL             =
2288
-            "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2289
-        return (int)$this->_do_wpdb_query('get_var', [$SQL]);
2288
+            "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2289
+        return (int) $this->_do_wpdb_query('get_var', [$SQL]);
2290 2290
     }
2291 2291
 
2292 2292
 
@@ -2309,15 +2309,15 @@  discard block
 block discarded – undo
2309 2309
             $field_obj = $this->get_primary_key_field();
2310 2310
         }
2311 2311
         $column_to_count = $field_obj->get_qualified_column();
2312
-        $SQL             = "SELECT SUM(" . $column_to_count . ")"
2312
+        $SQL             = "SELECT SUM(".$column_to_count.")"
2313 2313
                            . $this->_construct_2nd_half_of_select_query($model_query_info);
2314 2314
         $return_value    = $this->_do_wpdb_query('get_var', [$SQL]);
2315 2315
         $data_type       = $field_obj->get_wpdb_data_type();
2316 2316
         if ($data_type === '%d' || $data_type === '%s') {
2317
-            return (float)$return_value;
2317
+            return (float) $return_value;
2318 2318
         }
2319 2319
         // must be %f
2320
-        return (float)$return_value;
2320
+        return (float) $return_value;
2321 2321
     }
2322 2322
 
2323 2323
 
@@ -2336,7 +2336,7 @@  discard block
 block discarded – undo
2336 2336
         // if we're in maintenance mode level 2, DON'T run any queries
2337 2337
         // because level 2 indicates the database needs updating and
2338 2338
         // is probably out of sync with the code
2339
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2339
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2340 2340
             throw new EE_Error(
2341 2341
                 sprintf(
2342 2342
                     esc_html__(
@@ -2347,7 +2347,7 @@  discard block
 block discarded – undo
2347 2347
             );
2348 2348
         }
2349 2349
         global $wpdb;
2350
-        if (! method_exists($wpdb, $wpdb_method)) {
2350
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2351 2351
             throw new EE_Error(
2352 2352
                 sprintf(
2353 2353
                     esc_html__(
@@ -2366,7 +2366,7 @@  discard block
 block discarded – undo
2366 2366
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2367 2367
         if (WP_DEBUG) {
2368 2368
             $wpdb->show_errors($old_show_errors_value);
2369
-            if (! empty($wpdb->last_error)) {
2369
+            if ( ! empty($wpdb->last_error)) {
2370 2370
                 throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2371 2371
             }
2372 2372
             if ($result === false) {
@@ -2436,7 +2436,7 @@  discard block
 block discarded – undo
2436 2436
                     // ummmm... you in trouble
2437 2437
                     return $result;
2438 2438
             }
2439
-            if (! empty($error_message)) {
2439
+            if ( ! empty($error_message)) {
2440 2440
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2441 2441
                 trigger_error($error_message);
2442 2442
             }
@@ -2513,11 +2513,11 @@  discard block
 block discarded – undo
2513 2513
      */
2514 2514
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2515 2515
     {
2516
-        return " FROM " . $model_query_info->get_full_join_sql() .
2517
-               $model_query_info->get_where_sql() .
2518
-               $model_query_info->get_group_by_sql() .
2519
-               $model_query_info->get_having_sql() .
2520
-               $model_query_info->get_order_by_sql() .
2516
+        return " FROM ".$model_query_info->get_full_join_sql().
2517
+               $model_query_info->get_where_sql().
2518
+               $model_query_info->get_group_by_sql().
2519
+               $model_query_info->get_having_sql().
2520
+               $model_query_info->get_order_by_sql().
2521 2521
                $model_query_info->get_limit_sql();
2522 2522
     }
2523 2523
 
@@ -2710,12 +2710,12 @@  discard block
 block discarded – undo
2710 2710
         $related_model = $this->get_related_model_obj($model_name);
2711 2711
         // we're just going to use the query params on the related model's normal get_all query,
2712 2712
         // except add a condition to say to match the current mod
2713
-        if (! isset($query_params['default_where_conditions'])) {
2713
+        if ( ! isset($query_params['default_where_conditions'])) {
2714 2714
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2715 2715
         }
2716 2716
         $this_model_name                                                 = $this->get_this_model_name();
2717 2717
         $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2718
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2718
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2719 2719
         return $related_model->count($query_params, $field_to_count, $distinct);
2720 2720
     }
2721 2721
 
@@ -2736,7 +2736,7 @@  discard block
 block discarded – undo
2736 2736
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2737 2737
     {
2738 2738
         $related_model = $this->get_related_model_obj($model_name);
2739
-        if (! is_array($query_params)) {
2739
+        if ( ! is_array($query_params)) {
2740 2740
             EE_Error::doing_it_wrong(
2741 2741
                 'EEM_Base::sum_related',
2742 2742
                 sprintf(
@@ -2749,12 +2749,12 @@  discard block
 block discarded – undo
2749 2749
         }
2750 2750
         // we're just going to use the query params on the related model's normal get_all query,
2751 2751
         // except add a condition to say to match the current mod
2752
-        if (! isset($query_params['default_where_conditions'])) {
2752
+        if ( ! isset($query_params['default_where_conditions'])) {
2753 2753
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2754 2754
         }
2755 2755
         $this_model_name                                                 = $this->get_this_model_name();
2756 2756
         $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2757
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2757
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2758 2758
         return $related_model->sum($query_params, $field_to_sum);
2759 2759
     }
2760 2760
 
@@ -2806,7 +2806,7 @@  discard block
 block discarded – undo
2806 2806
                 $field_with_model_name = $field;
2807 2807
             }
2808 2808
         }
2809
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2809
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2810 2810
             throw new EE_Error(
2811 2811
                 sprintf(
2812 2812
                     esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
@@ -2843,7 +2843,7 @@  discard block
 block discarded – undo
2843 2843
          * @param array    $fields_n_values keys are the fields and values are their new values
2844 2844
          * @param EEM_Base $model           the model used
2845 2845
          */
2846
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2846
+        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2847 2847
         if ($this->_satisfies_unique_indexes($field_n_values)) {
2848 2848
             $main_table = $this->_get_main_table();
2849 2849
             $new_id     = $this->_insert_into_specific_table($main_table, $field_n_values, false);
@@ -2945,14 +2945,14 @@  discard block
 block discarded – undo
2945 2945
                 || $this->get_primary_key_field()
2946 2946
                    instanceof
2947 2947
                    EE_Primary_Key_String_Field)
2948
-            && isset($fields_n_values[ $this->primary_key_name() ])
2948
+            && isset($fields_n_values[$this->primary_key_name()])
2949 2949
         ) {
2950
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2950
+            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2951 2951
         }
2952 2952
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2953 2953
             $uniqueness_where_params                              =
2954 2954
                 array_intersect_key($fields_n_values, $unique_index->fields());
2955
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2955
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2956 2956
         }
2957 2957
         // if there is nothing to base this search on, then we shouldn't find anything
2958 2958
         if (empty($query_params)) {
@@ -3029,16 +3029,16 @@  discard block
 block discarded – undo
3029 3029
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3030 3030
             // if the value we want to assign it to is NULL, just don't mention it for the insertion
3031 3031
             if ($prepared_value !== null) {
3032
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3032
+                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
3033 3033
                 $format_for_insertion[]                                   = $field_obj->get_wpdb_data_type();
3034 3034
             }
3035 3035
         }
3036 3036
         if ($table instanceof EE_Secondary_Table && $new_id) {
3037 3037
             // its not the main table, so we should have already saved the main table's PK which we just inserted
3038 3038
             // so add the fk to the main table as a column
3039
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3039
+            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
3040 3040
             $format_for_insertion[]                              =
3041
-                '%d';// yes right now we're only allowing these foreign keys to be INTs
3041
+                '%d'; // yes right now we're only allowing these foreign keys to be INTs
3042 3042
         }
3043 3043
         // insert the new entry
3044 3044
         $result = $this->_do_wpdb_query(
@@ -3055,7 +3055,7 @@  discard block
 block discarded – undo
3055 3055
             }
3056 3056
             // it's not an auto-increment primary key, so
3057 3057
             // it must have been supplied
3058
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3058
+            return $fields_n_values[$this->get_primary_key_field()->get_name()];
3059 3059
         }
3060 3060
         // we can't return a  primary key because there is none. instead return
3061 3061
         // a unique string indicating this model
@@ -3079,14 +3079,14 @@  discard block
 block discarded – undo
3079 3079
         if (
3080 3080
             ! $field_obj->is_nullable()
3081 3081
             && (
3082
-                ! isset($fields_n_values[ $field_obj->get_name() ])
3083
-                || $fields_n_values[ $field_obj->get_name() ] === null
3082
+                ! isset($fields_n_values[$field_obj->get_name()])
3083
+                || $fields_n_values[$field_obj->get_name()] === null
3084 3084
             )
3085 3085
         ) {
3086
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3086
+            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
3087 3087
         }
3088
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3089
-            ? $fields_n_values[ $field_obj->get_name() ]
3088
+        $unprepared_value = isset($fields_n_values[$field_obj->get_name()])
3089
+            ? $fields_n_values[$field_obj->get_name()]
3090 3090
             : null;
3091 3091
         return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3092 3092
     }
@@ -3187,7 +3187,7 @@  discard block
 block discarded – undo
3187 3187
      */
3188 3188
     public function get_table_obj_by_alias($table_alias = '')
3189 3189
     {
3190
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3190
+        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3191 3191
     }
3192 3192
 
3193 3193
 
@@ -3201,7 +3201,7 @@  discard block
 block discarded – undo
3201 3201
         $other_tables = [];
3202 3202
         foreach ($this->_tables as $table_alias => $table) {
3203 3203
             if ($table instanceof EE_Secondary_Table) {
3204
-                $other_tables[ $table_alias ] = $table;
3204
+                $other_tables[$table_alias] = $table;
3205 3205
             }
3206 3206
         }
3207 3207
         return $other_tables;
@@ -3216,7 +3216,7 @@  discard block
 block discarded – undo
3216 3216
      */
3217 3217
     public function _get_fields_for_table($table_alias)
3218 3218
     {
3219
-        return $this->_fields[ $table_alias ];
3219
+        return $this->_fields[$table_alias];
3220 3220
     }
3221 3221
 
3222 3222
 
@@ -3245,7 +3245,7 @@  discard block
 block discarded – undo
3245 3245
                     $query_info_carrier,
3246 3246
                     'group_by'
3247 3247
                 );
3248
-            } elseif (! empty($query_params['group_by'])) {
3248
+            } elseif ( ! empty($query_params['group_by'])) {
3249 3249
                 $this->_extract_related_model_info_from_query_param(
3250 3250
                     $query_params['group_by'],
3251 3251
                     $query_info_carrier,
@@ -3267,7 +3267,7 @@  discard block
 block discarded – undo
3267 3267
                     $query_info_carrier,
3268 3268
                     'order_by'
3269 3269
                 );
3270
-            } elseif (! empty($query_params['order_by'])) {
3270
+            } elseif ( ! empty($query_params['order_by'])) {
3271 3271
                 $this->_extract_related_model_info_from_query_param(
3272 3272
                     $query_params['order_by'],
3273 3273
                     $query_info_carrier,
@@ -3302,8 +3302,8 @@  discard block
 block discarded – undo
3302 3302
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3303 3303
         $query_param_type
3304 3304
     ) {
3305
-        if (! empty($sub_query_params)) {
3306
-            $sub_query_params = (array)$sub_query_params;
3305
+        if ( ! empty($sub_query_params)) {
3306
+            $sub_query_params = (array) $sub_query_params;
3307 3307
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3308 3308
                 // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3309 3309
                 $this->_extract_related_model_info_from_query_param(
@@ -3318,7 +3318,7 @@  discard block
 block discarded – undo
3318 3318
                 $query_param_sans_stars =
3319 3319
                     $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3320 3320
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3321
-                    if (! is_array($possibly_array_of_params)) {
3321
+                    if ( ! is_array($possibly_array_of_params)) {
3322 3322
                         throw new EE_Error(
3323 3323
                             sprintf(
3324 3324
                                 esc_html__(
@@ -3344,7 +3344,7 @@  discard block
 block discarded – undo
3344 3344
                     // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3345 3345
                     // indicating that $possible_array_of_params[1] is actually a field name,
3346 3346
                     // from which we should extract query parameters!
3347
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3347
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3348 3348
                         throw new EE_Error(
3349 3349
                             sprintf(
3350 3350
                                 esc_html__(
@@ -3384,8 +3384,8 @@  discard block
 block discarded – undo
3384 3384
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3385 3385
         $query_param_type
3386 3386
     ) {
3387
-        if (! empty($sub_query_params)) {
3388
-            if (! is_array($sub_query_params)) {
3387
+        if ( ! empty($sub_query_params)) {
3388
+            if ( ! is_array($sub_query_params)) {
3389 3389
                 throw new EE_Error(
3390 3390
                     sprintf(
3391 3391
                         esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
@@ -3423,7 +3423,7 @@  discard block
 block discarded – undo
3423 3423
      */
3424 3424
     public function _create_model_query_info_carrier($query_params)
3425 3425
     {
3426
-        if (! is_array($query_params)) {
3426
+        if ( ! is_array($query_params)) {
3427 3427
             EE_Error::doing_it_wrong(
3428 3428
                 'EEM_Base::_create_model_query_info_carrier',
3429 3429
                 sprintf(
@@ -3456,7 +3456,7 @@  discard block
 block discarded – undo
3456 3456
             // only include if related to a cpt where no password has been set
3457 3457
             $query_params[0]['OR*nopassword'] = [
3458 3458
                 $where_param_key_for_password       => '',
3459
-                $where_param_key_for_password . '*' => ['IS_NULL'],
3459
+                $where_param_key_for_password.'*' => ['IS_NULL'],
3460 3460
             ];
3461 3461
         }
3462 3462
         $query_object = $this->_extract_related_models_from_query($query_params);
@@ -3510,7 +3510,7 @@  discard block
 block discarded – undo
3510 3510
         // set limit
3511 3511
         if (array_key_exists('limit', $query_params)) {
3512 3512
             if (is_array($query_params['limit'])) {
3513
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3513
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3514 3514
                     $e = sprintf(
3515 3515
                         esc_html__(
3516 3516
                             "Invalid DB query. You passed '%s' for the LIMIT, but only the following are valid: an integer, string representing an integer, a string like 'int,int', or an array like array(int,int)",
@@ -3518,12 +3518,12 @@  discard block
 block discarded – undo
3518 3518
                         ),
3519 3519
                         http_build_query($query_params['limit'])
3520 3520
                     );
3521
-                    throw new EE_Error($e . "|" . $e);
3521
+                    throw new EE_Error($e."|".$e);
3522 3522
                 }
3523 3523
                 // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3524
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3525
-            } elseif (! empty($query_params['limit'])) {
3526
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3524
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3525
+            } elseif ( ! empty($query_params['limit'])) {
3526
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3527 3527
             }
3528 3528
         }
3529 3529
         // set order by
@@ -3555,10 +3555,10 @@  discard block
 block discarded – undo
3555 3555
                 $order_array = [];
3556 3556
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3557 3557
                     $order         = $this->_extract_order($order);
3558
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3558
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3559 3559
                 }
3560
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3561
-            } elseif (! empty($query_params['order_by'])) {
3560
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3561
+            } elseif ( ! empty($query_params['order_by'])) {
3562 3562
                 $this->_extract_related_model_info_from_query_param(
3563 3563
                     $query_params['order_by'],
3564 3564
                     $query_object,
@@ -3569,7 +3569,7 @@  discard block
 block discarded – undo
3569 3569
                     ? $this->_extract_order($query_params['order'])
3570 3570
                     : 'DESC';
3571 3571
                 $query_object->set_order_by_sql(
3572
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3572
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3573 3573
                 );
3574 3574
             }
3575 3575
         }
@@ -3581,7 +3581,7 @@  discard block
 block discarded – undo
3581 3581
         ) {
3582 3582
             $pk_field = $this->get_primary_key_field();
3583 3583
             $order    = $this->_extract_order($query_params['order']);
3584
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3584
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3585 3585
         }
3586 3586
         // set group by
3587 3587
         if (array_key_exists('group_by', $query_params)) {
@@ -3591,10 +3591,10 @@  discard block
 block discarded – undo
3591 3591
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3592 3592
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3593 3593
                 }
3594
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3595
-            } elseif (! empty($query_params['group_by'])) {
3594
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3595
+            } elseif ( ! empty($query_params['group_by'])) {
3596 3596
                 $query_object->set_group_by_sql(
3597
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3597
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3598 3598
                 );
3599 3599
             }
3600 3600
         }
@@ -3604,7 +3604,7 @@  discard block
 block discarded – undo
3604 3604
         }
3605 3605
         // now, just verify they didn't pass anything wack
3606 3606
         foreach ($query_params as $query_key => $query_value) {
3607
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3607
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3608 3608
                 throw new EE_Error(
3609 3609
                     sprintf(
3610 3610
                         esc_html__(
@@ -3708,7 +3708,7 @@  discard block
 block discarded – undo
3708 3708
         $where_query_params = []
3709 3709
     ) {
3710 3710
         $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3711
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3711
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3712 3712
             throw new EE_Error(
3713 3713
                 sprintf(
3714 3714
                     esc_html__(
@@ -3738,7 +3738,7 @@  discard block
 block discarded – undo
3738 3738
                 // we don't want to add full or even minimum default where conditions from this model, so just continue
3739 3739
                 continue;
3740 3740
             }
3741
-            $overrides              = $this->_override_defaults_or_make_null_friendly(
3741
+            $overrides = $this->_override_defaults_or_make_null_friendly(
3742 3742
                 $related_model_universal_where_params,
3743 3743
                 $where_query_params,
3744 3744
                 $related_model,
@@ -3847,19 +3847,19 @@  discard block
 block discarded – undo
3847 3847
     ) {
3848 3848
         $null_friendly_where_conditions = [];
3849 3849
         $none_overridden                = true;
3850
-        $or_condition_key_for_defaults  = 'OR*' . get_class($model);
3850
+        $or_condition_key_for_defaults  = 'OR*'.get_class($model);
3851 3851
         foreach ($default_where_conditions as $key => $val) {
3852
-            if (isset($provided_where_conditions[ $key ])) {
3852
+            if (isset($provided_where_conditions[$key])) {
3853 3853
                 $none_overridden = false;
3854 3854
             } else {
3855
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3855
+                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3856 3856
             }
3857 3857
         }
3858 3858
         if ($none_overridden && $default_where_conditions) {
3859 3859
             if ($model->has_primary_key_field()) {
3860
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3860
+                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3861 3861
                                                                                    . "."
3862
-                                                                                   . $model->primary_key_name() ] =
3862
+                                                                                   . $model->primary_key_name()] =
3863 3863
                     ['IS NULL'];
3864 3864
             }/*else{
3865 3865
                 //@todo NO PK, use other defaults
@@ -3968,7 +3968,7 @@  discard block
 block discarded – undo
3968 3968
             foreach ($tables as $table_obj) {
3969 3969
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3970 3970
                                        . $table_obj->get_fully_qualified_pk_column();
3971
-                if (! in_array($qualified_pk_column, $selects)) {
3971
+                if ( ! in_array($qualified_pk_column, $selects)) {
3972 3972
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3973 3973
                 }
3974 3974
             }
@@ -4120,9 +4120,9 @@  discard block
 block discarded – undo
4120 4120
         $query_parameter_type
4121 4121
     ) {
4122 4122
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4123
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4123
+            if (strpos($possible_join_string, $valid_related_model_name.".") === 0) {
4124 4124
                 $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4125
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4125
+                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name."."));
4126 4126
                 if ($possible_join_string === '') {
4127 4127
                     // nothing left to $query_param
4128 4128
                     // we should actually end in a field name, not a model like this!
@@ -4254,7 +4254,7 @@  discard block
 block discarded – undo
4254 4254
     {
4255 4255
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4256 4256
         if ($SQL) {
4257
-            return " WHERE " . $SQL;
4257
+            return " WHERE ".$SQL;
4258 4258
         }
4259 4259
         return '';
4260 4260
     }
@@ -4272,7 +4272,7 @@  discard block
 block discarded – undo
4272 4272
     {
4273 4273
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4274 4274
         if ($SQL) {
4275
-            return " HAVING " . $SQL;
4275
+            return " HAVING ".$SQL;
4276 4276
         }
4277 4277
         return '';
4278 4278
     }
@@ -4295,7 +4295,7 @@  discard block
 block discarded – undo
4295 4295
             $query_param =
4296 4296
                 $this->_remove_stars_and_anything_after_from_condition_query_param_key(
4297 4297
                     $query_param
4298
-                );// str_replace("*",'',$query_param);
4298
+                ); // str_replace("*",'',$query_param);
4299 4299
             if (in_array($query_param, $this->_logic_query_param_keys)) {
4300 4300
                 switch ($query_param) {
4301 4301
                     case 'not':
@@ -4329,7 +4329,7 @@  discard block
 block discarded – undo
4329 4329
             } else {
4330 4330
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
4331 4331
                 // if it's not a normal field, maybe it's a custom selection?
4332
-                if (! $field_obj) {
4332
+                if ( ! $field_obj) {
4333 4333
                     if ($this->_custom_selections instanceof CustomSelects) {
4334 4334
                         $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4335 4335
                     } else {
@@ -4345,7 +4345,7 @@  discard block
 block discarded – undo
4345 4345
                     }
4346 4346
                 }
4347 4347
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4348
-                $where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4348
+                $where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
4349 4349
             }
4350 4350
         }
4351 4351
         return $where_clauses ? implode($glue, $where_clauses) : '';
@@ -4367,7 +4367,7 @@  discard block
 block discarded – undo
4367 4367
                 $field->get_model_name(),
4368 4368
                 $query_param
4369 4369
             );
4370
-            return $table_alias_prefix . $field->get_qualified_column();
4370
+            return $table_alias_prefix.$field->get_qualified_column();
4371 4371
         }
4372 4372
         if (
4373 4373
             $this->_custom_selections instanceof CustomSelects
@@ -4424,7 +4424,7 @@  discard block
 block discarded – undo
4424 4424
     {
4425 4425
         if (is_array($op_and_value)) {
4426 4426
             $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4427
-            if (! $operator) {
4427
+            if ( ! $operator) {
4428 4428
                 $php_array_like_string = [];
4429 4429
                 foreach ($op_and_value as $key => $value) {
4430 4430
                     $php_array_like_string[] = "$key=>$value";
@@ -4446,14 +4446,14 @@  discard block
 block discarded – undo
4446 4446
         }
4447 4447
         // check to see if the value is actually another field
4448 4448
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4449
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4449
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4450 4450
         }
4451 4451
         if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4452 4452
             // in this case, the value should be an array, or at least a comma-separated list
4453 4453
             // it will need to handle a little differently
4454 4454
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4455 4455
             // note: $cleaned_value has already been run through $wpdb->prepare()
4456
-            return $operator . SP . $cleaned_value;
4456
+            return $operator.SP.$cleaned_value;
4457 4457
         }
4458 4458
         if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4459 4459
             // the value should be an array with count of two.
@@ -4469,7 +4469,7 @@  discard block
 block discarded – undo
4469 4469
                 );
4470 4470
             }
4471 4471
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4472
-            return $operator . SP . $cleaned_value;
4472
+            return $operator.SP.$cleaned_value;
4473 4473
         }
4474 4474
         if (in_array($operator, $this->valid_null_style_operators())) {
4475 4475
             if ($value !== null) {
@@ -4489,10 +4489,10 @@  discard block
 block discarded – undo
4489 4489
         if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4490 4490
             // if the operator is 'LIKE', we want to allow percent signs (%) and not
4491 4491
             // remove other junk. So just treat it as a string.
4492
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4492
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4493 4493
         }
4494
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4495
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4494
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4495
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4496 4496
         }
4497 4497
         if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4498 4498
             throw new EE_Error(
@@ -4506,7 +4506,7 @@  discard block
 block discarded – undo
4506 4506
                 )
4507 4507
             );
4508 4508
         }
4509
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4509
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4510 4510
             throw new EE_Error(
4511 4511
                 sprintf(
4512 4512
                     esc_html__(
@@ -4545,7 +4545,7 @@  discard block
 block discarded – undo
4545 4545
         foreach ($values as $value) {
4546 4546
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4547 4547
         }
4548
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4548
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4549 4549
     }
4550 4550
 
4551 4551
 
@@ -4585,7 +4585,7 @@  discard block
 block discarded – undo
4585 4585
                                 . $main_table->get_table_name()
4586 4586
                                 . " WHERE FALSE";
4587 4587
         }
4588
-        return "(" . implode(",", $cleaned_values) . ")";
4588
+        return "(".implode(",", $cleaned_values).")";
4589 4589
     }
4590 4590
 
4591 4591
 
@@ -4604,7 +4604,7 @@  discard block
 block discarded – undo
4604 4604
                 $this->_prepare_value_for_use_in_db($value, $field_obj)
4605 4605
             );
4606 4606
         } //$field_obj should really just be a data type
4607
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4607
+        if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4608 4608
             throw new EE_Error(
4609 4609
                 sprintf(
4610 4610
                     esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
@@ -4641,14 +4641,14 @@  discard block
 block discarded – undo
4641 4641
             );
4642 4642
         }
4643 4643
         $number_of_parts       = count($query_param_parts);
4644
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4644
+        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4645 4645
         if ($number_of_parts === 1) {
4646 4646
             $field_name = $last_query_param_part;
4647 4647
             $model_obj  = $this;
4648 4648
         } else {// $number_of_parts >= 2
4649 4649
             // the last part is the column name, and there are only 2parts. therefore...
4650 4650
             $field_name = $last_query_param_part;
4651
-            $model_obj  = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4651
+            $model_obj  = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4652 4652
         }
4653 4653
         try {
4654 4654
             return $model_obj->field_settings_for($field_name);
@@ -4669,7 +4669,7 @@  discard block
 block discarded – undo
4669 4669
     public function _get_qualified_column_for_field($field_name)
4670 4670
     {
4671 4671
         $all_fields = $this->field_settings();
4672
-        $field      = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4672
+        $field      = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4673 4673
         if ($field) {
4674 4674
             return $field->get_qualified_column();
4675 4675
         }
@@ -4739,10 +4739,10 @@  discard block
 block discarded – undo
4739 4739
      */
4740 4740
     public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4741 4741
     {
4742
-        $table_prefix      = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4742
+        $table_prefix      = str_replace('.', '__', $model_relation_chain).(empty($model_relation_chain) ? '' : '__');
4743 4743
         $qualified_columns = [];
4744 4744
         foreach ($this->field_settings() as $field_name => $field) {
4745
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4745
+            $qualified_columns[] = $table_prefix.$field->get_qualified_column();
4746 4746
         }
4747 4747
         return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4748 4748
     }
@@ -4766,11 +4766,11 @@  discard block
 block discarded – undo
4766 4766
             if ($table_obj instanceof EE_Primary_Table) {
4767 4767
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4768 4768
                     ? $table_obj->get_select_join_limit($limit)
4769
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4769
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4770 4770
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4771 4771
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4772 4772
                     ? $table_obj->get_select_join_limit_join($limit)
4773
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4773
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4774 4774
             }
4775 4775
         }
4776 4776
         return $SQL;
@@ -4840,7 +4840,7 @@  discard block
 block discarded – undo
4840 4840
         foreach ($this->field_settings() as $field_obj) {
4841 4841
             // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4842 4842
             /** @var $field_obj EE_Model_Field_Base */
4843
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4843
+            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4844 4844
         }
4845 4845
         return $data_types;
4846 4846
     }
@@ -4855,8 +4855,8 @@  discard block
 block discarded – undo
4855 4855
      */
4856 4856
     public function get_related_model_obj($model_name)
4857 4857
     {
4858
-        $model_classname = "EEM_" . $model_name;
4859
-        if (! class_exists($model_classname)) {
4858
+        $model_classname = "EEM_".$model_name;
4859
+        if ( ! class_exists($model_classname)) {
4860 4860
             throw new EE_Error(
4861 4861
                 sprintf(
4862 4862
                     esc_html__(
@@ -4868,7 +4868,7 @@  discard block
 block discarded – undo
4868 4868
                 )
4869 4869
             );
4870 4870
         }
4871
-        return call_user_func($model_classname . "::instance");
4871
+        return call_user_func($model_classname."::instance");
4872 4872
     }
4873 4873
 
4874 4874
 
@@ -4895,7 +4895,7 @@  discard block
 block discarded – undo
4895 4895
         $belongs_to_relations = [];
4896 4896
         foreach ($this->relation_settings() as $model_name => $relation_obj) {
4897 4897
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
4898
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4898
+                $belongs_to_relations[$model_name] = $relation_obj;
4899 4899
             }
4900 4900
         }
4901 4901
         return $belongs_to_relations;
@@ -4912,7 +4912,7 @@  discard block
 block discarded – undo
4912 4912
     public function related_settings_for($relation_name)
4913 4913
     {
4914 4914
         $relatedModels = $this->relation_settings();
4915
-        if (! array_key_exists($relation_name, $relatedModels)) {
4915
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
4916 4916
             throw new EE_Error(
4917 4917
                 sprintf(
4918 4918
                     esc_html__(
@@ -4925,7 +4925,7 @@  discard block
 block discarded – undo
4925 4925
                 )
4926 4926
             );
4927 4927
         }
4928
-        return $relatedModels[ $relation_name ];
4928
+        return $relatedModels[$relation_name];
4929 4929
     }
4930 4930
 
4931 4931
 
@@ -4941,7 +4941,7 @@  discard block
 block discarded – undo
4941 4941
     public function field_settings_for($fieldName, $include_db_only_fields = true)
4942 4942
     {
4943 4943
         $fieldSettings = $this->field_settings($include_db_only_fields);
4944
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4944
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4945 4945
             throw new EE_Error(
4946 4946
                 sprintf(
4947 4947
                     esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
@@ -4950,7 +4950,7 @@  discard block
 block discarded – undo
4950 4950
                 )
4951 4951
             );
4952 4952
         }
4953
-        return $fieldSettings[ $fieldName ];
4953
+        return $fieldSettings[$fieldName];
4954 4954
     }
4955 4955
 
4956 4956
 
@@ -4963,7 +4963,7 @@  discard block
 block discarded – undo
4963 4963
     public function has_field($fieldName)
4964 4964
     {
4965 4965
         $fieldSettings = $this->field_settings(true);
4966
-        if (isset($fieldSettings[ $fieldName ])) {
4966
+        if (isset($fieldSettings[$fieldName])) {
4967 4967
             return true;
4968 4968
         }
4969 4969
         return false;
@@ -4979,7 +4979,7 @@  discard block
 block discarded – undo
4979 4979
     public function has_relation($relation_name)
4980 4980
     {
4981 4981
         $relations = $this->relation_settings();
4982
-        if (isset($relations[ $relation_name ])) {
4982
+        if (isset($relations[$relation_name])) {
4983 4983
             return true;
4984 4984
         }
4985 4985
         return false;
@@ -5015,7 +5015,7 @@  discard block
 block discarded – undo
5015 5015
                     break;
5016 5016
                 }
5017 5017
             }
5018
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5018
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5019 5019
                 throw new EE_Error(
5020 5020
                     sprintf(
5021 5021
                         esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
@@ -5075,17 +5075,17 @@  discard block
 block discarded – undo
5075 5075
      */
5076 5076
     public function get_foreign_key_to($model_name)
5077 5077
     {
5078
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5078
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5079 5079
             foreach ($this->field_settings() as $field) {
5080 5080
                 if (
5081 5081
                     $field instanceof EE_Foreign_Key_Field_Base
5082 5082
                     && in_array($model_name, $field->get_model_names_pointed_to())
5083 5083
                 ) {
5084
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5084
+                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
5085 5085
                     break;
5086 5086
                 }
5087 5087
             }
5088
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5088
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5089 5089
                 throw new EE_Error(
5090 5090
                     sprintf(
5091 5091
                         esc_html__(
@@ -5098,7 +5098,7 @@  discard block
 block discarded – undo
5098 5098
                 );
5099 5099
             }
5100 5100
         }
5101
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5101
+        return $this->_cache_foreign_key_to_fields[$model_name];
5102 5102
     }
5103 5103
 
5104 5104
 
@@ -5114,7 +5114,7 @@  discard block
 block discarded – undo
5114 5114
     {
5115 5115
         $table_alias_sans_model_relation_chain_prefix =
5116 5116
             EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5117
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5117
+        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
5118 5118
     }
5119 5119
 
5120 5120
 
@@ -5132,7 +5132,7 @@  discard block
 block discarded – undo
5132 5132
                 $this->_cached_fields = [];
5133 5133
                 foreach ($this->_fields as $fields_corresponding_to_table) {
5134 5134
                     foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5135
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5135
+                        $this->_cached_fields[$field_name] = $field_obj;
5136 5136
                     }
5137 5137
                 }
5138 5138
             }
@@ -5143,8 +5143,8 @@  discard block
 block discarded – undo
5143 5143
             foreach ($this->_fields as $fields_corresponding_to_table) {
5144 5144
                 foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5145 5145
                     /** @var $field_obj EE_Model_Field_Base */
5146
-                    if (! $field_obj->is_db_only_field()) {
5147
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5146
+                    if ( ! $field_obj->is_db_only_field()) {
5147
+                        $this->_cached_fields_non_db_only[$field_name] = $field_obj;
5148 5148
                     }
5149 5149
                 }
5150 5150
             }
@@ -5172,7 +5172,7 @@  discard block
 block discarded – undo
5172 5172
         $count_if_model_has_no_primary_key = 0;
5173 5173
         $has_primary_key                   = $this->has_primary_key_field();
5174 5174
         $primary_key_field                 = $has_primary_key ? $this->get_primary_key_field() : null;
5175
-        foreach ((array)$rows as $row) {
5175
+        foreach ((array) $rows as $row) {
5176 5176
             if (empty($row)) {
5177 5177
                 // wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5178 5178
                 return [];
@@ -5185,12 +5185,12 @@  discard block
 block discarded – undo
5185 5185
                     $primary_key_field->get_qualified_column(),
5186 5186
                     $primary_key_field->get_table_column()
5187 5187
                 );
5188
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5188
+                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
5189 5189
                     continue;
5190 5190
                 }
5191 5191
             }
5192 5192
             $classInstance = $this->instantiate_class_from_array_or_object($row);
5193
-            if (! $classInstance) {
5193
+            if ( ! $classInstance) {
5194 5194
                 throw new EE_Error(
5195 5195
                     sprintf(
5196 5196
                         esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -5203,7 +5203,7 @@  discard block
 block discarded – undo
5203 5203
             $classInstance->set_timezone($this->get_timezone(), true);
5204 5204
             // make sure if there is any timezone setting present that we set the timezone for the object
5205 5205
             $key                      = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5206
-            $array_of_objects[ $key ] = $classInstance;
5206
+            $array_of_objects[$key] = $classInstance;
5207 5207
             // also, for all the relations of type BelongsTo, see if we can cache
5208 5208
             // those related models
5209 5209
             // (we could do this for other relations too, but if there are conditions
@@ -5247,9 +5247,9 @@  discard block
 block discarded – undo
5247 5247
         $results = [];
5248 5248
         if ($this->_custom_selections instanceof CustomSelects) {
5249 5249
             foreach ($this->_custom_selections->columnAliases() as $alias) {
5250
-                if (isset($db_results_row[ $alias ])) {
5251
-                    $results[ $alias ] = $this->convertValueToDataType(
5252
-                        $db_results_row[ $alias ],
5250
+                if (isset($db_results_row[$alias])) {
5251
+                    $results[$alias] = $this->convertValueToDataType(
5252
+                        $db_results_row[$alias],
5253 5253
                         $this->_custom_selections->getDataTypeForAlias($alias)
5254 5254
                     );
5255 5255
                 }
@@ -5270,11 +5270,11 @@  discard block
 block discarded – undo
5270 5270
     {
5271 5271
         switch ($datatype) {
5272 5272
             case '%f':
5273
-                return (float)$value;
5273
+                return (float) $value;
5274 5274
             case '%d':
5275
-                return (int)$value;
5275
+                return (int) $value;
5276 5276
             default:
5277
-                return (string)$value;
5277
+                return (string) $value;
5278 5278
         }
5279 5279
     }
5280 5280
 
@@ -5294,7 +5294,7 @@  discard block
 block discarded – undo
5294 5294
         $this_model_fields_and_values = [];
5295 5295
         // setup the row using default values;
5296 5296
         foreach ($this->field_settings() as $field_name => $field_obj) {
5297
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5297
+            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
5298 5298
         }
5299 5299
         $className = $this->_get_class_name();
5300 5300
         return EE_Registry::instance()->load_class(
@@ -5315,20 +5315,20 @@  discard block
 block discarded – undo
5315 5315
      */
5316 5316
     public function instantiate_class_from_array_or_object($cols_n_values)
5317 5317
     {
5318
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5318
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
5319 5319
             $cols_n_values = get_object_vars($cols_n_values);
5320 5320
         }
5321 5321
         $primary_key = null;
5322 5322
         // make sure the array only has keys that are fields/columns on this model
5323 5323
         $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5324
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5325
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5324
+        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5325
+            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5326 5326
         }
5327 5327
         $className = $this->_get_class_name();
5328 5328
         // check we actually found results that we can use to build our model object
5329 5329
         // if not, return null
5330 5330
         if ($this->has_primary_key_field()) {
5331
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5331
+            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5332 5332
                 return null;
5333 5333
             }
5334 5334
         } elseif ($this->unique_indexes()) {
@@ -5340,7 +5340,7 @@  discard block
 block discarded – undo
5340 5340
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5341 5341
         if ($primary_key) {
5342 5342
             $classInstance = $this->get_from_entity_map($primary_key);
5343
-            if (! $classInstance) {
5343
+            if ( ! $classInstance) {
5344 5344
                 $classInstance = EE_Registry::instance()->load_class(
5345 5345
                     $className,
5346 5346
                     [$this_model_fields_n_values, $this->get_timezone()],
@@ -5370,8 +5370,8 @@  discard block
 block discarded – undo
5370 5370
      */
5371 5371
     public function get_from_entity_map($id)
5372 5372
     {
5373
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5374
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]
5373
+        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
5374
+            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id]
5375 5375
             : null;
5376 5376
     }
5377 5377
 
@@ -5394,7 +5394,7 @@  discard block
 block discarded – undo
5394 5394
     public function add_to_entity_map(EE_Base_Class $object)
5395 5395
     {
5396 5396
         $className = $this->_get_class_name();
5397
-        if (! $object instanceof $className) {
5397
+        if ( ! $object instanceof $className) {
5398 5398
             throw new EE_Error(
5399 5399
                 sprintf(
5400 5400
                     esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
@@ -5403,7 +5403,7 @@  discard block
 block discarded – undo
5403 5403
                 )
5404 5404
             );
5405 5405
         }
5406
-        if (! $object->ID()) {
5406
+        if ( ! $object->ID()) {
5407 5407
             throw new EE_Error(
5408 5408
                 sprintf(
5409 5409
                     esc_html__(
@@ -5419,7 +5419,7 @@  discard block
 block discarded – undo
5419 5419
         if ($classInstance) {
5420 5420
             return $classInstance;
5421 5421
         }
5422
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5422
+        $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5423 5423
         return $object;
5424 5424
     }
5425 5425
 
@@ -5434,11 +5434,11 @@  discard block
 block discarded – undo
5434 5434
     public function clear_entity_map($id = null)
5435 5435
     {
5436 5436
         if (empty($id)) {
5437
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = [];
5437
+            $this->_entity_map[EEM_Base::$_model_query_blog_id] = [];
5438 5438
             return true;
5439 5439
         }
5440
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5441
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5440
+        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5441
+            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5442 5442
             return true;
5443 5443
         }
5444 5444
         return false;
@@ -5479,18 +5479,18 @@  discard block
 block discarded – undo
5479 5479
             // there is a primary key on this table and its not set. Use defaults for all its columns
5480 5480
             if ($table_pk_value === null && $table_obj->get_pk_column()) {
5481 5481
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5482
-                    if (! $field_obj->is_db_only_field()) {
5482
+                    if ( ! $field_obj->is_db_only_field()) {
5483 5483
                         // prepare field as if its coming from db
5484 5484
                         $prepared_value                            =
5485 5485
                             $field_obj->prepare_for_set($field_obj->get_default_value());
5486
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5486
+                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5487 5487
                     }
5488 5488
                 }
5489 5489
             } else {
5490 5490
                 // the table's rows existed. Use their values
5491 5491
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5492
-                    if (! $field_obj->is_db_only_field()) {
5493
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5492
+                    if ( ! $field_obj->is_db_only_field()) {
5493
+                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5494 5494
                             $cols_n_values,
5495 5495
                             $field_obj->get_qualified_column(),
5496 5496
                             $field_obj->get_table_column()
@@ -5515,17 +5515,17 @@  discard block
 block discarded – undo
5515 5515
         // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5516 5516
         // does the field on the model relate to this column retrieved from the db?
5517 5517
         // or is it a db-only field? (not relating to the model)
5518
-        if (isset($cols_n_values[ $qualified_column ])) {
5519
-            $value = $cols_n_values[ $qualified_column ];
5520
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5521
-            $value = $cols_n_values[ $regular_column ];
5522
-        } elseif (! empty($this->foreign_key_aliases)) {
5518
+        if (isset($cols_n_values[$qualified_column])) {
5519
+            $value = $cols_n_values[$qualified_column];
5520
+        } elseif (isset($cols_n_values[$regular_column])) {
5521
+            $value = $cols_n_values[$regular_column];
5522
+        } elseif ( ! empty($this->foreign_key_aliases)) {
5523 5523
             // no PK?  ok check if there is a foreign key alias set for this table
5524 5524
             // then check if that alias exists in the incoming data
5525 5525
             // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5526 5526
             foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5527
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5528
-                    $value = $cols_n_values[ $FK_alias ];
5527
+                if ($PK_column === $qualified_column && isset($cols_n_values[$FK_alias])) {
5528
+                    $value = $cols_n_values[$FK_alias];
5529 5529
                     break;
5530 5530
                 }
5531 5531
             }
@@ -5561,7 +5561,7 @@  discard block
 block discarded – undo
5561 5561
                     $obj_in_map->clear_cache($relation_name, null, true);
5562 5562
                 }
5563 5563
             }
5564
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5564
+            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5565 5565
             return $obj_in_map;
5566 5566
         }
5567 5567
         return $this->get_one_by_ID($id);
@@ -5613,7 +5613,7 @@  discard block
 block discarded – undo
5613 5613
      */
5614 5614
     private function _get_class_name()
5615 5615
     {
5616
-        return "EE_" . $this->get_this_model_name();
5616
+        return "EE_".$this->get_this_model_name();
5617 5617
     }
5618 5618
 
5619 5619
 
@@ -5627,7 +5627,7 @@  discard block
 block discarded – undo
5627 5627
      */
5628 5628
     public function item_name($quantity = 1)
5629 5629
     {
5630
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5630
+        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5631 5631
     }
5632 5632
 
5633 5633
 
@@ -5659,7 +5659,7 @@  discard block
 block discarded – undo
5659 5659
     {
5660 5660
         $className = get_class($this);
5661 5661
         $tagName   = "FHEE__{$className}__{$methodName}";
5662
-        if (! has_filter($tagName)) {
5662
+        if ( ! has_filter($tagName)) {
5663 5663
             throw new EE_Error(
5664 5664
                 sprintf(
5665 5665
                     esc_html__(
@@ -5828,7 +5828,7 @@  discard block
 block discarded – undo
5828 5828
         $unique_indexes = [];
5829 5829
         foreach ($this->_indexes as $name => $index) {
5830 5830
             if ($index instanceof EE_Unique_Index) {
5831
-                $unique_indexes [ $name ] = $index;
5831
+                $unique_indexes [$name] = $index;
5832 5832
             }
5833 5833
         }
5834 5834
         return $unique_indexes;
@@ -5892,7 +5892,7 @@  discard block
 block discarded – undo
5892 5892
         $key_values_in_combined_pk = [];
5893 5893
         parse_str($index_primary_key_string, $key_values_in_combined_pk);
5894 5894
         foreach ($key_fields as $key_field_name => $field_obj) {
5895
-            if (! isset($key_values_in_combined_pk[ $key_field_name ])) {
5895
+            if ( ! isset($key_values_in_combined_pk[$key_field_name])) {
5896 5896
                 return null;
5897 5897
             }
5898 5898
         }
@@ -5912,7 +5912,7 @@  discard block
 block discarded – undo
5912 5912
     {
5913 5913
         $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5914 5914
         foreach ($keys_it_should_have as $key) {
5915
-            if (! isset($key_values[ $key ])) {
5915
+            if ( ! isset($key_values[$key])) {
5916 5916
                 return false;
5917 5917
             }
5918 5918
         }
@@ -5951,8 +5951,8 @@  discard block
 block discarded – undo
5951 5951
         }
5952 5952
         // even copies obviously won't have the same ID, so remove the primary key
5953 5953
         // from the WHERE conditions for finding copies (if there is a primary key, of course)
5954
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5955
-            unset($attributes_array[ $this->primary_key_name() ]);
5954
+        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5955
+            unset($attributes_array[$this->primary_key_name()]);
5956 5956
         }
5957 5957
         if (isset($query_params[0])) {
5958 5958
             $query_params[0] = array_merge($attributes_array, $query_params);
@@ -5974,7 +5974,7 @@  discard block
 block discarded – undo
5974 5974
      */
5975 5975
     public function get_one_copy($model_object_or_attributes_array, $query_params = [])
5976 5976
     {
5977
-        if (! is_array($query_params)) {
5977
+        if ( ! is_array($query_params)) {
5978 5978
             EE_Error::doing_it_wrong(
5979 5979
                 'EEM_Base::get_one_copy',
5980 5980
                 sprintf(
@@ -6024,7 +6024,7 @@  discard block
 block discarded – undo
6024 6024
     private function _prepare_operator_for_sql($operator_supplied)
6025 6025
     {
6026 6026
         $sql_operator =
6027
-            isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
6027
+            isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
6028 6028
                 : null;
6029 6029
         if ($sql_operator) {
6030 6030
             return $sql_operator;
@@ -6123,7 +6123,7 @@  discard block
 block discarded – undo
6123 6123
         $objs  = $this->get_all($query_params);
6124 6124
         $names = [];
6125 6125
         foreach ($objs as $obj) {
6126
-            $names[ $obj->ID() ] = $obj->name();
6126
+            $names[$obj->ID()] = $obj->name();
6127 6127
         }
6128 6128
         return $names;
6129 6129
     }
@@ -6143,7 +6143,7 @@  discard block
 block discarded – undo
6143 6143
      */
6144 6144
     public function get_IDs($model_objects, $filter_out_empty_ids = false)
6145 6145
     {
6146
-        if (! $this->has_primary_key_field()) {
6146
+        if ( ! $this->has_primary_key_field()) {
6147 6147
             if (WP_DEBUG) {
6148 6148
                 EE_Error::add_error(
6149 6149
                     esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
@@ -6156,7 +6156,7 @@  discard block
 block discarded – undo
6156 6156
         $IDs = [];
6157 6157
         foreach ($model_objects as $model_object) {
6158 6158
             $id = $model_object->ID();
6159
-            if (! $id) {
6159
+            if ( ! $id) {
6160 6160
                 if ($filter_out_empty_ids) {
6161 6161
                     continue;
6162 6162
                 }
@@ -6206,22 +6206,22 @@  discard block
 block discarded – undo
6206 6206
         EEM_Base::verify_is_valid_cap_context($context);
6207 6207
         // check if we ought to run the restriction generator first
6208 6208
         if (
6209
-            isset($this->_cap_restriction_generators[ $context ])
6210
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6211
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6209
+            isset($this->_cap_restriction_generators[$context])
6210
+            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
6211
+            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
6212 6212
         ) {
6213
-            $this->_cap_restrictions[ $context ] = array_merge(
6214
-                $this->_cap_restrictions[ $context ],
6215
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6213
+            $this->_cap_restrictions[$context] = array_merge(
6214
+                $this->_cap_restrictions[$context],
6215
+                $this->_cap_restriction_generators[$context]->generate_restrictions()
6216 6216
             );
6217 6217
         }
6218 6218
         // and make sure we've finalized the construction of each restriction
6219
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6219
+        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
6220 6220
             if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6221 6221
                 $where_conditions_obj->_finalize_construct($this);
6222 6222
             }
6223 6223
         }
6224
-        return $this->_cap_restrictions[ $context ];
6224
+        return $this->_cap_restrictions[$context];
6225 6225
     }
6226 6226
 
6227 6227
 
@@ -6251,9 +6251,9 @@  discard block
 block discarded – undo
6251 6251
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6252 6252
             if (
6253 6253
             ! EE_Capabilities::instance()
6254
-                             ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6254
+                             ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
6255 6255
             ) {
6256
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6256
+                $missing_caps[$cap] = $restriction_if_no_cap;
6257 6257
             }
6258 6258
         }
6259 6259
         return $missing_caps;
@@ -6286,8 +6286,8 @@  discard block
 block discarded – undo
6286 6286
     public function cap_action_for_context($context)
6287 6287
     {
6288 6288
         $mapping = $this->cap_contexts_to_cap_action_map();
6289
-        if (isset($mapping[ $context ])) {
6290
-            return $mapping[ $context ];
6289
+        if (isset($mapping[$context])) {
6290
+            return $mapping[$context];
6291 6291
         }
6292 6292
         if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6293 6293
             return $action;
@@ -6405,7 +6405,7 @@  discard block
 block discarded – undo
6405 6405
         foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6406 6406
             if (
6407 6407
                 $query_param_key === $logic_query_param_key
6408
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6408
+                || strpos($query_param_key, $logic_query_param_key.'*') === 0
6409 6409
             ) {
6410 6410
                 return true;
6411 6411
             }
@@ -6463,7 +6463,7 @@  discard block
 block discarded – undo
6463 6463
         if ($password_field instanceof EE_Password_Field) {
6464 6464
             $field_names = $password_field->protectedFields();
6465 6465
             foreach ($field_names as $field_name) {
6466
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6466
+                $fields[$field_name] = $this->field_settings_for($field_name);
6467 6467
             }
6468 6468
         }
6469 6469
         return $fields;
@@ -6489,7 +6489,7 @@  discard block
 block discarded – undo
6489 6489
         if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6490 6490
             $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6491 6491
         }
6492
-        if (! is_array($model_obj_or_fields_n_values)) {
6492
+        if ( ! is_array($model_obj_or_fields_n_values)) {
6493 6493
             throw new UnexpectedEntityException(
6494 6494
                 $model_obj_or_fields_n_values,
6495 6495
                 'EE_Base_Class',
@@ -6569,7 +6569,7 @@  discard block
 block discarded – undo
6569 6569
                 )
6570 6570
             );
6571 6571
         }
6572
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6572
+        return ($this->model_chain_to_password ? $this->model_chain_to_password.'.' : '').$password_field_name;
6573 6573
     }
6574 6574
 
6575 6575
 
Please login to merge, or discard this patch.
core/db_models/EEM_Change_Log.model.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -51,7 +51,7 @@
 block discarded – undo
51 51
      * constructor
52 52
      *
53 53
      * @access protected
54
-     * @param null $timezone
54
+     * @param string|null $timezone
55 55
      * @throws EE_Error
56 56
      */
57 57
     protected function __construct($timezone = '')
Please login to merge, or discard this patch.
Indentation   +227 added lines, -227 removed lines patch added patch discarded remove patch
@@ -11,93 +11,93 @@  discard block
 block discarded – undo
11 11
 class EEM_Change_Log extends EEM_Base
12 12
 {
13 13
 
14
-    /**
15
-     * the related object was created log type
16
-     */
17
-    const type_create = 'create';
18
-    /**
19
-     * the related object was updated (changed, or soft-deleted)
20
-     */
21
-    const type_update = 'update';
22
-    /**
23
-     * the related object was deleted permanently
24
-     */
25
-    const type_delete = 'delete';
26
-    /**
27
-     * the related item had something worth noting happen on it, but
28
-     * only for the purposes of debugging problems
29
-     */
30
-    const type_debug = 'debug';
31
-    /**
32
-     * the related item had an error occur on it
33
-     */
34
-    const type_error = 'error';
35
-    /**
36
-     * the related item is regarding some gateway interaction, like an IPN
37
-     * or request to process a payment
38
-     */
39
-    const type_gateway = 'gateway';
14
+	/**
15
+	 * the related object was created log type
16
+	 */
17
+	const type_create = 'create';
18
+	/**
19
+	 * the related object was updated (changed, or soft-deleted)
20
+	 */
21
+	const type_update = 'update';
22
+	/**
23
+	 * the related object was deleted permanently
24
+	 */
25
+	const type_delete = 'delete';
26
+	/**
27
+	 * the related item had something worth noting happen on it, but
28
+	 * only for the purposes of debugging problems
29
+	 */
30
+	const type_debug = 'debug';
31
+	/**
32
+	 * the related item had an error occur on it
33
+	 */
34
+	const type_error = 'error';
35
+	/**
36
+	 * the related item is regarding some gateway interaction, like an IPN
37
+	 * or request to process a payment
38
+	 */
39
+	const type_gateway = 'gateway';
40 40
 
41
-    /**
42
-     * private instance of the EEM_Change_Log object
43
-     *
44
-     * @access private
45
-     * @var EEM_Change_Log $_instance
46
-     */
47
-    protected static $_instance = null;
41
+	/**
42
+	 * private instance of the EEM_Change_Log object
43
+	 *
44
+	 * @access private
45
+	 * @var EEM_Change_Log $_instance
46
+	 */
47
+	protected static $_instance = null;
48 48
 
49 49
 
50
-    /**
51
-     * constructor
52
-     *
53
-     * @access protected
54
-     * @param null $timezone
55
-     * @throws EE_Error
56
-     */
57
-    protected function __construct($timezone = '')
58
-    {
59
-        global $current_user;
60
-        $this->singular_item       = esc_html__('Log', 'event_espresso');
61
-        $this->plural_item         = esc_html__('Logs', 'event_espresso');
62
-        $this->_tables             = array(
63
-            'Log' => new EE_Primary_Table('esp_log', 'LOG_ID'),
64
-        );
65
-        $models_this_can_attach_to = array_keys(EE_Registry::instance()->non_abstract_db_models);
66
-        $this->_fields             = array(
67
-            'Log' => array(
68
-                'LOG_ID'      => new EE_Primary_Key_Int_Field('LOG_ID', esc_html__('Log ID', 'event_espresso')),
69
-                'LOG_time'    => new EE_Datetime_Field(
70
-                    'LOG_time',
71
-                    esc_html__("Log Time", 'event_espresso'),
72
-                    false,
73
-                    EE_Datetime_Field::now
74
-                ),
75
-                'OBJ_ID'      => new EE_Foreign_Key_String_Field(
76
-                    'OBJ_ID',
77
-                    esc_html__("Object ID (int or string)", 'event_espresso'),
78
-                    true,
79
-                    null,
80
-                    $models_this_can_attach_to
81
-                ),
82
-                'OBJ_type'    => new EE_Any_Foreign_Model_Name_Field(
83
-                    'OBJ_type',
84
-                    esc_html__("Object Type", 'event_espresso'),
85
-                    true,
86
-                    null,
87
-                    $models_this_can_attach_to
88
-                ),
89
-                'LOG_type'    => new EE_Plain_Text_Field(
90
-                    'LOG_type',
91
-                    esc_html__("Type of log entry", "event_espresso"),
92
-                    false,
93
-                    self::type_debug
94
-                ),
95
-                'LOG_message' => new EE_Maybe_Serialized_Text_Field(
96
-                    'LOG_message',
97
-                    esc_html__("Log Message (body)", 'event_espresso'),
98
-                    true
99
-                ),
100
-                /*
50
+	/**
51
+	 * constructor
52
+	 *
53
+	 * @access protected
54
+	 * @param null $timezone
55
+	 * @throws EE_Error
56
+	 */
57
+	protected function __construct($timezone = '')
58
+	{
59
+		global $current_user;
60
+		$this->singular_item       = esc_html__('Log', 'event_espresso');
61
+		$this->plural_item         = esc_html__('Logs', 'event_espresso');
62
+		$this->_tables             = array(
63
+			'Log' => new EE_Primary_Table('esp_log', 'LOG_ID'),
64
+		);
65
+		$models_this_can_attach_to = array_keys(EE_Registry::instance()->non_abstract_db_models);
66
+		$this->_fields             = array(
67
+			'Log' => array(
68
+				'LOG_ID'      => new EE_Primary_Key_Int_Field('LOG_ID', esc_html__('Log ID', 'event_espresso')),
69
+				'LOG_time'    => new EE_Datetime_Field(
70
+					'LOG_time',
71
+					esc_html__("Log Time", 'event_espresso'),
72
+					false,
73
+					EE_Datetime_Field::now
74
+				),
75
+				'OBJ_ID'      => new EE_Foreign_Key_String_Field(
76
+					'OBJ_ID',
77
+					esc_html__("Object ID (int or string)", 'event_espresso'),
78
+					true,
79
+					null,
80
+					$models_this_can_attach_to
81
+				),
82
+				'OBJ_type'    => new EE_Any_Foreign_Model_Name_Field(
83
+					'OBJ_type',
84
+					esc_html__("Object Type", 'event_espresso'),
85
+					true,
86
+					null,
87
+					$models_this_can_attach_to
88
+				),
89
+				'LOG_type'    => new EE_Plain_Text_Field(
90
+					'LOG_type',
91
+					esc_html__("Type of log entry", "event_espresso"),
92
+					false,
93
+					self::type_debug
94
+				),
95
+				'LOG_message' => new EE_Maybe_Serialized_Text_Field(
96
+					'LOG_message',
97
+					esc_html__("Log Message (body)", 'event_espresso'),
98
+					true
99
+				),
100
+				/*
101 101
                  * Note: when querying for a change log's user, the OBJ_ID and OBJ_type fields are used,
102 102
                  * not the LOG_wp_user field. E.g.,
103 103
                  * `EEM_Change_Log::instance()->get_all(array(array('WP_User.ID'=>1)))` will actually return
@@ -106,158 +106,158 @@  discard block
 block discarded – undo
106 106
                  *  If you want the latter, you can't use the model's magic joining. E.g, you would need to do
107 107
                  * `EEM_Change_Log::instance()->get_all(array(array('LOG_wp_user' => 1)))`.
108 108
                  */
109
-                'LOG_wp_user' => new EE_WP_User_Field(
110
-                    'LOG_wp_user',
111
-                    esc_html__("User who was logged in while this occurred", 'event_espresso'),
112
-                    true
113
-                ),
114
-            ),
115
-        );
116
-        $this->_model_relations    = array();
117
-        foreach ($models_this_can_attach_to as $model) {
118
-            if ($model != 'Change_Log') {
119
-                $this->_model_relations[ $model ] = new EE_Belongs_To_Any_Relation();
120
-            }
121
-        }
122
-        // use completely custom caps for this
123
-        $this->_cap_restriction_generators = false;
124
-        // caps-wise this is all-or-nothing: if you have the default role you can access anything, otherwise nothing
125
-        foreach ($this->_cap_contexts_to_cap_action_map as $cap_context => $action) {
126
-            $this->_cap_restrictions[ $cap_context ][ EE_Restriction_Generator_Base::get_default_restrictions_cap() ]
127
-                = new EE_Return_None_Where_Conditions();
128
-        }
129
-        parent::__construct($timezone);
130
-    }
109
+				'LOG_wp_user' => new EE_WP_User_Field(
110
+					'LOG_wp_user',
111
+					esc_html__("User who was logged in while this occurred", 'event_espresso'),
112
+					true
113
+				),
114
+			),
115
+		);
116
+		$this->_model_relations    = array();
117
+		foreach ($models_this_can_attach_to as $model) {
118
+			if ($model != 'Change_Log') {
119
+				$this->_model_relations[ $model ] = new EE_Belongs_To_Any_Relation();
120
+			}
121
+		}
122
+		// use completely custom caps for this
123
+		$this->_cap_restriction_generators = false;
124
+		// caps-wise this is all-or-nothing: if you have the default role you can access anything, otherwise nothing
125
+		foreach ($this->_cap_contexts_to_cap_action_map as $cap_context => $action) {
126
+			$this->_cap_restrictions[ $cap_context ][ EE_Restriction_Generator_Base::get_default_restrictions_cap() ]
127
+				= new EE_Return_None_Where_Conditions();
128
+		}
129
+		parent::__construct($timezone);
130
+	}
131 131
 
132
-    /**
133
-     * @param string        $log_type !see the acceptable values of LOG_type in EEM__Change_Log::__construct
134
-     * @param mixed         $message  array|string of the message you want to record
135
-     * @param EE_Base_Class $related_model_obj
136
-     * @return EE_Change_Log
137
-     * @throws EE_Error
138
-     */
139
-    public function log($log_type, $message, $related_model_obj)
140
-    {
141
-        if ($related_model_obj instanceof EE_Base_Class) {
142
-            $obj_id   = $related_model_obj->ID();
143
-            $obj_type = $related_model_obj->get_model()->get_this_model_name();
144
-        } else {
145
-            $obj_id   = null;
146
-            $obj_type = null;
147
-        }
148
-        /** @var EE_Change_Log $log */
149
-        $log = EE_Change_Log::new_instance(array(
150
-            'LOG_type'    => $log_type,
151
-            'LOG_message' => $message,
152
-            'OBJ_ID'      => $obj_id,
153
-            'OBJ_type'    => $obj_type,
154
-        ));
155
-        $log->save();
156
-        return $log;
157
-    }
132
+	/**
133
+	 * @param string        $log_type !see the acceptable values of LOG_type in EEM__Change_Log::__construct
134
+	 * @param mixed         $message  array|string of the message you want to record
135
+	 * @param EE_Base_Class $related_model_obj
136
+	 * @return EE_Change_Log
137
+	 * @throws EE_Error
138
+	 */
139
+	public function log($log_type, $message, $related_model_obj)
140
+	{
141
+		if ($related_model_obj instanceof EE_Base_Class) {
142
+			$obj_id   = $related_model_obj->ID();
143
+			$obj_type = $related_model_obj->get_model()->get_this_model_name();
144
+		} else {
145
+			$obj_id   = null;
146
+			$obj_type = null;
147
+		}
148
+		/** @var EE_Change_Log $log */
149
+		$log = EE_Change_Log::new_instance(array(
150
+			'LOG_type'    => $log_type,
151
+			'LOG_message' => $message,
152
+			'OBJ_ID'      => $obj_id,
153
+			'OBJ_type'    => $obj_type,
154
+		));
155
+		$log->save();
156
+		return $log;
157
+	}
158 158
 
159 159
 
160
-    /**
161
-     * Adds a gateway log for the specified object, given its ID and type
162
-     *
163
-     * @param string $message
164
-     * @param mixed  $related_obj_id
165
-     * @param string $related_obj_type
166
-     * @throws EE_Error
167
-     * @return EE_Change_Log
168
-     */
169
-    public function gateway_log($message, $related_obj_id, $related_obj_type)
170
-    {
171
-        if (! EE_Registry::instance()->is_model_name($related_obj_type)) {
172
-            throw new EE_Error(
173
-                sprintf(
174
-                    esc_html__(
175
-                        "'%s' is not a model name. A model name must be provided when making a gateway log. Eg, 'Payment', 'Payment_Method', etc",
176
-                        "event_espresso"
177
-                    ),
178
-                    $related_obj_type
179
-                )
180
-            );
181
-        }
182
-        /** @var EE_Change_Log $log */
183
-        $log = EE_Change_Log::new_instance(array(
184
-            'LOG_type'    => EEM_Change_Log::type_gateway,
185
-            'LOG_message' => $message,
186
-            'OBJ_ID'      => $related_obj_id,
187
-            'OBJ_type'    => $related_obj_type,
188
-        ));
189
-        $log->save();
190
-        return $log;
191
-    }
160
+	/**
161
+	 * Adds a gateway log for the specified object, given its ID and type
162
+	 *
163
+	 * @param string $message
164
+	 * @param mixed  $related_obj_id
165
+	 * @param string $related_obj_type
166
+	 * @throws EE_Error
167
+	 * @return EE_Change_Log
168
+	 */
169
+	public function gateway_log($message, $related_obj_id, $related_obj_type)
170
+	{
171
+		if (! EE_Registry::instance()->is_model_name($related_obj_type)) {
172
+			throw new EE_Error(
173
+				sprintf(
174
+					esc_html__(
175
+						"'%s' is not a model name. A model name must be provided when making a gateway log. Eg, 'Payment', 'Payment_Method', etc",
176
+						"event_espresso"
177
+					),
178
+					$related_obj_type
179
+				)
180
+			);
181
+		}
182
+		/** @var EE_Change_Log $log */
183
+		$log = EE_Change_Log::new_instance(array(
184
+			'LOG_type'    => EEM_Change_Log::type_gateway,
185
+			'LOG_message' => $message,
186
+			'OBJ_ID'      => $related_obj_id,
187
+			'OBJ_type'    => $related_obj_type,
188
+		));
189
+		$log->save();
190
+		return $log;
191
+	}
192 192
 
193 193
 
194
-    /**
195
-     * Just gets the bare-bones wpdb results as an array in cases where efficiency is essential
196
-     *
197
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
198
-     * @return array of arrays
199
-     * @throws EE_Error
200
-     */
201
-    public function get_all_efficiently($query_params)
202
-    {
203
-        return $this->_get_all_wpdb_results($query_params);
204
-    }
194
+	/**
195
+	 * Just gets the bare-bones wpdb results as an array in cases where efficiency is essential
196
+	 *
197
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
198
+	 * @return array of arrays
199
+	 * @throws EE_Error
200
+	 */
201
+	public function get_all_efficiently($query_params)
202
+	{
203
+		return $this->_get_all_wpdb_results($query_params);
204
+	}
205 205
 
206 206
 
207
-    /**
208
-     * Executes a database query to delete gateway logs. Does not affect model objects, so if you attempt to use
209
-     * models after this, they may be out-of-sync with the database
210
-     *
211
-     * @param DateTime $datetime
212
-     * @return false|int
213
-     * @throws EE_Error
214
-     */
215
-    public function delete_gateway_logs_older_than(DateTime $datetime)
216
-    {
217
-        global $wpdb;
218
-        return $wpdb->query(
219
-            $wpdb->prepare(
220
-                'DELETE FROM ' . $this->table() . ' WHERE LOG_type = %s AND LOG_time < %s',
221
-                EEM_Change_Log::type_gateway,
222
-                $datetime->format(EE_Datetime_Field::mysql_timestamp_format)
223
-            )
224
-        );
225
-    }
207
+	/**
208
+	 * Executes a database query to delete gateway logs. Does not affect model objects, so if you attempt to use
209
+	 * models after this, they may be out-of-sync with the database
210
+	 *
211
+	 * @param DateTime $datetime
212
+	 * @return false|int
213
+	 * @throws EE_Error
214
+	 */
215
+	public function delete_gateway_logs_older_than(DateTime $datetime)
216
+	{
217
+		global $wpdb;
218
+		return $wpdb->query(
219
+			$wpdb->prepare(
220
+				'DELETE FROM ' . $this->table() . ' WHERE LOG_type = %s AND LOG_time < %s',
221
+				EEM_Change_Log::type_gateway,
222
+				$datetime->format(EE_Datetime_Field::mysql_timestamp_format)
223
+			)
224
+		);
225
+	}
226 226
 
227 227
 
228
-    /**
229
-     * Returns the map of type to pretty label for identifiers used for `LOG_type`.  Client code can register their own
230
-     * map vai the given filter.
231
-     *
232
-     * @return array
233
-     */
234
-    public static function get_pretty_label_map_for_registered_types()
235
-    {
236
-        return apply_filters(
237
-            'FHEE__EEM_Change_Log__get_pretty_label_map_for_registered_types',
238
-            array(
239
-                self::type_create =>  esc_html__("Create", "event_espresso"),
240
-                self::type_update =>  esc_html__("Update", "event_espresso"),
241
-                self::type_delete => esc_html__("Delete", "event_espresso"),
242
-                self::type_debug =>  esc_html__("Debug", "event_espresso"),
243
-                self::type_error =>  esc_html__("Error", "event_espresso"),
244
-                self::type_gateway => esc_html__("Gateway Interaction (IPN or Direct Payment)", 'event_espresso')
245
-            )
246
-        );
247
-    }
228
+	/**
229
+	 * Returns the map of type to pretty label for identifiers used for `LOG_type`.  Client code can register their own
230
+	 * map vai the given filter.
231
+	 *
232
+	 * @return array
233
+	 */
234
+	public static function get_pretty_label_map_for_registered_types()
235
+	{
236
+		return apply_filters(
237
+			'FHEE__EEM_Change_Log__get_pretty_label_map_for_registered_types',
238
+			array(
239
+				self::type_create =>  esc_html__("Create", "event_espresso"),
240
+				self::type_update =>  esc_html__("Update", "event_espresso"),
241
+				self::type_delete => esc_html__("Delete", "event_espresso"),
242
+				self::type_debug =>  esc_html__("Debug", "event_espresso"),
243
+				self::type_error =>  esc_html__("Error", "event_espresso"),
244
+				self::type_gateway => esc_html__("Gateway Interaction (IPN or Direct Payment)", 'event_espresso')
245
+			)
246
+		);
247
+	}
248 248
 
249 249
 
250
-    /**
251
-     * Return the pretty (localized) label for the given log type identifier.
252
-     * @param string $type_identifier
253
-     * @return string
254
-     */
255
-    public static function get_pretty_label_for_type($type_identifier)
256
-    {
257
-        $type_identifier_map = self::get_pretty_label_map_for_registered_types();
258
-        // we fallback to the incoming type identifier if there is no localized label for it.
259
-        return isset($type_identifier_map[ $type_identifier ])
260
-            ? $type_identifier_map[ $type_identifier ]
261
-            : $type_identifier;
262
-    }
250
+	/**
251
+	 * Return the pretty (localized) label for the given log type identifier.
252
+	 * @param string $type_identifier
253
+	 * @return string
254
+	 */
255
+	public static function get_pretty_label_for_type($type_identifier)
256
+	{
257
+		$type_identifier_map = self::get_pretty_label_map_for_registered_types();
258
+		// we fallback to the incoming type identifier if there is no localized label for it.
259
+		return isset($type_identifier_map[ $type_identifier ])
260
+			? $type_identifier_map[ $type_identifier ]
261
+			: $type_identifier;
262
+	}
263 263
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Event_Message_Template.model.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -19,7 +19,7 @@
 block discarded – undo
19 19
     /**
20 20
      * protected constructor to prevent direct creation
21 21
      *
22
-     * @param null $timezone
22
+     * @param string|null $timezone
23 23
      * @throws EE_Error
24 24
      */
25 25
     protected function __construct($timezone = '')
Please login to merge, or discard this patch.
Indentation   +103 added lines, -103 removed lines patch added patch discarded remove patch
@@ -12,116 +12,116 @@
 block discarded – undo
12 12
 class EEM_Event_Message_Template extends EEM_Base
13 13
 {
14 14
 
15
-    // private instance of the EEM_Event_Message_Template object
16
-    protected static $_instance = null;
15
+	// private instance of the EEM_Event_Message_Template object
16
+	protected static $_instance = null;
17 17
 
18 18
 
19
-    /**
20
-     * protected constructor to prevent direct creation
21
-     *
22
-     * @param null $timezone
23
-     * @throws EE_Error
24
-     */
25
-    protected function __construct($timezone = '')
26
-    {
27
-        $this->singular_item = esc_html__('Event Message Template', 'event_espresso');
28
-        $this->plural_item = esc_html__('Event Message Templates', 'event_espresso');
19
+	/**
20
+	 * protected constructor to prevent direct creation
21
+	 *
22
+	 * @param null $timezone
23
+	 * @throws EE_Error
24
+	 */
25
+	protected function __construct($timezone = '')
26
+	{
27
+		$this->singular_item = esc_html__('Event Message Template', 'event_espresso');
28
+		$this->plural_item = esc_html__('Event Message Templates', 'event_espresso');
29 29
 
30
-        $this->_tables = [
31
-            'Event_Message_Template' => new EE_Primary_Table('esp_event_message_template', 'EMT_ID'),
32
-        ];
33
-        $this->_fields = [
34
-            'Event_Message_Template' => [
35
-                'EMT_ID' => new EE_Primary_Key_Int_Field(
36
-                    'EMT_ID',
37
-                    esc_html__('Event Message Template ID', 'event_espresso')
38
-                ),
39
-                'EVT_ID' => new EE_Foreign_Key_Int_Field(
40
-                    'EVT_ID',
41
-                    esc_html__('The ID to the Event', 'event_espresso'),
42
-                    false,
43
-                    0,
44
-                    'Event'
45
-                ),
46
-                'GRP_ID' => new EE_Foreign_Key_Int_Field(
47
-                    'GRP_ID',
48
-                    esc_html__('The ID to the Message Template Group', 'event_espresso'),
49
-                    false,
50
-                    0,
51
-                    'Message_Template_Group'
52
-                ),
53
-            ],
54
-        ];
55
-        $this->_model_relations = [
56
-            'Event'                  => new EE_Belongs_To_Relation(),
57
-            'Message_Template_Group' => new EE_Belongs_To_Relation(),
58
-        ];
59
-        $path_to_event = 'Event';
60
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Event_Related_Public(
61
-            $path_to_event
62
-        );
63
-        $this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] = new EE_Restriction_Generator_Event_Related_Protected(
64
-            $path_to_event
65
-        );
66
-        $this->_cap_restriction_generators[ EEM_Base::caps_edit ] = new EE_Restriction_Generator_Event_Related_Protected(
67
-            $path_to_event
68
-        );
69
-        $this->_cap_restriction_generators[ EEM_Base::caps_delete ] = new EE_Restriction_Generator_Event_Related_Protected(
70
-            $path_to_event,
71
-            EEM_Base::caps_edit
72
-        );
73
-        parent::__construct($timezone);
74
-    }
30
+		$this->_tables = [
31
+			'Event_Message_Template' => new EE_Primary_Table('esp_event_message_template', 'EMT_ID'),
32
+		];
33
+		$this->_fields = [
34
+			'Event_Message_Template' => [
35
+				'EMT_ID' => new EE_Primary_Key_Int_Field(
36
+					'EMT_ID',
37
+					esc_html__('Event Message Template ID', 'event_espresso')
38
+				),
39
+				'EVT_ID' => new EE_Foreign_Key_Int_Field(
40
+					'EVT_ID',
41
+					esc_html__('The ID to the Event', 'event_espresso'),
42
+					false,
43
+					0,
44
+					'Event'
45
+				),
46
+				'GRP_ID' => new EE_Foreign_Key_Int_Field(
47
+					'GRP_ID',
48
+					esc_html__('The ID to the Message Template Group', 'event_espresso'),
49
+					false,
50
+					0,
51
+					'Message_Template_Group'
52
+				),
53
+			],
54
+		];
55
+		$this->_model_relations = [
56
+			'Event'                  => new EE_Belongs_To_Relation(),
57
+			'Message_Template_Group' => new EE_Belongs_To_Relation(),
58
+		];
59
+		$path_to_event = 'Event';
60
+		$this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Event_Related_Public(
61
+			$path_to_event
62
+		);
63
+		$this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] = new EE_Restriction_Generator_Event_Related_Protected(
64
+			$path_to_event
65
+		);
66
+		$this->_cap_restriction_generators[ EEM_Base::caps_edit ] = new EE_Restriction_Generator_Event_Related_Protected(
67
+			$path_to_event
68
+		);
69
+		$this->_cap_restriction_generators[ EEM_Base::caps_delete ] = new EE_Restriction_Generator_Event_Related_Protected(
70
+			$path_to_event,
71
+			EEM_Base::caps_edit
72
+		);
73
+		parent::__construct($timezone);
74
+	}
75 75
 
76 76
 
77
-    /**
78
-     * helper method to simply return an array of event ids for events attached to the given
79
-     * message template group.
80
-     *
81
-     * @param int $GRP_ID The MTP group we want attached events for.
82
-     * @return  array               An array of event ids.
83
-     * @throws EE_Error
84
-     * @since 4.3.0
85
-     */
86
-    public function get_attached_event_ids($GRP_ID)
87
-    {
88
-        $event_ids = $this->_get_all_wpdb_results([['GRP_ID' => $GRP_ID]], ARRAY_N, 'EVT_ID');
89
-        $event_ids = call_user_func_array('array_merge', $event_ids);
90
-        return $event_ids;
91
-    }
77
+	/**
78
+	 * helper method to simply return an array of event ids for events attached to the given
79
+	 * message template group.
80
+	 *
81
+	 * @param int $GRP_ID The MTP group we want attached events for.
82
+	 * @return  array               An array of event ids.
83
+	 * @throws EE_Error
84
+	 * @since 4.3.0
85
+	 */
86
+	public function get_attached_event_ids($GRP_ID)
87
+	{
88
+		$event_ids = $this->_get_all_wpdb_results([['GRP_ID' => $GRP_ID]], ARRAY_N, 'EVT_ID');
89
+		$event_ids = call_user_func_array('array_merge', $event_ids);
90
+		return $event_ids;
91
+	}
92 92
 
93 93
 
94
-    /**
95
-     * helper method for clearing event/group relations for the given event ids and grp ids.
96
-     *
97
-     * @param array $GRP_IDs An array of GRP_IDs. Optional. If empty then there must be EVT IDs.
98
-     * @param array $EVT_IDs An array of EVT_IDs.  Optional. If empty then there must be GRP IDs.
99
-     * @return int             How many rows were deleted.
100
-     * @throws EE_Error
101
-     * @throws EE_Error
102
-     */
103
-    public function delete_event_group_relations($GRP_IDs = [], $EVT_IDs = [])
104
-    {
105
-        if (empty($GRP_IDs) && empty($EVT_IDs)) {
106
-            throw new EE_Error(
107
-                sprintf(
108
-                    esc_html__(
109
-                        '%s requires either an array of GRP_IDs or EVT_IDs or both, but both cannot be empty.',
110
-                        'event_espresso'
111
-                    ),
112
-                    __METHOD__
113
-                )
114
-            );
115
-        }
94
+	/**
95
+	 * helper method for clearing event/group relations for the given event ids and grp ids.
96
+	 *
97
+	 * @param array $GRP_IDs An array of GRP_IDs. Optional. If empty then there must be EVT IDs.
98
+	 * @param array $EVT_IDs An array of EVT_IDs.  Optional. If empty then there must be GRP IDs.
99
+	 * @return int             How many rows were deleted.
100
+	 * @throws EE_Error
101
+	 * @throws EE_Error
102
+	 */
103
+	public function delete_event_group_relations($GRP_IDs = [], $EVT_IDs = [])
104
+	{
105
+		if (empty($GRP_IDs) && empty($EVT_IDs)) {
106
+			throw new EE_Error(
107
+				sprintf(
108
+					esc_html__(
109
+						'%s requires either an array of GRP_IDs or EVT_IDs or both, but both cannot be empty.',
110
+						'event_espresso'
111
+					),
112
+					__METHOD__
113
+				)
114
+			);
115
+		}
116 116
 
117
-        $where = [];
118
-        if (! empty($GRP_IDs)) {
119
-            $where['GRP_ID'] = ['IN', (array) $GRP_IDs];
120
-        }
121
-        if (! empty($EVT_IDs)) {
122
-            $where['EVT_ID'] = ['IN', (array) $EVT_IDs];
123
-        }
117
+		$where = [];
118
+		if (! empty($GRP_IDs)) {
119
+			$where['GRP_ID'] = ['IN', (array) $GRP_IDs];
120
+		}
121
+		if (! empty($EVT_IDs)) {
122
+			$where['EVT_ID'] = ['IN', (array) $EVT_IDs];
123
+		}
124 124
 
125
-        return $this->delete([$where], false);
126
-    }
125
+		return $this->delete([$where], false);
126
+	}
127 127
 }
Please login to merge, or discard this patch.