Completed
Branch models-cleanup/model-relations (278059)
by
unknown
79:14 queued 69:54
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   +6541 added lines, -6541 removed lines patch added patch discarded remove patch
@@ -37,6547 +37,6547 @@
 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 = "SELECT COUNT('{$column_to_count}')" . $this->_construct_2nd_half_of_select_query($model_query_info);
2288
-        return (int) $this->_do_wpdb_query('get_var', [$SQL]);
2289
-    }
2290
-
2291
-
2292
-    /**
2293
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2294
-     *
2295
-     * @param array  $query_params
2296
-     * @param string $field_to_sum name of field (array key in $_fields array)
2297
-     * @return float
2298
-     * @throws EE_Error
2299
-     * @throws ReflectionException
2300
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2301
-     */
2302
-    public function sum($query_params, $field_to_sum = null)
2303
-    {
2304
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2305
-        $field_obj = $field_to_sum
2306
-            ? $this->field_settings_for($field_to_sum)
2307
-            : $this->get_primary_key_field();
2308
-        $column_to_count = $field_obj->get_qualified_column();
2309
-        $SQL             = "SELECT SUM('{$column_to_count}')"
2310
-                           . $this->_construct_2nd_half_of_select_query($model_query_info);
2311
-        $return_value    = $this->_do_wpdb_query('get_var', [$SQL]);
2312
-        $data_type       = $field_obj->get_wpdb_data_type();
2313
-        if ($data_type === '%d' || $data_type === '%s') {
2314
-            return (float) $return_value;
2315
-        }
2316
-        // must be %f
2317
-        return (float) $return_value;
2318
-    }
2319
-
2320
-
2321
-    /**
2322
-     * Just calls the specified method on $wpdb with the given arguments
2323
-     * Consolidates a little extra error handling code
2324
-     *
2325
-     * @param string $wpdb_method
2326
-     * @param array  $arguments_to_provide
2327
-     * @return mixed
2328
-     * @throws EE_Error
2329
-     * @global wpdb  $wpdb
2330
-     */
2331
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2332
-    {
2333
-        // if we're in maintenance mode level 2, DON'T run any queries
2334
-        // because level 2 indicates the database needs updating and
2335
-        // is probably out of sync with the code
2336
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2337
-            throw new EE_Error(
2338
-                sprintf(
2339
-                    esc_html__(
2340
-                        "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.",
2341
-                        "event_espresso"
2342
-                    )
2343
-                )
2344
-            );
2345
-        }
2346
-        global $wpdb;
2347
-        if (! method_exists($wpdb, $wpdb_method)) {
2348
-            throw new EE_Error(
2349
-                sprintf(
2350
-                    esc_html__(
2351
-                        'There is no method named "%s" on Wordpress\' $wpdb object',
2352
-                        'event_espresso'
2353
-                    ),
2354
-                    $wpdb_method
2355
-                )
2356
-            );
2357
-        }
2358
-        $old_show_errors_value = $wpdb->show_errors;
2359
-        if (WP_DEBUG) {
2360
-            $wpdb->show_errors(false);
2361
-        }
2362
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2363
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2364
-        if (WP_DEBUG) {
2365
-            $wpdb->show_errors($old_show_errors_value);
2366
-            if (! empty($wpdb->last_error)) {
2367
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2368
-            }
2369
-            if ($result === false) {
2370
-                throw new EE_Error(
2371
-                    sprintf(
2372
-                        esc_html__(
2373
-                            'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2374
-                            'event_espresso'
2375
-                        ),
2376
-                        $wpdb_method,
2377
-                        var_export($arguments_to_provide, true)
2378
-                    )
2379
-                );
2380
-            }
2381
-        } elseif ($result === false) {
2382
-            EE_Error::add_error(
2383
-                sprintf(
2384
-                    esc_html__(
2385
-                        '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"',
2386
-                        'event_espresso'
2387
-                    ),
2388
-                    $wpdb_method,
2389
-                    var_export($arguments_to_provide, true),
2390
-                    $wpdb->last_error
2391
-                ),
2392
-                __FILE__,
2393
-                __FUNCTION__,
2394
-                __LINE__
2395
-            );
2396
-        }
2397
-        return $result;
2398
-    }
2399
-
2400
-
2401
-    /**
2402
-     * Attempts to run the indicated WPDB method with the provided arguments,
2403
-     * and if there's an error tries to verify the DB is correct. Uses
2404
-     * the static property EEM_Base::$_db_verification_level to determine whether
2405
-     * we should try to fix the EE core db, the addons, or just give up
2406
-     *
2407
-     * @param string $wpdb_method
2408
-     * @param array  $arguments_to_provide
2409
-     * @return mixed
2410
-     * @throws EE_Error
2411
-     */
2412
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2413
-    {
2414
-        global $wpdb;
2415
-        $wpdb->last_error = null;
2416
-        $result           = call_user_func_array([$wpdb, $wpdb_method], $arguments_to_provide);
2417
-        // was there an error running the query? but we don't care on new activations
2418
-        // (we're going to setup the DB anyway on new activations)
2419
-        if (
2420
-            ($result === false || ! empty($wpdb->last_error))
2421
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2422
-        ) {
2423
-            switch (EEM_Base::$_db_verification_level) {
2424
-                case EEM_Base::db_verified_none:
2425
-                    // let's double-check core's DB
2426
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2427
-                    break;
2428
-                case EEM_Base::db_verified_core:
2429
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2430
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2431
-                    break;
2432
-                case EEM_Base::db_verified_addons:
2433
-                    // ummmm... you in trouble
2434
-                    return $result;
2435
-            }
2436
-            if (! empty($error_message)) {
2437
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2438
-                trigger_error($error_message);
2439
-            }
2440
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2441
-        }
2442
-        return $result;
2443
-    }
2444
-
2445
-
2446
-    /**
2447
-     * Verifies the EE core database is up-to-date and records that we've done it on
2448
-     * EEM_Base::$_db_verification_level
2449
-     *
2450
-     * @param string $wpdb_method
2451
-     * @param array  $arguments_to_provide
2452
-     * @return string
2453
-     * @throws EE_Error
2454
-     */
2455
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2456
-    {
2457
-        global $wpdb;
2458
-        // ok remember that we've already attempted fixing the core db, in case the problem persists
2459
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2460
-        $error_message                    = sprintf(
2461
-            esc_html__(
2462
-                'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2463
-                'event_espresso'
2464
-            ),
2465
-            $wpdb->last_error,
2466
-            $wpdb_method,
2467
-            wp_json_encode($arguments_to_provide)
2468
-        );
2469
-        EE_System::instance()->initialize_db_if_no_migrations_required();
2470
-        return $error_message;
2471
-    }
2472
-
2473
-
2474
-    /**
2475
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2476
-     * EEM_Base::$_db_verification_level
2477
-     *
2478
-     * @param $wpdb_method
2479
-     * @param $arguments_to_provide
2480
-     * @return string
2481
-     * @throws EE_Error
2482
-     */
2483
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2484
-    {
2485
-        global $wpdb;
2486
-        // ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2487
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2488
-        $error_message                    = sprintf(
2489
-            esc_html__(
2490
-                'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2491
-                'event_espresso'
2492
-            ),
2493
-            $wpdb->last_error,
2494
-            $wpdb_method,
2495
-            wp_json_encode($arguments_to_provide)
2496
-        );
2497
-        EE_System::instance()->initialize_addons();
2498
-        return $error_message;
2499
-    }
2500
-
2501
-
2502
-    /**
2503
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2504
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2505
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2506
-     * ..."
2507
-     *
2508
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2509
-     * @return string
2510
-     */
2511
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2512
-    {
2513
-        return " FROM " . $model_query_info->get_full_join_sql() .
2514
-               $model_query_info->get_where_sql() .
2515
-               $model_query_info->get_group_by_sql() .
2516
-               $model_query_info->get_having_sql() .
2517
-               $model_query_info->get_order_by_sql() .
2518
-               $model_query_info->get_limit_sql();
2519
-    }
2520
-
2521
-
2522
-    /**
2523
-     * Set to easily debug the next X queries ran from this model.
2524
-     *
2525
-     * @param int $count
2526
-     */
2527
-    public function show_next_x_db_queries($count = 1)
2528
-    {
2529
-        $this->_show_next_x_db_queries = $count;
2530
-    }
2531
-
2532
-
2533
-    /**
2534
-     * @param $sql_query
2535
-     */
2536
-    public function show_db_query_if_previously_requested($sql_query)
2537
-    {
2538
-        if ($this->_show_next_x_db_queries > 0) {
2539
-            echo $sql_query;
2540
-            $this->_show_next_x_db_queries--;
2541
-        }
2542
-    }
2543
-
2544
-
2545
-    /**
2546
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2547
-     * There are the 3 cases:
2548
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2549
-     * $otherModelObject has no ID, it is first saved.
2550
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2551
-     * has no ID, it is first saved.
2552
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2553
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2554
-     * join table
2555
-     *
2556
-     * @param EE_Base_Class                     /int $thisModelObject
2557
-     * @param EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2558
-     * @param string $relationName                     , key in EEM_Base::_relations
2559
-     *                                                 an attendee to a group, you also want to specify which role they
2560
-     *                                                 will have in that group. So you would use this parameter to
2561
-     *                                                 specify array('role-column-name'=>'role-id')
2562
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2563
-     *                                                 to for relation to methods that allow you to further specify
2564
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2565
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2566
-     *                                                 because these will be inserted in any new rows created as well.
2567
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2568
-     * @throws EE_Error
2569
-     */
2570
-    public function add_relationship_to(
2571
-        $id_or_obj,
2572
-        $other_model_id_or_obj,
2573
-        $relationName,
2574
-        $extra_join_model_fields_n_values = []
2575
-    ) {
2576
-        $relation_obj = $this->related_settings_for($relationName);
2577
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2578
-    }
2579
-
2580
-
2581
-    /**
2582
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2583
-     * There are the 3 cases:
2584
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2585
-     * error
2586
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2587
-     * an error
2588
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2589
-     *
2590
-     * @param EE_Base_Class /int $id_or_obj
2591
-     * @param EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2592
-     * @param string $relationName key in EEM_Base::_relations
2593
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2594
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2595
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2596
-     *                             because these will be inserted in any new rows created as well.
2597
-     * @return boolean of success
2598
-     * @throws EE_Error
2599
-     */
2600
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = [])
2601
-    {
2602
-        $relation_obj = $this->related_settings_for($relationName);
2603
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2604
-    }
2605
-
2606
-
2607
-    /**
2608
-     * @param mixed  $id_or_obj
2609
-     * @param string $relationName
2610
-     * @param array  $where_query_params
2611
-     * @param EE_Base_Class[] objects to which relations were removed
2612
-     * @return EE_Base_Class[]
2613
-     * @throws EE_Error
2614
-     */
2615
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = [])
2616
-    {
2617
-        $relation_obj = $this->related_settings_for($relationName);
2618
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2619
-    }
2620
-
2621
-
2622
-    /**
2623
-     * Gets all the related items of the specified $model_name, using $query_params.
2624
-     * Note: by default, we remove the "default query params"
2625
-     * because we want to get even deleted items etc.
2626
-     *
2627
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2628
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2629
-     * @param array  $query_params see github link below for more info
2630
-     * @return EE_Base_Class[]
2631
-     * @throws EE_Error
2632
-     * @throws ReflectionException
2633
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2634
-     */
2635
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2636
-    {
2637
-        $model_obj         = $this->ensure_is_obj($id_or_obj);
2638
-        $relation_settings = $this->related_settings_for($model_name);
2639
-        return $relation_settings->get_all_related($model_obj, $query_params);
2640
-    }
2641
-
2642
-
2643
-    /**
2644
-     * Deletes all the model objects across the relation indicated by $model_name
2645
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2646
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2647
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2648
-     *
2649
-     * @param EE_Base_Class|int|string $id_or_obj
2650
-     * @param string                   $model_name
2651
-     * @param array                    $query_params
2652
-     * @return int how many deleted
2653
-     * @throws EE_Error
2654
-     * @throws ReflectionException
2655
-     */
2656
-    public function delete_related($id_or_obj, $model_name, $query_params = [])
2657
-    {
2658
-        $model_obj         = $this->ensure_is_obj($id_or_obj);
2659
-        $relation_settings = $this->related_settings_for($model_name);
2660
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2661
-    }
2662
-
2663
-
2664
-    /**
2665
-     * Hard deletes all the model objects across the relation indicated by $model_name
2666
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2667
-     * the model objects can't be hard deleted because of blocking related model objects,
2668
-     * just does a soft-delete on them instead.
2669
-     *
2670
-     * @param EE_Base_Class|int|string $id_or_obj
2671
-     * @param string                   $model_name
2672
-     * @param array                    $query_params
2673
-     * @return int how many deleted
2674
-     * @throws EE_Error
2675
-     * @throws ReflectionException
2676
-     */
2677
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = [])
2678
-    {
2679
-        $model_obj         = $this->ensure_is_obj($id_or_obj);
2680
-        $relation_settings = $this->related_settings_for($model_name);
2681
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2682
-    }
2683
-
2684
-
2685
-    /**
2686
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2687
-     * unless otherwise specified in the $query_params
2688
-     *
2689
-     * @param int             /EE_Base_Class $id_or_obj
2690
-     * @param string $model_name     like 'Event', or 'Registration'
2691
-     * @param array  $query_params
2692
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2693
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2694
-     *                               that by the setting $distinct to TRUE;
2695
-     * @return int
2696
-     * @throws EE_Error
2697
-     * @throws ReflectionException
2698
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2699
-     */
2700
-    public function count_related(
2701
-        $id_or_obj,
2702
-        $model_name,
2703
-        $query_params = [],
2704
-        $field_to_count = null,
2705
-        $distinct = false
2706
-    ) {
2707
-        $related_model = $this->get_related_model_obj($model_name);
2708
-        // we're just going to use the query params on the related model's normal get_all query,
2709
-        // except add a condition to say to match the current mod
2710
-        if (! isset($query_params['default_where_conditions'])) {
2711
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2712
-        }
2713
-        $this_model_name                                                 = $this->get_this_model_name();
2714
-        $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2715
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2716
-        return $related_model->count($query_params, $field_to_count, $distinct);
2717
-    }
2718
-
2719
-
2720
-    /**
2721
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2722
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2723
-     *
2724
-     * @param int           /EE_Base_Class $id_or_obj
2725
-     * @param string $model_name   like 'Event', or 'Registration'
2726
-     * @param array  $query_params
2727
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2728
-     * @return float
2729
-     * @throws EE_Error
2730
-     * @throws ReflectionException
2731
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2732
-     */
2733
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2734
-    {
2735
-        $related_model = $this->get_related_model_obj($model_name);
2736
-        if (! is_array($query_params)) {
2737
-            EE_Error::doing_it_wrong(
2738
-                'EEM_Base::sum_related',
2739
-                sprintf(
2740
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2741
-                    gettype($query_params)
2742
-                ),
2743
-                '4.6.0'
2744
-            );
2745
-            $query_params = [];
2746
-        }
2747
-        // we're just going to use the query params on the related model's normal get_all query,
2748
-        // except add a condition to say to match the current mod
2749
-        if (! isset($query_params['default_where_conditions'])) {
2750
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2751
-        }
2752
-        $this_model_name                                                 = $this->get_this_model_name();
2753
-        $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2754
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2755
-        return $related_model->sum($query_params, $field_to_sum);
2756
-    }
2757
-
2758
-
2759
-    /**
2760
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2761
-     * $modelObject
2762
-     *
2763
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2764
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2765
-     * @param array               $query_params     see github link below for more info
2766
-     * @return EE_Base_Class
2767
-     * @throws EE_Error
2768
-     * @throws ReflectionException
2769
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2770
-     */
2771
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2772
-    {
2773
-        $query_params['limit'] = 1;
2774
-        $results               = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2775
-        if ($results) {
2776
-            return array_shift($results);
2777
-        }
2778
-        return null;
2779
-    }
2780
-
2781
-
2782
-    /**
2783
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2784
-     *
2785
-     * @return string
2786
-     */
2787
-    public function get_this_model_name()
2788
-    {
2789
-        return str_replace("EEM_", "", get_class($this));
2790
-    }
2791
-
2792
-
2793
-    /**
2794
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2795
-     *
2796
-     * @return EE_Any_Foreign_Model_Name_Field
2797
-     * @throws EE_Error
2798
-     */
2799
-    public function get_field_containing_related_model_name()
2800
-    {
2801
-        foreach ($this->field_settings(true) as $field) {
2802
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2803
-                $field_with_model_name = $field;
2804
-            }
2805
-        }
2806
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2807
-            throw new EE_Error(
2808
-                sprintf(
2809
-                    esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2810
-                    $this->get_this_model_name()
2811
-                )
2812
-            );
2813
-        }
2814
-        return $field_with_model_name;
2815
-    }
2816
-
2817
-
2818
-    /**
2819
-     * Inserts a new entry into the database, for each table.
2820
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2821
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2822
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2823
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2824
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2825
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2826
-     *
2827
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2828
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2829
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2830
-     *                              of EEM_Base)
2831
-     * @return int|string new primary key on main table that got inserted
2832
-     * @throws EE_Error
2833
-     * @throws ReflectionException
2834
-     */
2835
-    public function insert($field_n_values)
2836
-    {
2837
-        /**
2838
-         * Filters the fields and their values before inserting an item using the models
2839
-         *
2840
-         * @param array    $fields_n_values keys are the fields and values are their new values
2841
-         * @param EEM_Base $model           the model used
2842
-         */
2843
-        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2844
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2845
-            $main_table = $this->_get_main_table();
2846
-            $new_id     = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2847
-            if ($new_id !== false) {
2848
-                foreach ($this->_get_other_tables() as $other_table) {
2849
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2850
-                }
2851
-            }
2852
-            /**
2853
-             * Done just after attempting to insert a new model object
2854
-             *
2855
-             * @param EEM_Base $model           used
2856
-             * @param array    $fields_n_values fields and their values
2857
-             * @param int|string the              ID of the newly-inserted model object
2858
-             */
2859
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2860
-            return $new_id;
2861
-        }
2862
-        return false;
2863
-    }
2864
-
2865
-
2866
-    /**
2867
-     * Checks that the result would satisfy the unique indexes on this model
2868
-     *
2869
-     * @param array  $field_n_values
2870
-     * @param string $action
2871
-     * @return boolean
2872
-     * @throws EE_Error
2873
-     * @throws ReflectionException
2874
-     */
2875
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2876
-    {
2877
-        foreach ($this->unique_indexes() as $index_name => $index) {
2878
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2879
-            if ($this->exists([$uniqueness_where_params])) {
2880
-                EE_Error::add_error(
2881
-                    sprintf(
2882
-                        esc_html__(
2883
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2884
-                            "event_espresso"
2885
-                        ),
2886
-                        $action,
2887
-                        $this->_get_class_name(),
2888
-                        $index_name,
2889
-                        implode(",", $index->field_names()),
2890
-                        http_build_query($uniqueness_where_params)
2891
-                    ),
2892
-                    __FILE__,
2893
-                    __FUNCTION__,
2894
-                    __LINE__
2895
-                );
2896
-                return false;
2897
-            }
2898
-        }
2899
-        return true;
2900
-    }
2901
-
2902
-
2903
-    /**
2904
-     * Checks the database for an item that conflicts (ie, if this item were
2905
-     * saved to the DB would break some uniqueness requirement, like a primary key
2906
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2907
-     * can be either an EE_Base_Class or an array of fields n values
2908
-     *
2909
-     * @param EE_Base_Class|array $obj_or_fields_array
2910
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2911
-     *                                                 when looking for conflicts
2912
-     *                                                 (ie, if false, we ignore the model object's primary key
2913
-     *                                                 when finding "conflicts". If true, it's also considered).
2914
-     *                                                 Only works for INT primary key,
2915
-     *                                                 STRING primary keys cannot be ignored
2916
-     * @return EE_Base_Class|array
2917
-     * @throws EE_Error
2918
-     * @throws ReflectionException
2919
-     */
2920
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2921
-    {
2922
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2923
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2924
-        } elseif (is_array($obj_or_fields_array)) {
2925
-            $fields_n_values = $obj_or_fields_array;
2926
-        } else {
2927
-            throw new EE_Error(
2928
-                sprintf(
2929
-                    esc_html__(
2930
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2931
-                        "event_espresso"
2932
-                    ),
2933
-                    get_class($this),
2934
-                    $obj_or_fields_array
2935
-                )
2936
-            );
2937
-        }
2938
-        $query_params = [];
2939
-        if (
2940
-            $this->has_primary_key_field()
2941
-            && ($include_primary_key
2942
-                || $this->get_primary_key_field()
2943
-                   instanceof
2944
-                   EE_Primary_Key_String_Field)
2945
-            && isset($fields_n_values[ $this->primary_key_name() ])
2946
-        ) {
2947
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2948
-        }
2949
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2950
-            $uniqueness_where_params                              =
2951
-                array_intersect_key($fields_n_values, $unique_index->fields());
2952
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2953
-        }
2954
-        // if there is nothing to base this search on, then we shouldn't find anything
2955
-        if (empty($query_params)) {
2956
-            return [];
2957
-        }
2958
-        return $this->get_one($query_params);
2959
-    }
2960
-
2961
-
2962
-    /**
2963
-     * Like count, but is optimized and returns a boolean instead of an int
2964
-     *
2965
-     * @param array $query_params
2966
-     * @return boolean
2967
-     * @throws EE_Error
2968
-     * @throws ReflectionException
2969
-     */
2970
-    public function exists($query_params)
2971
-    {
2972
-        $query_params['limit'] = 1;
2973
-        return $this->count($query_params) > 0;
2974
-    }
2975
-
2976
-
2977
-    /**
2978
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2979
-     *
2980
-     * @param int|string $id
2981
-     * @return boolean
2982
-     * @throws EE_Error
2983
-     * @throws ReflectionException
2984
-     */
2985
-    public function exists_by_ID($id)
2986
-    {
2987
-        return $this->exists(
2988
-            [
2989
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2990
-                [
2991
-                    $this->primary_key_name() => $id,
2992
-                ],
2993
-            ]
2994
-        );
2995
-    }
2996
-
2997
-
2998
-    /**
2999
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
3000
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
3001
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
3002
-     * on the main table)
3003
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
3004
-     * cases where we want to call it directly rather than via insert().
3005
-     *
3006
-     * @access   protected
3007
-     * @param EE_Table_Base $table
3008
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
3009
-     *                                       float
3010
-     * @param int           $new_id          for now we assume only int keys
3011
-     * @return int ID of new row inserted, or FALSE on failure
3012
-     * @throws EE_Error
3013
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
3014
-     */
3015
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
3016
-    {
3017
-        global $wpdb;
3018
-        $insertion_col_n_values = [];
3019
-        $format_for_insertion   = [];
3020
-        $fields_on_table        = $this->_get_fields_for_table($table->get_table_alias());
3021
-        foreach ($fields_on_table as $field_name => $field_obj) {
3022
-            // check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
3023
-            if ($field_obj->is_auto_increment()) {
3024
-                continue;
3025
-            }
3026
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3027
-            // if the value we want to assign it to is NULL, just don't mention it for the insertion
3028
-            if ($prepared_value !== null) {
3029
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3030
-                $format_for_insertion[]                                   = $field_obj->get_wpdb_data_type();
3031
-            }
3032
-        }
3033
-        if ($table instanceof EE_Secondary_Table && $new_id) {
3034
-            // its not the main table, so we should have already saved the main table's PK which we just inserted
3035
-            // so add the fk to the main table as a column
3036
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3037
-            $format_for_insertion[]                              =
3038
-                '%d';// yes right now we're only allowing these foreign keys to be INTs
3039
-        }
3040
-        // insert the new entry
3041
-        $result = $this->_do_wpdb_query(
3042
-            'insert',
3043
-            [$table->get_table_name(), $insertion_col_n_values, $format_for_insertion]
3044
-        );
3045
-        if ($result === false) {
3046
-            return false;
3047
-        }
3048
-        // ok, now what do we return for the ID of the newly-inserted thing?
3049
-        if ($this->has_primary_key_field()) {
3050
-            if ($this->get_primary_key_field()->is_auto_increment()) {
3051
-                return $wpdb->insert_id;
3052
-            }
3053
-            // it's not an auto-increment primary key, so
3054
-            // it must have been supplied
3055
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3056
-        }
3057
-        // we can't return a  primary key because there is none. instead return
3058
-        // a unique string indicating this model
3059
-        return $this->get_index_primary_key_string($fields_n_values);
3060
-    }
3061
-
3062
-
3063
-    /**
3064
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3065
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3066
-     * and there is no default, we pass it along. WPDB will take care of it)
3067
-     *
3068
-     * @param EE_Model_Field_Base $field_obj
3069
-     * @param array               $fields_n_values
3070
-     * @return mixed string|int|float depending on what the table column will be expecting
3071
-     * @throws EE_Error
3072
-     */
3073
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3074
-    {
3075
-        // if this field doesn't allow nullable, don't allow it
3076
-        if (
3077
-            ! $field_obj->is_nullable()
3078
-            && (
3079
-                ! isset($fields_n_values[ $field_obj->get_name() ])
3080
-                || $fields_n_values[ $field_obj->get_name() ] === null
3081
-            )
3082
-        ) {
3083
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3084
-        }
3085
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3086
-            ? $fields_n_values[ $field_obj->get_name() ]
3087
-            : null;
3088
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3089
-    }
3090
-
3091
-
3092
-    /**
3093
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3094
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3095
-     * the field's prepare_for_set() method.
3096
-     *
3097
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3098
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3099
-     *                                   top of file)
3100
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3101
-     *                                   $value is a custom selection
3102
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3103
-     */
3104
-    private function _prepare_value_for_use_in_db($value, $field)
3105
-    {
3106
-        if ($field && $field instanceof EE_Model_Field_Base) {
3107
-            // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3108
-            switch ($this->_values_already_prepared_by_model_object) {
3109
-                /** @noinspection PhpMissingBreakStatementInspection */
3110
-                case self::not_prepared_by_model_object:
3111
-                    $value = $field->prepare_for_set($value);
3112
-                // purposefully left out "return"
3113
-                case self::prepared_by_model_object:
3114
-                    /** @noinspection SuspiciousAssignmentsInspection */
3115
-                    $value = $field->prepare_for_use_in_db($value);
3116
-                case self::prepared_for_use_in_db:
3117
-                    // leave the value alone
3118
-            }
3119
-            return $value;
3120
-            // phpcs:enable
3121
-        }
3122
-        return $value;
3123
-    }
3124
-
3125
-
3126
-    /**
3127
-     * Returns the main table on this model
3128
-     *
3129
-     * @return EE_Primary_Table
3130
-     * @throws EE_Error
3131
-     */
3132
-    protected function _get_main_table()
3133
-    {
3134
-        foreach ($this->_tables as $table) {
3135
-            if ($table instanceof EE_Primary_Table) {
3136
-                return $table;
3137
-            }
3138
-        }
3139
-        throw new EE_Error(
3140
-            sprintf(
3141
-                esc_html__(
3142
-                    'There are no main tables on %s. They should be added to _tables array in the constructor',
3143
-                    'event_espresso'
3144
-                ),
3145
-                get_class($this)
3146
-            )
3147
-        );
3148
-    }
3149
-
3150
-
3151
-    /**
3152
-     * table
3153
-     * returns EE_Primary_Table table name
3154
-     *
3155
-     * @return string
3156
-     * @throws EE_Error
3157
-     */
3158
-    public function table()
3159
-    {
3160
-        return $this->_get_main_table()->get_table_name();
3161
-    }
3162
-
3163
-
3164
-    /**
3165
-     * table
3166
-     * returns first EE_Secondary_Table table name
3167
-     *
3168
-     * @return string
3169
-     */
3170
-    public function second_table()
3171
-    {
3172
-        // grab second table from tables array
3173
-        $second_table = end($this->_tables);
3174
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3175
-    }
3176
-
3177
-
3178
-    /**
3179
-     * get_table_obj_by_alias
3180
-     * returns table name given it's alias
3181
-     *
3182
-     * @param string $table_alias
3183
-     * @return EE_Primary_Table | EE_Secondary_Table
3184
-     */
3185
-    public function get_table_obj_by_alias($table_alias = '')
3186
-    {
3187
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3188
-    }
3189
-
3190
-
3191
-    /**
3192
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3193
-     *
3194
-     * @return EE_Secondary_Table[]
3195
-     */
3196
-    protected function _get_other_tables()
3197
-    {
3198
-        $other_tables = [];
3199
-        foreach ($this->_tables as $table_alias => $table) {
3200
-            if ($table instanceof EE_Secondary_Table) {
3201
-                $other_tables[ $table_alias ] = $table;
3202
-            }
3203
-        }
3204
-        return $other_tables;
3205
-    }
3206
-
3207
-
3208
-    /**
3209
-     * Finds all the fields that correspond to the given table
3210
-     *
3211
-     * @param string $table_alias , array key in EEM_Base::_tables
3212
-     * @return EE_Model_Field_Base[]
3213
-     */
3214
-    public function _get_fields_for_table($table_alias)
3215
-    {
3216
-        return $this->_fields[ $table_alias ];
3217
-    }
3218
-
3219
-
3220
-    /**
3221
-     * Recurses through all the where parameters, and finds all the related models we'll need
3222
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3223
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3224
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3225
-     * related Registration, Transaction, and Payment models.
3226
-     *
3227
-     * @param array $query_params see github link below for more info
3228
-     * @return EE_Model_Query_Info_Carrier
3229
-     * @throws EE_Error
3230
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3231
-     */
3232
-    public function _extract_related_models_from_query($query_params)
3233
-    {
3234
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3235
-        if (array_key_exists(0, $query_params)) {
3236
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3237
-        }
3238
-        if (array_key_exists('group_by', $query_params)) {
3239
-            if (is_array($query_params['group_by'])) {
3240
-                $this->_extract_related_models_from_sub_params_array_values(
3241
-                    $query_params['group_by'],
3242
-                    $query_info_carrier,
3243
-                    'group_by'
3244
-                );
3245
-            } elseif (! empty($query_params['group_by'])) {
3246
-                $this->_extract_related_model_info_from_query_param(
3247
-                    $query_params['group_by'],
3248
-                    $query_info_carrier,
3249
-                    'group_by'
3250
-                );
3251
-            }
3252
-        }
3253
-        if (array_key_exists('having', $query_params)) {
3254
-            $this->_extract_related_models_from_sub_params_array_keys(
3255
-                $query_params[0],
3256
-                $query_info_carrier,
3257
-                'having'
3258
-            );
3259
-        }
3260
-        if (array_key_exists('order_by', $query_params)) {
3261
-            if (is_array($query_params['order_by'])) {
3262
-                $this->_extract_related_models_from_sub_params_array_keys(
3263
-                    $query_params['order_by'],
3264
-                    $query_info_carrier,
3265
-                    'order_by'
3266
-                );
3267
-            } elseif (! empty($query_params['order_by'])) {
3268
-                $this->_extract_related_model_info_from_query_param(
3269
-                    $query_params['order_by'],
3270
-                    $query_info_carrier,
3271
-                    'order_by'
3272
-                );
3273
-            }
3274
-        }
3275
-        if (array_key_exists('force_join', $query_params)) {
3276
-            $this->_extract_related_models_from_sub_params_array_values(
3277
-                $query_params['force_join'],
3278
-                $query_info_carrier,
3279
-                'force_join'
3280
-            );
3281
-        }
3282
-        $this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3283
-        return $query_info_carrier;
3284
-    }
3285
-
3286
-
3287
-    /**
3288
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3289
-     *
3290
-     * @param array                       $sub_query_params
3291
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3292
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3293
-     * @return EE_Model_Query_Info_Carrier
3294
-     * @throws EE_Error
3295
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3296
-     */
3297
-    private function _extract_related_models_from_sub_params_array_keys(
3298
-        $sub_query_params,
3299
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3300
-        $query_param_type
3301
-    ) {
3302
-        if (! empty($sub_query_params)) {
3303
-            $sub_query_params = (array) $sub_query_params;
3304
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3305
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3306
-                $this->_extract_related_model_info_from_query_param(
3307
-                    $param,
3308
-                    $model_query_info_carrier,
3309
-                    $query_param_type
3310
-                );
3311
-                // if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3312
-                // indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3313
-                // extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3314
-                // of array('Registration.TXN_ID'=>23)
3315
-                $query_param_sans_stars =
3316
-                    $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3317
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3318
-                    if (! is_array($possibly_array_of_params)) {
3319
-                        throw new EE_Error(
3320
-                            sprintf(
3321
-                                esc_html__(
3322
-                                    "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'))",
3323
-                                    "event_espresso"
3324
-                                ),
3325
-                                $param,
3326
-                                $possibly_array_of_params
3327
-                            )
3328
-                        );
3329
-                    }
3330
-                    $this->_extract_related_models_from_sub_params_array_keys(
3331
-                        $possibly_array_of_params,
3332
-                        $model_query_info_carrier,
3333
-                        $query_param_type
3334
-                    );
3335
-                } elseif (
3336
-                    $query_param_type === 0 // ie WHERE
3337
-                    && is_array($possibly_array_of_params)
3338
-                    && isset($possibly_array_of_params[2])
3339
-                    && $possibly_array_of_params[2] == true
3340
-                ) {
3341
-                    // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3342
-                    // indicating that $possible_array_of_params[1] is actually a field name,
3343
-                    // from which we should extract query parameters!
3344
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3345
-                        throw new EE_Error(
3346
-                            sprintf(
3347
-                                esc_html__(
3348
-                                    "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3349
-                                    "event_espresso"
3350
-                                ),
3351
-                                $query_param_type,
3352
-                                implode(",", $possibly_array_of_params)
3353
-                            )
3354
-                        );
3355
-                    }
3356
-                    $this->_extract_related_model_info_from_query_param(
3357
-                        $possibly_array_of_params[1],
3358
-                        $model_query_info_carrier,
3359
-                        $query_param_type
3360
-                    );
3361
-                }
3362
-            }
3363
-        }
3364
-        return $model_query_info_carrier;
3365
-    }
3366
-
3367
-
3368
-    /**
3369
-     * For extracting related models from forced_joins, where the array values contain the info about what
3370
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3371
-     *
3372
-     * @param array                       $sub_query_params
3373
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3374
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3375
-     * @return EE_Model_Query_Info_Carrier
3376
-     * @throws EE_Error
3377
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3378
-     */
3379
-    private function _extract_related_models_from_sub_params_array_values(
3380
-        $sub_query_params,
3381
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3382
-        $query_param_type
3383
-    ) {
3384
-        if (! empty($sub_query_params)) {
3385
-            if (! is_array($sub_query_params)) {
3386
-                throw new EE_Error(
3387
-                    sprintf(
3388
-                        esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3389
-                        $sub_query_params
3390
-                    )
3391
-                );
3392
-            }
3393
-            foreach ($sub_query_params as $param) {
3394
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3395
-                $this->_extract_related_model_info_from_query_param(
3396
-                    $param,
3397
-                    $model_query_info_carrier,
3398
-                    $query_param_type
3399
-                );
3400
-            }
3401
-        }
3402
-        return $model_query_info_carrier;
3403
-    }
3404
-
3405
-
3406
-    /**
3407
-     * Extract all the query parts from  model query params
3408
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3409
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3410
-     * but use them in a different order. Eg, we need to know what models we are querying
3411
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3412
-     * other models before we can finalize the where clause SQL.
3413
-     *
3414
-     * @param array $query_params see github link below for more info
3415
-     * @return EE_Model_Query_Info_Carrier
3416
-     * @throws EE_Error
3417
-     * @throws ModelConfigurationException
3418
-     * @throws ReflectionException
3419
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3420
-     */
3421
-    public function _create_model_query_info_carrier($query_params)
3422
-    {
3423
-        if (! is_array($query_params)) {
3424
-            EE_Error::doing_it_wrong(
3425
-                'EEM_Base::_create_model_query_info_carrier',
3426
-                sprintf(
3427
-                    esc_html__(
3428
-                        '$query_params should be an array, you passed a variable of type %s',
3429
-                        'event_espresso'
3430
-                    ),
3431
-                    gettype($query_params)
3432
-                ),
3433
-                '4.6.0'
3434
-            );
3435
-            $query_params = [];
3436
-        }
3437
-        $query_params[0] = isset($query_params[0]) ? $query_params[0] : [];
3438
-        // first check if we should alter the query to account for caps or not
3439
-        // because the caps might require us to do extra joins
3440
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3441
-            $query_params[0] = array_replace_recursive(
3442
-                $query_params[0],
3443
-                $this->caps_where_conditions(
3444
-                    $query_params['caps']
3445
-                )
3446
-            );
3447
-        }
3448
-
3449
-        // check if we should alter the query to remove data related to protected
3450
-        // custom post types
3451
-        if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3452
-            $where_param_key_for_password = $this->modelChainAndPassword();
3453
-            // only include if related to a cpt where no password has been set
3454
-            $query_params[0]['OR*nopassword'] = [
3455
-                $where_param_key_for_password       => '',
3456
-                $where_param_key_for_password . '*' => ['IS_NULL'],
3457
-            ];
3458
-        }
3459
-        $query_object = $this->_extract_related_models_from_query($query_params);
3460
-        // verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3461
-        foreach ($query_params[0] as $key => $value) {
3462
-            if (is_int($key)) {
3463
-                throw new EE_Error(
3464
-                    sprintf(
3465
-                        esc_html__(
3466
-                            "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.",
3467
-                            "event_espresso"
3468
-                        ),
3469
-                        $key,
3470
-                        var_export($value, true),
3471
-                        var_export($query_params, true),
3472
-                        get_class($this)
3473
-                    )
3474
-                );
3475
-            }
3476
-        }
3477
-        if (
3478
-            array_key_exists('default_where_conditions', $query_params)
3479
-            && ! empty($query_params['default_where_conditions'])
3480
-        ) {
3481
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3482
-        } else {
3483
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3484
-        }
3485
-        $query_params[0] = array_merge(
3486
-            $this->_get_default_where_conditions_for_models_in_query(
3487
-                $query_object,
3488
-                $use_default_where_conditions,
3489
-                $query_params[0]
3490
-            ),
3491
-            $query_params[0]
3492
-        );
3493
-        $query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3494
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3495
-        // So we need to setup a subquery and use that for the main join.
3496
-        // Note for now this only works on the primary table for the model.
3497
-        // So for instance, you could set the limit array like this:
3498
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3499
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3500
-            $query_object->set_main_model_join_sql(
3501
-                $this->_construct_limit_join_select(
3502
-                    $query_params['on_join_limit'][0],
3503
-                    $query_params['on_join_limit'][1]
3504
-                )
3505
-            );
3506
-        }
3507
-        // set limit
3508
-        if (array_key_exists('limit', $query_params)) {
3509
-            if (is_array($query_params['limit'])) {
3510
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3511
-                    $e = sprintf(
3512
-                        esc_html__(
3513
-                            "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)",
3514
-                            "event_espresso"
3515
-                        ),
3516
-                        http_build_query($query_params['limit'])
3517
-                    );
3518
-                    throw new EE_Error($e . "|" . $e);
3519
-                }
3520
-                // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3521
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3522
-            } elseif (! empty($query_params['limit'])) {
3523
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3524
-            }
3525
-        }
3526
-        // set order by
3527
-        if (array_key_exists('order_by', $query_params)) {
3528
-            if (is_array($query_params['order_by'])) {
3529
-                // if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3530
-                // specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3531
-                // including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3532
-                if (array_key_exists('order', $query_params)) {
3533
-                    throw new EE_Error(
3534
-                        sprintf(
3535
-                            esc_html__(
3536
-                                "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 ",
3537
-                                "event_espresso"
3538
-                            ),
3539
-                            get_class($this),
3540
-                            implode(", ", array_keys($query_params['order_by'])),
3541
-                            implode(", ", $query_params['order_by']),
3542
-                            $query_params['order']
3543
-                        )
3544
-                    );
3545
-                }
3546
-                $this->_extract_related_models_from_sub_params_array_keys(
3547
-                    $query_params['order_by'],
3548
-                    $query_object,
3549
-                    'order_by'
3550
-                );
3551
-                // assume it's an array of fields to order by
3552
-                $order_array = [];
3553
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3554
-                    $order         = $this->_extract_order($order);
3555
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3556
-                }
3557
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3558
-            } elseif (! empty($query_params['order_by'])) {
3559
-                $this->_extract_related_model_info_from_query_param(
3560
-                    $query_params['order_by'],
3561
-                    $query_object,
3562
-                    'order',
3563
-                    $query_params['order_by']
3564
-                );
3565
-                $order = isset($query_params['order'])
3566
-                    ? $this->_extract_order($query_params['order'])
3567
-                    : 'DESC';
3568
-                $query_object->set_order_by_sql(
3569
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3570
-                );
3571
-            }
3572
-        }
3573
-        // if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3574
-        if (
3575
-            ! array_key_exists('order_by', $query_params)
3576
-            && array_key_exists('order', $query_params)
3577
-            && ! empty($query_params['order'])
3578
-        ) {
3579
-            $pk_field = $this->get_primary_key_field();
3580
-            $order    = $this->_extract_order($query_params['order']);
3581
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3582
-        }
3583
-        // set group by
3584
-        if (array_key_exists('group_by', $query_params)) {
3585
-            if (is_array($query_params['group_by'])) {
3586
-                // it's an array, so assume we'll be grouping by a bunch of stuff
3587
-                $group_by_array = [];
3588
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3589
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3590
-                }
3591
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3592
-            } elseif (! empty($query_params['group_by'])) {
3593
-                $query_object->set_group_by_sql(
3594
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3595
-                );
3596
-            }
3597
-        }
3598
-        // set having
3599
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3600
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3601
-        }
3602
-        // now, just verify they didn't pass anything wack
3603
-        foreach ($query_params as $query_key => $query_value) {
3604
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3605
-                throw new EE_Error(
3606
-                    sprintf(
3607
-                        esc_html__(
3608
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3609
-                            'event_espresso'
3610
-                        ),
3611
-                        $query_key,
3612
-                        get_class($this),
3613
-                        //                      print_r( $this->_allowed_query_params, TRUE )
3614
-                        implode(',', $this->_allowed_query_params)
3615
-                    )
3616
-                );
3617
-            }
3618
-        }
3619
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3620
-        if (empty($main_model_join_sql)) {
3621
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3622
-        }
3623
-        return $query_object;
3624
-    }
3625
-
3626
-
3627
-    /**
3628
-     * Gets the where conditions that should be imposed on the query based on the
3629
-     * context (eg reading frontend, backend, edit or delete).
3630
-     *
3631
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3632
-     * @return array
3633
-     * @throws EE_Error
3634
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3635
-     */
3636
-    public function caps_where_conditions($context = self::caps_read)
3637
-    {
3638
-        EEM_Base::verify_is_valid_cap_context($context);
3639
-        $cap_where_conditions = [];
3640
-        $cap_restrictions     = $this->caps_missing($context);
3641
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3642
-            $cap_where_conditions = array_replace_recursive(
3643
-                $cap_where_conditions,
3644
-                $restriction_if_no_cap->get_default_where_conditions()
3645
-            );
3646
-        }
3647
-        return apply_filters(
3648
-            'FHEE__EEM_Base__caps_where_conditions__return',
3649
-            $cap_where_conditions,
3650
-            $this,
3651
-            $context,
3652
-            $cap_restrictions
3653
-        );
3654
-    }
3655
-
3656
-
3657
-    /**
3658
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3659
-     * otherwise throws an exception
3660
-     *
3661
-     * @param string $should_be_order_string
3662
-     * @return string either ASC, asc, DESC or desc
3663
-     * @throws EE_Error
3664
-     */
3665
-    private function _extract_order($should_be_order_string)
3666
-    {
3667
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3668
-            return $should_be_order_string;
3669
-        }
3670
-        throw new EE_Error(
3671
-            sprintf(
3672
-                esc_html__(
3673
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3674
-                    "event_espresso"
3675
-                ),
3676
-                get_class($this),
3677
-                $should_be_order_string
3678
-            )
3679
-        );
3680
-    }
3681
-
3682
-
3683
-    /**
3684
-     * Looks at all the models which are included in this query, and asks each
3685
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3686
-     * so they can be merged
3687
-     *
3688
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3689
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3690
-     *                                                                  'none' means NO default where conditions will
3691
-     *                                                                  be used AT ALL during this query.
3692
-     *                                                                  'other_models_only' means default where
3693
-     *                                                                  conditions from other models will be used, but
3694
-     *                                                                  not for this primary model. 'all', the default,
3695
-     *                                                                  means default where conditions will apply as
3696
-     *                                                                  normal
3697
-     * @param array                       $where_query_params
3698
-     * @return array
3699
-     * @throws EE_Error
3700
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3701
-     */
3702
-    private function _get_default_where_conditions_for_models_in_query(
3703
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3704
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3705
-        $where_query_params = []
3706
-    ) {
3707
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3708
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3709
-            throw new EE_Error(
3710
-                sprintf(
3711
-                    esc_html__(
3712
-                        "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3713
-                        "event_espresso"
3714
-                    ),
3715
-                    $use_default_where_conditions,
3716
-                    implode(", ", $allowed_used_default_where_conditions_values)
3717
-                )
3718
-            );
3719
-        }
3720
-        $universal_query_params = [];
3721
-        if ($this->_should_use_default_where_conditions($use_default_where_conditions)) {
3722
-            $universal_query_params = $this->_get_default_where_conditions();
3723
-        } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions)) {
3724
-            $universal_query_params = $this->_get_minimum_where_conditions();
3725
-        }
3726
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3727
-            $related_model = $this->get_related_model_obj($model_name);
3728
-            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3729
-                $related_model_universal_where_params =
3730
-                    $related_model->_get_default_where_conditions($model_relation_path);
3731
-            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3732
-                $related_model_universal_where_params =
3733
-                    $related_model->_get_minimum_where_conditions($model_relation_path);
3734
-            } else {
3735
-                // we don't want to add full or even minimum default where conditions from this model, so just continue
3736
-                continue;
3737
-            }
3738
-            $overrides              = $this->_override_defaults_or_make_null_friendly(
3739
-                $related_model_universal_where_params,
3740
-                $where_query_params,
3741
-                $related_model,
3742
-                $model_relation_path
3743
-            );
3744
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3745
-                $universal_query_params,
3746
-                $overrides
3747
-            );
3748
-        }
3749
-        return $universal_query_params;
3750
-    }
3751
-
3752
-
3753
-    /**
3754
-     * Determines whether or not we should use default where conditions for the model in question
3755
-     * (this model, or other related models).
3756
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3757
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3758
-     * We should use default where conditions on related models when they requested to use default where conditions
3759
-     * on all models, or specifically just on other related models
3760
-     *
3761
-     * @param      $default_where_conditions_value
3762
-     * @param bool $for_this_model false means this is for OTHER related models
3763
-     * @return bool
3764
-     */
3765
-    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3766
-    {
3767
-        return (
3768
-                   $for_this_model
3769
-                   && in_array(
3770
-                       $default_where_conditions_value,
3771
-                       [
3772
-                           EEM_Base::default_where_conditions_all,
3773
-                           EEM_Base::default_where_conditions_this_only,
3774
-                           EEM_Base::default_where_conditions_minimum_others,
3775
-                       ],
3776
-                       true
3777
-                   )
3778
-               )
3779
-               || (
3780
-                   ! $for_this_model
3781
-                   && in_array(
3782
-                       $default_where_conditions_value,
3783
-                       [
3784
-                           EEM_Base::default_where_conditions_all,
3785
-                           EEM_Base::default_where_conditions_others_only,
3786
-                       ],
3787
-                       true
3788
-                   )
3789
-               );
3790
-    }
3791
-
3792
-
3793
-    /**
3794
-     * Determines whether or not we should use default minimum conditions for the model in question
3795
-     * (this model, or other related models).
3796
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3797
-     * where conditions.
3798
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3799
-     * on this model or others
3800
-     *
3801
-     * @param      $default_where_conditions_value
3802
-     * @param bool $for_this_model false means this is for OTHER related models
3803
-     * @return bool
3804
-     */
3805
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3806
-    {
3807
-        return (
3808
-                   $for_this_model
3809
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3810
-               )
3811
-               || (
3812
-                   ! $for_this_model
3813
-                   && in_array(
3814
-                       $default_where_conditions_value,
3815
-                       [
3816
-                           EEM_Base::default_where_conditions_minimum_others,
3817
-                           EEM_Base::default_where_conditions_minimum_all,
3818
-                       ],
3819
-                       true
3820
-                   )
3821
-               );
3822
-    }
3823
-
3824
-
3825
-    /**
3826
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3827
-     * then we also add a special where condition which allows for that model's primary key
3828
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3829
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3830
-     *
3831
-     * @param array    $default_where_conditions
3832
-     * @param array    $provided_where_conditions
3833
-     * @param EEM_Base $model
3834
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3835
-     * @return array
3836
-     * @throws EE_Error
3837
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3838
-     */
3839
-    private function _override_defaults_or_make_null_friendly(
3840
-        $default_where_conditions,
3841
-        $provided_where_conditions,
3842
-        $model,
3843
-        $model_relation_path
3844
-    ) {
3845
-        $null_friendly_where_conditions = [];
3846
-        $none_overridden                = true;
3847
-        $or_condition_key_for_defaults  = 'OR*' . get_class($model);
3848
-        foreach ($default_where_conditions as $key => $val) {
3849
-            if (isset($provided_where_conditions[ $key ])) {
3850
-                $none_overridden = false;
3851
-            } else {
3852
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3853
-            }
3854
-        }
3855
-        if ($none_overridden && $default_where_conditions) {
3856
-            if ($model->has_primary_key_field()) {
3857
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3858
-                                                                                   . "."
3859
-                                                                                   . $model->primary_key_name() ] =
3860
-                    ['IS NULL'];
3861
-            }/*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 = "SELECT COUNT('{$column_to_count}')" . $this->_construct_2nd_half_of_select_query($model_query_info);
2288
+		return (int) $this->_do_wpdb_query('get_var', [$SQL]);
2289
+	}
2290
+
2291
+
2292
+	/**
2293
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2294
+	 *
2295
+	 * @param array  $query_params
2296
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2297
+	 * @return float
2298
+	 * @throws EE_Error
2299
+	 * @throws ReflectionException
2300
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2301
+	 */
2302
+	public function sum($query_params, $field_to_sum = null)
2303
+	{
2304
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2305
+		$field_obj = $field_to_sum
2306
+			? $this->field_settings_for($field_to_sum)
2307
+			: $this->get_primary_key_field();
2308
+		$column_to_count = $field_obj->get_qualified_column();
2309
+		$SQL             = "SELECT SUM('{$column_to_count}')"
2310
+						   . $this->_construct_2nd_half_of_select_query($model_query_info);
2311
+		$return_value    = $this->_do_wpdb_query('get_var', [$SQL]);
2312
+		$data_type       = $field_obj->get_wpdb_data_type();
2313
+		if ($data_type === '%d' || $data_type === '%s') {
2314
+			return (float) $return_value;
2315
+		}
2316
+		// must be %f
2317
+		return (float) $return_value;
2318
+	}
2319
+
2320
+
2321
+	/**
2322
+	 * Just calls the specified method on $wpdb with the given arguments
2323
+	 * Consolidates a little extra error handling code
2324
+	 *
2325
+	 * @param string $wpdb_method
2326
+	 * @param array  $arguments_to_provide
2327
+	 * @return mixed
2328
+	 * @throws EE_Error
2329
+	 * @global wpdb  $wpdb
2330
+	 */
2331
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2332
+	{
2333
+		// if we're in maintenance mode level 2, DON'T run any queries
2334
+		// because level 2 indicates the database needs updating and
2335
+		// is probably out of sync with the code
2336
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2337
+			throw new EE_Error(
2338
+				sprintf(
2339
+					esc_html__(
2340
+						"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.",
2341
+						"event_espresso"
2342
+					)
2343
+				)
2344
+			);
2345
+		}
2346
+		global $wpdb;
2347
+		if (! method_exists($wpdb, $wpdb_method)) {
2348
+			throw new EE_Error(
2349
+				sprintf(
2350
+					esc_html__(
2351
+						'There is no method named "%s" on Wordpress\' $wpdb object',
2352
+						'event_espresso'
2353
+					),
2354
+					$wpdb_method
2355
+				)
2356
+			);
2357
+		}
2358
+		$old_show_errors_value = $wpdb->show_errors;
2359
+		if (WP_DEBUG) {
2360
+			$wpdb->show_errors(false);
2361
+		}
2362
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2363
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2364
+		if (WP_DEBUG) {
2365
+			$wpdb->show_errors($old_show_errors_value);
2366
+			if (! empty($wpdb->last_error)) {
2367
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2368
+			}
2369
+			if ($result === false) {
2370
+				throw new EE_Error(
2371
+					sprintf(
2372
+						esc_html__(
2373
+							'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2374
+							'event_espresso'
2375
+						),
2376
+						$wpdb_method,
2377
+						var_export($arguments_to_provide, true)
2378
+					)
2379
+				);
2380
+			}
2381
+		} elseif ($result === false) {
2382
+			EE_Error::add_error(
2383
+				sprintf(
2384
+					esc_html__(
2385
+						'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"',
2386
+						'event_espresso'
2387
+					),
2388
+					$wpdb_method,
2389
+					var_export($arguments_to_provide, true),
2390
+					$wpdb->last_error
2391
+				),
2392
+				__FILE__,
2393
+				__FUNCTION__,
2394
+				__LINE__
2395
+			);
2396
+		}
2397
+		return $result;
2398
+	}
2399
+
2400
+
2401
+	/**
2402
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2403
+	 * and if there's an error tries to verify the DB is correct. Uses
2404
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2405
+	 * we should try to fix the EE core db, the addons, or just give up
2406
+	 *
2407
+	 * @param string $wpdb_method
2408
+	 * @param array  $arguments_to_provide
2409
+	 * @return mixed
2410
+	 * @throws EE_Error
2411
+	 */
2412
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2413
+	{
2414
+		global $wpdb;
2415
+		$wpdb->last_error = null;
2416
+		$result           = call_user_func_array([$wpdb, $wpdb_method], $arguments_to_provide);
2417
+		// was there an error running the query? but we don't care on new activations
2418
+		// (we're going to setup the DB anyway on new activations)
2419
+		if (
2420
+			($result === false || ! empty($wpdb->last_error))
2421
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2422
+		) {
2423
+			switch (EEM_Base::$_db_verification_level) {
2424
+				case EEM_Base::db_verified_none:
2425
+					// let's double-check core's DB
2426
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2427
+					break;
2428
+				case EEM_Base::db_verified_core:
2429
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2430
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2431
+					break;
2432
+				case EEM_Base::db_verified_addons:
2433
+					// ummmm... you in trouble
2434
+					return $result;
2435
+			}
2436
+			if (! empty($error_message)) {
2437
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2438
+				trigger_error($error_message);
2439
+			}
2440
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2441
+		}
2442
+		return $result;
2443
+	}
2444
+
2445
+
2446
+	/**
2447
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2448
+	 * EEM_Base::$_db_verification_level
2449
+	 *
2450
+	 * @param string $wpdb_method
2451
+	 * @param array  $arguments_to_provide
2452
+	 * @return string
2453
+	 * @throws EE_Error
2454
+	 */
2455
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2456
+	{
2457
+		global $wpdb;
2458
+		// ok remember that we've already attempted fixing the core db, in case the problem persists
2459
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2460
+		$error_message                    = sprintf(
2461
+			esc_html__(
2462
+				'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2463
+				'event_espresso'
2464
+			),
2465
+			$wpdb->last_error,
2466
+			$wpdb_method,
2467
+			wp_json_encode($arguments_to_provide)
2468
+		);
2469
+		EE_System::instance()->initialize_db_if_no_migrations_required();
2470
+		return $error_message;
2471
+	}
2472
+
2473
+
2474
+	/**
2475
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2476
+	 * EEM_Base::$_db_verification_level
2477
+	 *
2478
+	 * @param $wpdb_method
2479
+	 * @param $arguments_to_provide
2480
+	 * @return string
2481
+	 * @throws EE_Error
2482
+	 */
2483
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2484
+	{
2485
+		global $wpdb;
2486
+		// ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2487
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2488
+		$error_message                    = sprintf(
2489
+			esc_html__(
2490
+				'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2491
+				'event_espresso'
2492
+			),
2493
+			$wpdb->last_error,
2494
+			$wpdb_method,
2495
+			wp_json_encode($arguments_to_provide)
2496
+		);
2497
+		EE_System::instance()->initialize_addons();
2498
+		return $error_message;
2499
+	}
2500
+
2501
+
2502
+	/**
2503
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2504
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2505
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2506
+	 * ..."
2507
+	 *
2508
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2509
+	 * @return string
2510
+	 */
2511
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2512
+	{
2513
+		return " FROM " . $model_query_info->get_full_join_sql() .
2514
+			   $model_query_info->get_where_sql() .
2515
+			   $model_query_info->get_group_by_sql() .
2516
+			   $model_query_info->get_having_sql() .
2517
+			   $model_query_info->get_order_by_sql() .
2518
+			   $model_query_info->get_limit_sql();
2519
+	}
2520
+
2521
+
2522
+	/**
2523
+	 * Set to easily debug the next X queries ran from this model.
2524
+	 *
2525
+	 * @param int $count
2526
+	 */
2527
+	public function show_next_x_db_queries($count = 1)
2528
+	{
2529
+		$this->_show_next_x_db_queries = $count;
2530
+	}
2531
+
2532
+
2533
+	/**
2534
+	 * @param $sql_query
2535
+	 */
2536
+	public function show_db_query_if_previously_requested($sql_query)
2537
+	{
2538
+		if ($this->_show_next_x_db_queries > 0) {
2539
+			echo $sql_query;
2540
+			$this->_show_next_x_db_queries--;
2541
+		}
2542
+	}
2543
+
2544
+
2545
+	/**
2546
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2547
+	 * There are the 3 cases:
2548
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2549
+	 * $otherModelObject has no ID, it is first saved.
2550
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2551
+	 * has no ID, it is first saved.
2552
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2553
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2554
+	 * join table
2555
+	 *
2556
+	 * @param EE_Base_Class                     /int $thisModelObject
2557
+	 * @param EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2558
+	 * @param string $relationName                     , key in EEM_Base::_relations
2559
+	 *                                                 an attendee to a group, you also want to specify which role they
2560
+	 *                                                 will have in that group. So you would use this parameter to
2561
+	 *                                                 specify array('role-column-name'=>'role-id')
2562
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2563
+	 *                                                 to for relation to methods that allow you to further specify
2564
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2565
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2566
+	 *                                                 because these will be inserted in any new rows created as well.
2567
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2568
+	 * @throws EE_Error
2569
+	 */
2570
+	public function add_relationship_to(
2571
+		$id_or_obj,
2572
+		$other_model_id_or_obj,
2573
+		$relationName,
2574
+		$extra_join_model_fields_n_values = []
2575
+	) {
2576
+		$relation_obj = $this->related_settings_for($relationName);
2577
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2578
+	}
2579
+
2580
+
2581
+	/**
2582
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2583
+	 * There are the 3 cases:
2584
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2585
+	 * error
2586
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2587
+	 * an error
2588
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2589
+	 *
2590
+	 * @param EE_Base_Class /int $id_or_obj
2591
+	 * @param EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2592
+	 * @param string $relationName key in EEM_Base::_relations
2593
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2594
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2595
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2596
+	 *                             because these will be inserted in any new rows created as well.
2597
+	 * @return boolean of success
2598
+	 * @throws EE_Error
2599
+	 */
2600
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = [])
2601
+	{
2602
+		$relation_obj = $this->related_settings_for($relationName);
2603
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2604
+	}
2605
+
2606
+
2607
+	/**
2608
+	 * @param mixed  $id_or_obj
2609
+	 * @param string $relationName
2610
+	 * @param array  $where_query_params
2611
+	 * @param EE_Base_Class[] objects to which relations were removed
2612
+	 * @return EE_Base_Class[]
2613
+	 * @throws EE_Error
2614
+	 */
2615
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = [])
2616
+	{
2617
+		$relation_obj = $this->related_settings_for($relationName);
2618
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2619
+	}
2620
+
2621
+
2622
+	/**
2623
+	 * Gets all the related items of the specified $model_name, using $query_params.
2624
+	 * Note: by default, we remove the "default query params"
2625
+	 * because we want to get even deleted items etc.
2626
+	 *
2627
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2628
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2629
+	 * @param array  $query_params see github link below for more info
2630
+	 * @return EE_Base_Class[]
2631
+	 * @throws EE_Error
2632
+	 * @throws ReflectionException
2633
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2634
+	 */
2635
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2636
+	{
2637
+		$model_obj         = $this->ensure_is_obj($id_or_obj);
2638
+		$relation_settings = $this->related_settings_for($model_name);
2639
+		return $relation_settings->get_all_related($model_obj, $query_params);
2640
+	}
2641
+
2642
+
2643
+	/**
2644
+	 * Deletes all the model objects across the relation indicated by $model_name
2645
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2646
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2647
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2648
+	 *
2649
+	 * @param EE_Base_Class|int|string $id_or_obj
2650
+	 * @param string                   $model_name
2651
+	 * @param array                    $query_params
2652
+	 * @return int how many deleted
2653
+	 * @throws EE_Error
2654
+	 * @throws ReflectionException
2655
+	 */
2656
+	public function delete_related($id_or_obj, $model_name, $query_params = [])
2657
+	{
2658
+		$model_obj         = $this->ensure_is_obj($id_or_obj);
2659
+		$relation_settings = $this->related_settings_for($model_name);
2660
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2661
+	}
2662
+
2663
+
2664
+	/**
2665
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2666
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2667
+	 * the model objects can't be hard deleted because of blocking related model objects,
2668
+	 * just does a soft-delete on them instead.
2669
+	 *
2670
+	 * @param EE_Base_Class|int|string $id_or_obj
2671
+	 * @param string                   $model_name
2672
+	 * @param array                    $query_params
2673
+	 * @return int how many deleted
2674
+	 * @throws EE_Error
2675
+	 * @throws ReflectionException
2676
+	 */
2677
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = [])
2678
+	{
2679
+		$model_obj         = $this->ensure_is_obj($id_or_obj);
2680
+		$relation_settings = $this->related_settings_for($model_name);
2681
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2682
+	}
2683
+
2684
+
2685
+	/**
2686
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2687
+	 * unless otherwise specified in the $query_params
2688
+	 *
2689
+	 * @param int             /EE_Base_Class $id_or_obj
2690
+	 * @param string $model_name     like 'Event', or 'Registration'
2691
+	 * @param array  $query_params
2692
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2693
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2694
+	 *                               that by the setting $distinct to TRUE;
2695
+	 * @return int
2696
+	 * @throws EE_Error
2697
+	 * @throws ReflectionException
2698
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2699
+	 */
2700
+	public function count_related(
2701
+		$id_or_obj,
2702
+		$model_name,
2703
+		$query_params = [],
2704
+		$field_to_count = null,
2705
+		$distinct = false
2706
+	) {
2707
+		$related_model = $this->get_related_model_obj($model_name);
2708
+		// we're just going to use the query params on the related model's normal get_all query,
2709
+		// except add a condition to say to match the current mod
2710
+		if (! isset($query_params['default_where_conditions'])) {
2711
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2712
+		}
2713
+		$this_model_name                                                 = $this->get_this_model_name();
2714
+		$this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2715
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2716
+		return $related_model->count($query_params, $field_to_count, $distinct);
2717
+	}
2718
+
2719
+
2720
+	/**
2721
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2722
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2723
+	 *
2724
+	 * @param int           /EE_Base_Class $id_or_obj
2725
+	 * @param string $model_name   like 'Event', or 'Registration'
2726
+	 * @param array  $query_params
2727
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2728
+	 * @return float
2729
+	 * @throws EE_Error
2730
+	 * @throws ReflectionException
2731
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2732
+	 */
2733
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2734
+	{
2735
+		$related_model = $this->get_related_model_obj($model_name);
2736
+		if (! is_array($query_params)) {
2737
+			EE_Error::doing_it_wrong(
2738
+				'EEM_Base::sum_related',
2739
+				sprintf(
2740
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2741
+					gettype($query_params)
2742
+				),
2743
+				'4.6.0'
2744
+			);
2745
+			$query_params = [];
2746
+		}
2747
+		// we're just going to use the query params on the related model's normal get_all query,
2748
+		// except add a condition to say to match the current mod
2749
+		if (! isset($query_params['default_where_conditions'])) {
2750
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2751
+		}
2752
+		$this_model_name                                                 = $this->get_this_model_name();
2753
+		$this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2754
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2755
+		return $related_model->sum($query_params, $field_to_sum);
2756
+	}
2757
+
2758
+
2759
+	/**
2760
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2761
+	 * $modelObject
2762
+	 *
2763
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2764
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2765
+	 * @param array               $query_params     see github link below for more info
2766
+	 * @return EE_Base_Class
2767
+	 * @throws EE_Error
2768
+	 * @throws ReflectionException
2769
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2770
+	 */
2771
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2772
+	{
2773
+		$query_params['limit'] = 1;
2774
+		$results               = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2775
+		if ($results) {
2776
+			return array_shift($results);
2777
+		}
2778
+		return null;
2779
+	}
2780
+
2781
+
2782
+	/**
2783
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2784
+	 *
2785
+	 * @return string
2786
+	 */
2787
+	public function get_this_model_name()
2788
+	{
2789
+		return str_replace("EEM_", "", get_class($this));
2790
+	}
2791
+
2792
+
2793
+	/**
2794
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2795
+	 *
2796
+	 * @return EE_Any_Foreign_Model_Name_Field
2797
+	 * @throws EE_Error
2798
+	 */
2799
+	public function get_field_containing_related_model_name()
2800
+	{
2801
+		foreach ($this->field_settings(true) as $field) {
2802
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2803
+				$field_with_model_name = $field;
2804
+			}
2805
+		}
2806
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2807
+			throw new EE_Error(
2808
+				sprintf(
2809
+					esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2810
+					$this->get_this_model_name()
2811
+				)
2812
+			);
2813
+		}
2814
+		return $field_with_model_name;
2815
+	}
2816
+
2817
+
2818
+	/**
2819
+	 * Inserts a new entry into the database, for each table.
2820
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2821
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2822
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2823
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2824
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2825
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2826
+	 *
2827
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2828
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2829
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2830
+	 *                              of EEM_Base)
2831
+	 * @return int|string new primary key on main table that got inserted
2832
+	 * @throws EE_Error
2833
+	 * @throws ReflectionException
2834
+	 */
2835
+	public function insert($field_n_values)
2836
+	{
2837
+		/**
2838
+		 * Filters the fields and their values before inserting an item using the models
2839
+		 *
2840
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2841
+		 * @param EEM_Base $model           the model used
2842
+		 */
2843
+		$field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2844
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2845
+			$main_table = $this->_get_main_table();
2846
+			$new_id     = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2847
+			if ($new_id !== false) {
2848
+				foreach ($this->_get_other_tables() as $other_table) {
2849
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2850
+				}
2851
+			}
2852
+			/**
2853
+			 * Done just after attempting to insert a new model object
2854
+			 *
2855
+			 * @param EEM_Base $model           used
2856
+			 * @param array    $fields_n_values fields and their values
2857
+			 * @param int|string the              ID of the newly-inserted model object
2858
+			 */
2859
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2860
+			return $new_id;
2861
+		}
2862
+		return false;
2863
+	}
2864
+
2865
+
2866
+	/**
2867
+	 * Checks that the result would satisfy the unique indexes on this model
2868
+	 *
2869
+	 * @param array  $field_n_values
2870
+	 * @param string $action
2871
+	 * @return boolean
2872
+	 * @throws EE_Error
2873
+	 * @throws ReflectionException
2874
+	 */
2875
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2876
+	{
2877
+		foreach ($this->unique_indexes() as $index_name => $index) {
2878
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2879
+			if ($this->exists([$uniqueness_where_params])) {
2880
+				EE_Error::add_error(
2881
+					sprintf(
2882
+						esc_html__(
2883
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2884
+							"event_espresso"
2885
+						),
2886
+						$action,
2887
+						$this->_get_class_name(),
2888
+						$index_name,
2889
+						implode(",", $index->field_names()),
2890
+						http_build_query($uniqueness_where_params)
2891
+					),
2892
+					__FILE__,
2893
+					__FUNCTION__,
2894
+					__LINE__
2895
+				);
2896
+				return false;
2897
+			}
2898
+		}
2899
+		return true;
2900
+	}
2901
+
2902
+
2903
+	/**
2904
+	 * Checks the database for an item that conflicts (ie, if this item were
2905
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2906
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2907
+	 * can be either an EE_Base_Class or an array of fields n values
2908
+	 *
2909
+	 * @param EE_Base_Class|array $obj_or_fields_array
2910
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2911
+	 *                                                 when looking for conflicts
2912
+	 *                                                 (ie, if false, we ignore the model object's primary key
2913
+	 *                                                 when finding "conflicts". If true, it's also considered).
2914
+	 *                                                 Only works for INT primary key,
2915
+	 *                                                 STRING primary keys cannot be ignored
2916
+	 * @return EE_Base_Class|array
2917
+	 * @throws EE_Error
2918
+	 * @throws ReflectionException
2919
+	 */
2920
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2921
+	{
2922
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2923
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2924
+		} elseif (is_array($obj_or_fields_array)) {
2925
+			$fields_n_values = $obj_or_fields_array;
2926
+		} else {
2927
+			throw new EE_Error(
2928
+				sprintf(
2929
+					esc_html__(
2930
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2931
+						"event_espresso"
2932
+					),
2933
+					get_class($this),
2934
+					$obj_or_fields_array
2935
+				)
2936
+			);
2937
+		}
2938
+		$query_params = [];
2939
+		if (
2940
+			$this->has_primary_key_field()
2941
+			&& ($include_primary_key
2942
+				|| $this->get_primary_key_field()
2943
+				   instanceof
2944
+				   EE_Primary_Key_String_Field)
2945
+			&& isset($fields_n_values[ $this->primary_key_name() ])
2946
+		) {
2947
+			$query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2948
+		}
2949
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2950
+			$uniqueness_where_params                              =
2951
+				array_intersect_key($fields_n_values, $unique_index->fields());
2952
+			$query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2953
+		}
2954
+		// if there is nothing to base this search on, then we shouldn't find anything
2955
+		if (empty($query_params)) {
2956
+			return [];
2957
+		}
2958
+		return $this->get_one($query_params);
2959
+	}
2960
+
2961
+
2962
+	/**
2963
+	 * Like count, but is optimized and returns a boolean instead of an int
2964
+	 *
2965
+	 * @param array $query_params
2966
+	 * @return boolean
2967
+	 * @throws EE_Error
2968
+	 * @throws ReflectionException
2969
+	 */
2970
+	public function exists($query_params)
2971
+	{
2972
+		$query_params['limit'] = 1;
2973
+		return $this->count($query_params) > 0;
2974
+	}
2975
+
2976
+
2977
+	/**
2978
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2979
+	 *
2980
+	 * @param int|string $id
2981
+	 * @return boolean
2982
+	 * @throws EE_Error
2983
+	 * @throws ReflectionException
2984
+	 */
2985
+	public function exists_by_ID($id)
2986
+	{
2987
+		return $this->exists(
2988
+			[
2989
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2990
+				[
2991
+					$this->primary_key_name() => $id,
2992
+				],
2993
+			]
2994
+		);
2995
+	}
2996
+
2997
+
2998
+	/**
2999
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
3000
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
3001
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
3002
+	 * on the main table)
3003
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
3004
+	 * cases where we want to call it directly rather than via insert().
3005
+	 *
3006
+	 * @access   protected
3007
+	 * @param EE_Table_Base $table
3008
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
3009
+	 *                                       float
3010
+	 * @param int           $new_id          for now we assume only int keys
3011
+	 * @return int ID of new row inserted, or FALSE on failure
3012
+	 * @throws EE_Error
3013
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
3014
+	 */
3015
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
3016
+	{
3017
+		global $wpdb;
3018
+		$insertion_col_n_values = [];
3019
+		$format_for_insertion   = [];
3020
+		$fields_on_table        = $this->_get_fields_for_table($table->get_table_alias());
3021
+		foreach ($fields_on_table as $field_name => $field_obj) {
3022
+			// check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
3023
+			if ($field_obj->is_auto_increment()) {
3024
+				continue;
3025
+			}
3026
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3027
+			// if the value we want to assign it to is NULL, just don't mention it for the insertion
3028
+			if ($prepared_value !== null) {
3029
+				$insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3030
+				$format_for_insertion[]                                   = $field_obj->get_wpdb_data_type();
3031
+			}
3032
+		}
3033
+		if ($table instanceof EE_Secondary_Table && $new_id) {
3034
+			// its not the main table, so we should have already saved the main table's PK which we just inserted
3035
+			// so add the fk to the main table as a column
3036
+			$insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3037
+			$format_for_insertion[]                              =
3038
+				'%d';// yes right now we're only allowing these foreign keys to be INTs
3039
+		}
3040
+		// insert the new entry
3041
+		$result = $this->_do_wpdb_query(
3042
+			'insert',
3043
+			[$table->get_table_name(), $insertion_col_n_values, $format_for_insertion]
3044
+		);
3045
+		if ($result === false) {
3046
+			return false;
3047
+		}
3048
+		// ok, now what do we return for the ID of the newly-inserted thing?
3049
+		if ($this->has_primary_key_field()) {
3050
+			if ($this->get_primary_key_field()->is_auto_increment()) {
3051
+				return $wpdb->insert_id;
3052
+			}
3053
+			// it's not an auto-increment primary key, so
3054
+			// it must have been supplied
3055
+			return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3056
+		}
3057
+		// we can't return a  primary key because there is none. instead return
3058
+		// a unique string indicating this model
3059
+		return $this->get_index_primary_key_string($fields_n_values);
3060
+	}
3061
+
3062
+
3063
+	/**
3064
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3065
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3066
+	 * and there is no default, we pass it along. WPDB will take care of it)
3067
+	 *
3068
+	 * @param EE_Model_Field_Base $field_obj
3069
+	 * @param array               $fields_n_values
3070
+	 * @return mixed string|int|float depending on what the table column will be expecting
3071
+	 * @throws EE_Error
3072
+	 */
3073
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3074
+	{
3075
+		// if this field doesn't allow nullable, don't allow it
3076
+		if (
3077
+			! $field_obj->is_nullable()
3078
+			&& (
3079
+				! isset($fields_n_values[ $field_obj->get_name() ])
3080
+				|| $fields_n_values[ $field_obj->get_name() ] === null
3081
+			)
3082
+		) {
3083
+			$fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3084
+		}
3085
+		$unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3086
+			? $fields_n_values[ $field_obj->get_name() ]
3087
+			: null;
3088
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3089
+	}
3090
+
3091
+
3092
+	/**
3093
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3094
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3095
+	 * the field's prepare_for_set() method.
3096
+	 *
3097
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3098
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3099
+	 *                                   top of file)
3100
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3101
+	 *                                   $value is a custom selection
3102
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3103
+	 */
3104
+	private function _prepare_value_for_use_in_db($value, $field)
3105
+	{
3106
+		if ($field && $field instanceof EE_Model_Field_Base) {
3107
+			// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3108
+			switch ($this->_values_already_prepared_by_model_object) {
3109
+				/** @noinspection PhpMissingBreakStatementInspection */
3110
+				case self::not_prepared_by_model_object:
3111
+					$value = $field->prepare_for_set($value);
3112
+				// purposefully left out "return"
3113
+				case self::prepared_by_model_object:
3114
+					/** @noinspection SuspiciousAssignmentsInspection */
3115
+					$value = $field->prepare_for_use_in_db($value);
3116
+				case self::prepared_for_use_in_db:
3117
+					// leave the value alone
3118
+			}
3119
+			return $value;
3120
+			// phpcs:enable
3121
+		}
3122
+		return $value;
3123
+	}
3124
+
3125
+
3126
+	/**
3127
+	 * Returns the main table on this model
3128
+	 *
3129
+	 * @return EE_Primary_Table
3130
+	 * @throws EE_Error
3131
+	 */
3132
+	protected function _get_main_table()
3133
+	{
3134
+		foreach ($this->_tables as $table) {
3135
+			if ($table instanceof EE_Primary_Table) {
3136
+				return $table;
3137
+			}
3138
+		}
3139
+		throw new EE_Error(
3140
+			sprintf(
3141
+				esc_html__(
3142
+					'There are no main tables on %s. They should be added to _tables array in the constructor',
3143
+					'event_espresso'
3144
+				),
3145
+				get_class($this)
3146
+			)
3147
+		);
3148
+	}
3149
+
3150
+
3151
+	/**
3152
+	 * table
3153
+	 * returns EE_Primary_Table table name
3154
+	 *
3155
+	 * @return string
3156
+	 * @throws EE_Error
3157
+	 */
3158
+	public function table()
3159
+	{
3160
+		return $this->_get_main_table()->get_table_name();
3161
+	}
3162
+
3163
+
3164
+	/**
3165
+	 * table
3166
+	 * returns first EE_Secondary_Table table name
3167
+	 *
3168
+	 * @return string
3169
+	 */
3170
+	public function second_table()
3171
+	{
3172
+		// grab second table from tables array
3173
+		$second_table = end($this->_tables);
3174
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3175
+	}
3176
+
3177
+
3178
+	/**
3179
+	 * get_table_obj_by_alias
3180
+	 * returns table name given it's alias
3181
+	 *
3182
+	 * @param string $table_alias
3183
+	 * @return EE_Primary_Table | EE_Secondary_Table
3184
+	 */
3185
+	public function get_table_obj_by_alias($table_alias = '')
3186
+	{
3187
+		return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3188
+	}
3189
+
3190
+
3191
+	/**
3192
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3193
+	 *
3194
+	 * @return EE_Secondary_Table[]
3195
+	 */
3196
+	protected function _get_other_tables()
3197
+	{
3198
+		$other_tables = [];
3199
+		foreach ($this->_tables as $table_alias => $table) {
3200
+			if ($table instanceof EE_Secondary_Table) {
3201
+				$other_tables[ $table_alias ] = $table;
3202
+			}
3203
+		}
3204
+		return $other_tables;
3205
+	}
3206
+
3207
+
3208
+	/**
3209
+	 * Finds all the fields that correspond to the given table
3210
+	 *
3211
+	 * @param string $table_alias , array key in EEM_Base::_tables
3212
+	 * @return EE_Model_Field_Base[]
3213
+	 */
3214
+	public function _get_fields_for_table($table_alias)
3215
+	{
3216
+		return $this->_fields[ $table_alias ];
3217
+	}
3218
+
3219
+
3220
+	/**
3221
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3222
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3223
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3224
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3225
+	 * related Registration, Transaction, and Payment models.
3226
+	 *
3227
+	 * @param array $query_params see github link below for more info
3228
+	 * @return EE_Model_Query_Info_Carrier
3229
+	 * @throws EE_Error
3230
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3231
+	 */
3232
+	public function _extract_related_models_from_query($query_params)
3233
+	{
3234
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3235
+		if (array_key_exists(0, $query_params)) {
3236
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3237
+		}
3238
+		if (array_key_exists('group_by', $query_params)) {
3239
+			if (is_array($query_params['group_by'])) {
3240
+				$this->_extract_related_models_from_sub_params_array_values(
3241
+					$query_params['group_by'],
3242
+					$query_info_carrier,
3243
+					'group_by'
3244
+				);
3245
+			} elseif (! empty($query_params['group_by'])) {
3246
+				$this->_extract_related_model_info_from_query_param(
3247
+					$query_params['group_by'],
3248
+					$query_info_carrier,
3249
+					'group_by'
3250
+				);
3251
+			}
3252
+		}
3253
+		if (array_key_exists('having', $query_params)) {
3254
+			$this->_extract_related_models_from_sub_params_array_keys(
3255
+				$query_params[0],
3256
+				$query_info_carrier,
3257
+				'having'
3258
+			);
3259
+		}
3260
+		if (array_key_exists('order_by', $query_params)) {
3261
+			if (is_array($query_params['order_by'])) {
3262
+				$this->_extract_related_models_from_sub_params_array_keys(
3263
+					$query_params['order_by'],
3264
+					$query_info_carrier,
3265
+					'order_by'
3266
+				);
3267
+			} elseif (! empty($query_params['order_by'])) {
3268
+				$this->_extract_related_model_info_from_query_param(
3269
+					$query_params['order_by'],
3270
+					$query_info_carrier,
3271
+					'order_by'
3272
+				);
3273
+			}
3274
+		}
3275
+		if (array_key_exists('force_join', $query_params)) {
3276
+			$this->_extract_related_models_from_sub_params_array_values(
3277
+				$query_params['force_join'],
3278
+				$query_info_carrier,
3279
+				'force_join'
3280
+			);
3281
+		}
3282
+		$this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3283
+		return $query_info_carrier;
3284
+	}
3285
+
3286
+
3287
+	/**
3288
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3289
+	 *
3290
+	 * @param array                       $sub_query_params
3291
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3292
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3293
+	 * @return EE_Model_Query_Info_Carrier
3294
+	 * @throws EE_Error
3295
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3296
+	 */
3297
+	private function _extract_related_models_from_sub_params_array_keys(
3298
+		$sub_query_params,
3299
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3300
+		$query_param_type
3301
+	) {
3302
+		if (! empty($sub_query_params)) {
3303
+			$sub_query_params = (array) $sub_query_params;
3304
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3305
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3306
+				$this->_extract_related_model_info_from_query_param(
3307
+					$param,
3308
+					$model_query_info_carrier,
3309
+					$query_param_type
3310
+				);
3311
+				// if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3312
+				// indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3313
+				// extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3314
+				// of array('Registration.TXN_ID'=>23)
3315
+				$query_param_sans_stars =
3316
+					$this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3317
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3318
+					if (! is_array($possibly_array_of_params)) {
3319
+						throw new EE_Error(
3320
+							sprintf(
3321
+								esc_html__(
3322
+									"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'))",
3323
+									"event_espresso"
3324
+								),
3325
+								$param,
3326
+								$possibly_array_of_params
3327
+							)
3328
+						);
3329
+					}
3330
+					$this->_extract_related_models_from_sub_params_array_keys(
3331
+						$possibly_array_of_params,
3332
+						$model_query_info_carrier,
3333
+						$query_param_type
3334
+					);
3335
+				} elseif (
3336
+					$query_param_type === 0 // ie WHERE
3337
+					&& is_array($possibly_array_of_params)
3338
+					&& isset($possibly_array_of_params[2])
3339
+					&& $possibly_array_of_params[2] == true
3340
+				) {
3341
+					// then $possible_array_of_params looks something like array('<','DTT_sold',true)
3342
+					// indicating that $possible_array_of_params[1] is actually a field name,
3343
+					// from which we should extract query parameters!
3344
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3345
+						throw new EE_Error(
3346
+							sprintf(
3347
+								esc_html__(
3348
+									"Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3349
+									"event_espresso"
3350
+								),
3351
+								$query_param_type,
3352
+								implode(",", $possibly_array_of_params)
3353
+							)
3354
+						);
3355
+					}
3356
+					$this->_extract_related_model_info_from_query_param(
3357
+						$possibly_array_of_params[1],
3358
+						$model_query_info_carrier,
3359
+						$query_param_type
3360
+					);
3361
+				}
3362
+			}
3363
+		}
3364
+		return $model_query_info_carrier;
3365
+	}
3366
+
3367
+
3368
+	/**
3369
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3370
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3371
+	 *
3372
+	 * @param array                       $sub_query_params
3373
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3374
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3375
+	 * @return EE_Model_Query_Info_Carrier
3376
+	 * @throws EE_Error
3377
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3378
+	 */
3379
+	private function _extract_related_models_from_sub_params_array_values(
3380
+		$sub_query_params,
3381
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3382
+		$query_param_type
3383
+	) {
3384
+		if (! empty($sub_query_params)) {
3385
+			if (! is_array($sub_query_params)) {
3386
+				throw new EE_Error(
3387
+					sprintf(
3388
+						esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3389
+						$sub_query_params
3390
+					)
3391
+				);
3392
+			}
3393
+			foreach ($sub_query_params as $param) {
3394
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3395
+				$this->_extract_related_model_info_from_query_param(
3396
+					$param,
3397
+					$model_query_info_carrier,
3398
+					$query_param_type
3399
+				);
3400
+			}
3401
+		}
3402
+		return $model_query_info_carrier;
3403
+	}
3404
+
3405
+
3406
+	/**
3407
+	 * Extract all the query parts from  model query params
3408
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3409
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3410
+	 * but use them in a different order. Eg, we need to know what models we are querying
3411
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3412
+	 * other models before we can finalize the where clause SQL.
3413
+	 *
3414
+	 * @param array $query_params see github link below for more info
3415
+	 * @return EE_Model_Query_Info_Carrier
3416
+	 * @throws EE_Error
3417
+	 * @throws ModelConfigurationException
3418
+	 * @throws ReflectionException
3419
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3420
+	 */
3421
+	public function _create_model_query_info_carrier($query_params)
3422
+	{
3423
+		if (! is_array($query_params)) {
3424
+			EE_Error::doing_it_wrong(
3425
+				'EEM_Base::_create_model_query_info_carrier',
3426
+				sprintf(
3427
+					esc_html__(
3428
+						'$query_params should be an array, you passed a variable of type %s',
3429
+						'event_espresso'
3430
+					),
3431
+					gettype($query_params)
3432
+				),
3433
+				'4.6.0'
3434
+			);
3435
+			$query_params = [];
3436
+		}
3437
+		$query_params[0] = isset($query_params[0]) ? $query_params[0] : [];
3438
+		// first check if we should alter the query to account for caps or not
3439
+		// because the caps might require us to do extra joins
3440
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3441
+			$query_params[0] = array_replace_recursive(
3442
+				$query_params[0],
3443
+				$this->caps_where_conditions(
3444
+					$query_params['caps']
3445
+				)
3446
+			);
3447
+		}
3448
+
3449
+		// check if we should alter the query to remove data related to protected
3450
+		// custom post types
3451
+		if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3452
+			$where_param_key_for_password = $this->modelChainAndPassword();
3453
+			// only include if related to a cpt where no password has been set
3454
+			$query_params[0]['OR*nopassword'] = [
3455
+				$where_param_key_for_password       => '',
3456
+				$where_param_key_for_password . '*' => ['IS_NULL'],
3457
+			];
3458
+		}
3459
+		$query_object = $this->_extract_related_models_from_query($query_params);
3460
+		// verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3461
+		foreach ($query_params[0] as $key => $value) {
3462
+			if (is_int($key)) {
3463
+				throw new EE_Error(
3464
+					sprintf(
3465
+						esc_html__(
3466
+							"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.",
3467
+							"event_espresso"
3468
+						),
3469
+						$key,
3470
+						var_export($value, true),
3471
+						var_export($query_params, true),
3472
+						get_class($this)
3473
+					)
3474
+				);
3475
+			}
3476
+		}
3477
+		if (
3478
+			array_key_exists('default_where_conditions', $query_params)
3479
+			&& ! empty($query_params['default_where_conditions'])
3480
+		) {
3481
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3482
+		} else {
3483
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3484
+		}
3485
+		$query_params[0] = array_merge(
3486
+			$this->_get_default_where_conditions_for_models_in_query(
3487
+				$query_object,
3488
+				$use_default_where_conditions,
3489
+				$query_params[0]
3490
+			),
3491
+			$query_params[0]
3492
+		);
3493
+		$query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3494
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3495
+		// So we need to setup a subquery and use that for the main join.
3496
+		// Note for now this only works on the primary table for the model.
3497
+		// So for instance, you could set the limit array like this:
3498
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3499
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3500
+			$query_object->set_main_model_join_sql(
3501
+				$this->_construct_limit_join_select(
3502
+					$query_params['on_join_limit'][0],
3503
+					$query_params['on_join_limit'][1]
3504
+				)
3505
+			);
3506
+		}
3507
+		// set limit
3508
+		if (array_key_exists('limit', $query_params)) {
3509
+			if (is_array($query_params['limit'])) {
3510
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3511
+					$e = sprintf(
3512
+						esc_html__(
3513
+							"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)",
3514
+							"event_espresso"
3515
+						),
3516
+						http_build_query($query_params['limit'])
3517
+					);
3518
+					throw new EE_Error($e . "|" . $e);
3519
+				}
3520
+				// they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3521
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3522
+			} elseif (! empty($query_params['limit'])) {
3523
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3524
+			}
3525
+		}
3526
+		// set order by
3527
+		if (array_key_exists('order_by', $query_params)) {
3528
+			if (is_array($query_params['order_by'])) {
3529
+				// if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3530
+				// specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3531
+				// including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3532
+				if (array_key_exists('order', $query_params)) {
3533
+					throw new EE_Error(
3534
+						sprintf(
3535
+							esc_html__(
3536
+								"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 ",
3537
+								"event_espresso"
3538
+							),
3539
+							get_class($this),
3540
+							implode(", ", array_keys($query_params['order_by'])),
3541
+							implode(", ", $query_params['order_by']),
3542
+							$query_params['order']
3543
+						)
3544
+					);
3545
+				}
3546
+				$this->_extract_related_models_from_sub_params_array_keys(
3547
+					$query_params['order_by'],
3548
+					$query_object,
3549
+					'order_by'
3550
+				);
3551
+				// assume it's an array of fields to order by
3552
+				$order_array = [];
3553
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3554
+					$order         = $this->_extract_order($order);
3555
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3556
+				}
3557
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3558
+			} elseif (! empty($query_params['order_by'])) {
3559
+				$this->_extract_related_model_info_from_query_param(
3560
+					$query_params['order_by'],
3561
+					$query_object,
3562
+					'order',
3563
+					$query_params['order_by']
3564
+				);
3565
+				$order = isset($query_params['order'])
3566
+					? $this->_extract_order($query_params['order'])
3567
+					: 'DESC';
3568
+				$query_object->set_order_by_sql(
3569
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3570
+				);
3571
+			}
3572
+		}
3573
+		// if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3574
+		if (
3575
+			! array_key_exists('order_by', $query_params)
3576
+			&& array_key_exists('order', $query_params)
3577
+			&& ! empty($query_params['order'])
3578
+		) {
3579
+			$pk_field = $this->get_primary_key_field();
3580
+			$order    = $this->_extract_order($query_params['order']);
3581
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3582
+		}
3583
+		// set group by
3584
+		if (array_key_exists('group_by', $query_params)) {
3585
+			if (is_array($query_params['group_by'])) {
3586
+				// it's an array, so assume we'll be grouping by a bunch of stuff
3587
+				$group_by_array = [];
3588
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3589
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3590
+				}
3591
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3592
+			} elseif (! empty($query_params['group_by'])) {
3593
+				$query_object->set_group_by_sql(
3594
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3595
+				);
3596
+			}
3597
+		}
3598
+		// set having
3599
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3600
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3601
+		}
3602
+		// now, just verify they didn't pass anything wack
3603
+		foreach ($query_params as $query_key => $query_value) {
3604
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3605
+				throw new EE_Error(
3606
+					sprintf(
3607
+						esc_html__(
3608
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3609
+							'event_espresso'
3610
+						),
3611
+						$query_key,
3612
+						get_class($this),
3613
+						//                      print_r( $this->_allowed_query_params, TRUE )
3614
+						implode(',', $this->_allowed_query_params)
3615
+					)
3616
+				);
3617
+			}
3618
+		}
3619
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3620
+		if (empty($main_model_join_sql)) {
3621
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3622
+		}
3623
+		return $query_object;
3624
+	}
3625
+
3626
+
3627
+	/**
3628
+	 * Gets the where conditions that should be imposed on the query based on the
3629
+	 * context (eg reading frontend, backend, edit or delete).
3630
+	 *
3631
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3632
+	 * @return array
3633
+	 * @throws EE_Error
3634
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3635
+	 */
3636
+	public function caps_where_conditions($context = self::caps_read)
3637
+	{
3638
+		EEM_Base::verify_is_valid_cap_context($context);
3639
+		$cap_where_conditions = [];
3640
+		$cap_restrictions     = $this->caps_missing($context);
3641
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3642
+			$cap_where_conditions = array_replace_recursive(
3643
+				$cap_where_conditions,
3644
+				$restriction_if_no_cap->get_default_where_conditions()
3645
+			);
3646
+		}
3647
+		return apply_filters(
3648
+			'FHEE__EEM_Base__caps_where_conditions__return',
3649
+			$cap_where_conditions,
3650
+			$this,
3651
+			$context,
3652
+			$cap_restrictions
3653
+		);
3654
+	}
3655
+
3656
+
3657
+	/**
3658
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3659
+	 * otherwise throws an exception
3660
+	 *
3661
+	 * @param string $should_be_order_string
3662
+	 * @return string either ASC, asc, DESC or desc
3663
+	 * @throws EE_Error
3664
+	 */
3665
+	private function _extract_order($should_be_order_string)
3666
+	{
3667
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3668
+			return $should_be_order_string;
3669
+		}
3670
+		throw new EE_Error(
3671
+			sprintf(
3672
+				esc_html__(
3673
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3674
+					"event_espresso"
3675
+				),
3676
+				get_class($this),
3677
+				$should_be_order_string
3678
+			)
3679
+		);
3680
+	}
3681
+
3682
+
3683
+	/**
3684
+	 * Looks at all the models which are included in this query, and asks each
3685
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3686
+	 * so they can be merged
3687
+	 *
3688
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3689
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3690
+	 *                                                                  'none' means NO default where conditions will
3691
+	 *                                                                  be used AT ALL during this query.
3692
+	 *                                                                  'other_models_only' means default where
3693
+	 *                                                                  conditions from other models will be used, but
3694
+	 *                                                                  not for this primary model. 'all', the default,
3695
+	 *                                                                  means default where conditions will apply as
3696
+	 *                                                                  normal
3697
+	 * @param array                       $where_query_params
3698
+	 * @return array
3699
+	 * @throws EE_Error
3700
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3701
+	 */
3702
+	private function _get_default_where_conditions_for_models_in_query(
3703
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3704
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3705
+		$where_query_params = []
3706
+	) {
3707
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3708
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3709
+			throw new EE_Error(
3710
+				sprintf(
3711
+					esc_html__(
3712
+						"You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3713
+						"event_espresso"
3714
+					),
3715
+					$use_default_where_conditions,
3716
+					implode(", ", $allowed_used_default_where_conditions_values)
3717
+				)
3718
+			);
3719
+		}
3720
+		$universal_query_params = [];
3721
+		if ($this->_should_use_default_where_conditions($use_default_where_conditions)) {
3722
+			$universal_query_params = $this->_get_default_where_conditions();
3723
+		} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions)) {
3724
+			$universal_query_params = $this->_get_minimum_where_conditions();
3725
+		}
3726
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3727
+			$related_model = $this->get_related_model_obj($model_name);
3728
+			if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3729
+				$related_model_universal_where_params =
3730
+					$related_model->_get_default_where_conditions($model_relation_path);
3731
+			} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3732
+				$related_model_universal_where_params =
3733
+					$related_model->_get_minimum_where_conditions($model_relation_path);
3734
+			} else {
3735
+				// we don't want to add full or even minimum default where conditions from this model, so just continue
3736
+				continue;
3737
+			}
3738
+			$overrides              = $this->_override_defaults_or_make_null_friendly(
3739
+				$related_model_universal_where_params,
3740
+				$where_query_params,
3741
+				$related_model,
3742
+				$model_relation_path
3743
+			);
3744
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3745
+				$universal_query_params,
3746
+				$overrides
3747
+			);
3748
+		}
3749
+		return $universal_query_params;
3750
+	}
3751
+
3752
+
3753
+	/**
3754
+	 * Determines whether or not we should use default where conditions for the model in question
3755
+	 * (this model, or other related models).
3756
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3757
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3758
+	 * We should use default where conditions on related models when they requested to use default where conditions
3759
+	 * on all models, or specifically just on other related models
3760
+	 *
3761
+	 * @param      $default_where_conditions_value
3762
+	 * @param bool $for_this_model false means this is for OTHER related models
3763
+	 * @return bool
3764
+	 */
3765
+	private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3766
+	{
3767
+		return (
3768
+				   $for_this_model
3769
+				   && in_array(
3770
+					   $default_where_conditions_value,
3771
+					   [
3772
+						   EEM_Base::default_where_conditions_all,
3773
+						   EEM_Base::default_where_conditions_this_only,
3774
+						   EEM_Base::default_where_conditions_minimum_others,
3775
+					   ],
3776
+					   true
3777
+				   )
3778
+			   )
3779
+			   || (
3780
+				   ! $for_this_model
3781
+				   && in_array(
3782
+					   $default_where_conditions_value,
3783
+					   [
3784
+						   EEM_Base::default_where_conditions_all,
3785
+						   EEM_Base::default_where_conditions_others_only,
3786
+					   ],
3787
+					   true
3788
+				   )
3789
+			   );
3790
+	}
3791
+
3792
+
3793
+	/**
3794
+	 * Determines whether or not we should use default minimum conditions for the model in question
3795
+	 * (this model, or other related models).
3796
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3797
+	 * where conditions.
3798
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3799
+	 * on this model or others
3800
+	 *
3801
+	 * @param      $default_where_conditions_value
3802
+	 * @param bool $for_this_model false means this is for OTHER related models
3803
+	 * @return bool
3804
+	 */
3805
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3806
+	{
3807
+		return (
3808
+				   $for_this_model
3809
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3810
+			   )
3811
+			   || (
3812
+				   ! $for_this_model
3813
+				   && in_array(
3814
+					   $default_where_conditions_value,
3815
+					   [
3816
+						   EEM_Base::default_where_conditions_minimum_others,
3817
+						   EEM_Base::default_where_conditions_minimum_all,
3818
+					   ],
3819
+					   true
3820
+				   )
3821
+			   );
3822
+	}
3823
+
3824
+
3825
+	/**
3826
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3827
+	 * then we also add a special where condition which allows for that model's primary key
3828
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3829
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3830
+	 *
3831
+	 * @param array    $default_where_conditions
3832
+	 * @param array    $provided_where_conditions
3833
+	 * @param EEM_Base $model
3834
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3835
+	 * @return array
3836
+	 * @throws EE_Error
3837
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3838
+	 */
3839
+	private function _override_defaults_or_make_null_friendly(
3840
+		$default_where_conditions,
3841
+		$provided_where_conditions,
3842
+		$model,
3843
+		$model_relation_path
3844
+	) {
3845
+		$null_friendly_where_conditions = [];
3846
+		$none_overridden                = true;
3847
+		$or_condition_key_for_defaults  = 'OR*' . get_class($model);
3848
+		foreach ($default_where_conditions as $key => $val) {
3849
+			if (isset($provided_where_conditions[ $key ])) {
3850
+				$none_overridden = false;
3851
+			} else {
3852
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3853
+			}
3854
+		}
3855
+		if ($none_overridden && $default_where_conditions) {
3856
+			if ($model->has_primary_key_field()) {
3857
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3858
+																				   . "."
3859
+																				   . $model->primary_key_name() ] =
3860
+					['IS NULL'];
3861
+			}/*else{
3862 3862
                 //@todo NO PK, use other defaults
3863 3863
             }*/
3864
-        }
3865
-        return $null_friendly_where_conditions;
3866
-    }
3867
-
3868
-
3869
-    /**
3870
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3871
-     * default where conditions on all get_all, update, and delete queries done by this model.
3872
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3873
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3874
-     *
3875
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3876
-     * @return array
3877
-     * @throws EE_Error
3878
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3879
-     */
3880
-    private function _get_default_where_conditions($model_relation_path = '')
3881
-    {
3882
-        if ($this->_ignore_where_strategy) {
3883
-            return [];
3884
-        }
3885
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3886
-    }
3887
-
3888
-
3889
-    /**
3890
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3891
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3892
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3893
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3894
-     * Similar to _get_default_where_conditions
3895
-     *
3896
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3897
-     * @return array
3898
-     * @throws EE_Error
3899
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3900
-     */
3901
-    protected function _get_minimum_where_conditions($model_relation_path = '')
3902
-    {
3903
-        if ($this->_ignore_where_strategy) {
3904
-            return [];
3905
-        }
3906
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3907
-    }
3908
-
3909
-
3910
-    /**
3911
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3912
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3913
-     *
3914
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3915
-     * @return string
3916
-     * @throws EE_Error
3917
-     */
3918
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3919
-    {
3920
-        $selects = $this->_get_columns_to_select_for_this_model();
3921
-        foreach (
3922
-            $model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included
3923
-        ) {
3924
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3925
-            $other_model_selects  = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3926
-            foreach ($other_model_selects as $key => $value) {
3927
-                $selects[] = $value;
3928
-            }
3929
-        }
3930
-        return implode(", ", $selects);
3931
-    }
3932
-
3933
-
3934
-    /**
3935
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3936
-     * So that's going to be the columns for all the fields on the model
3937
-     *
3938
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3939
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3940
-     */
3941
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3942
-    {
3943
-        $fields                                       = $this->field_settings();
3944
-        $selects                                      = [];
3945
-        $table_alias_with_model_relation_chain_prefix =
3946
-            EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3947
-                $model_relation_chain,
3948
-                $this->get_this_model_name()
3949
-            );
3950
-        foreach ($fields as $field_obj) {
3951
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3952
-                         . $field_obj->get_table_alias()
3953
-                         . "."
3954
-                         . $field_obj->get_table_column()
3955
-                         . " AS '"
3956
-                         . $table_alias_with_model_relation_chain_prefix
3957
-                         . $field_obj->get_table_alias()
3958
-                         . "."
3959
-                         . $field_obj->get_table_column()
3960
-                         . "'";
3961
-        }
3962
-        // make sure we are also getting the PKs of each table
3963
-        $tables = $this->get_tables();
3964
-        if (count($tables) > 1) {
3965
-            foreach ($tables as $table_obj) {
3966
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3967
-                                       . $table_obj->get_fully_qualified_pk_column();
3968
-                if (! in_array($qualified_pk_column, $selects)) {
3969
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3970
-                }
3971
-            }
3972
-        }
3973
-        return $selects;
3974
-    }
3975
-
3976
-
3977
-    /**
3978
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3979
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3980
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3981
-     * SQL for joining, and the data types
3982
-     *
3983
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3984
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3985
-     * @param string                      $query_param_type     like Registration.Transaction.TXN_ID
3986
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3987
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3988
-     *                                                          or 'Registration's
3989
-     * @param string|null                 $original_query_param what it originally was (eg
3990
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3991
-     *                                                          matches $query_param
3992
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3993
-     * @throws EE_Error
3994
-     */
3995
-    private function _extract_related_model_info_from_query_param(
3996
-        $query_param,
3997
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3998
-        $query_param_type,
3999
-        $original_query_param = null
4000
-    ) {
4001
-        if ($original_query_param === null) {
4002
-            $original_query_param = $query_param;
4003
-        }
4004
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4005
-        // whether or not to allow logic_query_params like 'NOT','OR', or 'AND'
4006
-        $allow_logic_query_params = in_array($query_param_type, ['where', 'having', 0, 'custom_selects'], true);
4007
-        $allow_fields             = in_array(
4008
-            $query_param_type,
4009
-            ['where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0],
4010
-            true
4011
-        );
4012
-        // check to see if we have a field on this model
4013
-        $this_model_fields = $this->field_settings(true);
4014
-        if (array_key_exists($query_param, $this_model_fields)) {
4015
-            if ($allow_fields) {
4016
-                return;
4017
-            }
4018
-            throw new EE_Error(
4019
-                sprintf(
4020
-                    esc_html__(
4021
-                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
4022
-                        "event_espresso"
4023
-                    ),
4024
-                    $query_param,
4025
-                    get_class($this),
4026
-                    $query_param_type,
4027
-                    $original_query_param
4028
-                )
4029
-            );
4030
-        }
4031
-        // check if this is a special logic query param
4032
-        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4033
-            if ($allow_logic_query_params) {
4034
-                return;
4035
-            }
4036
-            throw new EE_Error(
4037
-                sprintf(
4038
-                    esc_html__(
4039
-                        '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',
4040
-                        'event_espresso'
4041
-                    ),
4042
-                    implode('", "', $this->_logic_query_param_keys),
4043
-                    $query_param,
4044
-                    get_class($this),
4045
-                    '<br />',
4046
-                    "\t"
4047
-                    . ' $passed_in_query_info = <pre>'
4048
-                    . print_r($passed_in_query_info, true)
4049
-                    . '</pre>'
4050
-                    . "\n\t"
4051
-                    . ' $query_param_type = '
4052
-                    . $query_param_type
4053
-                    . "\n\t"
4054
-                    . ' $original_query_param = '
4055
-                    . $original_query_param
4056
-                )
4057
-            );
4058
-        }
4059
-        // check if it's a custom selection
4060
-        if (
4061
-            $this->_custom_selections instanceof CustomSelects
4062
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4063
-        ) {
4064
-            return;
4065
-        }
4066
-        // check if has a model name at the beginning
4067
-        // and
4068
-        // check if it's a field on a related model
4069
-        if (
4070
-            $this->extractJoinModelFromQueryParams(
4071
-                $passed_in_query_info,
4072
-                $query_param,
4073
-                $original_query_param,
4074
-                $query_param_type
4075
-            )
4076
-        ) {
4077
-            return;
4078
-        }
4079
-
4080
-        // ok so $query_param didn't start with a model name
4081
-        // and we previously confirmed it wasn't a logic query param or field on the current model
4082
-        // it's wack, that's what it is
4083
-        throw new EE_Error(
4084
-            sprintf(
4085
-                esc_html__(
4086
-                    "There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4087
-                    "event_espresso"
4088
-                ),
4089
-                $query_param,
4090
-                get_class($this),
4091
-                $query_param_type,
4092
-                $original_query_param
4093
-            )
4094
-        );
4095
-    }
4096
-
4097
-
4098
-    /**
4099
-     * Extracts any possible join model information from the provided possible_join_string.
4100
-     * This method will read the provided $possible_join_string value and determine if there are any possible model
4101
-     * join
4102
-     * parts that should be added to the query.
4103
-     *
4104
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4105
-     * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4106
-     * @param null|string                 $original_query_param
4107
-     * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4108
-     *                                                           ('where', 'order_by', 'group_by', 'custom_selects'
4109
-     *                                                           etc.)
4110
-     * @return bool  returns true if a join was added and false if not.
4111
-     * @throws EE_Error
4112
-     */
4113
-    private function extractJoinModelFromQueryParams(
4114
-        EE_Model_Query_Info_Carrier $query_info_carrier,
4115
-        $possible_join_string,
4116
-        $original_query_param,
4117
-        $query_parameter_type
4118
-    ) {
4119
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4120
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4121
-                $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4122
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4123
-                if ($possible_join_string === '') {
4124
-                    // nothing left to $query_param
4125
-                    // we should actually end in a field name, not a model like this!
4126
-                    throw new EE_Error(
4127
-                        sprintf(
4128
-                            esc_html__(
4129
-                                "Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4130
-                                "event_espresso"
4131
-                            ),
4132
-                            $possible_join_string,
4133
-                            $query_parameter_type,
4134
-                            get_class($this),
4135
-                            $valid_related_model_name
4136
-                        )
4137
-                    );
4138
-                }
4139
-                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4140
-                $related_model_obj->_extract_related_model_info_from_query_param(
4141
-                    $possible_join_string,
4142
-                    $query_info_carrier,
4143
-                    $query_parameter_type,
4144
-                    $original_query_param
4145
-                );
4146
-                return true;
4147
-            }
4148
-            if ($possible_join_string === $valid_related_model_name) {
4149
-                $this->_add_join_to_model(
4150
-                    $valid_related_model_name,
4151
-                    $query_info_carrier,
4152
-                    $original_query_param
4153
-                );
4154
-                return true;
4155
-            }
4156
-        }
4157
-        return false;
4158
-    }
4159
-
4160
-
4161
-    /**
4162
-     * Extracts related models from Custom Selects and sets up any joins for those related models.
4163
-     *
4164
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4165
-     * @throws EE_Error
4166
-     */
4167
-    private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4168
-    {
4169
-        if (
4170
-            $this->_custom_selections instanceof CustomSelects
4171
-            && ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4172
-                || $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4173
-            )
4174
-        ) {
4175
-            $original_selects = $this->_custom_selections->originalSelects();
4176
-            foreach ($original_selects as $alias => $select_configuration) {
4177
-                $this->extractJoinModelFromQueryParams(
4178
-                    $query_info_carrier,
4179
-                    $select_configuration[0],
4180
-                    $select_configuration[0],
4181
-                    'custom_selects'
4182
-                );
4183
-            }
4184
-        }
4185
-    }
4186
-
4187
-
4188
-    /**
4189
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4190
-     * and store it on $passed_in_query_info
4191
-     *
4192
-     * @param string                      $model_name
4193
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4194
-     * @param string                      $original_query_param used to extract the relation chain between the queried
4195
-     *                                                          model and $model_name. Eg, if we are querying Event,
4196
-     *                                                          and are adding a join to 'Payment' with the original
4197
-     *                                                          query param key
4198
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4199
-     *                                                          to extract 'Registration.Transaction.Payment', in case
4200
-     *                                                          Payment wants to add default query params so that it
4201
-     *                                                          will know what models to prepend onto its default query
4202
-     *                                                          params or in case it wants to rename tables (in case
4203
-     *                                                          there are multiple joins to the same table)
4204
-     * @return void
4205
-     * @throws EE_Error
4206
-     */
4207
-    private function _add_join_to_model(
4208
-        $model_name,
4209
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4210
-        $original_query_param
4211
-    ) {
4212
-        $relation_obj         = $this->related_settings_for($model_name);
4213
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4214
-        // check if the relation is HABTM, because then we're essentially doing two joins
4215
-        // If so, join first to the JOIN table, and add its data types, and then continue as normal
4216
-        if ($relation_obj instanceof EE_HABTM_Relation) {
4217
-            $join_model_obj = $relation_obj->get_join_model();
4218
-            // replace the model specified with the join model for this relation chain, whi
4219
-            $relation_chain_to_join_model =
4220
-                EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4221
-                    $model_name,
4222
-                    $join_model_obj->get_this_model_name(),
4223
-                    $model_relation_chain
4224
-                );
4225
-            $passed_in_query_info->merge(
4226
-                new EE_Model_Query_Info_Carrier(
4227
-                    [$relation_chain_to_join_model => $join_model_obj->get_this_model_name()],
4228
-                    $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4229
-                )
4230
-            );
4231
-        }
4232
-        // now just join to the other table pointed to by the relation object, and add its data types
4233
-        $passed_in_query_info->merge(
4234
-            new EE_Model_Query_Info_Carrier(
4235
-                [$model_relation_chain => $model_name],
4236
-                $relation_obj->get_join_statement($model_relation_chain)
4237
-            )
4238
-        );
4239
-    }
4240
-
4241
-
4242
-    /**
4243
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4244
-     *
4245
-     * @param array $where_params
4246
-     * @return string of SQL
4247
-     * @throws EE_Error
4248
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4249
-     */
4250
-    private function _construct_where_clause($where_params)
4251
-    {
4252
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4253
-        if ($SQL) {
4254
-            return " WHERE " . $SQL;
4255
-        }
4256
-        return '';
4257
-    }
4258
-
4259
-
4260
-    /**
4261
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4262
-     * and should be passed HAVING parameters, not WHERE parameters
4263
-     *
4264
-     * @param array $having_params
4265
-     * @return string
4266
-     * @throws EE_Error
4267
-     */
4268
-    private function _construct_having_clause($having_params)
4269
-    {
4270
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4271
-        if ($SQL) {
4272
-            return " HAVING " . $SQL;
4273
-        }
4274
-        return '';
4275
-    }
4276
-
4277
-
4278
-    /**
4279
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4280
-     * Event_Meta.meta_value = 'foo'))"
4281
-     *
4282
-     * @param array  $where_params
4283
-     * @param string $glue joins each sub-clause together. Should really only be " AND " or " OR "...
4284
-     * @return string of SQL
4285
-     * @throws EE_Error
4286
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4287
-     */
4288
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4289
-    {
4290
-        $where_clauses = [];
4291
-        // loop over where params:
4292
-        // keys are query params and values are the operators and values OR sub conditions
4293
-        foreach ($where_params as $query_param => $value) {
4294
-            $query_param =
4295
-                $this->_remove_stars_and_anything_after_from_condition_query_param_key(
4296
-                    $query_param
4297
-                );// str_replace("*",'',$query_param);
4298
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
4299
-                $open = ' (';
4300
-                $close = ')';
4301
-                $conditions = '';
4302
-                switch ($query_param) {
4303
-                    case 'not':
4304
-                    case 'NOT':
4305
-                        $open = " !{$open}";
4306
-                        $conditions = $this->_construct_condition_clause_recursive($value, $glue);
4307
-                        break;
4308
-                    case 'and':
4309
-                    case 'AND':
4310
-                        $conditions = $this->_construct_condition_clause_recursive($value, ' AND ');
4311
-                        break;
4312
-                    case 'or':
4313
-                    case 'OR':
4314
-                        $conditions = $this->_construct_condition_clause_recursive($value, ' OR ');
4315
-                        break;
4316
-                }
4317
-                if ($conditions !== '') {
4318
-                    $where_clauses[] = "{$open}{$conditions}{$close}";
4319
-                }
4320
-            } else {
4321
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4322
-                // if it's not a normal field, maybe it's a custom selection?
4323
-                if (! $field_obj) {
4324
-                    if ($this->_custom_selections instanceof CustomSelects) {
4325
-                        $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4326
-                    } else {
4327
-                        throw new EE_Error(
4328
-                            sprintf(
4329
-                                esc_html__(
4330
-                                    "%s is neither a valid model field name, nor a custom selection",
4331
-                                    "event_espresso"
4332
-                                ),
4333
-                                $query_param
4334
-                            )
4335
-                        );
4336
-                    }
4337
-                }
4338
-                $op_and_value_sql = $this->_construct_op_and_value($value, $field_obj);
4339
-                $where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4340
-            }
4341
-        }
4342
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4343
-    }
4344
-
4345
-
4346
-    /**
4347
-     * Takes the input parameter and extract the table name (alias) and column name
4348
-     *
4349
-     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4350
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4351
-     * @throws EE_Error
4352
-     */
4353
-    private function _deduce_column_name_from_query_param($query_param)
4354
-    {
4355
-        $field = $this->_deduce_field_from_query_param($query_param);
4356
-        if ($field) {
4357
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4358
-                $field->get_model_name(),
4359
-                $query_param
4360
-            );
4361
-            return $table_alias_prefix . $field->get_qualified_column();
4362
-        }
4363
-        if (
4364
-            $this->_custom_selections instanceof CustomSelects
4365
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4366
-        ) {
4367
-            // maybe it's custom selection item?
4368
-            // if so, just use it as the "column name"
4369
-            return $query_param;
4370
-        }
4371
-        $custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4372
-            ? implode(',', $this->_custom_selections->columnAliases())
4373
-            : '';
4374
-        throw new EE_Error(
4375
-            sprintf(
4376
-                esc_html__(
4377
-                    "%s is not a valid field on this model, nor a custom selection (%s)",
4378
-                    "event_espresso"
4379
-                ),
4380
-                $query_param,
4381
-                $custom_select_aliases
4382
-            )
4383
-        );
4384
-    }
4385
-
4386
-
4387
-    /**
4388
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4389
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4390
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4391
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4392
-     *
4393
-     * @param string $condition_query_param_key
4394
-     * @return string
4395
-     */
4396
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4397
-    {
4398
-        $pos_of_star = strpos($condition_query_param_key, '*');
4399
-        if ($pos_of_star === false) {
4400
-            return $condition_query_param_key;
4401
-        }
4402
-        return substr($condition_query_param_key, 0, $pos_of_star);
4403
-    }
4404
-
4405
-
4406
-    /**
4407
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4408
-     *
4409
-     * @param mixed      array | string    $op_and_value
4410
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4411
-     * @return string
4412
-     * @throws EE_Error
4413
-     */
4414
-    private function _construct_op_and_value($op_and_value, $field_obj)
4415
-    {
4416
-        if (is_array($op_and_value)) {
4417
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4418
-            if (! $operator) {
4419
-                $php_array_like_string = [];
4420
-                foreach ($op_and_value as $key => $value) {
4421
-                    $php_array_like_string[] = "$key=>$value";
4422
-                }
4423
-                throw new EE_Error(
4424
-                    sprintf(
4425
-                        esc_html__(
4426
-                            "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))",
4427
-                            "event_espresso"
4428
-                        ),
4429
-                        implode(",", $php_array_like_string)
4430
-                    )
4431
-                );
4432
-            }
4433
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4434
-        } else {
4435
-            $operator = '=';
4436
-            $value    = $op_and_value;
4437
-        }
4438
-        // check to see if the value is actually another field
4439
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4440
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4441
-        }
4442
-        if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4443
-            // in this case, the value should be an array, or at least a comma-separated list
4444
-            // it will need to handle a little differently
4445
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4446
-            // note: $cleaned_value has already been run through $wpdb->prepare()
4447
-            return $operator . SP . $cleaned_value;
4448
-        }
4449
-        if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4450
-            // the value should be an array with count of two.
4451
-            if (count($value) !== 2) {
4452
-                throw new EE_Error(
4453
-                    sprintf(
4454
-                        esc_html__(
4455
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4456
-                            'event_espresso'
4457
-                        ),
4458
-                        "BETWEEN"
4459
-                    )
4460
-                );
4461
-            }
4462
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4463
-            return $operator . SP . $cleaned_value;
4464
-        }
4465
-        if (in_array($operator, $this->valid_null_style_operators())) {
4466
-            if ($value !== null) {
4467
-                throw new EE_Error(
4468
-                    sprintf(
4469
-                        esc_html__(
4470
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4471
-                            "event_espresso"
4472
-                        ),
4473
-                        $value,
4474
-                        $operator
4475
-                    )
4476
-                );
4477
-            }
4478
-            return $operator;
4479
-        }
4480
-        if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4481
-            // if the operator is 'LIKE', we want to allow percent signs (%) and not
4482
-            // remove other junk. So just treat it as a string.
4483
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4484
-        }
4485
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4486
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4487
-        }
4488
-        if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4489
-            throw new EE_Error(
4490
-                sprintf(
4491
-                    esc_html__(
4492
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4493
-                        'event_espresso'
4494
-                    ),
4495
-                    $operator,
4496
-                    $operator
4497
-                )
4498
-            );
4499
-        }
4500
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4501
-            throw new EE_Error(
4502
-                sprintf(
4503
-                    esc_html__(
4504
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4505
-                        'event_espresso'
4506
-                    ),
4507
-                    $operator,
4508
-                    $operator
4509
-                )
4510
-            );
4511
-        }
4512
-        throw new EE_Error(
4513
-            sprintf(
4514
-                esc_html__(
4515
-                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4516
-                    "event_espresso"
4517
-                ),
4518
-                http_build_query($op_and_value)
4519
-            )
4520
-        );
4521
-    }
4522
-
4523
-
4524
-    /**
4525
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4526
-     *
4527
-     * @param array                      $values
4528
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4529
-     *                                              '%s'
4530
-     * @return string
4531
-     * @throws EE_Error
4532
-     */
4533
-    public function _construct_between_value($values, $field_obj)
4534
-    {
4535
-        $cleaned_values = [];
4536
-        foreach ($values as $value) {
4537
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4538
-        }
4539
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4540
-    }
4541
-
4542
-
4543
-    /**
4544
-     * Takes an array or a comma-separated list of $values and cleans them
4545
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4546
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4547
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4548
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4549
-     *
4550
-     * @param mixed                      $values    array or comma-separated string
4551
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4552
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4553
-     * @throws EE_Error
4554
-     */
4555
-    public function _construct_in_value($values, $field_obj)
4556
-    {
4557
-        // check if the value is a CSV list
4558
-        if (is_string($values)) {
4559
-            // in which case, turn it into an array
4560
-            $values = explode(",", $values);
4561
-        }
4562
-        $cleaned_values = [];
4563
-        foreach ($values as $value) {
4564
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4565
-        }
4566
-        // we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4567
-        // but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4568
-        // which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4569
-        if (empty($cleaned_values)) {
4570
-            $all_fields       = $this->field_settings();
4571
-            $a_field          = array_shift($all_fields);
4572
-            $main_table       = $this->_get_main_table();
4573
-            $cleaned_values[] = "SELECT "
4574
-                                . $a_field->get_table_column()
4575
-                                . " FROM "
4576
-                                . $main_table->get_table_name()
4577
-                                . " WHERE FALSE";
4578
-        }
4579
-        return "(" . implode(",", $cleaned_values) . ")";
4580
-    }
4581
-
4582
-
4583
-    /**
4584
-     * @param mixed                      $value
4585
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4586
-     * @return false|null|string
4587
-     * @throws EE_Error
4588
-     */
4589
-    private function _wpdb_prepare_using_field($value, $field_obj)
4590
-    {
4591
-        global $wpdb;
4592
-        if ($field_obj instanceof EE_Model_Field_Base) {
4593
-            return $wpdb->prepare(
4594
-                $field_obj->get_wpdb_data_type(),
4595
-                $this->_prepare_value_for_use_in_db($value, $field_obj)
4596
-            );
4597
-        } //$field_obj should really just be a data type
4598
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4599
-            throw new EE_Error(
4600
-                sprintf(
4601
-                    esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4602
-                    $field_obj,
4603
-                    implode(",", $this->_valid_wpdb_data_types)
4604
-                )
4605
-            );
4606
-        }
4607
-        return $wpdb->prepare($field_obj, $value);
4608
-    }
4609
-
4610
-
4611
-    /**
4612
-     * Takes the input parameter and finds the model field that it indicates.
4613
-     *
4614
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4615
-     * @return EE_Model_Field_Base
4616
-     * @throws EE_Error
4617
-     */
4618
-    protected function _deduce_field_from_query_param($query_param_name)
4619
-    {
4620
-        // ok, now proceed with deducing which part is the model's name, and which is the field's name
4621
-        // which will help us find the database table and column
4622
-        $query_param_parts = explode(".", $query_param_name);
4623
-        if (empty($query_param_parts)) {
4624
-            throw new EE_Error(
4625
-                sprintf(
4626
-                    esc_html__(
4627
-                        "_extract_column_name is empty when trying to extract column and table name from %s",
4628
-                        'event_espresso'
4629
-                    ),
4630
-                    $query_param_name
4631
-                )
4632
-            );
4633
-        }
4634
-        $number_of_parts       = count($query_param_parts);
4635
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4636
-        if ($number_of_parts === 1) {
4637
-            $field_name = $last_query_param_part;
4638
-            $model_obj  = $this;
4639
-        } else {// $number_of_parts >= 2
4640
-            // the last part is the column name, and there are only 2parts. therefore...
4641
-            $field_name = $last_query_param_part;
4642
-            $model_obj  = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4643
-        }
4644
-        try {
4645
-            return $model_obj->field_settings_for($field_name);
4646
-        } catch (EE_Error $e) {
4647
-            return null;
4648
-        }
4649
-    }
4650
-
4651
-
4652
-    /**
4653
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4654
-     * alias and column which corresponds to it
4655
-     *
4656
-     * @param string $field_name
4657
-     * @return string
4658
-     * @throws EE_Error
4659
-     */
4660
-    public function _get_qualified_column_for_field($field_name)
4661
-    {
4662
-        $all_fields = $this->field_settings();
4663
-        $field      = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4664
-        if ($field) {
4665
-            return $field->get_qualified_column();
4666
-        }
4667
-        throw new EE_Error(
4668
-            sprintf(
4669
-                esc_html__(
4670
-                    "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.",
4671
-                    'event_espresso'
4672
-                ),
4673
-                $field_name,
4674
-                get_class($this)
4675
-            )
4676
-        );
4677
-    }
4678
-
4679
-
4680
-    /**
4681
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4682
-     * Example usage:
4683
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4684
-     *      array(),
4685
-     *      ARRAY_A,
4686
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4687
-     *  );
4688
-     * is equivalent to
4689
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4690
-     * and
4691
-     *  EEM_Event::instance()->get_all_wpdb_results(
4692
-     *      array(
4693
-     *          array(
4694
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4695
-     *          ),
4696
-     *          ARRAY_A,
4697
-     *          implode(
4698
-     *              ', ',
4699
-     *              array_merge(
4700
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4701
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4702
-     *              )
4703
-     *          )
4704
-     *      )
4705
-     *  );
4706
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4707
-     *
4708
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4709
-     *                                            and the one whose fields you are selecting for example: when querying
4710
-     *                                            tickets model and selecting fields from the tickets model you would
4711
-     *                                            leave this parameter empty, because no models are needed to join
4712
-     *                                            between the queried model and the selected one. Likewise when
4713
-     *                                            querying the datetime model and selecting fields from the tickets
4714
-     *                                            model, it would also be left empty, because there is a direct
4715
-     *                                            relation from datetimes to tickets, so no model is needed to join
4716
-     *                                            them together. However, when querying from the event model and
4717
-     *                                            selecting fields from the ticket model, you should provide the string
4718
-     *                                            'Datetime', indicating that the event model must first join to the
4719
-     *                                            datetime model in order to find its relation to ticket model.
4720
-     *                                            Also, when querying from the venue model and selecting fields from
4721
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4722
-     *                                            indicating you need to join the venue model to the event model,
4723
-     *                                            to the datetime model, in order to find its relation to the ticket
4724
-     *                                            model. This string is used to deduce the prefix that gets added onto
4725
-     *                                            the models' tables qualified columns
4726
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4727
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4728
-     *                                            qualified column names
4729
-     * @return array|string
4730
-     */
4731
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4732
-    {
4733
-        $table_prefix      = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4734
-        $qualified_columns = [];
4735
-        foreach ($this->field_settings() as $field_name => $field) {
4736
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4737
-        }
4738
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4739
-    }
4740
-
4741
-
4742
-    /**
4743
-     * constructs the select use on special limit joins
4744
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4745
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4746
-     * (as that is typically where the limits would be set).
4747
-     *
4748
-     * @param string       $table_alias The table the select is being built for
4749
-     * @param mixed|string $limit       The limit for this select
4750
-     * @return string                The final select join element for the query.
4751
-     * @throws EE_Error
4752
-     */
4753
-    public function _construct_limit_join_select($table_alias, $limit)
4754
-    {
4755
-        $SQL = '';
4756
-        foreach ($this->_tables as $table_obj) {
4757
-            if ($table_obj instanceof EE_Primary_Table) {
4758
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4759
-                    ? $table_obj->get_select_join_limit($limit)
4760
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4761
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4762
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4763
-                    ? $table_obj->get_select_join_limit_join($limit)
4764
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4765
-            }
4766
-        }
4767
-        return $SQL;
4768
-    }
4769
-
4770
-
4771
-    /**
4772
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4773
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4774
-     *
4775
-     * @return string SQL
4776
-     * @throws EE_Error
4777
-     */
4778
-    public function _construct_internal_join()
4779
-    {
4780
-        $SQL = $this->_get_main_table()->get_table_sql();
4781
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4782
-        return $SQL;
4783
-    }
4784
-
4785
-
4786
-    /**
4787
-     * Constructs the SQL for joining all the tables on this model.
4788
-     * Normally $alias should be the primary table's alias, but in cases where
4789
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4790
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4791
-     * alias, this will construct SQL like:
4792
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4793
-     * With $alias being a secondary table's alias, this will construct SQL like:
4794
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4795
-     *
4796
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4797
-     * @return string
4798
-     * @throws EE_Error
4799
-     */
4800
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4801
-    {
4802
-        $SQL               = '';
4803
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4804
-        foreach ($this->_tables as $table_obj) {
4805
-            if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4806
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4807
-                    // so we're joining to this table, meaning the table is already in
4808
-                    // the FROM statement, BUT the primary table isn't. So we want
4809
-                    // to add the inverse join sql
4810
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4811
-                } else {
4812
-                    // just add a regular JOIN to this table from the primary table
4813
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4814
-                }
4815
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4816
-        }
4817
-        return $SQL;
4818
-    }
4819
-
4820
-
4821
-    /**
4822
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4823
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4824
-     * their data type (eg, '%s', '%d', etc)
4825
-     *
4826
-     * @return array
4827
-     */
4828
-    public function _get_data_types()
4829
-    {
4830
-        $data_types = [];
4831
-        foreach ($this->field_settings() as $field_obj) {
4832
-            // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4833
-            /** @var $field_obj EE_Model_Field_Base */
4834
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4835
-        }
4836
-        return $data_types;
4837
-    }
4838
-
4839
-
4840
-    /**
4841
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4842
-     *
4843
-     * @param string $model_name
4844
-     * @return EEM_Base
4845
-     * @throws EE_Error
4846
-     */
4847
-    public function get_related_model_obj($model_name)
4848
-    {
4849
-        $model_classname = "EEM_" . $model_name;
4850
-        if (! class_exists($model_classname)) {
4851
-            throw new EE_Error(
4852
-                sprintf(
4853
-                    esc_html__(
4854
-                        "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4855
-                        'event_espresso'
4856
-                    ),
4857
-                    $model_name,
4858
-                    $model_classname
4859
-                )
4860
-            );
4861
-        }
4862
-        return call_user_func($model_classname . "::instance");
4863
-    }
4864
-
4865
-
4866
-    /**
4867
-     * Returns the array of EE_ModelRelations for this model.
4868
-     *
4869
-     * @return EE_Model_Relation_Base[]
4870
-     */
4871
-    public function relation_settings()
4872
-    {
4873
-        return $this->_model_relations;
4874
-    }
4875
-
4876
-
4877
-    /**
4878
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4879
-     * because without THOSE models, this model probably doesn't have much purpose.
4880
-     * (Eg, without an event, datetimes have little purpose.)
4881
-     *
4882
-     * @return EE_Belongs_To_Relation[]
4883
-     */
4884
-    public function belongs_to_relations()
4885
-    {
4886
-        $belongs_to_relations = [];
4887
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4888
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4889
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4890
-            }
4891
-        }
4892
-        return $belongs_to_relations;
4893
-    }
4894
-
4895
-
4896
-    /**
4897
-     * Returns the specified EE_Model_Relation, or throws an exception
4898
-     *
4899
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4900
-     * @return EE_Model_Relation_Base
4901
-     * @throws EE_Error
4902
-     */
4903
-    public function related_settings_for($relation_name)
4904
-    {
4905
-        $relatedModels = $this->relation_settings();
4906
-        if (! array_key_exists($relation_name, $relatedModels)) {
4907
-            throw new EE_Error(
4908
-                sprintf(
4909
-                    esc_html__(
4910
-                        'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4911
-                        'event_espresso'
4912
-                    ),
4913
-                    $relation_name,
4914
-                    $this->_get_class_name(),
4915
-                    implode(', ', array_keys($relatedModels))
4916
-                )
4917
-            );
4918
-        }
4919
-        return $relatedModels[ $relation_name ];
4920
-    }
4921
-
4922
-
4923
-    /**
4924
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4925
-     * fields
4926
-     *
4927
-     * @param string  $fieldName
4928
-     * @param boolean $include_db_only_fields
4929
-     * @return EE_Model_Field_Base
4930
-     * @throws EE_Error
4931
-     */
4932
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
4933
-    {
4934
-        $fieldSettings = $this->field_settings($include_db_only_fields);
4935
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4936
-            throw new EE_Error(
4937
-                sprintf(
4938
-                    esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
4939
-                    $fieldName,
4940
-                    get_class($this)
4941
-                )
4942
-            );
4943
-        }
4944
-        return $fieldSettings[ $fieldName ];
4945
-    }
4946
-
4947
-
4948
-    /**
4949
-     * Checks if this field exists on this model
4950
-     *
4951
-     * @param string $fieldName a key in the model's _field_settings array
4952
-     * @return boolean
4953
-     */
4954
-    public function has_field($fieldName)
4955
-    {
4956
-        $fieldSettings = $this->field_settings(true);
4957
-        if (isset($fieldSettings[ $fieldName ])) {
4958
-            return true;
4959
-        }
4960
-        return false;
4961
-    }
4962
-
4963
-
4964
-    /**
4965
-     * Returns whether or not this model has a relation to the specified model
4966
-     *
4967
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4968
-     * @return boolean
4969
-     */
4970
-    public function has_relation($relation_name)
4971
-    {
4972
-        $relations = $this->relation_settings();
4973
-        if (isset($relations[ $relation_name ])) {
4974
-            return true;
4975
-        }
4976
-        return false;
4977
-    }
4978
-
4979
-
4980
-    /**
4981
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4982
-     * Eg, on EE_Answer that would be ANS_ID field object
4983
-     *
4984
-     * @param $field_obj
4985
-     * @return boolean
4986
-     */
4987
-    public function is_primary_key_field($field_obj)
4988
-    {
4989
-        return $field_obj instanceof EE_Primary_Key_Field_Base;
4990
-    }
4991
-
4992
-
4993
-    /**
4994
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4995
-     * Eg, on EE_Answer that would be ANS_ID field object
4996
-     *
4997
-     * @return EE_Model_Field_Base
4998
-     * @throws EE_Error
4999
-     */
5000
-    public function get_primary_key_field()
5001
-    {
5002
-        if ($this->_primary_key_field === null) {
5003
-            foreach ($this->field_settings(true) as $field_obj) {
5004
-                if ($this->is_primary_key_field($field_obj)) {
5005
-                    $this->_primary_key_field = $field_obj;
5006
-                    break;
5007
-                }
5008
-            }
5009
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5010
-                throw new EE_Error(
5011
-                    sprintf(
5012
-                        esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
5013
-                        get_class($this)
5014
-                    )
5015
-                );
5016
-            }
5017
-        }
5018
-        return $this->_primary_key_field;
5019
-    }
5020
-
5021
-
5022
-    /**
5023
-     * Returns whether or not not there is a primary key on this model.
5024
-     * Internally does some caching.
5025
-     *
5026
-     * @return boolean
5027
-     */
5028
-    public function has_primary_key_field()
5029
-    {
5030
-        if ($this->_has_primary_key_field === null) {
5031
-            try {
5032
-                $this->get_primary_key_field();
5033
-                $this->_has_primary_key_field = true;
5034
-            } catch (EE_Error $e) {
5035
-                $this->_has_primary_key_field = false;
5036
-            }
5037
-        }
5038
-        return $this->_has_primary_key_field;
5039
-    }
5040
-
5041
-
5042
-    /**
5043
-     * Finds the first field of type $field_class_name.
5044
-     *
5045
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5046
-     *                                 EE_Foreign_Key_Field, etc
5047
-     * @return EE_Model_Field_Base or null if none is found
5048
-     */
5049
-    public function get_a_field_of_type($field_class_name)
5050
-    {
5051
-        foreach ($this->field_settings() as $field) {
5052
-            if ($field instanceof $field_class_name) {
5053
-                return $field;
5054
-            }
5055
-        }
5056
-        return null;
5057
-    }
5058
-
5059
-
5060
-    /**
5061
-     * Gets a foreign key field pointing to model.
5062
-     *
5063
-     * @param string $model_name eg Event, Registration, not EEM_Event
5064
-     * @return EE_Foreign_Key_Field_Base
5065
-     * @throws EE_Error
5066
-     */
5067
-    public function get_foreign_key_to($model_name)
5068
-    {
5069
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5070
-            foreach ($this->field_settings() as $field) {
5071
-                if (
5072
-                    $field instanceof EE_Foreign_Key_Field_Base
5073
-                    && in_array($model_name, $field->get_model_names_pointed_to())
5074
-                ) {
5075
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5076
-                    break;
5077
-                }
5078
-            }
5079
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5080
-                throw new EE_Error(
5081
-                    sprintf(
5082
-                        esc_html__(
5083
-                            "There is no foreign key field pointing to model %s on model %s",
5084
-                            'event_espresso'
5085
-                        ),
5086
-                        $model_name,
5087
-                        get_class($this)
5088
-                    )
5089
-                );
5090
-            }
5091
-        }
5092
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5093
-    }
5094
-
5095
-
5096
-    /**
5097
-     * Gets the table name (including $wpdb->prefix) for the table alias
5098
-     *
5099
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5100
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5101
-     *                            Either one works
5102
-     * @return string
5103
-     */
5104
-    public function get_table_for_alias($table_alias)
5105
-    {
5106
-        $table_alias_sans_model_relation_chain_prefix =
5107
-            EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5108
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5109
-    }
5110
-
5111
-
5112
-    /**
5113
-     * Returns a flat array of all field son this model, instead of organizing them
5114
-     * by table_alias as they are in the constructor.
5115
-     *
5116
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5117
-     * @return EE_Model_Field_Base[] where the keys are the field's name
5118
-     */
5119
-    public function field_settings($include_db_only_fields = false)
5120
-    {
5121
-        if ($include_db_only_fields) {
5122
-            if ($this->_cached_fields === null) {
5123
-                $this->_cached_fields = [];
5124
-                foreach ($this->_fields as $fields_corresponding_to_table) {
5125
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5126
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5127
-                    }
5128
-                }
5129
-            }
5130
-            return $this->_cached_fields;
5131
-        }
5132
-        if ($this->_cached_fields_non_db_only === null) {
5133
-            $this->_cached_fields_non_db_only = [];
5134
-            foreach ($this->_fields as $fields_corresponding_to_table) {
5135
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5136
-                    /** @var $field_obj EE_Model_Field_Base */
5137
-                    if (! $field_obj->is_db_only_field()) {
5138
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5139
-                    }
5140
-                }
5141
-            }
5142
-        }
5143
-        return $this->_cached_fields_non_db_only;
5144
-    }
5145
-
5146
-
5147
-    /**
5148
-     *        cycle though array of attendees and create objects out of each item
5149
-     *
5150
-     * @access        private
5151
-     * @param array $rows        of results of $wpdb->get_results($query,ARRAY_A)
5152
-     * @return EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5153
-     *                           numerically indexed)
5154
-     * @throws EE_Error
5155
-     * @throws ReflectionException
5156
-     */
5157
-    protected function _create_objects($rows = [])
5158
-    {
5159
-        $array_of_objects = [];
5160
-        if (empty($rows)) {
5161
-            return [];
5162
-        }
5163
-        $count_if_model_has_no_primary_key = 0;
5164
-        $has_primary_key                   = $this->has_primary_key_field();
5165
-        $primary_key_field                 = $has_primary_key ? $this->get_primary_key_field() : null;
5166
-        foreach ((array) $rows as $row) {
5167
-            if (empty($row)) {
5168
-                // wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5169
-                return [];
5170
-            }
5171
-            // check if we've already set this object in the results array,
5172
-            // in which case there's no need to process it further (again)
5173
-            if ($has_primary_key) {
5174
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5175
-                    $row,
5176
-                    $primary_key_field->get_qualified_column(),
5177
-                    $primary_key_field->get_table_column()
5178
-                );
5179
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5180
-                    continue;
5181
-                }
5182
-            }
5183
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
5184
-            if (! $classInstance) {
5185
-                throw new EE_Error(
5186
-                    sprintf(
5187
-                        esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
5188
-                        $this->get_this_model_name(),
5189
-                        http_build_query($row)
5190
-                    )
5191
-                );
5192
-            }
5193
-            // set the timezone on the instantiated objects
5194
-            $classInstance->set_timezone($this->get_timezone(), true);
5195
-            // make sure if there is any timezone setting present that we set the timezone for the object
5196
-            $key                      = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5197
-            $array_of_objects[ $key ] = $classInstance;
5198
-            // also, for all the relations of type BelongsTo, see if we can cache
5199
-            // those related models
5200
-            // (we could do this for other relations too, but if there are conditions
5201
-            // that filtered out some fo the results, then we'd be caching an incomplete set
5202
-            // so it requires a little more thought than just caching them immediately...)
5203
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
5204
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
5205
-                    // check if this model's INFO is present. If so, cache it on the model
5206
-                    $other_model           = $relation_obj->get_other_model();
5207
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5208
-                    // if we managed to make a model object from the results, cache it on the main model object
5209
-                    if ($other_model_obj_maybe) {
5210
-                        // set timezone on these other model objects if they are present
5211
-                        $other_model_obj_maybe->set_timezone($this->get_timezone(), true);
5212
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
5213
-                    }
5214
-                }
5215
-            }
5216
-            // also, if this was a custom select query, let's see if there are any results for the custom select fields
5217
-            // and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5218
-            // the field in the CustomSelects object
5219
-            if ($this->_custom_selections instanceof CustomSelects) {
5220
-                $classInstance->setCustomSelectsValues(
5221
-                    $this->getValuesForCustomSelectAliasesFromResults($row)
5222
-                );
5223
-            }
5224
-        }
5225
-        return $array_of_objects;
5226
-    }
5227
-
5228
-
5229
-    /**
5230
-     * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5231
-     * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5232
-     *
5233
-     * @param array $db_results_row
5234
-     * @return array
5235
-     */
5236
-    protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5237
-    {
5238
-        $results = [];
5239
-        if ($this->_custom_selections instanceof CustomSelects) {
5240
-            foreach ($this->_custom_selections->columnAliases() as $alias) {
5241
-                if (isset($db_results_row[ $alias ])) {
5242
-                    $results[ $alias ] = $this->convertValueToDataType(
5243
-                        $db_results_row[ $alias ],
5244
-                        $this->_custom_selections->getDataTypeForAlias($alias)
5245
-                    );
5246
-                }
5247
-            }
5248
-        }
5249
-        return $results;
5250
-    }
5251
-
5252
-
5253
-    /**
5254
-     * This will set the value for the given alias
5255
-     *
5256
-     * @param string $value
5257
-     * @param string $datatype (one of %d, %s, %f)
5258
-     * @return int|string|float (int for %d, string for %s, float for %f)
5259
-     */
5260
-    protected function convertValueToDataType($value, $datatype)
5261
-    {
5262
-        switch ($datatype) {
5263
-            case '%f':
5264
-                return (float) $value;
5265
-            case '%d':
5266
-                return (int) $value;
5267
-            default:
5268
-                return (string) $value;
5269
-        }
5270
-    }
5271
-
5272
-
5273
-    /**
5274
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5275
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5276
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5277
-     * object (as set in the model_field!).
5278
-     *
5279
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5280
-     * @throws EE_Error
5281
-     * @throws ReflectionException
5282
-     */
5283
-    public function create_default_object()
5284
-    {
5285
-        $this_model_fields_and_values = [];
5286
-        // setup the row using default values;
5287
-        foreach ($this->field_settings() as $field_name => $field_obj) {
5288
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5289
-        }
5290
-        $className = $this->_get_class_name();
5291
-        return EE_Registry::instance()->load_class(
5292
-            $className,
5293
-            [$this_model_fields_and_values],
5294
-            false,
5295
-            false
5296
-        );
5297
-    }
5298
-
5299
-
5300
-    /**
5301
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5302
-     *                             or an stdClass where each property is the name of a column,
5303
-     * @return EE_Base_Class
5304
-     * @throws EE_Error
5305
-     * @throws ReflectionException
5306
-     */
5307
-    public function instantiate_class_from_array_or_object($cols_n_values)
5308
-    {
5309
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5310
-            $cols_n_values = get_object_vars($cols_n_values);
5311
-        }
5312
-        $primary_key = null;
5313
-        // make sure the array only has keys that are fields/columns on this model
5314
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5315
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5316
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5317
-        }
5318
-        $className = $this->_get_class_name();
5319
-        // check we actually found results that we can use to build our model object
5320
-        // if not, return null
5321
-        if ($this->has_primary_key_field()) {
5322
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5323
-                return null;
5324
-            }
5325
-        } elseif ($this->unique_indexes()) {
5326
-            $first_column = reset($this_model_fields_n_values);
5327
-            if (empty($first_column)) {
5328
-                return null;
5329
-            }
5330
-        }
5331
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5332
-        if ($primary_key) {
5333
-            $classInstance = $this->get_from_entity_map($primary_key);
5334
-            if (! $classInstance) {
5335
-                $classInstance = EE_Registry::instance()->load_class(
5336
-                    $className,
5337
-                    [$this_model_fields_n_values, $this->get_timezone()],
5338
-                    true,
5339
-                    false
5340
-                );
5341
-                // add this new object to the entity map
5342
-                $classInstance = $this->add_to_entity_map($classInstance);
5343
-            }
5344
-        } else {
5345
-            $classInstance = EE_Registry::instance()->load_class(
5346
-                $className,
5347
-                [$this_model_fields_n_values, $this->get_timezone()],
5348
-                true,
5349
-                false
5350
-            );
5351
-        }
5352
-        return $classInstance;
5353
-    }
5354
-
5355
-
5356
-    /**
5357
-     * Gets the model object from the  entity map if it exists
5358
-     *
5359
-     * @param int|string $id the ID of the model object
5360
-     * @return EE_Base_Class
5361
-     */
5362
-    public function get_from_entity_map($id)
5363
-    {
5364
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5365
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]
5366
-            : null;
5367
-    }
5368
-
5369
-
5370
-    /**
5371
-     * add_to_entity_map
5372
-     * Adds the object to the model's entity mappings
5373
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5374
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5375
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5376
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5377
-     *        then this method should be called immediately after the update query
5378
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5379
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5380
-     *
5381
-     * @param EE_Base_Class $object
5382
-     * @return EE_Base_Class
5383
-     * @throws EE_Error
5384
-     */
5385
-    public function add_to_entity_map(EE_Base_Class $object)
5386
-    {
5387
-        $className = $this->_get_class_name();
5388
-        if (! $object instanceof $className) {
5389
-            throw new EE_Error(
5390
-                sprintf(
5391
-                    esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5392
-                    is_object($object) ? get_class($object) : $object,
5393
-                    $className
5394
-                )
5395
-            );
5396
-        }
5397
-        if (! $object->ID()) {
5398
-            throw new EE_Error(
5399
-                sprintf(
5400
-                    esc_html__(
5401
-                        "You tried storing a model object with NO ID in the %s entity mapper.",
5402
-                        "event_espresso"
5403
-                    ),
5404
-                    get_class($this)
5405
-                )
5406
-            );
5407
-        }
5408
-        // double check it's not already there
5409
-        $classInstance = $this->get_from_entity_map($object->ID());
5410
-        if ($classInstance) {
5411
-            return $classInstance;
5412
-        }
5413
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5414
-        return $object;
5415
-    }
5416
-
5417
-
5418
-    /**
5419
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5420
-     * if no identifier is provided, then the entire entity map is emptied
5421
-     *
5422
-     * @param int|string $id the ID of the model object
5423
-     * @return boolean
5424
-     */
5425
-    public function clear_entity_map($id = null)
5426
-    {
5427
-        if (empty($id)) {
5428
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = [];
5429
-            return true;
5430
-        }
5431
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5432
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5433
-            return true;
5434
-        }
5435
-        return false;
5436
-    }
5437
-
5438
-
5439
-    /**
5440
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5441
-     * Given an array where keys are column (or column alias) names and values,
5442
-     * returns an array of their corresponding field names and database values
5443
-     *
5444
-     * @param array $cols_n_values
5445
-     * @return array
5446
-     */
5447
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5448
-    {
5449
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5450
-    }
5451
-
5452
-
5453
-    /**
5454
-     * _deduce_fields_n_values_from_cols_n_values
5455
-     * Given an array where keys are column (or column alias) names and values,
5456
-     * returns an array of their corresponding field names and database values
5457
-     *
5458
-     * @param array $cols_n_values
5459
-     * @return array
5460
-     */
5461
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5462
-    {
5463
-        $this_model_fields_n_values = [];
5464
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5465
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5466
-                $cols_n_values,
5467
-                $table_obj->get_fully_qualified_pk_column(),
5468
-                $table_obj->get_pk_column()
5469
-            );
5470
-            // there is a primary key on this table and its not set. Use defaults for all its columns
5471
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5472
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5473
-                    if (! $field_obj->is_db_only_field()) {
5474
-                        // prepare field as if its coming from db
5475
-                        $prepared_value                            =
5476
-                            $field_obj->prepare_for_set($field_obj->get_default_value());
5477
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5478
-                    }
5479
-                }
5480
-            } else {
5481
-                // the table's rows existed. Use their values
5482
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5483
-                    if (! $field_obj->is_db_only_field()) {
5484
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5485
-                            $cols_n_values,
5486
-                            $field_obj->get_qualified_column(),
5487
-                            $field_obj->get_table_column()
5488
-                        );
5489
-                    }
5490
-                }
5491
-            }
5492
-        }
5493
-        return $this_model_fields_n_values;
5494
-    }
5495
-
5496
-
5497
-    /**
5498
-     * @param array  $cols_n_values
5499
-     * @param string $qualified_column
5500
-     * @param string $regular_column
5501
-     * @return null
5502
-     */
5503
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5504
-    {
5505
-        $value = null;
5506
-        // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5507
-        // does the field on the model relate to this column retrieved from the db?
5508
-        // or is it a db-only field? (not relating to the model)
5509
-        if (isset($cols_n_values[ $qualified_column ])) {
5510
-            $value = $cols_n_values[ $qualified_column ];
5511
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5512
-            $value = $cols_n_values[ $regular_column ];
5513
-        } elseif (! empty($this->foreign_key_aliases)) {
5514
-            // no PK?  ok check if there is a foreign key alias set for this table
5515
-            // then check if that alias exists in the incoming data
5516
-            // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5517
-            foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5518
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5519
-                    $value = $cols_n_values[ $FK_alias ];
5520
-                    break;
5521
-                }
5522
-            }
5523
-        }
5524
-        return $value;
5525
-    }
5526
-
5527
-
5528
-    /**
5529
-     * refresh_entity_map_from_db
5530
-     * Makes sure the model object in the entity map at $id assumes the values
5531
-     * of the database (opposite of EE_base_Class::save())
5532
-     *
5533
-     * @param int|string $id
5534
-     * @return EE_Base_Class
5535
-     * @throws EE_Error
5536
-     * @throws ReflectionException
5537
-     */
5538
-    public function refresh_entity_map_from_db($id)
5539
-    {
5540
-        $obj_in_map = $this->get_from_entity_map($id);
5541
-        if ($obj_in_map) {
5542
-            $wpdb_results = $this->_get_all_wpdb_results(
5543
-                [[$this->get_primary_key_field()->get_name() => $id], 'limit' => 1]
5544
-            );
5545
-            if ($wpdb_results && is_array($wpdb_results)) {
5546
-                $one_row = reset($wpdb_results);
5547
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5548
-                    $obj_in_map->set_from_db($field_name, $db_value);
5549
-                }
5550
-                // clear the cache of related model objects
5551
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5552
-                    $obj_in_map->clear_cache($relation_name, null, true);
5553
-                }
5554
-            }
5555
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5556
-            return $obj_in_map;
5557
-        }
5558
-        return $this->get_one_by_ID($id);
5559
-    }
5560
-
5561
-
5562
-    /**
5563
-     * refresh_entity_map_with
5564
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5565
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5566
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5567
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5568
-     *
5569
-     * @param int|string    $id
5570
-     * @param EE_Base_Class $replacing_model_obj
5571
-     * @return EE_Base_Class
5572
-     * @throws EE_Error
5573
-     * @throws ReflectionException
5574
-     */
5575
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5576
-    {
5577
-        $obj_in_map = $this->get_from_entity_map($id);
5578
-        if ($obj_in_map) {
5579
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5580
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5581
-                    $obj_in_map->set($field_name, $value);
5582
-                }
5583
-                // make the model object in the entity map's cache match the $replacing_model_obj
5584
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5585
-                    $obj_in_map->clear_cache($relation_name, null, true);
5586
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5587
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5588
-                    }
5589
-                }
5590
-            }
5591
-            return $obj_in_map;
5592
-        }
5593
-        $this->add_to_entity_map($replacing_model_obj);
5594
-        return $replacing_model_obj;
5595
-    }
5596
-
5597
-
5598
-    /**
5599
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5600
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5601
-     * require_once($this->_getClassName().".class.php");
5602
-     *
5603
-     * @return string
5604
-     */
5605
-    private function _get_class_name()
5606
-    {
5607
-        return "EE_" . $this->get_this_model_name();
5608
-    }
5609
-
5610
-
5611
-    /**
5612
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5613
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5614
-     * it would be 'Events'.
5615
-     *
5616
-     * @param int $quantity
5617
-     * @return string
5618
-     */
5619
-    public function item_name($quantity = 1)
5620
-    {
5621
-        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5622
-    }
5623
-
5624
-
5625
-    /**
5626
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5627
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5628
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5629
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5630
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5631
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5632
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5633
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5634
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5635
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5636
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5637
-     *        return $previousReturnValue.$returnString;
5638
-     * }
5639
-     * require('EEM_Answer.model.php');
5640
-     * $answer=EEM_Answer::instance();
5641
-     * echo $answer->my_callback('monkeys',100);
5642
-     * //will output "you called my_callback! and passed args:monkeys,100"
5643
-     *
5644
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5645
-     * @param array  $args       array of original arguments passed to the function
5646
-     * @return mixed whatever the plugin which calls add_filter decides
5647
-     * @throws EE_Error
5648
-     */
5649
-    public function __call($methodName, $args)
5650
-    {
5651
-        $className = get_class($this);
5652
-        $tagName   = "FHEE__{$className}__{$methodName}";
5653
-        if (! has_filter($tagName)) {
5654
-            throw new EE_Error(
5655
-                sprintf(
5656
-                    esc_html__(
5657
-                        '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 );',
5658
-                        'event_espresso'
5659
-                    ),
5660
-                    $methodName,
5661
-                    $className,
5662
-                    $tagName,
5663
-                    '<br />'
5664
-                )
5665
-            );
5666
-        }
5667
-        return apply_filters($tagName, null, $this, $args);
5668
-    }
5669
-
5670
-
5671
-    /**
5672
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5673
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5674
-     *
5675
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5676
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5677
-     *                                                       the object's class name
5678
-     *                                                       or object's ID
5679
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5680
-     *                                                       exists in the database. If it does not, we add it
5681
-     * @return EE_Base_Class
5682
-     * @throws EE_Error
5683
-     * @throws ReflectionException
5684
-     */
5685
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5686
-    {
5687
-        $className = $this->_get_class_name();
5688
-        if ($base_class_obj_or_id instanceof $className) {
5689
-            $model_object = $base_class_obj_or_id;
5690
-        } else {
5691
-            $primary_key_field = $this->get_primary_key_field();
5692
-            if (
5693
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5694
-                && (
5695
-                    is_int($base_class_obj_or_id)
5696
-                    || is_string($base_class_obj_or_id)
5697
-                )
5698
-            ) {
5699
-                // assume it's an ID.
5700
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5701
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5702
-            } elseif (
5703
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5704
-                && is_string($base_class_obj_or_id)
5705
-            ) {
5706
-                // assume its a string representation of the object
5707
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5708
-            } else {
5709
-                throw new EE_Error(
5710
-                    sprintf(
5711
-                        esc_html__(
5712
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5713
-                            'event_espresso'
5714
-                        ),
5715
-                        $base_class_obj_or_id,
5716
-                        $this->_get_class_name(),
5717
-                        print_r($base_class_obj_or_id, true)
5718
-                    )
5719
-                );
5720
-            }
5721
-        }
5722
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5723
-            $model_object->save();
5724
-        }
5725
-        return $model_object;
5726
-    }
5727
-
5728
-
5729
-    /**
5730
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5731
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5732
-     * returns it ID.
5733
-     *
5734
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5735
-     * @return int|string depending on the type of this model object's ID
5736
-     * @throws EE_Error
5737
-     */
5738
-    public function ensure_is_ID($base_class_obj_or_id)
5739
-    {
5740
-        $className = $this->_get_class_name();
5741
-        if ($base_class_obj_or_id instanceof $className) {
5742
-            $id = $base_class_obj_or_id->ID();
5743
-        } elseif (is_int($base_class_obj_or_id)) {
5744
-            // assume it's an ID
5745
-            $id = $base_class_obj_or_id;
5746
-        } elseif (is_string($base_class_obj_or_id)) {
5747
-            // assume its a string representation of the object
5748
-            $id = $base_class_obj_or_id;
5749
-        } else {
5750
-            throw new EE_Error(
5751
-                sprintf(
5752
-                    esc_html__(
5753
-                        "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5754
-                        'event_espresso'
5755
-                    ),
5756
-                    $base_class_obj_or_id,
5757
-                    $this->_get_class_name(),
5758
-                    print_r($base_class_obj_or_id, true)
5759
-                )
5760
-            );
5761
-        }
5762
-        return $id;
5763
-    }
5764
-
5765
-
5766
-    /**
5767
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5768
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5769
-     * been sanitized and converted into the appropriate domain.
5770
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5771
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5772
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5773
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5774
-     * $EVT = EEM_Event::instance(); $old_setting =
5775
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5776
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5777
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5778
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5779
-     *
5780
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5781
-     * @return void
5782
-     */
5783
-    public function assume_values_already_prepared_by_model_object(
5784
-        $values_already_prepared = self::not_prepared_by_model_object
5785
-    ) {
5786
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5787
-    }
5788
-
5789
-
5790
-    /**
5791
-     * Read comments for assume_values_already_prepared_by_model_object()
5792
-     *
5793
-     * @return int
5794
-     */
5795
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5796
-    {
5797
-        return $this->_values_already_prepared_by_model_object;
5798
-    }
5799
-
5800
-
5801
-    /**
5802
-     * Gets all the indexes on this model
5803
-     *
5804
-     * @return EE_Index[]
5805
-     */
5806
-    public function indexes()
5807
-    {
5808
-        return $this->_indexes;
5809
-    }
5810
-
5811
-
5812
-    /**
5813
-     * Gets all the Unique Indexes on this model
5814
-     *
5815
-     * @return EE_Unique_Index[]
5816
-     */
5817
-    public function unique_indexes()
5818
-    {
5819
-        $unique_indexes = [];
5820
-        foreach ($this->_indexes as $name => $index) {
5821
-            if ($index instanceof EE_Unique_Index) {
5822
-                $unique_indexes [ $name ] = $index;
5823
-            }
5824
-        }
5825
-        return $unique_indexes;
5826
-    }
5827
-
5828
-
5829
-    /**
5830
-     * Gets all the fields which, when combined, make the primary key.
5831
-     * This is usually just an array with 1 element (the primary key), but in cases
5832
-     * where there is no primary key, it's a combination of fields as defined
5833
-     * on a primary index
5834
-     *
5835
-     * @return EE_Model_Field_Base[] indexed by the field's name
5836
-     * @throws EE_Error
5837
-     */
5838
-    public function get_combined_primary_key_fields()
5839
-    {
5840
-        foreach ($this->indexes() as $index) {
5841
-            if ($index instanceof EE_Primary_Key_Index) {
5842
-                return $index->fields();
5843
-            }
5844
-        }
5845
-        return [$this->primary_key_name() => $this->get_primary_key_field()];
5846
-    }
5847
-
5848
-
5849
-    /**
5850
-     * Used to build a primary key string (when the model has no primary key),
5851
-     * which can be used a unique string to identify this model object.
5852
-     *
5853
-     * @param array $fields_n_values keys are field names, values are their values.
5854
-     *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5855
-     *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5856
-     *                               before passing it to this function (that will convert it from columns-n-values
5857
-     *                               to field-names-n-values).
5858
-     * @return string
5859
-     * @throws EE_Error
5860
-     */
5861
-    public function get_index_primary_key_string($fields_n_values)
5862
-    {
5863
-        $cols_n_values_for_primary_key_index = array_intersect_key(
5864
-            $fields_n_values,
5865
-            $this->get_combined_primary_key_fields()
5866
-        );
5867
-        return http_build_query($cols_n_values_for_primary_key_index);
5868
-    }
5869
-
5870
-
5871
-    /**
5872
-     * Gets the field values from the primary key string
5873
-     *
5874
-     * @param string $index_primary_key_string
5875
-     * @return null|array
5876
-     * @throws EE_Error
5877
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5878
-     */
5879
-    public function parse_index_primary_key_string($index_primary_key_string)
5880
-    {
5881
-        $key_fields = $this->get_combined_primary_key_fields();
5882
-        // check all of them are in the $id
5883
-        $key_values_in_combined_pk = [];
5884
-        parse_str($index_primary_key_string, $key_values_in_combined_pk);
5885
-        foreach ($key_fields as $key_field_name => $field_obj) {
5886
-            if (! isset($key_values_in_combined_pk[ $key_field_name ])) {
5887
-                return null;
5888
-            }
5889
-        }
5890
-        return $key_values_in_combined_pk;
5891
-    }
5892
-
5893
-
5894
-    /**
5895
-     * verifies that an array of key-value pairs for model fields has a key
5896
-     * for each field comprising the primary key index
5897
-     *
5898
-     * @param array $key_values
5899
-     * @return boolean
5900
-     * @throws EE_Error
5901
-     */
5902
-    public function has_all_combined_primary_key_fields($key_values)
5903
-    {
5904
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5905
-        foreach ($keys_it_should_have as $key) {
5906
-            if (! isset($key_values[ $key ])) {
5907
-                return false;
5908
-            }
5909
-        }
5910
-        return true;
5911
-    }
5912
-
5913
-
5914
-    /**
5915
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5916
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5917
-     *
5918
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5919
-     * @param array               $query_params                     see github link below for more info
5920
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5921
-     * @throws EE_Error
5922
-     * @throws ReflectionException
5923
-     * @return EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5924
-     *                                                              indexed)
5925
-     */
5926
-    public function get_all_copies($model_object_or_attributes_array, $query_params = [])
5927
-    {
5928
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5929
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5930
-        } elseif (is_array($model_object_or_attributes_array)) {
5931
-            $attributes_array = $model_object_or_attributes_array;
5932
-        } else {
5933
-            throw new EE_Error(
5934
-                sprintf(
5935
-                    esc_html__(
5936
-                        "get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5937
-                        "event_espresso"
5938
-                    ),
5939
-                    $model_object_or_attributes_array
5940
-                )
5941
-            );
5942
-        }
5943
-        // even copies obviously won't have the same ID, so remove the primary key
5944
-        // from the WHERE conditions for finding copies (if there is a primary key, of course)
5945
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5946
-            unset($attributes_array[ $this->primary_key_name() ]);
5947
-        }
5948
-        if (isset($query_params[0])) {
5949
-            $query_params[0] = array_merge($attributes_array, $query_params);
5950
-        } else {
5951
-            $query_params[0] = $attributes_array;
5952
-        }
5953
-        return $this->get_all($query_params);
5954
-    }
5955
-
5956
-
5957
-    /**
5958
-     * Gets the first copy we find. See get_all_copies for more details
5959
-     *
5960
-     * @param mixed EE_Base_Class | array        $model_object_or_attributes_array
5961
-     * @param array $query_params
5962
-     * @return EE_Base_Class
5963
-     * @throws EE_Error
5964
-     * @throws ReflectionException
5965
-     */
5966
-    public function get_one_copy($model_object_or_attributes_array, $query_params = [])
5967
-    {
5968
-        if (! is_array($query_params)) {
5969
-            EE_Error::doing_it_wrong(
5970
-                'EEM_Base::get_one_copy',
5971
-                sprintf(
5972
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5973
-                    gettype($query_params)
5974
-                ),
5975
-                '4.6.0'
5976
-            );
5977
-            $query_params = [];
5978
-        }
5979
-        $query_params['limit'] = 1;
5980
-        $copies                = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5981
-        if (is_array($copies)) {
5982
-            return array_shift($copies);
5983
-        }
5984
-        return null;
5985
-    }
5986
-
5987
-
5988
-    /**
5989
-     * Updates the item with the specified id. Ignores default query parameters because
5990
-     * we have specified the ID, and its assumed we KNOW what we're doing
5991
-     *
5992
-     * @param array      $fields_n_values keys are field names, values are their new values
5993
-     * @param int|string $id              the value of the primary key to update
5994
-     * @return int number of rows updated
5995
-     * @throws EE_Error
5996
-     * @throws ReflectionException
5997
-     */
5998
-    public function update_by_ID($fields_n_values, $id)
5999
-    {
6000
-        $query_params = [
6001
-            0                          => [$this->get_primary_key_field()->get_name() => $id],
6002
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
6003
-        ];
6004
-        return $this->update($fields_n_values, $query_params);
6005
-    }
6006
-
6007
-
6008
-    /**
6009
-     * Changes an operator which was supplied to the models into one usable in SQL
6010
-     *
6011
-     * @param string $operator_supplied
6012
-     * @return string an operator which can be used in SQL
6013
-     * @throws EE_Error
6014
-     */
6015
-    private function _prepare_operator_for_sql($operator_supplied)
6016
-    {
6017
-        $sql_operator =
6018
-            isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
6019
-                : null;
6020
-        if ($sql_operator) {
6021
-            return $sql_operator;
6022
-        }
6023
-        throw new EE_Error(
6024
-            sprintf(
6025
-                esc_html__(
6026
-                    "The operator '%s' is not in the list of valid operators: %s",
6027
-                    "event_espresso"
6028
-                ),
6029
-                $operator_supplied,
6030
-                implode(",", array_keys($this->_valid_operators))
6031
-            )
6032
-        );
6033
-    }
6034
-
6035
-
6036
-    /**
6037
-     * Gets the valid operators
6038
-     *
6039
-     * @return array keys are accepted strings, values are the SQL they are converted to
6040
-     */
6041
-    public function valid_operators()
6042
-    {
6043
-        return $this->_valid_operators;
6044
-    }
6045
-
6046
-
6047
-    /**
6048
-     * Gets the between-style operators (take 2 arguments).
6049
-     *
6050
-     * @return array keys are accepted strings, values are the SQL they are converted to
6051
-     */
6052
-    public function valid_between_style_operators()
6053
-    {
6054
-        return array_intersect(
6055
-            $this->valid_operators(),
6056
-            $this->_between_style_operators
6057
-        );
6058
-    }
6059
-
6060
-
6061
-    /**
6062
-     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6063
-     *
6064
-     * @return array keys are accepted strings, values are the SQL they are converted to
6065
-     */
6066
-    public function valid_like_style_operators()
6067
-    {
6068
-        return array_intersect(
6069
-            $this->valid_operators(),
6070
-            $this->_like_style_operators
6071
-        );
6072
-    }
6073
-
6074
-
6075
-    /**
6076
-     * Gets the "in"-style operators
6077
-     *
6078
-     * @return array keys are accepted strings, values are the SQL they are converted to
6079
-     */
6080
-    public function valid_in_style_operators()
6081
-    {
6082
-        return array_intersect(
6083
-            $this->valid_operators(),
6084
-            $this->_in_style_operators
6085
-        );
6086
-    }
6087
-
6088
-
6089
-    /**
6090
-     * Gets the "null"-style operators (accept no arguments)
6091
-     *
6092
-     * @return array keys are accepted strings, values are the SQL they are converted to
6093
-     */
6094
-    public function valid_null_style_operators()
6095
-    {
6096
-        return array_intersect(
6097
-            $this->valid_operators(),
6098
-            $this->_null_style_operators
6099
-        );
6100
-    }
6101
-
6102
-
6103
-    /**
6104
-     * Gets an array where keys are the primary keys and values are their 'names'
6105
-     * (as determined by the model object's name() function, which is often overridden)
6106
-     *
6107
-     * @param array $query_params like get_all's
6108
-     * @return string[]
6109
-     * @throws EE_Error
6110
-     * @throws ReflectionException
6111
-     */
6112
-    public function get_all_names($query_params = [])
6113
-    {
6114
-        $objs  = $this->get_all($query_params);
6115
-        $names = [];
6116
-        foreach ($objs as $obj) {
6117
-            $names[ $obj->ID() ] = $obj->name();
6118
-        }
6119
-        return $names;
6120
-    }
6121
-
6122
-
6123
-    /**
6124
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
6125
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6126
-     * this is duplicated effort and reduces efficiency) you would be better to use
6127
-     * array_keys() on $model_objects.
6128
-     *
6129
-     * @param EE_Base_Class[] $model_objects
6130
-     * @param boolean         $filter_out_empty_ids  if a model object has an ID of '' or 0, don't bother including it
6131
-     *                                               in the returned array
6132
-     * @return array
6133
-     * @throws EE_Error
6134
-     */
6135
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
6136
-    {
6137
-        if (! $this->has_primary_key_field()) {
6138
-            if (WP_DEBUG) {
6139
-                EE_Error::add_error(
6140
-                    esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6141
-                    __FILE__,
6142
-                    __FUNCTION__,
6143
-                    __LINE__
6144
-                );
6145
-            }
6146
-        }
6147
-        $IDs = [];
6148
-        foreach ($model_objects as $model_object) {
6149
-            $id = $model_object->ID();
6150
-            if (! $id) {
6151
-                if ($filter_out_empty_ids) {
6152
-                    continue;
6153
-                }
6154
-                if (WP_DEBUG) {
6155
-                    EE_Error::add_error(
6156
-                        esc_html__(
6157
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6158
-                            'event_espresso'
6159
-                        ),
6160
-                        __FILE__,
6161
-                        __FUNCTION__,
6162
-                        __LINE__
6163
-                    );
6164
-                }
6165
-            }
6166
-            $IDs[] = $id;
6167
-        }
6168
-        return $IDs;
6169
-    }
6170
-
6171
-
6172
-    /**
6173
-     * Returns the string used in capabilities relating to this model. If there
6174
-     * are no capabilities that relate to this model returns false
6175
-     *
6176
-     * @return string|false
6177
-     */
6178
-    public function cap_slug()
6179
-    {
6180
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6181
-    }
6182
-
6183
-
6184
-    /**
6185
-     * Returns the capability-restrictions array (@param string $context
6186
-     *
6187
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
6188
-     * @throws EE_Error
6189
-     * @see EEM_Base::_cap_restrictions).
6190
-     *      If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6191
-     *      only returns the cap restrictions array in that context (ie, the array
6192
-     *      at that key)
6193
-     *
6194
-     */
6195
-    public function cap_restrictions($context = EEM_Base::caps_read)
6196
-    {
6197
-        EEM_Base::verify_is_valid_cap_context($context);
6198
-        // check if we ought to run the restriction generator first
6199
-        if (
6200
-            isset($this->_cap_restriction_generators[ $context ])
6201
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6202
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6203
-        ) {
6204
-            $this->_cap_restrictions[ $context ] = array_merge(
6205
-                $this->_cap_restrictions[ $context ],
6206
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6207
-            );
6208
-        }
6209
-        // and make sure we've finalized the construction of each restriction
6210
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6211
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6212
-                $where_conditions_obj->_finalize_construct($this);
6213
-            }
6214
-        }
6215
-        return $this->_cap_restrictions[ $context ];
6216
-    }
6217
-
6218
-
6219
-    /**
6220
-     * Indicating whether or not this model thinks its a wp core model
6221
-     *
6222
-     * @return boolean
6223
-     */
6224
-    public function is_wp_core_model()
6225
-    {
6226
-        return $this->_wp_core_model;
6227
-    }
6228
-
6229
-
6230
-    /**
6231
-     * Gets all the caps that are missing which impose a restriction on
6232
-     * queries made in this context
6233
-     *
6234
-     * @param string $context one of EEM_Base::caps_ constants
6235
-     * @return EE_Default_Where_Conditions[] indexed by capability name
6236
-     * @throws EE_Error
6237
-     */
6238
-    public function caps_missing($context = EEM_Base::caps_read)
6239
-    {
6240
-        $missing_caps     = [];
6241
-        $cap_restrictions = $this->cap_restrictions($context);
6242
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6243
-            if (
6244
-                ! EE_Capabilities::instance()->current_user_can(
6245
-                    $cap,
6246
-                    $this->get_this_model_name() . '_model_applying_caps'
6247
-                )
6248
-            ) {
6249
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6250
-            }
6251
-        }
6252
-        return $missing_caps;
6253
-    }
6254
-
6255
-
6256
-    /**
6257
-     * Gets the mapping from capability contexts to action strings used in capability names
6258
-     *
6259
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6260
-     * one of 'read', 'edit', or 'delete'
6261
-     */
6262
-    public function cap_contexts_to_cap_action_map()
6263
-    {
6264
-        return apply_filters(
6265
-            'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6266
-            $this->_cap_contexts_to_cap_action_map,
6267
-            $this
6268
-        );
6269
-    }
6270
-
6271
-
6272
-    /**
6273
-     * Gets the action string for the specified capability context
6274
-     *
6275
-     * @param string $context
6276
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6277
-     * @throws EE_Error
6278
-     */
6279
-    public function cap_action_for_context($context)
6280
-    {
6281
-        $mapping = $this->cap_contexts_to_cap_action_map();
6282
-        if (isset($mapping[ $context ])) {
6283
-            return $mapping[ $context ];
6284
-        }
6285
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6286
-            return $action;
6287
-        }
6288
-        throw new EE_Error(
6289
-            sprintf(
6290
-                esc_html__(
6291
-                    'Cannot find capability restrictions for context "%1$s", allowed values are:%2$s',
6292
-                    'event_espresso'
6293
-                ),
6294
-                $context,
6295
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6296
-            )
6297
-        );
6298
-    }
6299
-
6300
-
6301
-    /**
6302
-     * Returns all the capability contexts which are valid when querying models
6303
-     *
6304
-     * @return array
6305
-     */
6306
-    public static function valid_cap_contexts()
6307
-    {
6308
-        return apply_filters(
6309
-            'FHEE__EEM_Base__valid_cap_contexts',
6310
-            [
6311
-                self::caps_read,
6312
-                self::caps_read_admin,
6313
-                self::caps_edit,
6314
-                self::caps_delete,
6315
-            ]
6316
-        );
6317
-    }
6318
-
6319
-
6320
-    /**
6321
-     * Returns all valid options for 'default_where_conditions'
6322
-     *
6323
-     * @return array
6324
-     */
6325
-    public static function valid_default_where_conditions()
6326
-    {
6327
-        return [
6328
-            EEM_Base::default_where_conditions_all,
6329
-            EEM_Base::default_where_conditions_this_only,
6330
-            EEM_Base::default_where_conditions_others_only,
6331
-            EEM_Base::default_where_conditions_minimum_all,
6332
-            EEM_Base::default_where_conditions_minimum_others,
6333
-            EEM_Base::default_where_conditions_none,
6334
-        ];
6335
-    }
6336
-
6337
-    // public static function default_where_conditions_full
6338
-
6339
-
6340
-    /**
6341
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6342
-     *
6343
-     * @param string $context
6344
-     * @return bool
6345
-     * @throws EE_Error
6346
-     */
6347
-    public static function verify_is_valid_cap_context($context)
6348
-    {
6349
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
6350
-        if (in_array($context, $valid_cap_contexts)) {
6351
-            return true;
6352
-        }
6353
-        throw new EE_Error(
6354
-            sprintf(
6355
-                esc_html__(
6356
-                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6357
-                    'event_espresso'
6358
-                ),
6359
-                $context,
6360
-                'EEM_Base',
6361
-                implode(',', $valid_cap_contexts)
6362
-            )
6363
-        );
6364
-    }
6365
-
6366
-
6367
-    /**
6368
-     * Clears all the models field caches. This is only useful when a sub-class
6369
-     * might have added a field or something and these caches might be invalidated
6370
-     */
6371
-    protected function _invalidate_field_caches()
6372
-    {
6373
-        $this->_cache_foreign_key_to_fields = [];
6374
-        $this->_cached_fields               = null;
6375
-        $this->_cached_fields_non_db_only   = null;
6376
-    }
6377
-
6378
-
6379
-    /**
6380
-     * Gets the list of all the where query param keys that relate to logic instead of field names
6381
-     * (eg "and", "or", "not").
6382
-     *
6383
-     * @return array
6384
-     */
6385
-    public function logic_query_param_keys()
6386
-    {
6387
-        return $this->_logic_query_param_keys;
6388
-    }
6389
-
6390
-
6391
-    /**
6392
-     * Determines whether or not the where query param array key is for a logic query param.
6393
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6394
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6395
-     *
6396
-     * @param $query_param_key
6397
-     * @return bool
6398
-     */
6399
-    public function is_logic_query_param_key($query_param_key)
6400
-    {
6401
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6402
-            if (
6403
-                $query_param_key === $logic_query_param_key
6404
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6405
-            ) {
6406
-                return true;
6407
-            }
6408
-        }
6409
-        return false;
6410
-    }
6411
-
6412
-
6413
-    /**
6414
-     * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6415
-     *
6416
-     * @return boolean
6417
-     * @since 4.9.74.p
6418
-     */
6419
-    public function hasPassword()
6420
-    {
6421
-        // if we don't yet know if there's a password field, find out and remember it for next time.
6422
-        if ($this->has_password_field === null) {
6423
-            $password_field           = $this->getPasswordField();
6424
-            $this->has_password_field = $password_field instanceof EE_Password_Field;
6425
-        }
6426
-        return $this->has_password_field;
6427
-    }
6428
-
6429
-
6430
-    /**
6431
-     * Returns the password field on this model, if there is one
6432
-     *
6433
-     * @return EE_Password_Field|null
6434
-     * @since 4.9.74.p
6435
-     */
6436
-    public function getPasswordField()
6437
-    {
6438
-        // if we definitely already know there is a password field or not (because has_password_field is true or false)
6439
-        // there's no need to search for it. If we don't know yet, then find out
6440
-        if ($this->has_password_field === null && $this->password_field === null) {
6441
-            $this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6442
-        }
6443
-        // don't bother setting has_password_field because that's hasPassword()'s job.
6444
-        return $this->password_field;
6445
-    }
6446
-
6447
-
6448
-    /**
6449
-     * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6450
-     *
6451
-     * @return EE_Model_Field_Base[]
6452
-     * @throws EE_Error
6453
-     * @since 4.9.74.p
6454
-     */
6455
-    public function getPasswordProtectedFields()
6456
-    {
6457
-        $password_field = $this->getPasswordField();
6458
-        $fields         = [];
6459
-        if ($password_field instanceof EE_Password_Field) {
6460
-            $field_names = $password_field->protectedFields();
6461
-            foreach ($field_names as $field_name) {
6462
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6463
-            }
6464
-        }
6465
-        return $fields;
6466
-    }
6467
-
6468
-
6469
-    /**
6470
-     * Checks if the current user can perform the requested action on this model
6471
-     *
6472
-     * @param string              $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6473
-     * @param EE_Base_Class|array $model_obj_or_fields_n_values
6474
-     * @return bool
6475
-     * @throws EE_Error
6476
-     * @throws InvalidArgumentException
6477
-     * @throws InvalidDataTypeException
6478
-     * @throws InvalidInterfaceException
6479
-     * @throws ReflectionException
6480
-     * @throws UnexpectedEntityException
6481
-     * @since 4.9.74.p
6482
-     */
6483
-    public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6484
-    {
6485
-        if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6486
-            $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6487
-        }
6488
-        if (! is_array($model_obj_or_fields_n_values)) {
6489
-            throw new UnexpectedEntityException(
6490
-                $model_obj_or_fields_n_values,
6491
-                'EE_Base_Class',
6492
-                sprintf(
6493
-                    esc_html__(
6494
-                        '%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.',
6495
-                        'event_espresso'
6496
-                    ),
6497
-                    __FUNCTION__
6498
-                )
6499
-            );
6500
-        }
6501
-        return $this->exists(
6502
-            $this->alter_query_params_to_restrict_by_ID(
6503
-                $this->get_index_primary_key_string($model_obj_or_fields_n_values),
6504
-                [
6505
-                    'default_where_conditions' => 'none',
6506
-                    'caps'                     => $cap_to_check,
6507
-                ]
6508
-            )
6509
-        );
6510
-    }
6511
-
6512
-
6513
-    /**
6514
-     * Returns the query param where conditions key to the password affecting this model.
6515
-     * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6516
-     *
6517
-     * @return null|string
6518
-     * @throws EE_Error
6519
-     * @throws InvalidArgumentException
6520
-     * @throws InvalidDataTypeException
6521
-     * @throws InvalidInterfaceException
6522
-     * @throws ModelConfigurationException
6523
-     * @throws ReflectionException
6524
-     * @since 4.9.74.p
6525
-     */
6526
-    public function modelChainAndPassword()
6527
-    {
6528
-        if ($this->model_chain_to_password === null) {
6529
-            throw new ModelConfigurationException(
6530
-                $this,
6531
-                esc_html_x(
6532
-                // @codingStandardsIgnoreStart
6533
-                    'Cannot exclude protected data because the model has not specified which model has the password.',
6534
-                    // @codingStandardsIgnoreEnd
6535
-                    '1: model name',
6536
-                    'event_espresso'
6537
-                )
6538
-            );
6539
-        }
6540
-        if ($this->model_chain_to_password === '') {
6541
-            $model_with_password = $this;
6542
-        } else {
6543
-            if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6544
-                $last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6545
-            } else {
6546
-                $last_model_in_chain = $this->model_chain_to_password;
6547
-            }
6548
-            $model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6549
-        }
6550
-
6551
-        $password_field = $model_with_password->getPasswordField();
6552
-        if ($password_field instanceof EE_Password_Field) {
6553
-            $password_field_name = $password_field->get_name();
6554
-        } else {
6555
-            throw new ModelConfigurationException(
6556
-                $this,
6557
-                sprintf(
6558
-                    esc_html_x(
6559
-                        '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"',
6560
-                        '1: model name, 2: special string',
6561
-                        'event_espresso'
6562
-                    ),
6563
-                    $model_with_password->get_this_model_name(),
6564
-                    $this->model_chain_to_password
6565
-                )
6566
-            );
6567
-        }
6568
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6569
-    }
6570
-
6571
-
6572
-    /**
6573
-     * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6574
-     * or if this model itself has a password affecting access to some of its other fields.
6575
-     *
6576
-     * @return boolean
6577
-     * @since 4.9.74.p
6578
-     */
6579
-    public function restrictedByRelatedModelPassword()
6580
-    {
6581
-        return $this->model_chain_to_password !== null;
6582
-    }
3864
+		}
3865
+		return $null_friendly_where_conditions;
3866
+	}
3867
+
3868
+
3869
+	/**
3870
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3871
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3872
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3873
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3874
+	 *
3875
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3876
+	 * @return array
3877
+	 * @throws EE_Error
3878
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3879
+	 */
3880
+	private function _get_default_where_conditions($model_relation_path = '')
3881
+	{
3882
+		if ($this->_ignore_where_strategy) {
3883
+			return [];
3884
+		}
3885
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3886
+	}
3887
+
3888
+
3889
+	/**
3890
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3891
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3892
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3893
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3894
+	 * Similar to _get_default_where_conditions
3895
+	 *
3896
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3897
+	 * @return array
3898
+	 * @throws EE_Error
3899
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3900
+	 */
3901
+	protected function _get_minimum_where_conditions($model_relation_path = '')
3902
+	{
3903
+		if ($this->_ignore_where_strategy) {
3904
+			return [];
3905
+		}
3906
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3907
+	}
3908
+
3909
+
3910
+	/**
3911
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3912
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3913
+	 *
3914
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3915
+	 * @return string
3916
+	 * @throws EE_Error
3917
+	 */
3918
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3919
+	{
3920
+		$selects = $this->_get_columns_to_select_for_this_model();
3921
+		foreach (
3922
+			$model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included
3923
+		) {
3924
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3925
+			$other_model_selects  = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3926
+			foreach ($other_model_selects as $key => $value) {
3927
+				$selects[] = $value;
3928
+			}
3929
+		}
3930
+		return implode(", ", $selects);
3931
+	}
3932
+
3933
+
3934
+	/**
3935
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3936
+	 * So that's going to be the columns for all the fields on the model
3937
+	 *
3938
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3939
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3940
+	 */
3941
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3942
+	{
3943
+		$fields                                       = $this->field_settings();
3944
+		$selects                                      = [];
3945
+		$table_alias_with_model_relation_chain_prefix =
3946
+			EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3947
+				$model_relation_chain,
3948
+				$this->get_this_model_name()
3949
+			);
3950
+		foreach ($fields as $field_obj) {
3951
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3952
+						 . $field_obj->get_table_alias()
3953
+						 . "."
3954
+						 . $field_obj->get_table_column()
3955
+						 . " AS '"
3956
+						 . $table_alias_with_model_relation_chain_prefix
3957
+						 . $field_obj->get_table_alias()
3958
+						 . "."
3959
+						 . $field_obj->get_table_column()
3960
+						 . "'";
3961
+		}
3962
+		// make sure we are also getting the PKs of each table
3963
+		$tables = $this->get_tables();
3964
+		if (count($tables) > 1) {
3965
+			foreach ($tables as $table_obj) {
3966
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3967
+									   . $table_obj->get_fully_qualified_pk_column();
3968
+				if (! in_array($qualified_pk_column, $selects)) {
3969
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3970
+				}
3971
+			}
3972
+		}
3973
+		return $selects;
3974
+	}
3975
+
3976
+
3977
+	/**
3978
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3979
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3980
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3981
+	 * SQL for joining, and the data types
3982
+	 *
3983
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3984
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3985
+	 * @param string                      $query_param_type     like Registration.Transaction.TXN_ID
3986
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3987
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3988
+	 *                                                          or 'Registration's
3989
+	 * @param string|null                 $original_query_param what it originally was (eg
3990
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3991
+	 *                                                          matches $query_param
3992
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3993
+	 * @throws EE_Error
3994
+	 */
3995
+	private function _extract_related_model_info_from_query_param(
3996
+		$query_param,
3997
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3998
+		$query_param_type,
3999
+		$original_query_param = null
4000
+	) {
4001
+		if ($original_query_param === null) {
4002
+			$original_query_param = $query_param;
4003
+		}
4004
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4005
+		// whether or not to allow logic_query_params like 'NOT','OR', or 'AND'
4006
+		$allow_logic_query_params = in_array($query_param_type, ['where', 'having', 0, 'custom_selects'], true);
4007
+		$allow_fields             = in_array(
4008
+			$query_param_type,
4009
+			['where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0],
4010
+			true
4011
+		);
4012
+		// check to see if we have a field on this model
4013
+		$this_model_fields = $this->field_settings(true);
4014
+		if (array_key_exists($query_param, $this_model_fields)) {
4015
+			if ($allow_fields) {
4016
+				return;
4017
+			}
4018
+			throw new EE_Error(
4019
+				sprintf(
4020
+					esc_html__(
4021
+						"Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
4022
+						"event_espresso"
4023
+					),
4024
+					$query_param,
4025
+					get_class($this),
4026
+					$query_param_type,
4027
+					$original_query_param
4028
+				)
4029
+			);
4030
+		}
4031
+		// check if this is a special logic query param
4032
+		if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4033
+			if ($allow_logic_query_params) {
4034
+				return;
4035
+			}
4036
+			throw new EE_Error(
4037
+				sprintf(
4038
+					esc_html__(
4039
+						'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',
4040
+						'event_espresso'
4041
+					),
4042
+					implode('", "', $this->_logic_query_param_keys),
4043
+					$query_param,
4044
+					get_class($this),
4045
+					'<br />',
4046
+					"\t"
4047
+					. ' $passed_in_query_info = <pre>'
4048
+					. print_r($passed_in_query_info, true)
4049
+					. '</pre>'
4050
+					. "\n\t"
4051
+					. ' $query_param_type = '
4052
+					. $query_param_type
4053
+					. "\n\t"
4054
+					. ' $original_query_param = '
4055
+					. $original_query_param
4056
+				)
4057
+			);
4058
+		}
4059
+		// check if it's a custom selection
4060
+		if (
4061
+			$this->_custom_selections instanceof CustomSelects
4062
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4063
+		) {
4064
+			return;
4065
+		}
4066
+		// check if has a model name at the beginning
4067
+		// and
4068
+		// check if it's a field on a related model
4069
+		if (
4070
+			$this->extractJoinModelFromQueryParams(
4071
+				$passed_in_query_info,
4072
+				$query_param,
4073
+				$original_query_param,
4074
+				$query_param_type
4075
+			)
4076
+		) {
4077
+			return;
4078
+		}
4079
+
4080
+		// ok so $query_param didn't start with a model name
4081
+		// and we previously confirmed it wasn't a logic query param or field on the current model
4082
+		// it's wack, that's what it is
4083
+		throw new EE_Error(
4084
+			sprintf(
4085
+				esc_html__(
4086
+					"There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4087
+					"event_espresso"
4088
+				),
4089
+				$query_param,
4090
+				get_class($this),
4091
+				$query_param_type,
4092
+				$original_query_param
4093
+			)
4094
+		);
4095
+	}
4096
+
4097
+
4098
+	/**
4099
+	 * Extracts any possible join model information from the provided possible_join_string.
4100
+	 * This method will read the provided $possible_join_string value and determine if there are any possible model
4101
+	 * join
4102
+	 * parts that should be added to the query.
4103
+	 *
4104
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4105
+	 * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4106
+	 * @param null|string                 $original_query_param
4107
+	 * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4108
+	 *                                                           ('where', 'order_by', 'group_by', 'custom_selects'
4109
+	 *                                                           etc.)
4110
+	 * @return bool  returns true if a join was added and false if not.
4111
+	 * @throws EE_Error
4112
+	 */
4113
+	private function extractJoinModelFromQueryParams(
4114
+		EE_Model_Query_Info_Carrier $query_info_carrier,
4115
+		$possible_join_string,
4116
+		$original_query_param,
4117
+		$query_parameter_type
4118
+	) {
4119
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4120
+			if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4121
+				$this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4122
+				$possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4123
+				if ($possible_join_string === '') {
4124
+					// nothing left to $query_param
4125
+					// we should actually end in a field name, not a model like this!
4126
+					throw new EE_Error(
4127
+						sprintf(
4128
+							esc_html__(
4129
+								"Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4130
+								"event_espresso"
4131
+							),
4132
+							$possible_join_string,
4133
+							$query_parameter_type,
4134
+							get_class($this),
4135
+							$valid_related_model_name
4136
+						)
4137
+					);
4138
+				}
4139
+				$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4140
+				$related_model_obj->_extract_related_model_info_from_query_param(
4141
+					$possible_join_string,
4142
+					$query_info_carrier,
4143
+					$query_parameter_type,
4144
+					$original_query_param
4145
+				);
4146
+				return true;
4147
+			}
4148
+			if ($possible_join_string === $valid_related_model_name) {
4149
+				$this->_add_join_to_model(
4150
+					$valid_related_model_name,
4151
+					$query_info_carrier,
4152
+					$original_query_param
4153
+				);
4154
+				return true;
4155
+			}
4156
+		}
4157
+		return false;
4158
+	}
4159
+
4160
+
4161
+	/**
4162
+	 * Extracts related models from Custom Selects and sets up any joins for those related models.
4163
+	 *
4164
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4165
+	 * @throws EE_Error
4166
+	 */
4167
+	private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4168
+	{
4169
+		if (
4170
+			$this->_custom_selections instanceof CustomSelects
4171
+			&& ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4172
+				|| $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4173
+			)
4174
+		) {
4175
+			$original_selects = $this->_custom_selections->originalSelects();
4176
+			foreach ($original_selects as $alias => $select_configuration) {
4177
+				$this->extractJoinModelFromQueryParams(
4178
+					$query_info_carrier,
4179
+					$select_configuration[0],
4180
+					$select_configuration[0],
4181
+					'custom_selects'
4182
+				);
4183
+			}
4184
+		}
4185
+	}
4186
+
4187
+
4188
+	/**
4189
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4190
+	 * and store it on $passed_in_query_info
4191
+	 *
4192
+	 * @param string                      $model_name
4193
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4194
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
4195
+	 *                                                          model and $model_name. Eg, if we are querying Event,
4196
+	 *                                                          and are adding a join to 'Payment' with the original
4197
+	 *                                                          query param key
4198
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4199
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
4200
+	 *                                                          Payment wants to add default query params so that it
4201
+	 *                                                          will know what models to prepend onto its default query
4202
+	 *                                                          params or in case it wants to rename tables (in case
4203
+	 *                                                          there are multiple joins to the same table)
4204
+	 * @return void
4205
+	 * @throws EE_Error
4206
+	 */
4207
+	private function _add_join_to_model(
4208
+		$model_name,
4209
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4210
+		$original_query_param
4211
+	) {
4212
+		$relation_obj         = $this->related_settings_for($model_name);
4213
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4214
+		// check if the relation is HABTM, because then we're essentially doing two joins
4215
+		// If so, join first to the JOIN table, and add its data types, and then continue as normal
4216
+		if ($relation_obj instanceof EE_HABTM_Relation) {
4217
+			$join_model_obj = $relation_obj->get_join_model();
4218
+			// replace the model specified with the join model for this relation chain, whi
4219
+			$relation_chain_to_join_model =
4220
+				EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4221
+					$model_name,
4222
+					$join_model_obj->get_this_model_name(),
4223
+					$model_relation_chain
4224
+				);
4225
+			$passed_in_query_info->merge(
4226
+				new EE_Model_Query_Info_Carrier(
4227
+					[$relation_chain_to_join_model => $join_model_obj->get_this_model_name()],
4228
+					$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4229
+				)
4230
+			);
4231
+		}
4232
+		// now just join to the other table pointed to by the relation object, and add its data types
4233
+		$passed_in_query_info->merge(
4234
+			new EE_Model_Query_Info_Carrier(
4235
+				[$model_relation_chain => $model_name],
4236
+				$relation_obj->get_join_statement($model_relation_chain)
4237
+			)
4238
+		);
4239
+	}
4240
+
4241
+
4242
+	/**
4243
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4244
+	 *
4245
+	 * @param array $where_params
4246
+	 * @return string of SQL
4247
+	 * @throws EE_Error
4248
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4249
+	 */
4250
+	private function _construct_where_clause($where_params)
4251
+	{
4252
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4253
+		if ($SQL) {
4254
+			return " WHERE " . $SQL;
4255
+		}
4256
+		return '';
4257
+	}
4258
+
4259
+
4260
+	/**
4261
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4262
+	 * and should be passed HAVING parameters, not WHERE parameters
4263
+	 *
4264
+	 * @param array $having_params
4265
+	 * @return string
4266
+	 * @throws EE_Error
4267
+	 */
4268
+	private function _construct_having_clause($having_params)
4269
+	{
4270
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4271
+		if ($SQL) {
4272
+			return " HAVING " . $SQL;
4273
+		}
4274
+		return '';
4275
+	}
4276
+
4277
+
4278
+	/**
4279
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4280
+	 * Event_Meta.meta_value = 'foo'))"
4281
+	 *
4282
+	 * @param array  $where_params
4283
+	 * @param string $glue joins each sub-clause together. Should really only be " AND " or " OR "...
4284
+	 * @return string of SQL
4285
+	 * @throws EE_Error
4286
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4287
+	 */
4288
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4289
+	{
4290
+		$where_clauses = [];
4291
+		// loop over where params:
4292
+		// keys are query params and values are the operators and values OR sub conditions
4293
+		foreach ($where_params as $query_param => $value) {
4294
+			$query_param =
4295
+				$this->_remove_stars_and_anything_after_from_condition_query_param_key(
4296
+					$query_param
4297
+				);// str_replace("*",'',$query_param);
4298
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
4299
+				$open = ' (';
4300
+				$close = ')';
4301
+				$conditions = '';
4302
+				switch ($query_param) {
4303
+					case 'not':
4304
+					case 'NOT':
4305
+						$open = " !{$open}";
4306
+						$conditions = $this->_construct_condition_clause_recursive($value, $glue);
4307
+						break;
4308
+					case 'and':
4309
+					case 'AND':
4310
+						$conditions = $this->_construct_condition_clause_recursive($value, ' AND ');
4311
+						break;
4312
+					case 'or':
4313
+					case 'OR':
4314
+						$conditions = $this->_construct_condition_clause_recursive($value, ' OR ');
4315
+						break;
4316
+				}
4317
+				if ($conditions !== '') {
4318
+					$where_clauses[] = "{$open}{$conditions}{$close}";
4319
+				}
4320
+			} else {
4321
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4322
+				// if it's not a normal field, maybe it's a custom selection?
4323
+				if (! $field_obj) {
4324
+					if ($this->_custom_selections instanceof CustomSelects) {
4325
+						$field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4326
+					} else {
4327
+						throw new EE_Error(
4328
+							sprintf(
4329
+								esc_html__(
4330
+									"%s is neither a valid model field name, nor a custom selection",
4331
+									"event_espresso"
4332
+								),
4333
+								$query_param
4334
+							)
4335
+						);
4336
+					}
4337
+				}
4338
+				$op_and_value_sql = $this->_construct_op_and_value($value, $field_obj);
4339
+				$where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4340
+			}
4341
+		}
4342
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4343
+	}
4344
+
4345
+
4346
+	/**
4347
+	 * Takes the input parameter and extract the table name (alias) and column name
4348
+	 *
4349
+	 * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4350
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4351
+	 * @throws EE_Error
4352
+	 */
4353
+	private function _deduce_column_name_from_query_param($query_param)
4354
+	{
4355
+		$field = $this->_deduce_field_from_query_param($query_param);
4356
+		if ($field) {
4357
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4358
+				$field->get_model_name(),
4359
+				$query_param
4360
+			);
4361
+			return $table_alias_prefix . $field->get_qualified_column();
4362
+		}
4363
+		if (
4364
+			$this->_custom_selections instanceof CustomSelects
4365
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4366
+		) {
4367
+			// maybe it's custom selection item?
4368
+			// if so, just use it as the "column name"
4369
+			return $query_param;
4370
+		}
4371
+		$custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4372
+			? implode(',', $this->_custom_selections->columnAliases())
4373
+			: '';
4374
+		throw new EE_Error(
4375
+			sprintf(
4376
+				esc_html__(
4377
+					"%s is not a valid field on this model, nor a custom selection (%s)",
4378
+					"event_espresso"
4379
+				),
4380
+				$query_param,
4381
+				$custom_select_aliases
4382
+			)
4383
+		);
4384
+	}
4385
+
4386
+
4387
+	/**
4388
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4389
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4390
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4391
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4392
+	 *
4393
+	 * @param string $condition_query_param_key
4394
+	 * @return string
4395
+	 */
4396
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4397
+	{
4398
+		$pos_of_star = strpos($condition_query_param_key, '*');
4399
+		if ($pos_of_star === false) {
4400
+			return $condition_query_param_key;
4401
+		}
4402
+		return substr($condition_query_param_key, 0, $pos_of_star);
4403
+	}
4404
+
4405
+
4406
+	/**
4407
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4408
+	 *
4409
+	 * @param mixed      array | string    $op_and_value
4410
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4411
+	 * @return string
4412
+	 * @throws EE_Error
4413
+	 */
4414
+	private function _construct_op_and_value($op_and_value, $field_obj)
4415
+	{
4416
+		if (is_array($op_and_value)) {
4417
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4418
+			if (! $operator) {
4419
+				$php_array_like_string = [];
4420
+				foreach ($op_and_value as $key => $value) {
4421
+					$php_array_like_string[] = "$key=>$value";
4422
+				}
4423
+				throw new EE_Error(
4424
+					sprintf(
4425
+						esc_html__(
4426
+							"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))",
4427
+							"event_espresso"
4428
+						),
4429
+						implode(",", $php_array_like_string)
4430
+					)
4431
+				);
4432
+			}
4433
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4434
+		} else {
4435
+			$operator = '=';
4436
+			$value    = $op_and_value;
4437
+		}
4438
+		// check to see if the value is actually another field
4439
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4440
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4441
+		}
4442
+		if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4443
+			// in this case, the value should be an array, or at least a comma-separated list
4444
+			// it will need to handle a little differently
4445
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4446
+			// note: $cleaned_value has already been run through $wpdb->prepare()
4447
+			return $operator . SP . $cleaned_value;
4448
+		}
4449
+		if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4450
+			// the value should be an array with count of two.
4451
+			if (count($value) !== 2) {
4452
+				throw new EE_Error(
4453
+					sprintf(
4454
+						esc_html__(
4455
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4456
+							'event_espresso'
4457
+						),
4458
+						"BETWEEN"
4459
+					)
4460
+				);
4461
+			}
4462
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4463
+			return $operator . SP . $cleaned_value;
4464
+		}
4465
+		if (in_array($operator, $this->valid_null_style_operators())) {
4466
+			if ($value !== null) {
4467
+				throw new EE_Error(
4468
+					sprintf(
4469
+						esc_html__(
4470
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4471
+							"event_espresso"
4472
+						),
4473
+						$value,
4474
+						$operator
4475
+					)
4476
+				);
4477
+			}
4478
+			return $operator;
4479
+		}
4480
+		if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4481
+			// if the operator is 'LIKE', we want to allow percent signs (%) and not
4482
+			// remove other junk. So just treat it as a string.
4483
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4484
+		}
4485
+		if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4486
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4487
+		}
4488
+		if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4489
+			throw new EE_Error(
4490
+				sprintf(
4491
+					esc_html__(
4492
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4493
+						'event_espresso'
4494
+					),
4495
+					$operator,
4496
+					$operator
4497
+				)
4498
+			);
4499
+		}
4500
+		if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4501
+			throw new EE_Error(
4502
+				sprintf(
4503
+					esc_html__(
4504
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4505
+						'event_espresso'
4506
+					),
4507
+					$operator,
4508
+					$operator
4509
+				)
4510
+			);
4511
+		}
4512
+		throw new EE_Error(
4513
+			sprintf(
4514
+				esc_html__(
4515
+					"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4516
+					"event_espresso"
4517
+				),
4518
+				http_build_query($op_and_value)
4519
+			)
4520
+		);
4521
+	}
4522
+
4523
+
4524
+	/**
4525
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4526
+	 *
4527
+	 * @param array                      $values
4528
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4529
+	 *                                              '%s'
4530
+	 * @return string
4531
+	 * @throws EE_Error
4532
+	 */
4533
+	public function _construct_between_value($values, $field_obj)
4534
+	{
4535
+		$cleaned_values = [];
4536
+		foreach ($values as $value) {
4537
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4538
+		}
4539
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4540
+	}
4541
+
4542
+
4543
+	/**
4544
+	 * Takes an array or a comma-separated list of $values and cleans them
4545
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4546
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4547
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4548
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4549
+	 *
4550
+	 * @param mixed                      $values    array or comma-separated string
4551
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4552
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4553
+	 * @throws EE_Error
4554
+	 */
4555
+	public function _construct_in_value($values, $field_obj)
4556
+	{
4557
+		// check if the value is a CSV list
4558
+		if (is_string($values)) {
4559
+			// in which case, turn it into an array
4560
+			$values = explode(",", $values);
4561
+		}
4562
+		$cleaned_values = [];
4563
+		foreach ($values as $value) {
4564
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4565
+		}
4566
+		// we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4567
+		// but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4568
+		// which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4569
+		if (empty($cleaned_values)) {
4570
+			$all_fields       = $this->field_settings();
4571
+			$a_field          = array_shift($all_fields);
4572
+			$main_table       = $this->_get_main_table();
4573
+			$cleaned_values[] = "SELECT "
4574
+								. $a_field->get_table_column()
4575
+								. " FROM "
4576
+								. $main_table->get_table_name()
4577
+								. " WHERE FALSE";
4578
+		}
4579
+		return "(" . implode(",", $cleaned_values) . ")";
4580
+	}
4581
+
4582
+
4583
+	/**
4584
+	 * @param mixed                      $value
4585
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4586
+	 * @return false|null|string
4587
+	 * @throws EE_Error
4588
+	 */
4589
+	private function _wpdb_prepare_using_field($value, $field_obj)
4590
+	{
4591
+		global $wpdb;
4592
+		if ($field_obj instanceof EE_Model_Field_Base) {
4593
+			return $wpdb->prepare(
4594
+				$field_obj->get_wpdb_data_type(),
4595
+				$this->_prepare_value_for_use_in_db($value, $field_obj)
4596
+			);
4597
+		} //$field_obj should really just be a data type
4598
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4599
+			throw new EE_Error(
4600
+				sprintf(
4601
+					esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4602
+					$field_obj,
4603
+					implode(",", $this->_valid_wpdb_data_types)
4604
+				)
4605
+			);
4606
+		}
4607
+		return $wpdb->prepare($field_obj, $value);
4608
+	}
4609
+
4610
+
4611
+	/**
4612
+	 * Takes the input parameter and finds the model field that it indicates.
4613
+	 *
4614
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4615
+	 * @return EE_Model_Field_Base
4616
+	 * @throws EE_Error
4617
+	 */
4618
+	protected function _deduce_field_from_query_param($query_param_name)
4619
+	{
4620
+		// ok, now proceed with deducing which part is the model's name, and which is the field's name
4621
+		// which will help us find the database table and column
4622
+		$query_param_parts = explode(".", $query_param_name);
4623
+		if (empty($query_param_parts)) {
4624
+			throw new EE_Error(
4625
+				sprintf(
4626
+					esc_html__(
4627
+						"_extract_column_name is empty when trying to extract column and table name from %s",
4628
+						'event_espresso'
4629
+					),
4630
+					$query_param_name
4631
+				)
4632
+			);
4633
+		}
4634
+		$number_of_parts       = count($query_param_parts);
4635
+		$last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4636
+		if ($number_of_parts === 1) {
4637
+			$field_name = $last_query_param_part;
4638
+			$model_obj  = $this;
4639
+		} else {// $number_of_parts >= 2
4640
+			// the last part is the column name, and there are only 2parts. therefore...
4641
+			$field_name = $last_query_param_part;
4642
+			$model_obj  = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4643
+		}
4644
+		try {
4645
+			return $model_obj->field_settings_for($field_name);
4646
+		} catch (EE_Error $e) {
4647
+			return null;
4648
+		}
4649
+	}
4650
+
4651
+
4652
+	/**
4653
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4654
+	 * alias and column which corresponds to it
4655
+	 *
4656
+	 * @param string $field_name
4657
+	 * @return string
4658
+	 * @throws EE_Error
4659
+	 */
4660
+	public function _get_qualified_column_for_field($field_name)
4661
+	{
4662
+		$all_fields = $this->field_settings();
4663
+		$field      = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4664
+		if ($field) {
4665
+			return $field->get_qualified_column();
4666
+		}
4667
+		throw new EE_Error(
4668
+			sprintf(
4669
+				esc_html__(
4670
+					"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.",
4671
+					'event_espresso'
4672
+				),
4673
+				$field_name,
4674
+				get_class($this)
4675
+			)
4676
+		);
4677
+	}
4678
+
4679
+
4680
+	/**
4681
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4682
+	 * Example usage:
4683
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4684
+	 *      array(),
4685
+	 *      ARRAY_A,
4686
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4687
+	 *  );
4688
+	 * is equivalent to
4689
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4690
+	 * and
4691
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4692
+	 *      array(
4693
+	 *          array(
4694
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4695
+	 *          ),
4696
+	 *          ARRAY_A,
4697
+	 *          implode(
4698
+	 *              ', ',
4699
+	 *              array_merge(
4700
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4701
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4702
+	 *              )
4703
+	 *          )
4704
+	 *      )
4705
+	 *  );
4706
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4707
+	 *
4708
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4709
+	 *                                            and the one whose fields you are selecting for example: when querying
4710
+	 *                                            tickets model and selecting fields from the tickets model you would
4711
+	 *                                            leave this parameter empty, because no models are needed to join
4712
+	 *                                            between the queried model and the selected one. Likewise when
4713
+	 *                                            querying the datetime model and selecting fields from the tickets
4714
+	 *                                            model, it would also be left empty, because there is a direct
4715
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4716
+	 *                                            them together. However, when querying from the event model and
4717
+	 *                                            selecting fields from the ticket model, you should provide the string
4718
+	 *                                            'Datetime', indicating that the event model must first join to the
4719
+	 *                                            datetime model in order to find its relation to ticket model.
4720
+	 *                                            Also, when querying from the venue model and selecting fields from
4721
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4722
+	 *                                            indicating you need to join the venue model to the event model,
4723
+	 *                                            to the datetime model, in order to find its relation to the ticket
4724
+	 *                                            model. This string is used to deduce the prefix that gets added onto
4725
+	 *                                            the models' tables qualified columns
4726
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4727
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4728
+	 *                                            qualified column names
4729
+	 * @return array|string
4730
+	 */
4731
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4732
+	{
4733
+		$table_prefix      = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4734
+		$qualified_columns = [];
4735
+		foreach ($this->field_settings() as $field_name => $field) {
4736
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4737
+		}
4738
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4739
+	}
4740
+
4741
+
4742
+	/**
4743
+	 * constructs the select use on special limit joins
4744
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4745
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4746
+	 * (as that is typically where the limits would be set).
4747
+	 *
4748
+	 * @param string       $table_alias The table the select is being built for
4749
+	 * @param mixed|string $limit       The limit for this select
4750
+	 * @return string                The final select join element for the query.
4751
+	 * @throws EE_Error
4752
+	 */
4753
+	public function _construct_limit_join_select($table_alias, $limit)
4754
+	{
4755
+		$SQL = '';
4756
+		foreach ($this->_tables as $table_obj) {
4757
+			if ($table_obj instanceof EE_Primary_Table) {
4758
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4759
+					? $table_obj->get_select_join_limit($limit)
4760
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4761
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4762
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4763
+					? $table_obj->get_select_join_limit_join($limit)
4764
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4765
+			}
4766
+		}
4767
+		return $SQL;
4768
+	}
4769
+
4770
+
4771
+	/**
4772
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4773
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4774
+	 *
4775
+	 * @return string SQL
4776
+	 * @throws EE_Error
4777
+	 */
4778
+	public function _construct_internal_join()
4779
+	{
4780
+		$SQL = $this->_get_main_table()->get_table_sql();
4781
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4782
+		return $SQL;
4783
+	}
4784
+
4785
+
4786
+	/**
4787
+	 * Constructs the SQL for joining all the tables on this model.
4788
+	 * Normally $alias should be the primary table's alias, but in cases where
4789
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4790
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4791
+	 * alias, this will construct SQL like:
4792
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4793
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4794
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4795
+	 *
4796
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4797
+	 * @return string
4798
+	 * @throws EE_Error
4799
+	 */
4800
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4801
+	{
4802
+		$SQL               = '';
4803
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4804
+		foreach ($this->_tables as $table_obj) {
4805
+			if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4806
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4807
+					// so we're joining to this table, meaning the table is already in
4808
+					// the FROM statement, BUT the primary table isn't. So we want
4809
+					// to add the inverse join sql
4810
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4811
+				} else {
4812
+					// just add a regular JOIN to this table from the primary table
4813
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4814
+				}
4815
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4816
+		}
4817
+		return $SQL;
4818
+	}
4819
+
4820
+
4821
+	/**
4822
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4823
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4824
+	 * their data type (eg, '%s', '%d', etc)
4825
+	 *
4826
+	 * @return array
4827
+	 */
4828
+	public function _get_data_types()
4829
+	{
4830
+		$data_types = [];
4831
+		foreach ($this->field_settings() as $field_obj) {
4832
+			// $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4833
+			/** @var $field_obj EE_Model_Field_Base */
4834
+			$data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4835
+		}
4836
+		return $data_types;
4837
+	}
4838
+
4839
+
4840
+	/**
4841
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4842
+	 *
4843
+	 * @param string $model_name
4844
+	 * @return EEM_Base
4845
+	 * @throws EE_Error
4846
+	 */
4847
+	public function get_related_model_obj($model_name)
4848
+	{
4849
+		$model_classname = "EEM_" . $model_name;
4850
+		if (! class_exists($model_classname)) {
4851
+			throw new EE_Error(
4852
+				sprintf(
4853
+					esc_html__(
4854
+						"You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4855
+						'event_espresso'
4856
+					),
4857
+					$model_name,
4858
+					$model_classname
4859
+				)
4860
+			);
4861
+		}
4862
+		return call_user_func($model_classname . "::instance");
4863
+	}
4864
+
4865
+
4866
+	/**
4867
+	 * Returns the array of EE_ModelRelations for this model.
4868
+	 *
4869
+	 * @return EE_Model_Relation_Base[]
4870
+	 */
4871
+	public function relation_settings()
4872
+	{
4873
+		return $this->_model_relations;
4874
+	}
4875
+
4876
+
4877
+	/**
4878
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4879
+	 * because without THOSE models, this model probably doesn't have much purpose.
4880
+	 * (Eg, without an event, datetimes have little purpose.)
4881
+	 *
4882
+	 * @return EE_Belongs_To_Relation[]
4883
+	 */
4884
+	public function belongs_to_relations()
4885
+	{
4886
+		$belongs_to_relations = [];
4887
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4888
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4889
+				$belongs_to_relations[ $model_name ] = $relation_obj;
4890
+			}
4891
+		}
4892
+		return $belongs_to_relations;
4893
+	}
4894
+
4895
+
4896
+	/**
4897
+	 * Returns the specified EE_Model_Relation, or throws an exception
4898
+	 *
4899
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4900
+	 * @return EE_Model_Relation_Base
4901
+	 * @throws EE_Error
4902
+	 */
4903
+	public function related_settings_for($relation_name)
4904
+	{
4905
+		$relatedModels = $this->relation_settings();
4906
+		if (! array_key_exists($relation_name, $relatedModels)) {
4907
+			throw new EE_Error(
4908
+				sprintf(
4909
+					esc_html__(
4910
+						'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4911
+						'event_espresso'
4912
+					),
4913
+					$relation_name,
4914
+					$this->_get_class_name(),
4915
+					implode(', ', array_keys($relatedModels))
4916
+				)
4917
+			);
4918
+		}
4919
+		return $relatedModels[ $relation_name ];
4920
+	}
4921
+
4922
+
4923
+	/**
4924
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4925
+	 * fields
4926
+	 *
4927
+	 * @param string  $fieldName
4928
+	 * @param boolean $include_db_only_fields
4929
+	 * @return EE_Model_Field_Base
4930
+	 * @throws EE_Error
4931
+	 */
4932
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
4933
+	{
4934
+		$fieldSettings = $this->field_settings($include_db_only_fields);
4935
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4936
+			throw new EE_Error(
4937
+				sprintf(
4938
+					esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
4939
+					$fieldName,
4940
+					get_class($this)
4941
+				)
4942
+			);
4943
+		}
4944
+		return $fieldSettings[ $fieldName ];
4945
+	}
4946
+
4947
+
4948
+	/**
4949
+	 * Checks if this field exists on this model
4950
+	 *
4951
+	 * @param string $fieldName a key in the model's _field_settings array
4952
+	 * @return boolean
4953
+	 */
4954
+	public function has_field($fieldName)
4955
+	{
4956
+		$fieldSettings = $this->field_settings(true);
4957
+		if (isset($fieldSettings[ $fieldName ])) {
4958
+			return true;
4959
+		}
4960
+		return false;
4961
+	}
4962
+
4963
+
4964
+	/**
4965
+	 * Returns whether or not this model has a relation to the specified model
4966
+	 *
4967
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4968
+	 * @return boolean
4969
+	 */
4970
+	public function has_relation($relation_name)
4971
+	{
4972
+		$relations = $this->relation_settings();
4973
+		if (isset($relations[ $relation_name ])) {
4974
+			return true;
4975
+		}
4976
+		return false;
4977
+	}
4978
+
4979
+
4980
+	/**
4981
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4982
+	 * Eg, on EE_Answer that would be ANS_ID field object
4983
+	 *
4984
+	 * @param $field_obj
4985
+	 * @return boolean
4986
+	 */
4987
+	public function is_primary_key_field($field_obj)
4988
+	{
4989
+		return $field_obj instanceof EE_Primary_Key_Field_Base;
4990
+	}
4991
+
4992
+
4993
+	/**
4994
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4995
+	 * Eg, on EE_Answer that would be ANS_ID field object
4996
+	 *
4997
+	 * @return EE_Model_Field_Base
4998
+	 * @throws EE_Error
4999
+	 */
5000
+	public function get_primary_key_field()
5001
+	{
5002
+		if ($this->_primary_key_field === null) {
5003
+			foreach ($this->field_settings(true) as $field_obj) {
5004
+				if ($this->is_primary_key_field($field_obj)) {
5005
+					$this->_primary_key_field = $field_obj;
5006
+					break;
5007
+				}
5008
+			}
5009
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5010
+				throw new EE_Error(
5011
+					sprintf(
5012
+						esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
5013
+						get_class($this)
5014
+					)
5015
+				);
5016
+			}
5017
+		}
5018
+		return $this->_primary_key_field;
5019
+	}
5020
+
5021
+
5022
+	/**
5023
+	 * Returns whether or not not there is a primary key on this model.
5024
+	 * Internally does some caching.
5025
+	 *
5026
+	 * @return boolean
5027
+	 */
5028
+	public function has_primary_key_field()
5029
+	{
5030
+		if ($this->_has_primary_key_field === null) {
5031
+			try {
5032
+				$this->get_primary_key_field();
5033
+				$this->_has_primary_key_field = true;
5034
+			} catch (EE_Error $e) {
5035
+				$this->_has_primary_key_field = false;
5036
+			}
5037
+		}
5038
+		return $this->_has_primary_key_field;
5039
+	}
5040
+
5041
+
5042
+	/**
5043
+	 * Finds the first field of type $field_class_name.
5044
+	 *
5045
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5046
+	 *                                 EE_Foreign_Key_Field, etc
5047
+	 * @return EE_Model_Field_Base or null if none is found
5048
+	 */
5049
+	public function get_a_field_of_type($field_class_name)
5050
+	{
5051
+		foreach ($this->field_settings() as $field) {
5052
+			if ($field instanceof $field_class_name) {
5053
+				return $field;
5054
+			}
5055
+		}
5056
+		return null;
5057
+	}
5058
+
5059
+
5060
+	/**
5061
+	 * Gets a foreign key field pointing to model.
5062
+	 *
5063
+	 * @param string $model_name eg Event, Registration, not EEM_Event
5064
+	 * @return EE_Foreign_Key_Field_Base
5065
+	 * @throws EE_Error
5066
+	 */
5067
+	public function get_foreign_key_to($model_name)
5068
+	{
5069
+		if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5070
+			foreach ($this->field_settings() as $field) {
5071
+				if (
5072
+					$field instanceof EE_Foreign_Key_Field_Base
5073
+					&& in_array($model_name, $field->get_model_names_pointed_to())
5074
+				) {
5075
+					$this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5076
+					break;
5077
+				}
5078
+			}
5079
+			if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5080
+				throw new EE_Error(
5081
+					sprintf(
5082
+						esc_html__(
5083
+							"There is no foreign key field pointing to model %s on model %s",
5084
+							'event_espresso'
5085
+						),
5086
+						$model_name,
5087
+						get_class($this)
5088
+					)
5089
+				);
5090
+			}
5091
+		}
5092
+		return $this->_cache_foreign_key_to_fields[ $model_name ];
5093
+	}
5094
+
5095
+
5096
+	/**
5097
+	 * Gets the table name (including $wpdb->prefix) for the table alias
5098
+	 *
5099
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5100
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5101
+	 *                            Either one works
5102
+	 * @return string
5103
+	 */
5104
+	public function get_table_for_alias($table_alias)
5105
+	{
5106
+		$table_alias_sans_model_relation_chain_prefix =
5107
+			EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5108
+		return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5109
+	}
5110
+
5111
+
5112
+	/**
5113
+	 * Returns a flat array of all field son this model, instead of organizing them
5114
+	 * by table_alias as they are in the constructor.
5115
+	 *
5116
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5117
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
5118
+	 */
5119
+	public function field_settings($include_db_only_fields = false)
5120
+	{
5121
+		if ($include_db_only_fields) {
5122
+			if ($this->_cached_fields === null) {
5123
+				$this->_cached_fields = [];
5124
+				foreach ($this->_fields as $fields_corresponding_to_table) {
5125
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5126
+						$this->_cached_fields[ $field_name ] = $field_obj;
5127
+					}
5128
+				}
5129
+			}
5130
+			return $this->_cached_fields;
5131
+		}
5132
+		if ($this->_cached_fields_non_db_only === null) {
5133
+			$this->_cached_fields_non_db_only = [];
5134
+			foreach ($this->_fields as $fields_corresponding_to_table) {
5135
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5136
+					/** @var $field_obj EE_Model_Field_Base */
5137
+					if (! $field_obj->is_db_only_field()) {
5138
+						$this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5139
+					}
5140
+				}
5141
+			}
5142
+		}
5143
+		return $this->_cached_fields_non_db_only;
5144
+	}
5145
+
5146
+
5147
+	/**
5148
+	 *        cycle though array of attendees and create objects out of each item
5149
+	 *
5150
+	 * @access        private
5151
+	 * @param array $rows        of results of $wpdb->get_results($query,ARRAY_A)
5152
+	 * @return EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5153
+	 *                           numerically indexed)
5154
+	 * @throws EE_Error
5155
+	 * @throws ReflectionException
5156
+	 */
5157
+	protected function _create_objects($rows = [])
5158
+	{
5159
+		$array_of_objects = [];
5160
+		if (empty($rows)) {
5161
+			return [];
5162
+		}
5163
+		$count_if_model_has_no_primary_key = 0;
5164
+		$has_primary_key                   = $this->has_primary_key_field();
5165
+		$primary_key_field                 = $has_primary_key ? $this->get_primary_key_field() : null;
5166
+		foreach ((array) $rows as $row) {
5167
+			if (empty($row)) {
5168
+				// wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5169
+				return [];
5170
+			}
5171
+			// check if we've already set this object in the results array,
5172
+			// in which case there's no need to process it further (again)
5173
+			if ($has_primary_key) {
5174
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5175
+					$row,
5176
+					$primary_key_field->get_qualified_column(),
5177
+					$primary_key_field->get_table_column()
5178
+				);
5179
+				if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5180
+					continue;
5181
+				}
5182
+			}
5183
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
5184
+			if (! $classInstance) {
5185
+				throw new EE_Error(
5186
+					sprintf(
5187
+						esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
5188
+						$this->get_this_model_name(),
5189
+						http_build_query($row)
5190
+					)
5191
+				);
5192
+			}
5193
+			// set the timezone on the instantiated objects
5194
+			$classInstance->set_timezone($this->get_timezone(), true);
5195
+			// make sure if there is any timezone setting present that we set the timezone for the object
5196
+			$key                      = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5197
+			$array_of_objects[ $key ] = $classInstance;
5198
+			// also, for all the relations of type BelongsTo, see if we can cache
5199
+			// those related models
5200
+			// (we could do this for other relations too, but if there are conditions
5201
+			// that filtered out some fo the results, then we'd be caching an incomplete set
5202
+			// so it requires a little more thought than just caching them immediately...)
5203
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
5204
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
5205
+					// check if this model's INFO is present. If so, cache it on the model
5206
+					$other_model           = $relation_obj->get_other_model();
5207
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5208
+					// if we managed to make a model object from the results, cache it on the main model object
5209
+					if ($other_model_obj_maybe) {
5210
+						// set timezone on these other model objects if they are present
5211
+						$other_model_obj_maybe->set_timezone($this->get_timezone(), true);
5212
+						$classInstance->cache($modelName, $other_model_obj_maybe);
5213
+					}
5214
+				}
5215
+			}
5216
+			// also, if this was a custom select query, let's see if there are any results for the custom select fields
5217
+			// and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5218
+			// the field in the CustomSelects object
5219
+			if ($this->_custom_selections instanceof CustomSelects) {
5220
+				$classInstance->setCustomSelectsValues(
5221
+					$this->getValuesForCustomSelectAliasesFromResults($row)
5222
+				);
5223
+			}
5224
+		}
5225
+		return $array_of_objects;
5226
+	}
5227
+
5228
+
5229
+	/**
5230
+	 * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5231
+	 * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5232
+	 *
5233
+	 * @param array $db_results_row
5234
+	 * @return array
5235
+	 */
5236
+	protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5237
+	{
5238
+		$results = [];
5239
+		if ($this->_custom_selections instanceof CustomSelects) {
5240
+			foreach ($this->_custom_selections->columnAliases() as $alias) {
5241
+				if (isset($db_results_row[ $alias ])) {
5242
+					$results[ $alias ] = $this->convertValueToDataType(
5243
+						$db_results_row[ $alias ],
5244
+						$this->_custom_selections->getDataTypeForAlias($alias)
5245
+					);
5246
+				}
5247
+			}
5248
+		}
5249
+		return $results;
5250
+	}
5251
+
5252
+
5253
+	/**
5254
+	 * This will set the value for the given alias
5255
+	 *
5256
+	 * @param string $value
5257
+	 * @param string $datatype (one of %d, %s, %f)
5258
+	 * @return int|string|float (int for %d, string for %s, float for %f)
5259
+	 */
5260
+	protected function convertValueToDataType($value, $datatype)
5261
+	{
5262
+		switch ($datatype) {
5263
+			case '%f':
5264
+				return (float) $value;
5265
+			case '%d':
5266
+				return (int) $value;
5267
+			default:
5268
+				return (string) $value;
5269
+		}
5270
+	}
5271
+
5272
+
5273
+	/**
5274
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5275
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5276
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5277
+	 * object (as set in the model_field!).
5278
+	 *
5279
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5280
+	 * @throws EE_Error
5281
+	 * @throws ReflectionException
5282
+	 */
5283
+	public function create_default_object()
5284
+	{
5285
+		$this_model_fields_and_values = [];
5286
+		// setup the row using default values;
5287
+		foreach ($this->field_settings() as $field_name => $field_obj) {
5288
+			$this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5289
+		}
5290
+		$className = $this->_get_class_name();
5291
+		return EE_Registry::instance()->load_class(
5292
+			$className,
5293
+			[$this_model_fields_and_values],
5294
+			false,
5295
+			false
5296
+		);
5297
+	}
5298
+
5299
+
5300
+	/**
5301
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5302
+	 *                             or an stdClass where each property is the name of a column,
5303
+	 * @return EE_Base_Class
5304
+	 * @throws EE_Error
5305
+	 * @throws ReflectionException
5306
+	 */
5307
+	public function instantiate_class_from_array_or_object($cols_n_values)
5308
+	{
5309
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5310
+			$cols_n_values = get_object_vars($cols_n_values);
5311
+		}
5312
+		$primary_key = null;
5313
+		// make sure the array only has keys that are fields/columns on this model
5314
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5315
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5316
+			$primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5317
+		}
5318
+		$className = $this->_get_class_name();
5319
+		// check we actually found results that we can use to build our model object
5320
+		// if not, return null
5321
+		if ($this->has_primary_key_field()) {
5322
+			if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5323
+				return null;
5324
+			}
5325
+		} elseif ($this->unique_indexes()) {
5326
+			$first_column = reset($this_model_fields_n_values);
5327
+			if (empty($first_column)) {
5328
+				return null;
5329
+			}
5330
+		}
5331
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5332
+		if ($primary_key) {
5333
+			$classInstance = $this->get_from_entity_map($primary_key);
5334
+			if (! $classInstance) {
5335
+				$classInstance = EE_Registry::instance()->load_class(
5336
+					$className,
5337
+					[$this_model_fields_n_values, $this->get_timezone()],
5338
+					true,
5339
+					false
5340
+				);
5341
+				// add this new object to the entity map
5342
+				$classInstance = $this->add_to_entity_map($classInstance);
5343
+			}
5344
+		} else {
5345
+			$classInstance = EE_Registry::instance()->load_class(
5346
+				$className,
5347
+				[$this_model_fields_n_values, $this->get_timezone()],
5348
+				true,
5349
+				false
5350
+			);
5351
+		}
5352
+		return $classInstance;
5353
+	}
5354
+
5355
+
5356
+	/**
5357
+	 * Gets the model object from the  entity map if it exists
5358
+	 *
5359
+	 * @param int|string $id the ID of the model object
5360
+	 * @return EE_Base_Class
5361
+	 */
5362
+	public function get_from_entity_map($id)
5363
+	{
5364
+		return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5365
+			? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]
5366
+			: null;
5367
+	}
5368
+
5369
+
5370
+	/**
5371
+	 * add_to_entity_map
5372
+	 * Adds the object to the model's entity mappings
5373
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5374
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5375
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5376
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5377
+	 *        then this method should be called immediately after the update query
5378
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5379
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5380
+	 *
5381
+	 * @param EE_Base_Class $object
5382
+	 * @return EE_Base_Class
5383
+	 * @throws EE_Error
5384
+	 */
5385
+	public function add_to_entity_map(EE_Base_Class $object)
5386
+	{
5387
+		$className = $this->_get_class_name();
5388
+		if (! $object instanceof $className) {
5389
+			throw new EE_Error(
5390
+				sprintf(
5391
+					esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5392
+					is_object($object) ? get_class($object) : $object,
5393
+					$className
5394
+				)
5395
+			);
5396
+		}
5397
+		if (! $object->ID()) {
5398
+			throw new EE_Error(
5399
+				sprintf(
5400
+					esc_html__(
5401
+						"You tried storing a model object with NO ID in the %s entity mapper.",
5402
+						"event_espresso"
5403
+					),
5404
+					get_class($this)
5405
+				)
5406
+			);
5407
+		}
5408
+		// double check it's not already there
5409
+		$classInstance = $this->get_from_entity_map($object->ID());
5410
+		if ($classInstance) {
5411
+			return $classInstance;
5412
+		}
5413
+		$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5414
+		return $object;
5415
+	}
5416
+
5417
+
5418
+	/**
5419
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5420
+	 * if no identifier is provided, then the entire entity map is emptied
5421
+	 *
5422
+	 * @param int|string $id the ID of the model object
5423
+	 * @return boolean
5424
+	 */
5425
+	public function clear_entity_map($id = null)
5426
+	{
5427
+		if (empty($id)) {
5428
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ] = [];
5429
+			return true;
5430
+		}
5431
+		if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5432
+			unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5433
+			return true;
5434
+		}
5435
+		return false;
5436
+	}
5437
+
5438
+
5439
+	/**
5440
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5441
+	 * Given an array where keys are column (or column alias) names and values,
5442
+	 * returns an array of their corresponding field names and database values
5443
+	 *
5444
+	 * @param array $cols_n_values
5445
+	 * @return array
5446
+	 */
5447
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5448
+	{
5449
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5450
+	}
5451
+
5452
+
5453
+	/**
5454
+	 * _deduce_fields_n_values_from_cols_n_values
5455
+	 * Given an array where keys are column (or column alias) names and values,
5456
+	 * returns an array of their corresponding field names and database values
5457
+	 *
5458
+	 * @param array $cols_n_values
5459
+	 * @return array
5460
+	 */
5461
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5462
+	{
5463
+		$this_model_fields_n_values = [];
5464
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5465
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5466
+				$cols_n_values,
5467
+				$table_obj->get_fully_qualified_pk_column(),
5468
+				$table_obj->get_pk_column()
5469
+			);
5470
+			// there is a primary key on this table and its not set. Use defaults for all its columns
5471
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5472
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5473
+					if (! $field_obj->is_db_only_field()) {
5474
+						// prepare field as if its coming from db
5475
+						$prepared_value                            =
5476
+							$field_obj->prepare_for_set($field_obj->get_default_value());
5477
+						$this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5478
+					}
5479
+				}
5480
+			} else {
5481
+				// the table's rows existed. Use their values
5482
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5483
+					if (! $field_obj->is_db_only_field()) {
5484
+						$this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5485
+							$cols_n_values,
5486
+							$field_obj->get_qualified_column(),
5487
+							$field_obj->get_table_column()
5488
+						);
5489
+					}
5490
+				}
5491
+			}
5492
+		}
5493
+		return $this_model_fields_n_values;
5494
+	}
5495
+
5496
+
5497
+	/**
5498
+	 * @param array  $cols_n_values
5499
+	 * @param string $qualified_column
5500
+	 * @param string $regular_column
5501
+	 * @return null
5502
+	 */
5503
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5504
+	{
5505
+		$value = null;
5506
+		// ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5507
+		// does the field on the model relate to this column retrieved from the db?
5508
+		// or is it a db-only field? (not relating to the model)
5509
+		if (isset($cols_n_values[ $qualified_column ])) {
5510
+			$value = $cols_n_values[ $qualified_column ];
5511
+		} elseif (isset($cols_n_values[ $regular_column ])) {
5512
+			$value = $cols_n_values[ $regular_column ];
5513
+		} elseif (! empty($this->foreign_key_aliases)) {
5514
+			// no PK?  ok check if there is a foreign key alias set for this table
5515
+			// then check if that alias exists in the incoming data
5516
+			// AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5517
+			foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5518
+				if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5519
+					$value = $cols_n_values[ $FK_alias ];
5520
+					break;
5521
+				}
5522
+			}
5523
+		}
5524
+		return $value;
5525
+	}
5526
+
5527
+
5528
+	/**
5529
+	 * refresh_entity_map_from_db
5530
+	 * Makes sure the model object in the entity map at $id assumes the values
5531
+	 * of the database (opposite of EE_base_Class::save())
5532
+	 *
5533
+	 * @param int|string $id
5534
+	 * @return EE_Base_Class
5535
+	 * @throws EE_Error
5536
+	 * @throws ReflectionException
5537
+	 */
5538
+	public function refresh_entity_map_from_db($id)
5539
+	{
5540
+		$obj_in_map = $this->get_from_entity_map($id);
5541
+		if ($obj_in_map) {
5542
+			$wpdb_results = $this->_get_all_wpdb_results(
5543
+				[[$this->get_primary_key_field()->get_name() => $id], 'limit' => 1]
5544
+			);
5545
+			if ($wpdb_results && is_array($wpdb_results)) {
5546
+				$one_row = reset($wpdb_results);
5547
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5548
+					$obj_in_map->set_from_db($field_name, $db_value);
5549
+				}
5550
+				// clear the cache of related model objects
5551
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5552
+					$obj_in_map->clear_cache($relation_name, null, true);
5553
+				}
5554
+			}
5555
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5556
+			return $obj_in_map;
5557
+		}
5558
+		return $this->get_one_by_ID($id);
5559
+	}
5560
+
5561
+
5562
+	/**
5563
+	 * refresh_entity_map_with
5564
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5565
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5566
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5567
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5568
+	 *
5569
+	 * @param int|string    $id
5570
+	 * @param EE_Base_Class $replacing_model_obj
5571
+	 * @return EE_Base_Class
5572
+	 * @throws EE_Error
5573
+	 * @throws ReflectionException
5574
+	 */
5575
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5576
+	{
5577
+		$obj_in_map = $this->get_from_entity_map($id);
5578
+		if ($obj_in_map) {
5579
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5580
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5581
+					$obj_in_map->set($field_name, $value);
5582
+				}
5583
+				// make the model object in the entity map's cache match the $replacing_model_obj
5584
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5585
+					$obj_in_map->clear_cache($relation_name, null, true);
5586
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5587
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5588
+					}
5589
+				}
5590
+			}
5591
+			return $obj_in_map;
5592
+		}
5593
+		$this->add_to_entity_map($replacing_model_obj);
5594
+		return $replacing_model_obj;
5595
+	}
5596
+
5597
+
5598
+	/**
5599
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5600
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5601
+	 * require_once($this->_getClassName().".class.php");
5602
+	 *
5603
+	 * @return string
5604
+	 */
5605
+	private function _get_class_name()
5606
+	{
5607
+		return "EE_" . $this->get_this_model_name();
5608
+	}
5609
+
5610
+
5611
+	/**
5612
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5613
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5614
+	 * it would be 'Events'.
5615
+	 *
5616
+	 * @param int $quantity
5617
+	 * @return string
5618
+	 */
5619
+	public function item_name($quantity = 1)
5620
+	{
5621
+		return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5622
+	}
5623
+
5624
+
5625
+	/**
5626
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5627
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5628
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5629
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5630
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5631
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5632
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5633
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5634
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5635
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5636
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5637
+	 *        return $previousReturnValue.$returnString;
5638
+	 * }
5639
+	 * require('EEM_Answer.model.php');
5640
+	 * $answer=EEM_Answer::instance();
5641
+	 * echo $answer->my_callback('monkeys',100);
5642
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5643
+	 *
5644
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5645
+	 * @param array  $args       array of original arguments passed to the function
5646
+	 * @return mixed whatever the plugin which calls add_filter decides
5647
+	 * @throws EE_Error
5648
+	 */
5649
+	public function __call($methodName, $args)
5650
+	{
5651
+		$className = get_class($this);
5652
+		$tagName   = "FHEE__{$className}__{$methodName}";
5653
+		if (! has_filter($tagName)) {
5654
+			throw new EE_Error(
5655
+				sprintf(
5656
+					esc_html__(
5657
+						'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 );',
5658
+						'event_espresso'
5659
+					),
5660
+					$methodName,
5661
+					$className,
5662
+					$tagName,
5663
+					'<br />'
5664
+				)
5665
+			);
5666
+		}
5667
+		return apply_filters($tagName, null, $this, $args);
5668
+	}
5669
+
5670
+
5671
+	/**
5672
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5673
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5674
+	 *
5675
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5676
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5677
+	 *                                                       the object's class name
5678
+	 *                                                       or object's ID
5679
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5680
+	 *                                                       exists in the database. If it does not, we add it
5681
+	 * @return EE_Base_Class
5682
+	 * @throws EE_Error
5683
+	 * @throws ReflectionException
5684
+	 */
5685
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5686
+	{
5687
+		$className = $this->_get_class_name();
5688
+		if ($base_class_obj_or_id instanceof $className) {
5689
+			$model_object = $base_class_obj_or_id;
5690
+		} else {
5691
+			$primary_key_field = $this->get_primary_key_field();
5692
+			if (
5693
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5694
+				&& (
5695
+					is_int($base_class_obj_or_id)
5696
+					|| is_string($base_class_obj_or_id)
5697
+				)
5698
+			) {
5699
+				// assume it's an ID.
5700
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5701
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5702
+			} elseif (
5703
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5704
+				&& is_string($base_class_obj_or_id)
5705
+			) {
5706
+				// assume its a string representation of the object
5707
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5708
+			} else {
5709
+				throw new EE_Error(
5710
+					sprintf(
5711
+						esc_html__(
5712
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5713
+							'event_espresso'
5714
+						),
5715
+						$base_class_obj_or_id,
5716
+						$this->_get_class_name(),
5717
+						print_r($base_class_obj_or_id, true)
5718
+					)
5719
+				);
5720
+			}
5721
+		}
5722
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5723
+			$model_object->save();
5724
+		}
5725
+		return $model_object;
5726
+	}
5727
+
5728
+
5729
+	/**
5730
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5731
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5732
+	 * returns it ID.
5733
+	 *
5734
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5735
+	 * @return int|string depending on the type of this model object's ID
5736
+	 * @throws EE_Error
5737
+	 */
5738
+	public function ensure_is_ID($base_class_obj_or_id)
5739
+	{
5740
+		$className = $this->_get_class_name();
5741
+		if ($base_class_obj_or_id instanceof $className) {
5742
+			$id = $base_class_obj_or_id->ID();
5743
+		} elseif (is_int($base_class_obj_or_id)) {
5744
+			// assume it's an ID
5745
+			$id = $base_class_obj_or_id;
5746
+		} elseif (is_string($base_class_obj_or_id)) {
5747
+			// assume its a string representation of the object
5748
+			$id = $base_class_obj_or_id;
5749
+		} else {
5750
+			throw new EE_Error(
5751
+				sprintf(
5752
+					esc_html__(
5753
+						"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5754
+						'event_espresso'
5755
+					),
5756
+					$base_class_obj_or_id,
5757
+					$this->_get_class_name(),
5758
+					print_r($base_class_obj_or_id, true)
5759
+				)
5760
+			);
5761
+		}
5762
+		return $id;
5763
+	}
5764
+
5765
+
5766
+	/**
5767
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5768
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5769
+	 * been sanitized and converted into the appropriate domain.
5770
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5771
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5772
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5773
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5774
+	 * $EVT = EEM_Event::instance(); $old_setting =
5775
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5776
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5777
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5778
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5779
+	 *
5780
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5781
+	 * @return void
5782
+	 */
5783
+	public function assume_values_already_prepared_by_model_object(
5784
+		$values_already_prepared = self::not_prepared_by_model_object
5785
+	) {
5786
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5787
+	}
5788
+
5789
+
5790
+	/**
5791
+	 * Read comments for assume_values_already_prepared_by_model_object()
5792
+	 *
5793
+	 * @return int
5794
+	 */
5795
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5796
+	{
5797
+		return $this->_values_already_prepared_by_model_object;
5798
+	}
5799
+
5800
+
5801
+	/**
5802
+	 * Gets all the indexes on this model
5803
+	 *
5804
+	 * @return EE_Index[]
5805
+	 */
5806
+	public function indexes()
5807
+	{
5808
+		return $this->_indexes;
5809
+	}
5810
+
5811
+
5812
+	/**
5813
+	 * Gets all the Unique Indexes on this model
5814
+	 *
5815
+	 * @return EE_Unique_Index[]
5816
+	 */
5817
+	public function unique_indexes()
5818
+	{
5819
+		$unique_indexes = [];
5820
+		foreach ($this->_indexes as $name => $index) {
5821
+			if ($index instanceof EE_Unique_Index) {
5822
+				$unique_indexes [ $name ] = $index;
5823
+			}
5824
+		}
5825
+		return $unique_indexes;
5826
+	}
5827
+
5828
+
5829
+	/**
5830
+	 * Gets all the fields which, when combined, make the primary key.
5831
+	 * This is usually just an array with 1 element (the primary key), but in cases
5832
+	 * where there is no primary key, it's a combination of fields as defined
5833
+	 * on a primary index
5834
+	 *
5835
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5836
+	 * @throws EE_Error
5837
+	 */
5838
+	public function get_combined_primary_key_fields()
5839
+	{
5840
+		foreach ($this->indexes() as $index) {
5841
+			if ($index instanceof EE_Primary_Key_Index) {
5842
+				return $index->fields();
5843
+			}
5844
+		}
5845
+		return [$this->primary_key_name() => $this->get_primary_key_field()];
5846
+	}
5847
+
5848
+
5849
+	/**
5850
+	 * Used to build a primary key string (when the model has no primary key),
5851
+	 * which can be used a unique string to identify this model object.
5852
+	 *
5853
+	 * @param array $fields_n_values keys are field names, values are their values.
5854
+	 *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5855
+	 *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5856
+	 *                               before passing it to this function (that will convert it from columns-n-values
5857
+	 *                               to field-names-n-values).
5858
+	 * @return string
5859
+	 * @throws EE_Error
5860
+	 */
5861
+	public function get_index_primary_key_string($fields_n_values)
5862
+	{
5863
+		$cols_n_values_for_primary_key_index = array_intersect_key(
5864
+			$fields_n_values,
5865
+			$this->get_combined_primary_key_fields()
5866
+		);
5867
+		return http_build_query($cols_n_values_for_primary_key_index);
5868
+	}
5869
+
5870
+
5871
+	/**
5872
+	 * Gets the field values from the primary key string
5873
+	 *
5874
+	 * @param string $index_primary_key_string
5875
+	 * @return null|array
5876
+	 * @throws EE_Error
5877
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5878
+	 */
5879
+	public function parse_index_primary_key_string($index_primary_key_string)
5880
+	{
5881
+		$key_fields = $this->get_combined_primary_key_fields();
5882
+		// check all of them are in the $id
5883
+		$key_values_in_combined_pk = [];
5884
+		parse_str($index_primary_key_string, $key_values_in_combined_pk);
5885
+		foreach ($key_fields as $key_field_name => $field_obj) {
5886
+			if (! isset($key_values_in_combined_pk[ $key_field_name ])) {
5887
+				return null;
5888
+			}
5889
+		}
5890
+		return $key_values_in_combined_pk;
5891
+	}
5892
+
5893
+
5894
+	/**
5895
+	 * verifies that an array of key-value pairs for model fields has a key
5896
+	 * for each field comprising the primary key index
5897
+	 *
5898
+	 * @param array $key_values
5899
+	 * @return boolean
5900
+	 * @throws EE_Error
5901
+	 */
5902
+	public function has_all_combined_primary_key_fields($key_values)
5903
+	{
5904
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5905
+		foreach ($keys_it_should_have as $key) {
5906
+			if (! isset($key_values[ $key ])) {
5907
+				return false;
5908
+			}
5909
+		}
5910
+		return true;
5911
+	}
5912
+
5913
+
5914
+	/**
5915
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5916
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5917
+	 *
5918
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5919
+	 * @param array               $query_params                     see github link below for more info
5920
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5921
+	 * @throws EE_Error
5922
+	 * @throws ReflectionException
5923
+	 * @return EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5924
+	 *                                                              indexed)
5925
+	 */
5926
+	public function get_all_copies($model_object_or_attributes_array, $query_params = [])
5927
+	{
5928
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5929
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5930
+		} elseif (is_array($model_object_or_attributes_array)) {
5931
+			$attributes_array = $model_object_or_attributes_array;
5932
+		} else {
5933
+			throw new EE_Error(
5934
+				sprintf(
5935
+					esc_html__(
5936
+						"get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5937
+						"event_espresso"
5938
+					),
5939
+					$model_object_or_attributes_array
5940
+				)
5941
+			);
5942
+		}
5943
+		// even copies obviously won't have the same ID, so remove the primary key
5944
+		// from the WHERE conditions for finding copies (if there is a primary key, of course)
5945
+		if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5946
+			unset($attributes_array[ $this->primary_key_name() ]);
5947
+		}
5948
+		if (isset($query_params[0])) {
5949
+			$query_params[0] = array_merge($attributes_array, $query_params);
5950
+		} else {
5951
+			$query_params[0] = $attributes_array;
5952
+		}
5953
+		return $this->get_all($query_params);
5954
+	}
5955
+
5956
+
5957
+	/**
5958
+	 * Gets the first copy we find. See get_all_copies for more details
5959
+	 *
5960
+	 * @param mixed EE_Base_Class | array        $model_object_or_attributes_array
5961
+	 * @param array $query_params
5962
+	 * @return EE_Base_Class
5963
+	 * @throws EE_Error
5964
+	 * @throws ReflectionException
5965
+	 */
5966
+	public function get_one_copy($model_object_or_attributes_array, $query_params = [])
5967
+	{
5968
+		if (! is_array($query_params)) {
5969
+			EE_Error::doing_it_wrong(
5970
+				'EEM_Base::get_one_copy',
5971
+				sprintf(
5972
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5973
+					gettype($query_params)
5974
+				),
5975
+				'4.6.0'
5976
+			);
5977
+			$query_params = [];
5978
+		}
5979
+		$query_params['limit'] = 1;
5980
+		$copies                = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5981
+		if (is_array($copies)) {
5982
+			return array_shift($copies);
5983
+		}
5984
+		return null;
5985
+	}
5986
+
5987
+
5988
+	/**
5989
+	 * Updates the item with the specified id. Ignores default query parameters because
5990
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5991
+	 *
5992
+	 * @param array      $fields_n_values keys are field names, values are their new values
5993
+	 * @param int|string $id              the value of the primary key to update
5994
+	 * @return int number of rows updated
5995
+	 * @throws EE_Error
5996
+	 * @throws ReflectionException
5997
+	 */
5998
+	public function update_by_ID($fields_n_values, $id)
5999
+	{
6000
+		$query_params = [
6001
+			0                          => [$this->get_primary_key_field()->get_name() => $id],
6002
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
6003
+		];
6004
+		return $this->update($fields_n_values, $query_params);
6005
+	}
6006
+
6007
+
6008
+	/**
6009
+	 * Changes an operator which was supplied to the models into one usable in SQL
6010
+	 *
6011
+	 * @param string $operator_supplied
6012
+	 * @return string an operator which can be used in SQL
6013
+	 * @throws EE_Error
6014
+	 */
6015
+	private function _prepare_operator_for_sql($operator_supplied)
6016
+	{
6017
+		$sql_operator =
6018
+			isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
6019
+				: null;
6020
+		if ($sql_operator) {
6021
+			return $sql_operator;
6022
+		}
6023
+		throw new EE_Error(
6024
+			sprintf(
6025
+				esc_html__(
6026
+					"The operator '%s' is not in the list of valid operators: %s",
6027
+					"event_espresso"
6028
+				),
6029
+				$operator_supplied,
6030
+				implode(",", array_keys($this->_valid_operators))
6031
+			)
6032
+		);
6033
+	}
6034
+
6035
+
6036
+	/**
6037
+	 * Gets the valid operators
6038
+	 *
6039
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6040
+	 */
6041
+	public function valid_operators()
6042
+	{
6043
+		return $this->_valid_operators;
6044
+	}
6045
+
6046
+
6047
+	/**
6048
+	 * Gets the between-style operators (take 2 arguments).
6049
+	 *
6050
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6051
+	 */
6052
+	public function valid_between_style_operators()
6053
+	{
6054
+		return array_intersect(
6055
+			$this->valid_operators(),
6056
+			$this->_between_style_operators
6057
+		);
6058
+	}
6059
+
6060
+
6061
+	/**
6062
+	 * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6063
+	 *
6064
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6065
+	 */
6066
+	public function valid_like_style_operators()
6067
+	{
6068
+		return array_intersect(
6069
+			$this->valid_operators(),
6070
+			$this->_like_style_operators
6071
+		);
6072
+	}
6073
+
6074
+
6075
+	/**
6076
+	 * Gets the "in"-style operators
6077
+	 *
6078
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6079
+	 */
6080
+	public function valid_in_style_operators()
6081
+	{
6082
+		return array_intersect(
6083
+			$this->valid_operators(),
6084
+			$this->_in_style_operators
6085
+		);
6086
+	}
6087
+
6088
+
6089
+	/**
6090
+	 * Gets the "null"-style operators (accept no arguments)
6091
+	 *
6092
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6093
+	 */
6094
+	public function valid_null_style_operators()
6095
+	{
6096
+		return array_intersect(
6097
+			$this->valid_operators(),
6098
+			$this->_null_style_operators
6099
+		);
6100
+	}
6101
+
6102
+
6103
+	/**
6104
+	 * Gets an array where keys are the primary keys and values are their 'names'
6105
+	 * (as determined by the model object's name() function, which is often overridden)
6106
+	 *
6107
+	 * @param array $query_params like get_all's
6108
+	 * @return string[]
6109
+	 * @throws EE_Error
6110
+	 * @throws ReflectionException
6111
+	 */
6112
+	public function get_all_names($query_params = [])
6113
+	{
6114
+		$objs  = $this->get_all($query_params);
6115
+		$names = [];
6116
+		foreach ($objs as $obj) {
6117
+			$names[ $obj->ID() ] = $obj->name();
6118
+		}
6119
+		return $names;
6120
+	}
6121
+
6122
+
6123
+	/**
6124
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
6125
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6126
+	 * this is duplicated effort and reduces efficiency) you would be better to use
6127
+	 * array_keys() on $model_objects.
6128
+	 *
6129
+	 * @param EE_Base_Class[] $model_objects
6130
+	 * @param boolean         $filter_out_empty_ids  if a model object has an ID of '' or 0, don't bother including it
6131
+	 *                                               in the returned array
6132
+	 * @return array
6133
+	 * @throws EE_Error
6134
+	 */
6135
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
6136
+	{
6137
+		if (! $this->has_primary_key_field()) {
6138
+			if (WP_DEBUG) {
6139
+				EE_Error::add_error(
6140
+					esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6141
+					__FILE__,
6142
+					__FUNCTION__,
6143
+					__LINE__
6144
+				);
6145
+			}
6146
+		}
6147
+		$IDs = [];
6148
+		foreach ($model_objects as $model_object) {
6149
+			$id = $model_object->ID();
6150
+			if (! $id) {
6151
+				if ($filter_out_empty_ids) {
6152
+					continue;
6153
+				}
6154
+				if (WP_DEBUG) {
6155
+					EE_Error::add_error(
6156
+						esc_html__(
6157
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6158
+							'event_espresso'
6159
+						),
6160
+						__FILE__,
6161
+						__FUNCTION__,
6162
+						__LINE__
6163
+					);
6164
+				}
6165
+			}
6166
+			$IDs[] = $id;
6167
+		}
6168
+		return $IDs;
6169
+	}
6170
+
6171
+
6172
+	/**
6173
+	 * Returns the string used in capabilities relating to this model. If there
6174
+	 * are no capabilities that relate to this model returns false
6175
+	 *
6176
+	 * @return string|false
6177
+	 */
6178
+	public function cap_slug()
6179
+	{
6180
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6181
+	}
6182
+
6183
+
6184
+	/**
6185
+	 * Returns the capability-restrictions array (@param string $context
6186
+	 *
6187
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
6188
+	 * @throws EE_Error
6189
+	 * @see EEM_Base::_cap_restrictions).
6190
+	 *      If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6191
+	 *      only returns the cap restrictions array in that context (ie, the array
6192
+	 *      at that key)
6193
+	 *
6194
+	 */
6195
+	public function cap_restrictions($context = EEM_Base::caps_read)
6196
+	{
6197
+		EEM_Base::verify_is_valid_cap_context($context);
6198
+		// check if we ought to run the restriction generator first
6199
+		if (
6200
+			isset($this->_cap_restriction_generators[ $context ])
6201
+			&& $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6202
+			&& ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6203
+		) {
6204
+			$this->_cap_restrictions[ $context ] = array_merge(
6205
+				$this->_cap_restrictions[ $context ],
6206
+				$this->_cap_restriction_generators[ $context ]->generate_restrictions()
6207
+			);
6208
+		}
6209
+		// and make sure we've finalized the construction of each restriction
6210
+		foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6211
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6212
+				$where_conditions_obj->_finalize_construct($this);
6213
+			}
6214
+		}
6215
+		return $this->_cap_restrictions[ $context ];
6216
+	}
6217
+
6218
+
6219
+	/**
6220
+	 * Indicating whether or not this model thinks its a wp core model
6221
+	 *
6222
+	 * @return boolean
6223
+	 */
6224
+	public function is_wp_core_model()
6225
+	{
6226
+		return $this->_wp_core_model;
6227
+	}
6228
+
6229
+
6230
+	/**
6231
+	 * Gets all the caps that are missing which impose a restriction on
6232
+	 * queries made in this context
6233
+	 *
6234
+	 * @param string $context one of EEM_Base::caps_ constants
6235
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
6236
+	 * @throws EE_Error
6237
+	 */
6238
+	public function caps_missing($context = EEM_Base::caps_read)
6239
+	{
6240
+		$missing_caps     = [];
6241
+		$cap_restrictions = $this->cap_restrictions($context);
6242
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6243
+			if (
6244
+				! EE_Capabilities::instance()->current_user_can(
6245
+					$cap,
6246
+					$this->get_this_model_name() . '_model_applying_caps'
6247
+				)
6248
+			) {
6249
+				$missing_caps[ $cap ] = $restriction_if_no_cap;
6250
+			}
6251
+		}
6252
+		return $missing_caps;
6253
+	}
6254
+
6255
+
6256
+	/**
6257
+	 * Gets the mapping from capability contexts to action strings used in capability names
6258
+	 *
6259
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6260
+	 * one of 'read', 'edit', or 'delete'
6261
+	 */
6262
+	public function cap_contexts_to_cap_action_map()
6263
+	{
6264
+		return apply_filters(
6265
+			'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6266
+			$this->_cap_contexts_to_cap_action_map,
6267
+			$this
6268
+		);
6269
+	}
6270
+
6271
+
6272
+	/**
6273
+	 * Gets the action string for the specified capability context
6274
+	 *
6275
+	 * @param string $context
6276
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6277
+	 * @throws EE_Error
6278
+	 */
6279
+	public function cap_action_for_context($context)
6280
+	{
6281
+		$mapping = $this->cap_contexts_to_cap_action_map();
6282
+		if (isset($mapping[ $context ])) {
6283
+			return $mapping[ $context ];
6284
+		}
6285
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6286
+			return $action;
6287
+		}
6288
+		throw new EE_Error(
6289
+			sprintf(
6290
+				esc_html__(
6291
+					'Cannot find capability restrictions for context "%1$s", allowed values are:%2$s',
6292
+					'event_espresso'
6293
+				),
6294
+				$context,
6295
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6296
+			)
6297
+		);
6298
+	}
6299
+
6300
+
6301
+	/**
6302
+	 * Returns all the capability contexts which are valid when querying models
6303
+	 *
6304
+	 * @return array
6305
+	 */
6306
+	public static function valid_cap_contexts()
6307
+	{
6308
+		return apply_filters(
6309
+			'FHEE__EEM_Base__valid_cap_contexts',
6310
+			[
6311
+				self::caps_read,
6312
+				self::caps_read_admin,
6313
+				self::caps_edit,
6314
+				self::caps_delete,
6315
+			]
6316
+		);
6317
+	}
6318
+
6319
+
6320
+	/**
6321
+	 * Returns all valid options for 'default_where_conditions'
6322
+	 *
6323
+	 * @return array
6324
+	 */
6325
+	public static function valid_default_where_conditions()
6326
+	{
6327
+		return [
6328
+			EEM_Base::default_where_conditions_all,
6329
+			EEM_Base::default_where_conditions_this_only,
6330
+			EEM_Base::default_where_conditions_others_only,
6331
+			EEM_Base::default_where_conditions_minimum_all,
6332
+			EEM_Base::default_where_conditions_minimum_others,
6333
+			EEM_Base::default_where_conditions_none,
6334
+		];
6335
+	}
6336
+
6337
+	// public static function default_where_conditions_full
6338
+
6339
+
6340
+	/**
6341
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6342
+	 *
6343
+	 * @param string $context
6344
+	 * @return bool
6345
+	 * @throws EE_Error
6346
+	 */
6347
+	public static function verify_is_valid_cap_context($context)
6348
+	{
6349
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
6350
+		if (in_array($context, $valid_cap_contexts)) {
6351
+			return true;
6352
+		}
6353
+		throw new EE_Error(
6354
+			sprintf(
6355
+				esc_html__(
6356
+					'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6357
+					'event_espresso'
6358
+				),
6359
+				$context,
6360
+				'EEM_Base',
6361
+				implode(',', $valid_cap_contexts)
6362
+			)
6363
+		);
6364
+	}
6365
+
6366
+
6367
+	/**
6368
+	 * Clears all the models field caches. This is only useful when a sub-class
6369
+	 * might have added a field or something and these caches might be invalidated
6370
+	 */
6371
+	protected function _invalidate_field_caches()
6372
+	{
6373
+		$this->_cache_foreign_key_to_fields = [];
6374
+		$this->_cached_fields               = null;
6375
+		$this->_cached_fields_non_db_only   = null;
6376
+	}
6377
+
6378
+
6379
+	/**
6380
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
6381
+	 * (eg "and", "or", "not").
6382
+	 *
6383
+	 * @return array
6384
+	 */
6385
+	public function logic_query_param_keys()
6386
+	{
6387
+		return $this->_logic_query_param_keys;
6388
+	}
6389
+
6390
+
6391
+	/**
6392
+	 * Determines whether or not the where query param array key is for a logic query param.
6393
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6394
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6395
+	 *
6396
+	 * @param $query_param_key
6397
+	 * @return bool
6398
+	 */
6399
+	public function is_logic_query_param_key($query_param_key)
6400
+	{
6401
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6402
+			if (
6403
+				$query_param_key === $logic_query_param_key
6404
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
6405
+			) {
6406
+				return true;
6407
+			}
6408
+		}
6409
+		return false;
6410
+	}
6411
+
6412
+
6413
+	/**
6414
+	 * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6415
+	 *
6416
+	 * @return boolean
6417
+	 * @since 4.9.74.p
6418
+	 */
6419
+	public function hasPassword()
6420
+	{
6421
+		// if we don't yet know if there's a password field, find out and remember it for next time.
6422
+		if ($this->has_password_field === null) {
6423
+			$password_field           = $this->getPasswordField();
6424
+			$this->has_password_field = $password_field instanceof EE_Password_Field;
6425
+		}
6426
+		return $this->has_password_field;
6427
+	}
6428
+
6429
+
6430
+	/**
6431
+	 * Returns the password field on this model, if there is one
6432
+	 *
6433
+	 * @return EE_Password_Field|null
6434
+	 * @since 4.9.74.p
6435
+	 */
6436
+	public function getPasswordField()
6437
+	{
6438
+		// if we definitely already know there is a password field or not (because has_password_field is true or false)
6439
+		// there's no need to search for it. If we don't know yet, then find out
6440
+		if ($this->has_password_field === null && $this->password_field === null) {
6441
+			$this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6442
+		}
6443
+		// don't bother setting has_password_field because that's hasPassword()'s job.
6444
+		return $this->password_field;
6445
+	}
6446
+
6447
+
6448
+	/**
6449
+	 * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6450
+	 *
6451
+	 * @return EE_Model_Field_Base[]
6452
+	 * @throws EE_Error
6453
+	 * @since 4.9.74.p
6454
+	 */
6455
+	public function getPasswordProtectedFields()
6456
+	{
6457
+		$password_field = $this->getPasswordField();
6458
+		$fields         = [];
6459
+		if ($password_field instanceof EE_Password_Field) {
6460
+			$field_names = $password_field->protectedFields();
6461
+			foreach ($field_names as $field_name) {
6462
+				$fields[ $field_name ] = $this->field_settings_for($field_name);
6463
+			}
6464
+		}
6465
+		return $fields;
6466
+	}
6467
+
6468
+
6469
+	/**
6470
+	 * Checks if the current user can perform the requested action on this model
6471
+	 *
6472
+	 * @param string              $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6473
+	 * @param EE_Base_Class|array $model_obj_or_fields_n_values
6474
+	 * @return bool
6475
+	 * @throws EE_Error
6476
+	 * @throws InvalidArgumentException
6477
+	 * @throws InvalidDataTypeException
6478
+	 * @throws InvalidInterfaceException
6479
+	 * @throws ReflectionException
6480
+	 * @throws UnexpectedEntityException
6481
+	 * @since 4.9.74.p
6482
+	 */
6483
+	public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6484
+	{
6485
+		if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6486
+			$model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6487
+		}
6488
+		if (! is_array($model_obj_or_fields_n_values)) {
6489
+			throw new UnexpectedEntityException(
6490
+				$model_obj_or_fields_n_values,
6491
+				'EE_Base_Class',
6492
+				sprintf(
6493
+					esc_html__(
6494
+						'%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.',
6495
+						'event_espresso'
6496
+					),
6497
+					__FUNCTION__
6498
+				)
6499
+			);
6500
+		}
6501
+		return $this->exists(
6502
+			$this->alter_query_params_to_restrict_by_ID(
6503
+				$this->get_index_primary_key_string($model_obj_or_fields_n_values),
6504
+				[
6505
+					'default_where_conditions' => 'none',
6506
+					'caps'                     => $cap_to_check,
6507
+				]
6508
+			)
6509
+		);
6510
+	}
6511
+
6512
+
6513
+	/**
6514
+	 * Returns the query param where conditions key to the password affecting this model.
6515
+	 * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6516
+	 *
6517
+	 * @return null|string
6518
+	 * @throws EE_Error
6519
+	 * @throws InvalidArgumentException
6520
+	 * @throws InvalidDataTypeException
6521
+	 * @throws InvalidInterfaceException
6522
+	 * @throws ModelConfigurationException
6523
+	 * @throws ReflectionException
6524
+	 * @since 4.9.74.p
6525
+	 */
6526
+	public function modelChainAndPassword()
6527
+	{
6528
+		if ($this->model_chain_to_password === null) {
6529
+			throw new ModelConfigurationException(
6530
+				$this,
6531
+				esc_html_x(
6532
+				// @codingStandardsIgnoreStart
6533
+					'Cannot exclude protected data because the model has not specified which model has the password.',
6534
+					// @codingStandardsIgnoreEnd
6535
+					'1: model name',
6536
+					'event_espresso'
6537
+				)
6538
+			);
6539
+		}
6540
+		if ($this->model_chain_to_password === '') {
6541
+			$model_with_password = $this;
6542
+		} else {
6543
+			if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6544
+				$last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6545
+			} else {
6546
+				$last_model_in_chain = $this->model_chain_to_password;
6547
+			}
6548
+			$model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6549
+		}
6550
+
6551
+		$password_field = $model_with_password->getPasswordField();
6552
+		if ($password_field instanceof EE_Password_Field) {
6553
+			$password_field_name = $password_field->get_name();
6554
+		} else {
6555
+			throw new ModelConfigurationException(
6556
+				$this,
6557
+				sprintf(
6558
+					esc_html_x(
6559
+						'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"',
6560
+						'1: model name, 2: special string',
6561
+						'event_espresso'
6562
+					),
6563
+					$model_with_password->get_this_model_name(),
6564
+					$this->model_chain_to_password
6565
+				)
6566
+			);
6567
+		}
6568
+		return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6569
+	}
6570
+
6571
+
6572
+	/**
6573
+	 * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6574
+	 * or if this model itself has a password affecting access to some of its other fields.
6575
+	 *
6576
+	 * @return boolean
6577
+	 * @since 4.9.74.p
6578
+	 */
6579
+	public function restrictedByRelatedModelPassword()
6580
+	{
6581
+		return $this->model_chain_to_password !== null;
6582
+	}
6583 6583
 }
Please login to merge, or discard this patch.
Spacing   +231 added lines, -231 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__(
@@ -645,7 +645,7 @@  discard block
 block discarded – undo
645 645
          * @param EE_Model_Relation_Base[] $_model_relations
646 646
          */
647 647
         $this->_model_relations = (array) apply_filters(
648
-            'FHEE__' . get_class($this) . '__construct__model_relations',
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
 
@@ -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,7 +1399,7 @@  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 1405
         $incoming_orderby         = isset($query_params['order_by']) ? (array) $query_params['order_by'] : [];
@@ -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(
@@ -1693,7 +1693,7 @@  discard block
 block discarded – undo
1693 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,8 +2283,8 @@  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;
2287
-        $SQL = "SELECT COUNT('{$column_to_count}')" . $this->_construct_2nd_half_of_select_query($model_query_info);
2286
+        $column_to_count = $distinct ? "DISTINCT ".$column_to_count : $column_to_count;
2287
+        $SQL = "SELECT COUNT('{$column_to_count}')".$this->_construct_2nd_half_of_select_query($model_query_info);
2288 2288
         return (int) $this->_do_wpdb_query('get_var', [$SQL]);
2289 2289
     }
2290 2290
 
@@ -2333,7 +2333,7 @@  discard block
 block discarded – undo
2333 2333
         // if we're in maintenance mode level 2, DON'T run any queries
2334 2334
         // because level 2 indicates the database needs updating and
2335 2335
         // is probably out of sync with the code
2336
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2336
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2337 2337
             throw new EE_Error(
2338 2338
                 sprintf(
2339 2339
                     esc_html__(
@@ -2344,7 +2344,7 @@  discard block
 block discarded – undo
2344 2344
             );
2345 2345
         }
2346 2346
         global $wpdb;
2347
-        if (! method_exists($wpdb, $wpdb_method)) {
2347
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2348 2348
             throw new EE_Error(
2349 2349
                 sprintf(
2350 2350
                     esc_html__(
@@ -2363,7 +2363,7 @@  discard block
 block discarded – undo
2363 2363
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2364 2364
         if (WP_DEBUG) {
2365 2365
             $wpdb->show_errors($old_show_errors_value);
2366
-            if (! empty($wpdb->last_error)) {
2366
+            if ( ! empty($wpdb->last_error)) {
2367 2367
                 throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2368 2368
             }
2369 2369
             if ($result === false) {
@@ -2433,7 +2433,7 @@  discard block
 block discarded – undo
2433 2433
                     // ummmm... you in trouble
2434 2434
                     return $result;
2435 2435
             }
2436
-            if (! empty($error_message)) {
2436
+            if ( ! empty($error_message)) {
2437 2437
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2438 2438
                 trigger_error($error_message);
2439 2439
             }
@@ -2510,11 +2510,11 @@  discard block
 block discarded – undo
2510 2510
      */
2511 2511
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2512 2512
     {
2513
-        return " FROM " . $model_query_info->get_full_join_sql() .
2514
-               $model_query_info->get_where_sql() .
2515
-               $model_query_info->get_group_by_sql() .
2516
-               $model_query_info->get_having_sql() .
2517
-               $model_query_info->get_order_by_sql() .
2513
+        return " FROM ".$model_query_info->get_full_join_sql().
2514
+               $model_query_info->get_where_sql().
2515
+               $model_query_info->get_group_by_sql().
2516
+               $model_query_info->get_having_sql().
2517
+               $model_query_info->get_order_by_sql().
2518 2518
                $model_query_info->get_limit_sql();
2519 2519
     }
2520 2520
 
@@ -2707,12 +2707,12 @@  discard block
 block discarded – undo
2707 2707
         $related_model = $this->get_related_model_obj($model_name);
2708 2708
         // we're just going to use the query params on the related model's normal get_all query,
2709 2709
         // except add a condition to say to match the current mod
2710
-        if (! isset($query_params['default_where_conditions'])) {
2710
+        if ( ! isset($query_params['default_where_conditions'])) {
2711 2711
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2712 2712
         }
2713 2713
         $this_model_name                                                 = $this->get_this_model_name();
2714 2714
         $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2715
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2715
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2716 2716
         return $related_model->count($query_params, $field_to_count, $distinct);
2717 2717
     }
2718 2718
 
@@ -2733,7 +2733,7 @@  discard block
 block discarded – undo
2733 2733
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2734 2734
     {
2735 2735
         $related_model = $this->get_related_model_obj($model_name);
2736
-        if (! is_array($query_params)) {
2736
+        if ( ! is_array($query_params)) {
2737 2737
             EE_Error::doing_it_wrong(
2738 2738
                 'EEM_Base::sum_related',
2739 2739
                 sprintf(
@@ -2746,12 +2746,12 @@  discard block
 block discarded – undo
2746 2746
         }
2747 2747
         // we're just going to use the query params on the related model's normal get_all query,
2748 2748
         // except add a condition to say to match the current mod
2749
-        if (! isset($query_params['default_where_conditions'])) {
2749
+        if ( ! isset($query_params['default_where_conditions'])) {
2750 2750
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2751 2751
         }
2752 2752
         $this_model_name                                                 = $this->get_this_model_name();
2753 2753
         $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2754
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2754
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2755 2755
         return $related_model->sum($query_params, $field_to_sum);
2756 2756
     }
2757 2757
 
@@ -2803,7 +2803,7 @@  discard block
 block discarded – undo
2803 2803
                 $field_with_model_name = $field;
2804 2804
             }
2805 2805
         }
2806
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2806
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2807 2807
             throw new EE_Error(
2808 2808
                 sprintf(
2809 2809
                     esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
@@ -2942,14 +2942,14 @@  discard block
 block discarded – undo
2942 2942
                 || $this->get_primary_key_field()
2943 2943
                    instanceof
2944 2944
                    EE_Primary_Key_String_Field)
2945
-            && isset($fields_n_values[ $this->primary_key_name() ])
2945
+            && isset($fields_n_values[$this->primary_key_name()])
2946 2946
         ) {
2947
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2947
+            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2948 2948
         }
2949 2949
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2950 2950
             $uniqueness_where_params                              =
2951 2951
                 array_intersect_key($fields_n_values, $unique_index->fields());
2952
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2952
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2953 2953
         }
2954 2954
         // if there is nothing to base this search on, then we shouldn't find anything
2955 2955
         if (empty($query_params)) {
@@ -3026,16 +3026,16 @@  discard block
 block discarded – undo
3026 3026
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3027 3027
             // if the value we want to assign it to is NULL, just don't mention it for the insertion
3028 3028
             if ($prepared_value !== null) {
3029
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3029
+                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
3030 3030
                 $format_for_insertion[]                                   = $field_obj->get_wpdb_data_type();
3031 3031
             }
3032 3032
         }
3033 3033
         if ($table instanceof EE_Secondary_Table && $new_id) {
3034 3034
             // its not the main table, so we should have already saved the main table's PK which we just inserted
3035 3035
             // so add the fk to the main table as a column
3036
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3036
+            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
3037 3037
             $format_for_insertion[]                              =
3038
-                '%d';// yes right now we're only allowing these foreign keys to be INTs
3038
+                '%d'; // yes right now we're only allowing these foreign keys to be INTs
3039 3039
         }
3040 3040
         // insert the new entry
3041 3041
         $result = $this->_do_wpdb_query(
@@ -3052,7 +3052,7 @@  discard block
 block discarded – undo
3052 3052
             }
3053 3053
             // it's not an auto-increment primary key, so
3054 3054
             // it must have been supplied
3055
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3055
+            return $fields_n_values[$this->get_primary_key_field()->get_name()];
3056 3056
         }
3057 3057
         // we can't return a  primary key because there is none. instead return
3058 3058
         // a unique string indicating this model
@@ -3076,14 +3076,14 @@  discard block
 block discarded – undo
3076 3076
         if (
3077 3077
             ! $field_obj->is_nullable()
3078 3078
             && (
3079
-                ! isset($fields_n_values[ $field_obj->get_name() ])
3080
-                || $fields_n_values[ $field_obj->get_name() ] === null
3079
+                ! isset($fields_n_values[$field_obj->get_name()])
3080
+                || $fields_n_values[$field_obj->get_name()] === null
3081 3081
             )
3082 3082
         ) {
3083
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3083
+            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
3084 3084
         }
3085
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3086
-            ? $fields_n_values[ $field_obj->get_name() ]
3085
+        $unprepared_value = isset($fields_n_values[$field_obj->get_name()])
3086
+            ? $fields_n_values[$field_obj->get_name()]
3087 3087
             : null;
3088 3088
         return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3089 3089
     }
@@ -3184,7 +3184,7 @@  discard block
 block discarded – undo
3184 3184
      */
3185 3185
     public function get_table_obj_by_alias($table_alias = '')
3186 3186
     {
3187
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3187
+        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3188 3188
     }
3189 3189
 
3190 3190
 
@@ -3198,7 +3198,7 @@  discard block
 block discarded – undo
3198 3198
         $other_tables = [];
3199 3199
         foreach ($this->_tables as $table_alias => $table) {
3200 3200
             if ($table instanceof EE_Secondary_Table) {
3201
-                $other_tables[ $table_alias ] = $table;
3201
+                $other_tables[$table_alias] = $table;
3202 3202
             }
3203 3203
         }
3204 3204
         return $other_tables;
@@ -3213,7 +3213,7 @@  discard block
 block discarded – undo
3213 3213
      */
3214 3214
     public function _get_fields_for_table($table_alias)
3215 3215
     {
3216
-        return $this->_fields[ $table_alias ];
3216
+        return $this->_fields[$table_alias];
3217 3217
     }
3218 3218
 
3219 3219
 
@@ -3242,7 +3242,7 @@  discard block
 block discarded – undo
3242 3242
                     $query_info_carrier,
3243 3243
                     'group_by'
3244 3244
                 );
3245
-            } elseif (! empty($query_params['group_by'])) {
3245
+            } elseif ( ! empty($query_params['group_by'])) {
3246 3246
                 $this->_extract_related_model_info_from_query_param(
3247 3247
                     $query_params['group_by'],
3248 3248
                     $query_info_carrier,
@@ -3264,7 +3264,7 @@  discard block
 block discarded – undo
3264 3264
                     $query_info_carrier,
3265 3265
                     'order_by'
3266 3266
                 );
3267
-            } elseif (! empty($query_params['order_by'])) {
3267
+            } elseif ( ! empty($query_params['order_by'])) {
3268 3268
                 $this->_extract_related_model_info_from_query_param(
3269 3269
                     $query_params['order_by'],
3270 3270
                     $query_info_carrier,
@@ -3299,7 +3299,7 @@  discard block
 block discarded – undo
3299 3299
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3300 3300
         $query_param_type
3301 3301
     ) {
3302
-        if (! empty($sub_query_params)) {
3302
+        if ( ! empty($sub_query_params)) {
3303 3303
             $sub_query_params = (array) $sub_query_params;
3304 3304
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3305 3305
                 // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
@@ -3315,7 +3315,7 @@  discard block
 block discarded – undo
3315 3315
                 $query_param_sans_stars =
3316 3316
                     $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3317 3317
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3318
-                    if (! is_array($possibly_array_of_params)) {
3318
+                    if ( ! is_array($possibly_array_of_params)) {
3319 3319
                         throw new EE_Error(
3320 3320
                             sprintf(
3321 3321
                                 esc_html__(
@@ -3341,7 +3341,7 @@  discard block
 block discarded – undo
3341 3341
                     // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3342 3342
                     // indicating that $possible_array_of_params[1] is actually a field name,
3343 3343
                     // from which we should extract query parameters!
3344
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3344
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3345 3345
                         throw new EE_Error(
3346 3346
                             sprintf(
3347 3347
                                 esc_html__(
@@ -3381,8 +3381,8 @@  discard block
 block discarded – undo
3381 3381
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3382 3382
         $query_param_type
3383 3383
     ) {
3384
-        if (! empty($sub_query_params)) {
3385
-            if (! is_array($sub_query_params)) {
3384
+        if ( ! empty($sub_query_params)) {
3385
+            if ( ! is_array($sub_query_params)) {
3386 3386
                 throw new EE_Error(
3387 3387
                     sprintf(
3388 3388
                         esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
@@ -3420,7 +3420,7 @@  discard block
 block discarded – undo
3420 3420
      */
3421 3421
     public function _create_model_query_info_carrier($query_params)
3422 3422
     {
3423
-        if (! is_array($query_params)) {
3423
+        if ( ! is_array($query_params)) {
3424 3424
             EE_Error::doing_it_wrong(
3425 3425
                 'EEM_Base::_create_model_query_info_carrier',
3426 3426
                 sprintf(
@@ -3453,7 +3453,7 @@  discard block
 block discarded – undo
3453 3453
             // only include if related to a cpt where no password has been set
3454 3454
             $query_params[0]['OR*nopassword'] = [
3455 3455
                 $where_param_key_for_password       => '',
3456
-                $where_param_key_for_password . '*' => ['IS_NULL'],
3456
+                $where_param_key_for_password.'*' => ['IS_NULL'],
3457 3457
             ];
3458 3458
         }
3459 3459
         $query_object = $this->_extract_related_models_from_query($query_params);
@@ -3507,7 +3507,7 @@  discard block
 block discarded – undo
3507 3507
         // set limit
3508 3508
         if (array_key_exists('limit', $query_params)) {
3509 3509
             if (is_array($query_params['limit'])) {
3510
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3510
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3511 3511
                     $e = sprintf(
3512 3512
                         esc_html__(
3513 3513
                             "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)",
@@ -3515,12 +3515,12 @@  discard block
 block discarded – undo
3515 3515
                         ),
3516 3516
                         http_build_query($query_params['limit'])
3517 3517
                     );
3518
-                    throw new EE_Error($e . "|" . $e);
3518
+                    throw new EE_Error($e."|".$e);
3519 3519
                 }
3520 3520
                 // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3521
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3522
-            } elseif (! empty($query_params['limit'])) {
3523
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3521
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3522
+            } elseif ( ! empty($query_params['limit'])) {
3523
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3524 3524
             }
3525 3525
         }
3526 3526
         // set order by
@@ -3552,10 +3552,10 @@  discard block
 block discarded – undo
3552 3552
                 $order_array = [];
3553 3553
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3554 3554
                     $order         = $this->_extract_order($order);
3555
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3555
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3556 3556
                 }
3557
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3558
-            } elseif (! empty($query_params['order_by'])) {
3557
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3558
+            } elseif ( ! empty($query_params['order_by'])) {
3559 3559
                 $this->_extract_related_model_info_from_query_param(
3560 3560
                     $query_params['order_by'],
3561 3561
                     $query_object,
@@ -3566,7 +3566,7 @@  discard block
 block discarded – undo
3566 3566
                     ? $this->_extract_order($query_params['order'])
3567 3567
                     : 'DESC';
3568 3568
                 $query_object->set_order_by_sql(
3569
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3569
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3570 3570
                 );
3571 3571
             }
3572 3572
         }
@@ -3578,7 +3578,7 @@  discard block
 block discarded – undo
3578 3578
         ) {
3579 3579
             $pk_field = $this->get_primary_key_field();
3580 3580
             $order    = $this->_extract_order($query_params['order']);
3581
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3581
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3582 3582
         }
3583 3583
         // set group by
3584 3584
         if (array_key_exists('group_by', $query_params)) {
@@ -3588,10 +3588,10 @@  discard block
 block discarded – undo
3588 3588
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3589 3589
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3590 3590
                 }
3591
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3592
-            } elseif (! empty($query_params['group_by'])) {
3591
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3592
+            } elseif ( ! empty($query_params['group_by'])) {
3593 3593
                 $query_object->set_group_by_sql(
3594
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3594
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3595 3595
                 );
3596 3596
             }
3597 3597
         }
@@ -3601,7 +3601,7 @@  discard block
 block discarded – undo
3601 3601
         }
3602 3602
         // now, just verify they didn't pass anything wack
3603 3603
         foreach ($query_params as $query_key => $query_value) {
3604
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3604
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3605 3605
                 throw new EE_Error(
3606 3606
                     sprintf(
3607 3607
                         esc_html__(
@@ -3705,7 +3705,7 @@  discard block
 block discarded – undo
3705 3705
         $where_query_params = []
3706 3706
     ) {
3707 3707
         $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3708
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3708
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3709 3709
             throw new EE_Error(
3710 3710
                 sprintf(
3711 3711
                     esc_html__(
@@ -3735,7 +3735,7 @@  discard block
 block discarded – undo
3735 3735
                 // we don't want to add full or even minimum default where conditions from this model, so just continue
3736 3736
                 continue;
3737 3737
             }
3738
-            $overrides              = $this->_override_defaults_or_make_null_friendly(
3738
+            $overrides = $this->_override_defaults_or_make_null_friendly(
3739 3739
                 $related_model_universal_where_params,
3740 3740
                 $where_query_params,
3741 3741
                 $related_model,
@@ -3844,19 +3844,19 @@  discard block
 block discarded – undo
3844 3844
     ) {
3845 3845
         $null_friendly_where_conditions = [];
3846 3846
         $none_overridden                = true;
3847
-        $or_condition_key_for_defaults  = 'OR*' . get_class($model);
3847
+        $or_condition_key_for_defaults  = 'OR*'.get_class($model);
3848 3848
         foreach ($default_where_conditions as $key => $val) {
3849
-            if (isset($provided_where_conditions[ $key ])) {
3849
+            if (isset($provided_where_conditions[$key])) {
3850 3850
                 $none_overridden = false;
3851 3851
             } else {
3852
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3852
+                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3853 3853
             }
3854 3854
         }
3855 3855
         if ($none_overridden && $default_where_conditions) {
3856 3856
             if ($model->has_primary_key_field()) {
3857
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3857
+                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3858 3858
                                                                                    . "."
3859
-                                                                                   . $model->primary_key_name() ] =
3859
+                                                                                   . $model->primary_key_name()] =
3860 3860
                     ['IS NULL'];
3861 3861
             }/*else{
3862 3862
                 //@todo NO PK, use other defaults
@@ -3965,7 +3965,7 @@  discard block
 block discarded – undo
3965 3965
             foreach ($tables as $table_obj) {
3966 3966
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3967 3967
                                        . $table_obj->get_fully_qualified_pk_column();
3968
-                if (! in_array($qualified_pk_column, $selects)) {
3968
+                if ( ! in_array($qualified_pk_column, $selects)) {
3969 3969
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3970 3970
                 }
3971 3971
             }
@@ -4117,9 +4117,9 @@  discard block
 block discarded – undo
4117 4117
         $query_parameter_type
4118 4118
     ) {
4119 4119
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4120
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4120
+            if (strpos($possible_join_string, $valid_related_model_name.".") === 0) {
4121 4121
                 $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4122
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4122
+                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name."."));
4123 4123
                 if ($possible_join_string === '') {
4124 4124
                     // nothing left to $query_param
4125 4125
                     // we should actually end in a field name, not a model like this!
@@ -4251,7 +4251,7 @@  discard block
 block discarded – undo
4251 4251
     {
4252 4252
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4253 4253
         if ($SQL) {
4254
-            return " WHERE " . $SQL;
4254
+            return " WHERE ".$SQL;
4255 4255
         }
4256 4256
         return '';
4257 4257
     }
@@ -4269,7 +4269,7 @@  discard block
 block discarded – undo
4269 4269
     {
4270 4270
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4271 4271
         if ($SQL) {
4272
-            return " HAVING " . $SQL;
4272
+            return " HAVING ".$SQL;
4273 4273
         }
4274 4274
         return '';
4275 4275
     }
@@ -4294,7 +4294,7 @@  discard block
 block discarded – undo
4294 4294
             $query_param =
4295 4295
                 $this->_remove_stars_and_anything_after_from_condition_query_param_key(
4296 4296
                     $query_param
4297
-                );// str_replace("*",'',$query_param);
4297
+                ); // str_replace("*",'',$query_param);
4298 4298
             if (in_array($query_param, $this->_logic_query_param_keys)) {
4299 4299
                 $open = ' (';
4300 4300
                 $close = ')';
@@ -4320,7 +4320,7 @@  discard block
 block discarded – undo
4320 4320
             } else {
4321 4321
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
4322 4322
                 // if it's not a normal field, maybe it's a custom selection?
4323
-                if (! $field_obj) {
4323
+                if ( ! $field_obj) {
4324 4324
                     if ($this->_custom_selections instanceof CustomSelects) {
4325 4325
                         $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4326 4326
                     } else {
@@ -4336,7 +4336,7 @@  discard block
 block discarded – undo
4336 4336
                     }
4337 4337
                 }
4338 4338
                 $op_and_value_sql = $this->_construct_op_and_value($value, $field_obj);
4339
-                $where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4339
+                $where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
4340 4340
             }
4341 4341
         }
4342 4342
         return $where_clauses ? implode($glue, $where_clauses) : '';
@@ -4358,7 +4358,7 @@  discard block
 block discarded – undo
4358 4358
                 $field->get_model_name(),
4359 4359
                 $query_param
4360 4360
             );
4361
-            return $table_alias_prefix . $field->get_qualified_column();
4361
+            return $table_alias_prefix.$field->get_qualified_column();
4362 4362
         }
4363 4363
         if (
4364 4364
             $this->_custom_selections instanceof CustomSelects
@@ -4415,7 +4415,7 @@  discard block
 block discarded – undo
4415 4415
     {
4416 4416
         if (is_array($op_and_value)) {
4417 4417
             $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4418
-            if (! $operator) {
4418
+            if ( ! $operator) {
4419 4419
                 $php_array_like_string = [];
4420 4420
                 foreach ($op_and_value as $key => $value) {
4421 4421
                     $php_array_like_string[] = "$key=>$value";
@@ -4437,14 +4437,14 @@  discard block
 block discarded – undo
4437 4437
         }
4438 4438
         // check to see if the value is actually another field
4439 4439
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4440
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4440
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4441 4441
         }
4442 4442
         if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4443 4443
             // in this case, the value should be an array, or at least a comma-separated list
4444 4444
             // it will need to handle a little differently
4445 4445
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4446 4446
             // note: $cleaned_value has already been run through $wpdb->prepare()
4447
-            return $operator . SP . $cleaned_value;
4447
+            return $operator.SP.$cleaned_value;
4448 4448
         }
4449 4449
         if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4450 4450
             // the value should be an array with count of two.
@@ -4460,7 +4460,7 @@  discard block
 block discarded – undo
4460 4460
                 );
4461 4461
             }
4462 4462
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4463
-            return $operator . SP . $cleaned_value;
4463
+            return $operator.SP.$cleaned_value;
4464 4464
         }
4465 4465
         if (in_array($operator, $this->valid_null_style_operators())) {
4466 4466
             if ($value !== null) {
@@ -4480,10 +4480,10 @@  discard block
 block discarded – undo
4480 4480
         if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4481 4481
             // if the operator is 'LIKE', we want to allow percent signs (%) and not
4482 4482
             // remove other junk. So just treat it as a string.
4483
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4483
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4484 4484
         }
4485
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4486
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4485
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4486
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4487 4487
         }
4488 4488
         if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4489 4489
             throw new EE_Error(
@@ -4497,7 +4497,7 @@  discard block
 block discarded – undo
4497 4497
                 )
4498 4498
             );
4499 4499
         }
4500
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4500
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4501 4501
             throw new EE_Error(
4502 4502
                 sprintf(
4503 4503
                     esc_html__(
@@ -4536,7 +4536,7 @@  discard block
 block discarded – undo
4536 4536
         foreach ($values as $value) {
4537 4537
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4538 4538
         }
4539
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4539
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4540 4540
     }
4541 4541
 
4542 4542
 
@@ -4576,7 +4576,7 @@  discard block
 block discarded – undo
4576 4576
                                 . $main_table->get_table_name()
4577 4577
                                 . " WHERE FALSE";
4578 4578
         }
4579
-        return "(" . implode(",", $cleaned_values) . ")";
4579
+        return "(".implode(",", $cleaned_values).")";
4580 4580
     }
4581 4581
 
4582 4582
 
@@ -4595,7 +4595,7 @@  discard block
 block discarded – undo
4595 4595
                 $this->_prepare_value_for_use_in_db($value, $field_obj)
4596 4596
             );
4597 4597
         } //$field_obj should really just be a data type
4598
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4598
+        if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4599 4599
             throw new EE_Error(
4600 4600
                 sprintf(
4601 4601
                     esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
@@ -4632,14 +4632,14 @@  discard block
 block discarded – undo
4632 4632
             );
4633 4633
         }
4634 4634
         $number_of_parts       = count($query_param_parts);
4635
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4635
+        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4636 4636
         if ($number_of_parts === 1) {
4637 4637
             $field_name = $last_query_param_part;
4638 4638
             $model_obj  = $this;
4639 4639
         } else {// $number_of_parts >= 2
4640 4640
             // the last part is the column name, and there are only 2parts. therefore...
4641 4641
             $field_name = $last_query_param_part;
4642
-            $model_obj  = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4642
+            $model_obj  = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4643 4643
         }
4644 4644
         try {
4645 4645
             return $model_obj->field_settings_for($field_name);
@@ -4660,7 +4660,7 @@  discard block
 block discarded – undo
4660 4660
     public function _get_qualified_column_for_field($field_name)
4661 4661
     {
4662 4662
         $all_fields = $this->field_settings();
4663
-        $field      = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4663
+        $field      = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4664 4664
         if ($field) {
4665 4665
             return $field->get_qualified_column();
4666 4666
         }
@@ -4730,10 +4730,10 @@  discard block
 block discarded – undo
4730 4730
      */
4731 4731
     public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4732 4732
     {
4733
-        $table_prefix      = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4733
+        $table_prefix      = str_replace('.', '__', $model_relation_chain).(empty($model_relation_chain) ? '' : '__');
4734 4734
         $qualified_columns = [];
4735 4735
         foreach ($this->field_settings() as $field_name => $field) {
4736
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4736
+            $qualified_columns[] = $table_prefix.$field->get_qualified_column();
4737 4737
         }
4738 4738
         return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4739 4739
     }
@@ -4757,11 +4757,11 @@  discard block
 block discarded – undo
4757 4757
             if ($table_obj instanceof EE_Primary_Table) {
4758 4758
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4759 4759
                     ? $table_obj->get_select_join_limit($limit)
4760
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4760
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4761 4761
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4762 4762
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4763 4763
                     ? $table_obj->get_select_join_limit_join($limit)
4764
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4764
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4765 4765
             }
4766 4766
         }
4767 4767
         return $SQL;
@@ -4831,7 +4831,7 @@  discard block
 block discarded – undo
4831 4831
         foreach ($this->field_settings() as $field_obj) {
4832 4832
             // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4833 4833
             /** @var $field_obj EE_Model_Field_Base */
4834
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4834
+            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4835 4835
         }
4836 4836
         return $data_types;
4837 4837
     }
@@ -4846,8 +4846,8 @@  discard block
 block discarded – undo
4846 4846
      */
4847 4847
     public function get_related_model_obj($model_name)
4848 4848
     {
4849
-        $model_classname = "EEM_" . $model_name;
4850
-        if (! class_exists($model_classname)) {
4849
+        $model_classname = "EEM_".$model_name;
4850
+        if ( ! class_exists($model_classname)) {
4851 4851
             throw new EE_Error(
4852 4852
                 sprintf(
4853 4853
                     esc_html__(
@@ -4859,7 +4859,7 @@  discard block
 block discarded – undo
4859 4859
                 )
4860 4860
             );
4861 4861
         }
4862
-        return call_user_func($model_classname . "::instance");
4862
+        return call_user_func($model_classname."::instance");
4863 4863
     }
4864 4864
 
4865 4865
 
@@ -4886,7 +4886,7 @@  discard block
 block discarded – undo
4886 4886
         $belongs_to_relations = [];
4887 4887
         foreach ($this->relation_settings() as $model_name => $relation_obj) {
4888 4888
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
4889
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4889
+                $belongs_to_relations[$model_name] = $relation_obj;
4890 4890
             }
4891 4891
         }
4892 4892
         return $belongs_to_relations;
@@ -4903,7 +4903,7 @@  discard block
 block discarded – undo
4903 4903
     public function related_settings_for($relation_name)
4904 4904
     {
4905 4905
         $relatedModels = $this->relation_settings();
4906
-        if (! array_key_exists($relation_name, $relatedModels)) {
4906
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
4907 4907
             throw new EE_Error(
4908 4908
                 sprintf(
4909 4909
                     esc_html__(
@@ -4916,7 +4916,7 @@  discard block
 block discarded – undo
4916 4916
                 )
4917 4917
             );
4918 4918
         }
4919
-        return $relatedModels[ $relation_name ];
4919
+        return $relatedModels[$relation_name];
4920 4920
     }
4921 4921
 
4922 4922
 
@@ -4932,7 +4932,7 @@  discard block
 block discarded – undo
4932 4932
     public function field_settings_for($fieldName, $include_db_only_fields = true)
4933 4933
     {
4934 4934
         $fieldSettings = $this->field_settings($include_db_only_fields);
4935
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4935
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4936 4936
             throw new EE_Error(
4937 4937
                 sprintf(
4938 4938
                     esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
@@ -4941,7 +4941,7 @@  discard block
 block discarded – undo
4941 4941
                 )
4942 4942
             );
4943 4943
         }
4944
-        return $fieldSettings[ $fieldName ];
4944
+        return $fieldSettings[$fieldName];
4945 4945
     }
4946 4946
 
4947 4947
 
@@ -4954,7 +4954,7 @@  discard block
 block discarded – undo
4954 4954
     public function has_field($fieldName)
4955 4955
     {
4956 4956
         $fieldSettings = $this->field_settings(true);
4957
-        if (isset($fieldSettings[ $fieldName ])) {
4957
+        if (isset($fieldSettings[$fieldName])) {
4958 4958
             return true;
4959 4959
         }
4960 4960
         return false;
@@ -4970,7 +4970,7 @@  discard block
 block discarded – undo
4970 4970
     public function has_relation($relation_name)
4971 4971
     {
4972 4972
         $relations = $this->relation_settings();
4973
-        if (isset($relations[ $relation_name ])) {
4973
+        if (isset($relations[$relation_name])) {
4974 4974
             return true;
4975 4975
         }
4976 4976
         return false;
@@ -5006,7 +5006,7 @@  discard block
 block discarded – undo
5006 5006
                     break;
5007 5007
                 }
5008 5008
             }
5009
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5009
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5010 5010
                 throw new EE_Error(
5011 5011
                     sprintf(
5012 5012
                         esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
@@ -5066,17 +5066,17 @@  discard block
 block discarded – undo
5066 5066
      */
5067 5067
     public function get_foreign_key_to($model_name)
5068 5068
     {
5069
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5069
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5070 5070
             foreach ($this->field_settings() as $field) {
5071 5071
                 if (
5072 5072
                     $field instanceof EE_Foreign_Key_Field_Base
5073 5073
                     && in_array($model_name, $field->get_model_names_pointed_to())
5074 5074
                 ) {
5075
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5075
+                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
5076 5076
                     break;
5077 5077
                 }
5078 5078
             }
5079
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5079
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5080 5080
                 throw new EE_Error(
5081 5081
                     sprintf(
5082 5082
                         esc_html__(
@@ -5089,7 +5089,7 @@  discard block
 block discarded – undo
5089 5089
                 );
5090 5090
             }
5091 5091
         }
5092
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5092
+        return $this->_cache_foreign_key_to_fields[$model_name];
5093 5093
     }
5094 5094
 
5095 5095
 
@@ -5105,7 +5105,7 @@  discard block
 block discarded – undo
5105 5105
     {
5106 5106
         $table_alias_sans_model_relation_chain_prefix =
5107 5107
             EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5108
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5108
+        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
5109 5109
     }
5110 5110
 
5111 5111
 
@@ -5123,7 +5123,7 @@  discard block
 block discarded – undo
5123 5123
                 $this->_cached_fields = [];
5124 5124
                 foreach ($this->_fields as $fields_corresponding_to_table) {
5125 5125
                     foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5126
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5126
+                        $this->_cached_fields[$field_name] = $field_obj;
5127 5127
                     }
5128 5128
                 }
5129 5129
             }
@@ -5134,8 +5134,8 @@  discard block
 block discarded – undo
5134 5134
             foreach ($this->_fields as $fields_corresponding_to_table) {
5135 5135
                 foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5136 5136
                     /** @var $field_obj EE_Model_Field_Base */
5137
-                    if (! $field_obj->is_db_only_field()) {
5138
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5137
+                    if ( ! $field_obj->is_db_only_field()) {
5138
+                        $this->_cached_fields_non_db_only[$field_name] = $field_obj;
5139 5139
                     }
5140 5140
                 }
5141 5141
             }
@@ -5176,12 +5176,12 @@  discard block
 block discarded – undo
5176 5176
                     $primary_key_field->get_qualified_column(),
5177 5177
                     $primary_key_field->get_table_column()
5178 5178
                 );
5179
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5179
+                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
5180 5180
                     continue;
5181 5181
                 }
5182 5182
             }
5183 5183
             $classInstance = $this->instantiate_class_from_array_or_object($row);
5184
-            if (! $classInstance) {
5184
+            if ( ! $classInstance) {
5185 5185
                 throw new EE_Error(
5186 5186
                     sprintf(
5187 5187
                         esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -5194,7 +5194,7 @@  discard block
 block discarded – undo
5194 5194
             $classInstance->set_timezone($this->get_timezone(), true);
5195 5195
             // make sure if there is any timezone setting present that we set the timezone for the object
5196 5196
             $key                      = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5197
-            $array_of_objects[ $key ] = $classInstance;
5197
+            $array_of_objects[$key] = $classInstance;
5198 5198
             // also, for all the relations of type BelongsTo, see if we can cache
5199 5199
             // those related models
5200 5200
             // (we could do this for other relations too, but if there are conditions
@@ -5238,9 +5238,9 @@  discard block
 block discarded – undo
5238 5238
         $results = [];
5239 5239
         if ($this->_custom_selections instanceof CustomSelects) {
5240 5240
             foreach ($this->_custom_selections->columnAliases() as $alias) {
5241
-                if (isset($db_results_row[ $alias ])) {
5242
-                    $results[ $alias ] = $this->convertValueToDataType(
5243
-                        $db_results_row[ $alias ],
5241
+                if (isset($db_results_row[$alias])) {
5242
+                    $results[$alias] = $this->convertValueToDataType(
5243
+                        $db_results_row[$alias],
5244 5244
                         $this->_custom_selections->getDataTypeForAlias($alias)
5245 5245
                     );
5246 5246
                 }
@@ -5285,7 +5285,7 @@  discard block
 block discarded – undo
5285 5285
         $this_model_fields_and_values = [];
5286 5286
         // setup the row using default values;
5287 5287
         foreach ($this->field_settings() as $field_name => $field_obj) {
5288
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5288
+            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
5289 5289
         }
5290 5290
         $className = $this->_get_class_name();
5291 5291
         return EE_Registry::instance()->load_class(
@@ -5306,20 +5306,20 @@  discard block
 block discarded – undo
5306 5306
      */
5307 5307
     public function instantiate_class_from_array_or_object($cols_n_values)
5308 5308
     {
5309
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5309
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
5310 5310
             $cols_n_values = get_object_vars($cols_n_values);
5311 5311
         }
5312 5312
         $primary_key = null;
5313 5313
         // make sure the array only has keys that are fields/columns on this model
5314 5314
         $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5315
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5316
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5315
+        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5316
+            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5317 5317
         }
5318 5318
         $className = $this->_get_class_name();
5319 5319
         // check we actually found results that we can use to build our model object
5320 5320
         // if not, return null
5321 5321
         if ($this->has_primary_key_field()) {
5322
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5322
+            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5323 5323
                 return null;
5324 5324
             }
5325 5325
         } elseif ($this->unique_indexes()) {
@@ -5331,7 +5331,7 @@  discard block
 block discarded – undo
5331 5331
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5332 5332
         if ($primary_key) {
5333 5333
             $classInstance = $this->get_from_entity_map($primary_key);
5334
-            if (! $classInstance) {
5334
+            if ( ! $classInstance) {
5335 5335
                 $classInstance = EE_Registry::instance()->load_class(
5336 5336
                     $className,
5337 5337
                     [$this_model_fields_n_values, $this->get_timezone()],
@@ -5361,8 +5361,8 @@  discard block
 block discarded – undo
5361 5361
      */
5362 5362
     public function get_from_entity_map($id)
5363 5363
     {
5364
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5365
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]
5364
+        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
5365
+            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id]
5366 5366
             : null;
5367 5367
     }
5368 5368
 
@@ -5385,7 +5385,7 @@  discard block
 block discarded – undo
5385 5385
     public function add_to_entity_map(EE_Base_Class $object)
5386 5386
     {
5387 5387
         $className = $this->_get_class_name();
5388
-        if (! $object instanceof $className) {
5388
+        if ( ! $object instanceof $className) {
5389 5389
             throw new EE_Error(
5390 5390
                 sprintf(
5391 5391
                     esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
@@ -5394,7 +5394,7 @@  discard block
 block discarded – undo
5394 5394
                 )
5395 5395
             );
5396 5396
         }
5397
-        if (! $object->ID()) {
5397
+        if ( ! $object->ID()) {
5398 5398
             throw new EE_Error(
5399 5399
                 sprintf(
5400 5400
                     esc_html__(
@@ -5410,7 +5410,7 @@  discard block
 block discarded – undo
5410 5410
         if ($classInstance) {
5411 5411
             return $classInstance;
5412 5412
         }
5413
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5413
+        $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5414 5414
         return $object;
5415 5415
     }
5416 5416
 
@@ -5425,11 +5425,11 @@  discard block
 block discarded – undo
5425 5425
     public function clear_entity_map($id = null)
5426 5426
     {
5427 5427
         if (empty($id)) {
5428
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = [];
5428
+            $this->_entity_map[EEM_Base::$_model_query_blog_id] = [];
5429 5429
             return true;
5430 5430
         }
5431
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5432
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5431
+        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5432
+            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5433 5433
             return true;
5434 5434
         }
5435 5435
         return false;
@@ -5470,18 +5470,18 @@  discard block
 block discarded – undo
5470 5470
             // there is a primary key on this table and its not set. Use defaults for all its columns
5471 5471
             if ($table_pk_value === null && $table_obj->get_pk_column()) {
5472 5472
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5473
-                    if (! $field_obj->is_db_only_field()) {
5473
+                    if ( ! $field_obj->is_db_only_field()) {
5474 5474
                         // prepare field as if its coming from db
5475 5475
                         $prepared_value                            =
5476 5476
                             $field_obj->prepare_for_set($field_obj->get_default_value());
5477
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5477
+                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5478 5478
                     }
5479 5479
                 }
5480 5480
             } else {
5481 5481
                 // the table's rows existed. Use their values
5482 5482
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5483
-                    if (! $field_obj->is_db_only_field()) {
5484
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5483
+                    if ( ! $field_obj->is_db_only_field()) {
5484
+                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5485 5485
                             $cols_n_values,
5486 5486
                             $field_obj->get_qualified_column(),
5487 5487
                             $field_obj->get_table_column()
@@ -5506,17 +5506,17 @@  discard block
 block discarded – undo
5506 5506
         // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5507 5507
         // does the field on the model relate to this column retrieved from the db?
5508 5508
         // or is it a db-only field? (not relating to the model)
5509
-        if (isset($cols_n_values[ $qualified_column ])) {
5510
-            $value = $cols_n_values[ $qualified_column ];
5511
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5512
-            $value = $cols_n_values[ $regular_column ];
5513
-        } elseif (! empty($this->foreign_key_aliases)) {
5509
+        if (isset($cols_n_values[$qualified_column])) {
5510
+            $value = $cols_n_values[$qualified_column];
5511
+        } elseif (isset($cols_n_values[$regular_column])) {
5512
+            $value = $cols_n_values[$regular_column];
5513
+        } elseif ( ! empty($this->foreign_key_aliases)) {
5514 5514
             // no PK?  ok check if there is a foreign key alias set for this table
5515 5515
             // then check if that alias exists in the incoming data
5516 5516
             // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5517 5517
             foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5518
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5519
-                    $value = $cols_n_values[ $FK_alias ];
5518
+                if ($PK_column === $qualified_column && isset($cols_n_values[$FK_alias])) {
5519
+                    $value = $cols_n_values[$FK_alias];
5520 5520
                     break;
5521 5521
                 }
5522 5522
             }
@@ -5552,7 +5552,7 @@  discard block
 block discarded – undo
5552 5552
                     $obj_in_map->clear_cache($relation_name, null, true);
5553 5553
                 }
5554 5554
             }
5555
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5555
+            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5556 5556
             return $obj_in_map;
5557 5557
         }
5558 5558
         return $this->get_one_by_ID($id);
@@ -5604,7 +5604,7 @@  discard block
 block discarded – undo
5604 5604
      */
5605 5605
     private function _get_class_name()
5606 5606
     {
5607
-        return "EE_" . $this->get_this_model_name();
5607
+        return "EE_".$this->get_this_model_name();
5608 5608
     }
5609 5609
 
5610 5610
 
@@ -5650,7 +5650,7 @@  discard block
 block discarded – undo
5650 5650
     {
5651 5651
         $className = get_class($this);
5652 5652
         $tagName   = "FHEE__{$className}__{$methodName}";
5653
-        if (! has_filter($tagName)) {
5653
+        if ( ! has_filter($tagName)) {
5654 5654
             throw new EE_Error(
5655 5655
                 sprintf(
5656 5656
                     esc_html__(
@@ -5819,7 +5819,7 @@  discard block
 block discarded – undo
5819 5819
         $unique_indexes = [];
5820 5820
         foreach ($this->_indexes as $name => $index) {
5821 5821
             if ($index instanceof EE_Unique_Index) {
5822
-                $unique_indexes [ $name ] = $index;
5822
+                $unique_indexes [$name] = $index;
5823 5823
             }
5824 5824
         }
5825 5825
         return $unique_indexes;
@@ -5883,7 +5883,7 @@  discard block
 block discarded – undo
5883 5883
         $key_values_in_combined_pk = [];
5884 5884
         parse_str($index_primary_key_string, $key_values_in_combined_pk);
5885 5885
         foreach ($key_fields as $key_field_name => $field_obj) {
5886
-            if (! isset($key_values_in_combined_pk[ $key_field_name ])) {
5886
+            if ( ! isset($key_values_in_combined_pk[$key_field_name])) {
5887 5887
                 return null;
5888 5888
             }
5889 5889
         }
@@ -5903,7 +5903,7 @@  discard block
 block discarded – undo
5903 5903
     {
5904 5904
         $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5905 5905
         foreach ($keys_it_should_have as $key) {
5906
-            if (! isset($key_values[ $key ])) {
5906
+            if ( ! isset($key_values[$key])) {
5907 5907
                 return false;
5908 5908
             }
5909 5909
         }
@@ -5942,8 +5942,8 @@  discard block
 block discarded – undo
5942 5942
         }
5943 5943
         // even copies obviously won't have the same ID, so remove the primary key
5944 5944
         // from the WHERE conditions for finding copies (if there is a primary key, of course)
5945
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5946
-            unset($attributes_array[ $this->primary_key_name() ]);
5945
+        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5946
+            unset($attributes_array[$this->primary_key_name()]);
5947 5947
         }
5948 5948
         if (isset($query_params[0])) {
5949 5949
             $query_params[0] = array_merge($attributes_array, $query_params);
@@ -5965,7 +5965,7 @@  discard block
 block discarded – undo
5965 5965
      */
5966 5966
     public function get_one_copy($model_object_or_attributes_array, $query_params = [])
5967 5967
     {
5968
-        if (! is_array($query_params)) {
5968
+        if ( ! is_array($query_params)) {
5969 5969
             EE_Error::doing_it_wrong(
5970 5970
                 'EEM_Base::get_one_copy',
5971 5971
                 sprintf(
@@ -6015,7 +6015,7 @@  discard block
 block discarded – undo
6015 6015
     private function _prepare_operator_for_sql($operator_supplied)
6016 6016
     {
6017 6017
         $sql_operator =
6018
-            isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
6018
+            isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
6019 6019
                 : null;
6020 6020
         if ($sql_operator) {
6021 6021
             return $sql_operator;
@@ -6114,7 +6114,7 @@  discard block
 block discarded – undo
6114 6114
         $objs  = $this->get_all($query_params);
6115 6115
         $names = [];
6116 6116
         foreach ($objs as $obj) {
6117
-            $names[ $obj->ID() ] = $obj->name();
6117
+            $names[$obj->ID()] = $obj->name();
6118 6118
         }
6119 6119
         return $names;
6120 6120
     }
@@ -6134,7 +6134,7 @@  discard block
 block discarded – undo
6134 6134
      */
6135 6135
     public function get_IDs($model_objects, $filter_out_empty_ids = false)
6136 6136
     {
6137
-        if (! $this->has_primary_key_field()) {
6137
+        if ( ! $this->has_primary_key_field()) {
6138 6138
             if (WP_DEBUG) {
6139 6139
                 EE_Error::add_error(
6140 6140
                     esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
@@ -6147,7 +6147,7 @@  discard block
 block discarded – undo
6147 6147
         $IDs = [];
6148 6148
         foreach ($model_objects as $model_object) {
6149 6149
             $id = $model_object->ID();
6150
-            if (! $id) {
6150
+            if ( ! $id) {
6151 6151
                 if ($filter_out_empty_ids) {
6152 6152
                     continue;
6153 6153
                 }
@@ -6197,22 +6197,22 @@  discard block
 block discarded – undo
6197 6197
         EEM_Base::verify_is_valid_cap_context($context);
6198 6198
         // check if we ought to run the restriction generator first
6199 6199
         if (
6200
-            isset($this->_cap_restriction_generators[ $context ])
6201
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6202
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6200
+            isset($this->_cap_restriction_generators[$context])
6201
+            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
6202
+            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
6203 6203
         ) {
6204
-            $this->_cap_restrictions[ $context ] = array_merge(
6205
-                $this->_cap_restrictions[ $context ],
6206
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6204
+            $this->_cap_restrictions[$context] = array_merge(
6205
+                $this->_cap_restrictions[$context],
6206
+                $this->_cap_restriction_generators[$context]->generate_restrictions()
6207 6207
             );
6208 6208
         }
6209 6209
         // and make sure we've finalized the construction of each restriction
6210
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6210
+        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
6211 6211
             if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6212 6212
                 $where_conditions_obj->_finalize_construct($this);
6213 6213
             }
6214 6214
         }
6215
-        return $this->_cap_restrictions[ $context ];
6215
+        return $this->_cap_restrictions[$context];
6216 6216
     }
6217 6217
 
6218 6218
 
@@ -6243,10 +6243,10 @@  discard block
 block discarded – undo
6243 6243
             if (
6244 6244
                 ! EE_Capabilities::instance()->current_user_can(
6245 6245
                     $cap,
6246
-                    $this->get_this_model_name() . '_model_applying_caps'
6246
+                    $this->get_this_model_name().'_model_applying_caps'
6247 6247
                 )
6248 6248
             ) {
6249
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6249
+                $missing_caps[$cap] = $restriction_if_no_cap;
6250 6250
             }
6251 6251
         }
6252 6252
         return $missing_caps;
@@ -6279,8 +6279,8 @@  discard block
 block discarded – undo
6279 6279
     public function cap_action_for_context($context)
6280 6280
     {
6281 6281
         $mapping = $this->cap_contexts_to_cap_action_map();
6282
-        if (isset($mapping[ $context ])) {
6283
-            return $mapping[ $context ];
6282
+        if (isset($mapping[$context])) {
6283
+            return $mapping[$context];
6284 6284
         }
6285 6285
         if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6286 6286
             return $action;
@@ -6401,7 +6401,7 @@  discard block
 block discarded – undo
6401 6401
         foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6402 6402
             if (
6403 6403
                 $query_param_key === $logic_query_param_key
6404
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6404
+                || strpos($query_param_key, $logic_query_param_key.'*') === 0
6405 6405
             ) {
6406 6406
                 return true;
6407 6407
             }
@@ -6459,7 +6459,7 @@  discard block
 block discarded – undo
6459 6459
         if ($password_field instanceof EE_Password_Field) {
6460 6460
             $field_names = $password_field->protectedFields();
6461 6461
             foreach ($field_names as $field_name) {
6462
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6462
+                $fields[$field_name] = $this->field_settings_for($field_name);
6463 6463
             }
6464 6464
         }
6465 6465
         return $fields;
@@ -6485,7 +6485,7 @@  discard block
 block discarded – undo
6485 6485
         if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6486 6486
             $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6487 6487
         }
6488
-        if (! is_array($model_obj_or_fields_n_values)) {
6488
+        if ( ! is_array($model_obj_or_fields_n_values)) {
6489 6489
             throw new UnexpectedEntityException(
6490 6490
                 $model_obj_or_fields_n_values,
6491 6491
                 'EE_Base_Class',
@@ -6565,7 +6565,7 @@  discard block
 block discarded – undo
6565 6565
                 )
6566 6566
             );
6567 6567
         }
6568
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6568
+        return ($this->model_chain_to_password ? $this->model_chain_to_password.'.' : '').$password_field_name;
6569 6569
     }
6570 6570
 
6571 6571
 
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.