Completed
Branch FET/editor-dates-tickets-refac... (767d9b)
by
unknown
27:39 queued 18:33
created
caffeinated/modules/recaptcha_invisible/InvisibleRecaptcha.php 2 patches
Indentation   +238 added lines, -238 removed lines patch added patch discarded remove patch
@@ -27,268 +27,268 @@
 block discarded – undo
27 27
 class InvisibleRecaptcha
28 28
 {
29 29
 
30
-    const URL_GOOGLE_RECAPTCHA_API          = 'https://www.google.com/recaptcha/api/siteverify';
30
+	const URL_GOOGLE_RECAPTCHA_API          = 'https://www.google.com/recaptcha/api/siteverify';
31 31
 
32
-    const SESSION_DATA_KEY_RECAPTCHA_PASSED = 'recaptcha_passed';
32
+	const SESSION_DATA_KEY_RECAPTCHA_PASSED = 'recaptcha_passed';
33 33
 
34
-    /**
35
-     * @var EE_Registration_Config $config
36
-     */
37
-    private $config;
34
+	/**
35
+	 * @var EE_Registration_Config $config
36
+	 */
37
+	private $config;
38 38
 
39
-    /**
40
-     * @var EE_Session $session
41
-     */
42
-    private $session;
39
+	/**
40
+	 * @var EE_Session $session
41
+	 */
42
+	private $session;
43 43
 
44
-    /**
45
-     * @var boolean $recaptcha_passed
46
-     */
47
-    private $recaptcha_passed;
44
+	/**
45
+	 * @var boolean $recaptcha_passed
46
+	 */
47
+	private $recaptcha_passed;
48 48
 
49 49
 
50
-    /**
51
-     * InvisibleRecaptcha constructor.
52
-     *
53
-     * @param EE_Registration_Config $registration_config
54
-     * @param EE_Session             $session
55
-     */
56
-    public function __construct(EE_Registration_Config $registration_config, EE_Session $session)
57
-    {
58
-        $this->config = $registration_config;
59
-        $this->session = $session;
60
-    }
50
+	/**
51
+	 * InvisibleRecaptcha constructor.
52
+	 *
53
+	 * @param EE_Registration_Config $registration_config
54
+	 * @param EE_Session             $session
55
+	 */
56
+	public function __construct(EE_Registration_Config $registration_config, EE_Session $session)
57
+	{
58
+		$this->config = $registration_config;
59
+		$this->session = $session;
60
+	}
61 61
 
62 62
 
63
-    /**
64
-     * @return boolean
65
-     */
66
-    public function useInvisibleRecaptcha()
67
-    {
68
-        return $this->config->use_captcha && $this->config->recaptcha_theme === 'invisible';
69
-    }
63
+	/**
64
+	 * @return boolean
65
+	 */
66
+	public function useInvisibleRecaptcha()
67
+	{
68
+		return $this->config->use_captcha && $this->config->recaptcha_theme === 'invisible';
69
+	}
70 70
 
71 71
 
72
-    /**
73
-     * @param array $input_settings
74
-     * @return EE_Invisible_Recaptcha_Input
75
-     * @throws InvalidDataTypeException
76
-     * @throws InvalidInterfaceException
77
-     * @throws InvalidArgumentException
78
-     * @throws DomainException
79
-     */
80
-    public function getInput(array $input_settings = array())
81
-    {
82
-        return new EE_Invisible_Recaptcha_Input(
83
-            $input_settings,
84
-            $this->config
85
-        );
86
-    }
72
+	/**
73
+	 * @param array $input_settings
74
+	 * @return EE_Invisible_Recaptcha_Input
75
+	 * @throws InvalidDataTypeException
76
+	 * @throws InvalidInterfaceException
77
+	 * @throws InvalidArgumentException
78
+	 * @throws DomainException
79
+	 */
80
+	public function getInput(array $input_settings = array())
81
+	{
82
+		return new EE_Invisible_Recaptcha_Input(
83
+			$input_settings,
84
+			$this->config
85
+		);
86
+	}
87 87
 
88 88
 
89
-    /**
90
-     * @param array $input_settings
91
-     * @return string
92
-     * @throws EE_Error
93
-     * @throws InvalidDataTypeException
94
-     * @throws InvalidInterfaceException
95
-     * @throws InvalidArgumentException
96
-     * @throws DomainException
97
-     */
98
-    public function getInputHtml(array $input_settings = array())
99
-    {
100
-        return $this->getInput($input_settings)->get_html_for_input();
101
-    }
89
+	/**
90
+	 * @param array $input_settings
91
+	 * @return string
92
+	 * @throws EE_Error
93
+	 * @throws InvalidDataTypeException
94
+	 * @throws InvalidInterfaceException
95
+	 * @throws InvalidArgumentException
96
+	 * @throws DomainException
97
+	 */
98
+	public function getInputHtml(array $input_settings = array())
99
+	{
100
+		return $this->getInput($input_settings)->get_html_for_input();
101
+	}
102 102
 
103 103
 
104
-    /**
105
-     * @param EE_Form_Section_Proper $form
106
-     * @param array                  $input_settings
107
-     * @throws EE_Error
108
-     * @throws InvalidArgumentException
109
-     * @throws InvalidDataTypeException
110
-     * @throws InvalidInterfaceException
111
-     * @throws DomainException
112
-     */
113
-    public function addToFormSection(EE_Form_Section_Proper $form, array $input_settings = array())
114
-    {
115
-        $form->add_subsections(
116
-            array(
117
-                'espresso_recaptcha' => $this->getInput($input_settings),
118
-            ),
119
-            null,
120
-            false
121
-        );
122
-    }
104
+	/**
105
+	 * @param EE_Form_Section_Proper $form
106
+	 * @param array                  $input_settings
107
+	 * @throws EE_Error
108
+	 * @throws InvalidArgumentException
109
+	 * @throws InvalidDataTypeException
110
+	 * @throws InvalidInterfaceException
111
+	 * @throws DomainException
112
+	 */
113
+	public function addToFormSection(EE_Form_Section_Proper $form, array $input_settings = array())
114
+	{
115
+		$form->add_subsections(
116
+			array(
117
+				'espresso_recaptcha' => $this->getInput($input_settings),
118
+			),
119
+			null,
120
+			false
121
+		);
122
+	}
123 123
 
124 124
 
125
-    /**
126
-     * @param RequestInterface $request
127
-     * @return boolean
128
-     * @throws InvalidArgumentException
129
-     * @throws InvalidDataTypeException
130
-     * @throws InvalidInterfaceException
131
-     * @throws RuntimeException
132
-     */
133
-    public function verifyToken(RequestInterface $request)
134
-    {
135
-        static $previous_recaptcha_response = array();
136
-        $grecaptcha_response = $request->getRequestParam('g-recaptcha-response');
137
-        // if this token has already been verified, then return previous response
138
-        if (isset($previous_recaptcha_response[ $grecaptcha_response ])) {
139
-            return $previous_recaptcha_response[ $grecaptcha_response ];
140
-        }
141
-        // still here but no g-recaptcha-response ? - verification failed
142
-        if (! $grecaptcha_response) {
143
-            EE_Error::add_error(
144
-                sprintf(
145
-                    /* translators: 1: missing parameter */
146
-                    esc_html__(
147
-                        // @codingStandardsIgnoreStart
148
-                        'We\'re sorry but an attempt to verify the form\'s reCAPTCHA has failed. Missing "%1$s". Please try again.',
149
-                        // @codingStandardsIgnoreEnd
150
-                        'event_espresso'
151
-                    ),
152
-                    'g-recaptcha-response'
153
-                ),
154
-                __FILE__,
155
-                __FUNCTION__,
156
-                __LINE__
157
-            );
158
-            return false;
159
-        }
160
-        // will update to true if everything passes
161
-        $previous_recaptcha_response[ $grecaptcha_response ] = false;
162
-        $response                                            = wp_safe_remote_post(
163
-            InvisibleRecaptcha::URL_GOOGLE_RECAPTCHA_API,
164
-            array(
165
-                'body' => array(
166
-                    'secret'   => $this->config->recaptcha_privatekey,
167
-                    'response' => $grecaptcha_response,
168
-                    'remoteip' => $request->ipAddress(),
169
-                ),
170
-            )
171
-        );
172
-        if ($response instanceof WP_Error) {
173
-            $this->generateError($response->get_error_messages());
174
-            return false;
175
-        }
176
-        $results = json_decode(wp_remote_retrieve_body($response), true);
177
-        if (filter_var($results['success'], FILTER_VALIDATE_BOOLEAN) !== true) {
178
-            $errors   = array_map(
179
-                array($this, 'getErrorCode'),
180
-                $results['error-codes']
181
-            );
182
-            if (isset($results['challenge_ts'])) {
183
-                $errors[] = 'challenge timestamp: ' . $results['challenge_ts'] . '.';
184
-            }
185
-            $this->generateError(implode(' ', $errors), true);
186
-        }
187
-        $previous_recaptcha_response[ $grecaptcha_response ] = true;
188
-        add_action('shutdown', array($this, 'setSessionData'));
189
-        return true;
190
-    }
125
+	/**
126
+	 * @param RequestInterface $request
127
+	 * @return boolean
128
+	 * @throws InvalidArgumentException
129
+	 * @throws InvalidDataTypeException
130
+	 * @throws InvalidInterfaceException
131
+	 * @throws RuntimeException
132
+	 */
133
+	public function verifyToken(RequestInterface $request)
134
+	{
135
+		static $previous_recaptcha_response = array();
136
+		$grecaptcha_response = $request->getRequestParam('g-recaptcha-response');
137
+		// if this token has already been verified, then return previous response
138
+		if (isset($previous_recaptcha_response[ $grecaptcha_response ])) {
139
+			return $previous_recaptcha_response[ $grecaptcha_response ];
140
+		}
141
+		// still here but no g-recaptcha-response ? - verification failed
142
+		if (! $grecaptcha_response) {
143
+			EE_Error::add_error(
144
+				sprintf(
145
+					/* translators: 1: missing parameter */
146
+					esc_html__(
147
+						// @codingStandardsIgnoreStart
148
+						'We\'re sorry but an attempt to verify the form\'s reCAPTCHA has failed. Missing "%1$s". Please try again.',
149
+						// @codingStandardsIgnoreEnd
150
+						'event_espresso'
151
+					),
152
+					'g-recaptcha-response'
153
+				),
154
+				__FILE__,
155
+				__FUNCTION__,
156
+				__LINE__
157
+			);
158
+			return false;
159
+		}
160
+		// will update to true if everything passes
161
+		$previous_recaptcha_response[ $grecaptcha_response ] = false;
162
+		$response                                            = wp_safe_remote_post(
163
+			InvisibleRecaptcha::URL_GOOGLE_RECAPTCHA_API,
164
+			array(
165
+				'body' => array(
166
+					'secret'   => $this->config->recaptcha_privatekey,
167
+					'response' => $grecaptcha_response,
168
+					'remoteip' => $request->ipAddress(),
169
+				),
170
+			)
171
+		);
172
+		if ($response instanceof WP_Error) {
173
+			$this->generateError($response->get_error_messages());
174
+			return false;
175
+		}
176
+		$results = json_decode(wp_remote_retrieve_body($response), true);
177
+		if (filter_var($results['success'], FILTER_VALIDATE_BOOLEAN) !== true) {
178
+			$errors   = array_map(
179
+				array($this, 'getErrorCode'),
180
+				$results['error-codes']
181
+			);
182
+			if (isset($results['challenge_ts'])) {
183
+				$errors[] = 'challenge timestamp: ' . $results['challenge_ts'] . '.';
184
+			}
185
+			$this->generateError(implode(' ', $errors), true);
186
+		}
187
+		$previous_recaptcha_response[ $grecaptcha_response ] = true;
188
+		add_action('shutdown', array($this, 'setSessionData'));
189
+		return true;
190
+	}
191 191
 
192 192
 
193
-    /**
194
-     * @param string $error_response
195
-     * @param bool   $show_errors
196
-     * @return void
197
-     * @throws RuntimeException
198
-     */
199
-    public function generateError($error_response = '', $show_errors = false)
200
-    {
201
-        throw new RuntimeException(
202
-            sprintf(
203
-                esc_html__(
204
-                    'We\'re sorry but an attempt to verify the form\'s reCAPTCHA has failed. %1$s %2$s Please try again.',
205
-                    'event_espresso'
206
-                ),
207
-                '<br />',
208
-                $show_errors || current_user_can('manage_options') ? $error_response : ''
209
-            )
210
-        );
211
-    }
193
+	/**
194
+	 * @param string $error_response
195
+	 * @param bool   $show_errors
196
+	 * @return void
197
+	 * @throws RuntimeException
198
+	 */
199
+	public function generateError($error_response = '', $show_errors = false)
200
+	{
201
+		throw new RuntimeException(
202
+			sprintf(
203
+				esc_html__(
204
+					'We\'re sorry but an attempt to verify the form\'s reCAPTCHA has failed. %1$s %2$s Please try again.',
205
+					'event_espresso'
206
+				),
207
+				'<br />',
208
+				$show_errors || current_user_can('manage_options') ? $error_response : ''
209
+			)
210
+		);
211
+	}
212 212
 
213 213
 
214
-    /**
215
-     * @param string $error_code
216
-     * @return string
217
-     */
218
-    public function getErrorCode(&$error_code)
219
-    {
220
-        $error_codes = array(
221
-            'missing-input-secret'   => 'The secret parameter is missing.',
222
-            'invalid-input-secret'   => 'The secret parameter is invalid or malformed.',
223
-            'missing-input-response' => 'The response parameter is missing.',
224
-            'invalid-input-response' => 'The response parameter is invalid or malformed.',
225
-            'bad-request'            => 'The request is invalid or malformed.',
226
-            'timeout-or-duplicate'   => 'The request took too long to be sent or was a duplicate of a previous request.',
227
-        );
228
-        return isset($error_codes[ $error_code ]) ? $error_codes[ $error_code ] : '';
229
-    }
214
+	/**
215
+	 * @param string $error_code
216
+	 * @return string
217
+	 */
218
+	public function getErrorCode(&$error_code)
219
+	{
220
+		$error_codes = array(
221
+			'missing-input-secret'   => 'The secret parameter is missing.',
222
+			'invalid-input-secret'   => 'The secret parameter is invalid or malformed.',
223
+			'missing-input-response' => 'The response parameter is missing.',
224
+			'invalid-input-response' => 'The response parameter is invalid or malformed.',
225
+			'bad-request'            => 'The request is invalid or malformed.',
226
+			'timeout-or-duplicate'   => 'The request took too long to be sent or was a duplicate of a previous request.',
227
+		);
228
+		return isset($error_codes[ $error_code ]) ? $error_codes[ $error_code ] : '';
229
+	}
230 230
 
231 231
 
232
-    /**
233
-     * @return array
234
-     * @throws InvalidInterfaceException
235
-     * @throws InvalidDataTypeException
236
-     * @throws InvalidArgumentException
237
-     */
238
-    public function getLocalizedVars()
239
-    {
240
-        return (array) apply_filters(
241
-            'FHEE__EventEspresso_caffeinated_modules_recaptcha_invisible_InvisibleRecaptcha__getLocalizedVars__localized_vars',
242
-            array(
243
-                'siteKey'          => $this->config->recaptcha_publickey,
244
-                'recaptcha_passed' => $this->recaptchaPassed(),
245
-                'wp_debug'         => WP_DEBUG,
246
-                'disable_submit'   => defined('EE_EVENT_QUEUE_BASE_URL'),
247
-                'failed_message'   => esc_html__(
248
-                    'We\'re sorry but an attempt to verify the form\'s reCAPTCHA has failed. Please try again.',
249
-                    'event_espresso'
250
-                )
251
-            )
252
-        );
253
-    }
232
+	/**
233
+	 * @return array
234
+	 * @throws InvalidInterfaceException
235
+	 * @throws InvalidDataTypeException
236
+	 * @throws InvalidArgumentException
237
+	 */
238
+	public function getLocalizedVars()
239
+	{
240
+		return (array) apply_filters(
241
+			'FHEE__EventEspresso_caffeinated_modules_recaptcha_invisible_InvisibleRecaptcha__getLocalizedVars__localized_vars',
242
+			array(
243
+				'siteKey'          => $this->config->recaptcha_publickey,
244
+				'recaptcha_passed' => $this->recaptchaPassed(),
245
+				'wp_debug'         => WP_DEBUG,
246
+				'disable_submit'   => defined('EE_EVENT_QUEUE_BASE_URL'),
247
+				'failed_message'   => esc_html__(
248
+					'We\'re sorry but an attempt to verify the form\'s reCAPTCHA has failed. Please try again.',
249
+					'event_espresso'
250
+				)
251
+			)
252
+		);
253
+	}
254 254
 
255 255
 
256
-    /**
257
-     * @return boolean
258
-     * @throws InvalidInterfaceException
259
-     * @throws InvalidDataTypeException
260
-     * @throws InvalidArgumentException
261
-     */
262
-    public function recaptchaPassed()
263
-    {
264
-        if ($this->recaptcha_passed !== null) {
265
-            return $this->recaptcha_passed;
266
-        }
267
-        // logged in means you have already passed a turing test of sorts
268
-        if ($this->useInvisibleRecaptcha() === false || is_user_logged_in()) {
269
-            $this->recaptcha_passed = true;
270
-            return $this->recaptcha_passed;
271
-        }
272
-        // was test already passed?
273
-        $this->recaptcha_passed = filter_var(
274
-            $this->session->get_session_data(
275
-                InvisibleRecaptcha::SESSION_DATA_KEY_RECAPTCHA_PASSED
276
-            ),
277
-            FILTER_VALIDATE_BOOLEAN
278
-        );
279
-        return $this->recaptcha_passed;
280
-    }
256
+	/**
257
+	 * @return boolean
258
+	 * @throws InvalidInterfaceException
259
+	 * @throws InvalidDataTypeException
260
+	 * @throws InvalidArgumentException
261
+	 */
262
+	public function recaptchaPassed()
263
+	{
264
+		if ($this->recaptcha_passed !== null) {
265
+			return $this->recaptcha_passed;
266
+		}
267
+		// logged in means you have already passed a turing test of sorts
268
+		if ($this->useInvisibleRecaptcha() === false || is_user_logged_in()) {
269
+			$this->recaptcha_passed = true;
270
+			return $this->recaptcha_passed;
271
+		}
272
+		// was test already passed?
273
+		$this->recaptcha_passed = filter_var(
274
+			$this->session->get_session_data(
275
+				InvisibleRecaptcha::SESSION_DATA_KEY_RECAPTCHA_PASSED
276
+			),
277
+			FILTER_VALIDATE_BOOLEAN
278
+		);
279
+		return $this->recaptcha_passed;
280
+	}
281 281
 
282 282
 
283
-    /**
284
-     * @throws InvalidArgumentException
285
-     * @throws InvalidDataTypeException
286
-     * @throws InvalidInterfaceException
287
-     */
288
-    public function setSessionData()
289
-    {
290
-        $this->session->set_session_data(
291
-            array(InvisibleRecaptcha::SESSION_DATA_KEY_RECAPTCHA_PASSED => true)
292
-        );
293
-    }
283
+	/**
284
+	 * @throws InvalidArgumentException
285
+	 * @throws InvalidDataTypeException
286
+	 * @throws InvalidInterfaceException
287
+	 */
288
+	public function setSessionData()
289
+	{
290
+		$this->session->set_session_data(
291
+			array(InvisibleRecaptcha::SESSION_DATA_KEY_RECAPTCHA_PASSED => true)
292
+		);
293
+	}
294 294
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -135,11 +135,11 @@  discard block
 block discarded – undo
135 135
         static $previous_recaptcha_response = array();
136 136
         $grecaptcha_response = $request->getRequestParam('g-recaptcha-response');
137 137
         // if this token has already been verified, then return previous response
138
-        if (isset($previous_recaptcha_response[ $grecaptcha_response ])) {
139
-            return $previous_recaptcha_response[ $grecaptcha_response ];
138
+        if (isset($previous_recaptcha_response[$grecaptcha_response])) {
139
+            return $previous_recaptcha_response[$grecaptcha_response];
140 140
         }
141 141
         // still here but no g-recaptcha-response ? - verification failed
142
-        if (! $grecaptcha_response) {
142
+        if ( ! $grecaptcha_response) {
143 143
             EE_Error::add_error(
144 144
                 sprintf(
145 145
                     /* translators: 1: missing parameter */
@@ -158,7 +158,7 @@  discard block
 block discarded – undo
158 158
             return false;
159 159
         }
160 160
         // will update to true if everything passes
161
-        $previous_recaptcha_response[ $grecaptcha_response ] = false;
161
+        $previous_recaptcha_response[$grecaptcha_response] = false;
162 162
         $response                                            = wp_safe_remote_post(
163 163
             InvisibleRecaptcha::URL_GOOGLE_RECAPTCHA_API,
164 164
             array(
@@ -175,16 +175,16 @@  discard block
 block discarded – undo
175 175
         }
176 176
         $results = json_decode(wp_remote_retrieve_body($response), true);
177 177
         if (filter_var($results['success'], FILTER_VALIDATE_BOOLEAN) !== true) {
178
-            $errors   = array_map(
178
+            $errors = array_map(
179 179
                 array($this, 'getErrorCode'),
180 180
                 $results['error-codes']
181 181
             );
182 182
             if (isset($results['challenge_ts'])) {
183
-                $errors[] = 'challenge timestamp: ' . $results['challenge_ts'] . '.';
183
+                $errors[] = 'challenge timestamp: '.$results['challenge_ts'].'.';
184 184
             }
185 185
             $this->generateError(implode(' ', $errors), true);
186 186
         }
187
-        $previous_recaptcha_response[ $grecaptcha_response ] = true;
187
+        $previous_recaptcha_response[$grecaptcha_response] = true;
188 188
         add_action('shutdown', array($this, 'setSessionData'));
189 189
         return true;
190 190
     }
@@ -225,7 +225,7 @@  discard block
 block discarded – undo
225 225
             'bad-request'            => 'The request is invalid or malformed.',
226 226
             'timeout-or-duplicate'   => 'The request took too long to be sent or was a duplicate of a previous request.',
227 227
         );
228
-        return isset($error_codes[ $error_code ]) ? $error_codes[ $error_code ] : '';
228
+        return isset($error_codes[$error_code]) ? $error_codes[$error_code] : '';
229 229
     }
230 230
 
231 231
 
Please login to merge, or discard this patch.
core/db_classes/EE_Ticket.class.php 2 patches
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -129,7 +129,7 @@  discard block
 block discarded – undo
129 129
     public function ticket_status($display = false, $remaining = null)
130 130
     {
131 131
         $remaining = is_bool($remaining) ? $remaining : $this->is_remaining();
132
-        if (! $remaining) {
132
+        if ( ! $remaining) {
133 133
             return $display ? EEH_Template::pretty_status(EE_Ticket::sold_out, false, 'sentence') : EE_Ticket::sold_out;
134 134
         }
135 135
         if ($this->get('TKT_deleted')) {
@@ -247,7 +247,7 @@  discard block
 block discarded – undo
247 247
             : '';
248 248
         $last_date = $this->last_datetime() instanceof EE_Datetime ? $this->last_datetime()->get_i18n_datetime('DTT_EVT_end', $dt_frmt) : '';
249 249
 
250
-        return $first_date && $last_date ? $first_date . $conjunction . $last_date : '';
250
+        return $first_date && $last_date ? $first_date.$conjunction.$last_date : '';
251 251
     }
252 252
 
253 253
 
@@ -274,7 +274,7 @@  discard block
 block discarded – undo
274 274
      */
275 275
     public function datetimes($query_params = array())
276 276
     {
277
-        if (! isset($query_params['order_by'])) {
277
+        if ( ! isset($query_params['order_by'])) {
278 278
             $query_params['order_by']['DTT_order'] = 'ASC';
279 279
         }
280 280
         return $this->get_many_related('Datetime', $query_params);
@@ -319,7 +319,7 @@  discard block
 block discarded – undo
319 319
                 if (empty($tickets_sold['datetime'])) {
320 320
                     return $total;
321 321
                 }
322
-                if (! empty($dtt_id) && ! isset($tickets_sold['datetime'][ $dtt_id ])) {
322
+                if ( ! empty($dtt_id) && ! isset($tickets_sold['datetime'][$dtt_id])) {
323 323
                     EE_Error::add_error(
324 324
                         __(
325 325
                             'You\'ve requested the amount of tickets sold for a given ticket and datetime, however there are no records for the datetime id you included.  Are you SURE that is a datetime related to this ticket?',
@@ -331,7 +331,7 @@  discard block
 block discarded – undo
331 331
                     );
332 332
                     return $total;
333 333
                 }
334
-                return empty($dtt_id) ? $tickets_sold['datetime'] : $tickets_sold['datetime'][ $dtt_id ];
334
+                return empty($dtt_id) ? $tickets_sold['datetime'] : $tickets_sold['datetime'][$dtt_id];
335 335
                 break;
336 336
             default:
337 337
                 return $total;
@@ -349,9 +349,9 @@  discard block
 block discarded – undo
349 349
     {
350 350
         $datetimes = $this->get_many_related('Datetime');
351 351
         $tickets_sold = array();
352
-        if (! empty($datetimes)) {
352
+        if ( ! empty($datetimes)) {
353 353
             foreach ($datetimes as $datetime) {
354
-                $tickets_sold['datetime'][ $datetime->ID() ] = $datetime->get('DTT_sold');
354
+                $tickets_sold['datetime'][$datetime->ID()] = $datetime->get('DTT_sold');
355 355
             }
356 356
         }
357 357
         // Tickets sold
@@ -924,7 +924,7 @@  discard block
 block discarded – undo
924 924
                 'TKT_qty',
925 925
                 $qty
926 926
             );
927
-            if (! $success) {
927
+            if ( ! $success) {
928 928
                 // The datetimes were successfully bumped, but not the
929 929
                 // ticket. So we need to manually rollback the datetimes.
930 930
                 $this->decreaseReservedForDatetimes($qty);
@@ -1373,7 +1373,7 @@  discard block
 block discarded – undo
1373 1373
         foreach ($this->datetimes() as $datetime) {
1374 1374
             $times[] = $datetime->start_date_and_time();
1375 1375
         }
1376
-        return $this->name() . ' @ ' . implode(', ', $times) . ' for ' . $this->pretty_price();
1376
+        return $this->name().' @ '.implode(', ', $times).' for '.$this->pretty_price();
1377 1377
     }
1378 1378
 
1379 1379
 
@@ -1472,7 +1472,7 @@  discard block
 block discarded – undo
1472 1472
     {
1473 1473
         // get one datetime to use for getting the event
1474 1474
         $datetime = $this->first_datetime();
1475
-        if (! $datetime instanceof \EE_Datetime) {
1475
+        if ( ! $datetime instanceof \EE_Datetime) {
1476 1476
             throw new UnexpectedEntityException(
1477 1477
                 $datetime,
1478 1478
                 'EE_Datetime',
@@ -1483,7 +1483,7 @@  discard block
 block discarded – undo
1483 1483
             );
1484 1484
         }
1485 1485
         $event = $datetime->event();
1486
-        if (! $event instanceof \EE_Event) {
1486
+        if ( ! $event instanceof \EE_Event) {
1487 1487
             throw new UnexpectedEntityException(
1488 1488
                 $event,
1489 1489
                 'EE_Event',
Please login to merge, or discard this patch.
Indentation   +1734 added lines, -1734 removed lines patch added patch discarded remove patch
@@ -14,1742 +14,1742 @@
 block discarded – undo
14 14
 class EE_Ticket extends EE_Soft_Delete_Base_Class implements EEI_Line_Item_Object, EEI_Event_Relation, EEI_Has_Icon
15 15
 {
16 16
 
17
-    /**
18
-     * TicKet Sold out:
19
-     * constant used by ticket_status() to indicate that a ticket is sold out
20
-     * and no longer available for purchase
21
-     */
22
-    const sold_out = 'TKS';
23
-
24
-    /**
25
-     * TicKet Expired:
26
-     * constant used by ticket_status() to indicate that a ticket is expired
27
-     * and no longer available for purchase
28
-     */
29
-    const expired = 'TKE';
30
-
31
-    /**
32
-     * TicKet Archived:
33
-     * constant used by ticket_status() to indicate that a ticket is archived
34
-     * and no longer available for purchase
35
-     */
36
-    const archived = 'TKA';
37
-
38
-    /**
39
-     * TicKet Pending:
40
-     * constant used by ticket_status() to indicate that a ticket is pending
41
-     * and is NOT YET available for purchase
42
-     */
43
-    const pending = 'TKP';
44
-
45
-    /**
46
-     * TicKet On sale:
47
-     * constant used by ticket_status() to indicate that a ticket is On Sale
48
-     * and IS available for purchase
49
-     */
50
-    const onsale = 'TKO';
51
-
52
-    /**
53
-     * extra meta key for tracking ticket reservations
54
-     *
55
-     * @type string
56
-     */
57
-    const META_KEY_TICKET_RESERVATIONS = 'ticket_reservations';
58
-
59
-    /**
60
-     * cached result from method of the same name
61
-     *
62
-     * @var float $_ticket_total_with_taxes
63
-     */
64
-    private $_ticket_total_with_taxes;
65
-
66
-
67
-    /**
68
-     * @param array  $props_n_values          incoming values
69
-     * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
70
-     *                                        used.)
71
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
72
-     *                                        date_format and the second value is the time format
73
-     * @return EE_Ticket
74
-     * @throws EE_Error
75
-     */
76
-    public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
77
-    {
78
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
79
-        return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
80
-    }
81
-
82
-
83
-    /**
84
-     * @param array  $props_n_values  incoming values from the database
85
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
86
-     *                                the website will be used.
87
-     * @return EE_Ticket
88
-     * @throws EE_Error
89
-     */
90
-    public static function new_instance_from_db($props_n_values = array(), $timezone = null)
91
-    {
92
-        return new self($props_n_values, true, $timezone);
93
-    }
94
-
95
-
96
-    /**
97
-     * @return bool
98
-     * @throws EE_Error
99
-     */
100
-    public function parent()
101
-    {
102
-        return $this->get('TKT_parent');
103
-    }
104
-
105
-
106
-    /**
107
-     * return if a ticket has quantities available for purchase
108
-     *
109
-     * @param  int $DTT_ID the primary key for a particular datetime
110
-     * @return boolean
111
-     * @throws EE_Error
112
-     */
113
-    public function available($DTT_ID = 0)
114
-    {
115
-        // are we checking availability for a particular datetime ?
116
-        if ($DTT_ID) {
117
-            // get that datetime object
118
-            $datetime = $this->get_first_related('Datetime', array(array('DTT_ID' => $DTT_ID)));
119
-            // if  ticket sales for this datetime have exceeded the reg limit...
120
-            if ($datetime instanceof EE_Datetime && $datetime->sold_out()) {
121
-                return false;
122
-            }
123
-        }
124
-        // datetime is still open for registration, but is this ticket sold out ?
125
-        return $this->qty() < 1 || $this->qty() > $this->sold() ? true : false;
126
-    }
127
-
128
-
129
-    /**
130
-     * Using the start date and end date this method calculates whether the ticket is On Sale, Pending, or Expired
131
-     *
132
-     * @param bool        $display   true = we'll return a localized string, otherwise we just return the value of the
133
-     *                               relevant status const
134
-     * @param bool | null $remaining if it is already known that tickets are available, then simply pass a bool to save
135
-     *               further processing
136
-     * @return mixed status int if the display string isn't requested
137
-     * @throws EE_Error
138
-     */
139
-    public function ticket_status($display = false, $remaining = null)
140
-    {
141
-        $remaining = is_bool($remaining) ? $remaining : $this->is_remaining();
142
-        if (! $remaining) {
143
-            return $display ? EEH_Template::pretty_status(EE_Ticket::sold_out, false, 'sentence') : EE_Ticket::sold_out;
144
-        }
145
-        if ($this->get('TKT_deleted')) {
146
-            return $display ? EEH_Template::pretty_status(EE_Ticket::archived, false, 'sentence') : EE_Ticket::archived;
147
-        }
148
-        if ($this->is_expired()) {
149
-            return $display ? EEH_Template::pretty_status(EE_Ticket::expired, false, 'sentence') : EE_Ticket::expired;
150
-        }
151
-        if ($this->is_pending()) {
152
-            return $display ? EEH_Template::pretty_status(EE_Ticket::pending, false, 'sentence') : EE_Ticket::pending;
153
-        }
154
-        if ($this->is_on_sale()) {
155
-            return $display ? EEH_Template::pretty_status(EE_Ticket::onsale, false, 'sentence') : EE_Ticket::onsale;
156
-        }
157
-        return '';
158
-    }
159
-
160
-
161
-    /**
162
-     * The purpose of this method is to simply return a boolean for whether there are any tickets remaining for sale
163
-     * considering ALL the factors used for figuring that out.
164
-     *
165
-     * @access public
166
-     * @param  int $DTT_ID if an int above 0 is included here then we get a specific dtt.
167
-     * @return boolean         true = tickets remaining, false not.
168
-     * @throws EE_Error
169
-     */
170
-    public function is_remaining($DTT_ID = 0)
171
-    {
172
-        $num_remaining = $this->remaining($DTT_ID);
173
-        if ($num_remaining === 0) {
174
-            return false;
175
-        }
176
-        if ($num_remaining > 0 && $num_remaining < $this->min()) {
177
-            return false;
178
-        }
179
-        return true;
180
-    }
181
-
182
-
183
-    /**
184
-     * return the total number of tickets available for purchase
185
-     *
186
-     * @param  int $DTT_ID the primary key for a particular datetime.
187
-     *                     set to 0 for all related datetimes
188
-     * @return int
189
-     * @throws EE_Error
190
-     */
191
-    public function remaining($DTT_ID = 0)
192
-    {
193
-        return $this->real_quantity_on_ticket('saleable', $DTT_ID);
194
-    }
195
-
196
-
197
-    /**
198
-     * Gets min
199
-     *
200
-     * @return int
201
-     * @throws EE_Error
202
-     */
203
-    public function min()
204
-    {
205
-        return $this->get('TKT_min');
206
-    }
207
-
208
-
209
-    /**
210
-     * return if a ticket is no longer available cause its available dates have expired.
211
-     *
212
-     * @return boolean
213
-     * @throws EE_Error
214
-     */
215
-    public function is_expired()
216
-    {
217
-        return ($this->get_raw('TKT_end_date') < time());
218
-    }
219
-
220
-
221
-    /**
222
-     * Return if a ticket is yet to go on sale or not
223
-     *
224
-     * @return boolean
225
-     * @throws EE_Error
226
-     */
227
-    public function is_pending()
228
-    {
229
-        return ($this->get_raw('TKT_start_date') > time());
230
-    }
231
-
232
-
233
-    /**
234
-     * Return if a ticket is on sale or not
235
-     *
236
-     * @return boolean
237
-     * @throws EE_Error
238
-     */
239
-    public function is_on_sale()
240
-    {
241
-        return ($this->get_raw('TKT_start_date') < time() && $this->get_raw('TKT_end_date') > time());
242
-    }
243
-
244
-
245
-    /**
246
-     * This returns the chronologically last datetime that this ticket is associated with
247
-     *
248
-     * @param string $dt_frmt
249
-     * @param string $conjunction - conjunction junction what's your function ? this string joins the start date with
250
-     *                            the end date ie: Jan 01 "to" Dec 31
251
-     * @return string
252
-     * @throws EE_Error
253
-     */
254
-    public function date_range($dt_frmt = '', $conjunction = ' - ')
255
-    {
256
-        $dt_frmt = ! empty($dt_frmt) ? $dt_frmt : $this->_dt_frmt;
257
-        $first_date = $this->first_datetime() instanceof EE_Datetime ? $this->first_datetime()->get_i18n_datetime('DTT_EVT_start', $dt_frmt)
258
-            : '';
259
-        $last_date = $this->last_datetime() instanceof EE_Datetime ? $this->last_datetime()->get_i18n_datetime('DTT_EVT_end', $dt_frmt) : '';
260
-
261
-        return $first_date && $last_date ? $first_date . $conjunction . $last_date : '';
262
-    }
263
-
264
-
265
-    /**
266
-     * This returns the chronologically first datetime that this ticket is associated with
267
-     *
268
-     * @return EE_Datetime
269
-     * @throws EE_Error
270
-     */
271
-    public function first_datetime()
272
-    {
273
-        $datetimes = $this->datetimes(array('limit' => 1));
274
-        return reset($datetimes);
275
-    }
276
-
277
-
278
-    /**
279
-     * Gets all the datetimes this ticket can be used for attending.
280
-     * Unless otherwise specified, orders datetimes by start date.
281
-     *
282
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
283
-     * @return EE_Datetime[]|EE_Base_Class[]
284
-     * @throws EE_Error
285
-     */
286
-    public function datetimes($query_params = array())
287
-    {
288
-        if (! isset($query_params['order_by'])) {
289
-            $query_params['order_by']['DTT_order'] = 'ASC';
290
-        }
291
-        return $this->get_many_related('Datetime', $query_params);
292
-    }
293
-
294
-
295
-    /**
296
-     * This returns the chronologically last datetime that this ticket is associated with
297
-     *
298
-     * @return EE_Datetime
299
-     * @throws EE_Error
300
-     */
301
-    public function last_datetime()
302
-    {
303
-        $datetimes = $this->datetimes(array('limit' => 1, 'order_by' => array('DTT_EVT_start' => 'DESC')));
304
-        return end($datetimes);
305
-    }
306
-
307
-
308
-    /**
309
-     * This returns the total tickets sold depending on the given parameters.
310
-     *
311
-     * @param  string $what   Can be one of two options: 'ticket', 'datetime'.
312
-     *                        'ticket' = total ticket sales for all datetimes this ticket is related to
313
-     *                        'datetime' = total ticket sales for a specified datetime (required $dtt_id)
314
-     *                        'datetime' = total ticket sales in the datetime_ticket table.
315
-     *                        If $dtt_id is not given then we return an array of sales indexed by datetime.
316
-     *                        If $dtt_id IS given then we return the tickets sold for that given datetime.
317
-     * @param  int    $dtt_id [optional] include the dtt_id with $what = 'datetime'.
318
-     * @return mixed (array|int)          how many tickets have sold
319
-     * @throws EE_Error
320
-     */
321
-    public function tickets_sold($what = 'ticket', $dtt_id = null)
322
-    {
323
-        $total = 0;
324
-        $tickets_sold = $this->_all_tickets_sold();
325
-        switch ($what) {
326
-            case 'ticket':
327
-                return $tickets_sold['ticket'];
328
-                break;
329
-            case 'datetime':
330
-                if (empty($tickets_sold['datetime'])) {
331
-                    return $total;
332
-                }
333
-                if (! empty($dtt_id) && ! isset($tickets_sold['datetime'][ $dtt_id ])) {
334
-                    EE_Error::add_error(
335
-                        __(
336
-                            'You\'ve requested the amount of tickets sold for a given ticket and datetime, however there are no records for the datetime id you included.  Are you SURE that is a datetime related to this ticket?',
337
-                            'event_espresso'
338
-                        ),
339
-                        __FILE__,
340
-                        __FUNCTION__,
341
-                        __LINE__
342
-                    );
343
-                    return $total;
344
-                }
345
-                return empty($dtt_id) ? $tickets_sold['datetime'] : $tickets_sold['datetime'][ $dtt_id ];
346
-                break;
347
-            default:
348
-                return $total;
349
-        }
350
-    }
351
-
352
-
353
-    /**
354
-     * This returns an array indexed by datetime_id for tickets sold with this ticket.
355
-     *
356
-     * @return EE_Ticket[]
357
-     * @throws EE_Error
358
-     */
359
-    protected function _all_tickets_sold()
360
-    {
361
-        $datetimes = $this->get_many_related('Datetime');
362
-        $tickets_sold = array();
363
-        if (! empty($datetimes)) {
364
-            foreach ($datetimes as $datetime) {
365
-                $tickets_sold['datetime'][ $datetime->ID() ] = $datetime->get('DTT_sold');
366
-            }
367
-        }
368
-        // Tickets sold
369
-        $tickets_sold['ticket'] = $this->sold();
370
-        return $tickets_sold;
371
-    }
372
-
373
-
374
-    /**
375
-     * This returns the base price object for the ticket.
376
-     *
377
-     * @param  bool $return_array whether to return as an array indexed by price id or just the object.
378
-     * @return EE_Price|EE_Base_Class|EE_Price[]|EE_Base_Class[]
379
-     * @throws EE_Error
380
-     */
381
-    public function base_price($return_array = false)
382
-    {
383
-        $_where = array('Price_Type.PBT_ID' => EEM_Price_Type::base_type_base_price);
384
-        return $return_array
385
-            ? $this->get_many_related('Price', array($_where))
386
-            : $this->get_first_related('Price', array($_where));
387
-    }
388
-
389
-
390
-    /**
391
-     * This returns ONLY the price modifiers for the ticket (i.e. no taxes or base price)
392
-     *
393
-     * @access public
394
-     * @return EE_Price[]
395
-     * @throws EE_Error
396
-     */
397
-    public function price_modifiers()
398
-    {
399
-        $query_params = array(
400
-            0 => array(
401
-                'Price_Type.PBT_ID' => array(
402
-                    'NOT IN',
403
-                    array(EEM_Price_Type::base_type_base_price, EEM_Price_Type::base_type_tax),
404
-                ),
405
-            ),
406
-        );
407
-        return $this->prices($query_params);
408
-    }
409
-
410
-
411
-    /**
412
-     * Gets all the prices that combine to form the final price of this ticket
413
-     *
414
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
415
-     * @return EE_Price[]|EE_Base_Class[]
416
-     * @throws EE_Error
417
-     */
418
-    public function prices($query_params = array())
419
-    {
420
-        return $this->get_many_related('Price', $query_params);
421
-    }
422
-
423
-
424
-    /**
425
-     * Gets all the ticket applicabilities (ie, relations between datetimes and tickets)
426
-     *
427
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
428
-     * @return EE_Datetime_Ticket|EE_Base_Class[]
429
-     * @throws EE_Error
430
-     */
431
-    public function datetime_tickets($query_params = array())
432
-    {
433
-        return $this->get_many_related('Datetime_Ticket', $query_params);
434
-    }
435
-
436
-
437
-    /**
438
-     * Gets all the datetimes from the db ordered by DTT_order
439
-     *
440
-     * @param boolean $show_expired
441
-     * @param boolean $show_deleted
442
-     * @return EE_Datetime[]
443
-     * @throws EE_Error
444
-     */
445
-    public function datetimes_ordered($show_expired = true, $show_deleted = false)
446
-    {
447
-        return EEM_Datetime::instance($this->_timezone)->get_datetimes_for_ticket_ordered_by_DTT_order(
448
-            $this->ID(),
449
-            $show_expired,
450
-            $show_deleted
451
-        );
452
-    }
453
-
454
-
455
-    /**
456
-     * Gets ID
457
-     *
458
-     * @return string
459
-     * @throws EE_Error
460
-     */
461
-    public function ID()
462
-    {
463
-        return $this->get('TKT_ID');
464
-    }
465
-
466
-
467
-    /**
468
-     * get the author of the ticket.
469
-     *
470
-     * @since 4.5.0
471
-     * @return int
472
-     * @throws EE_Error
473
-     */
474
-    public function wp_user()
475
-    {
476
-        return $this->get('TKT_wp_user');
477
-    }
478
-
479
-
480
-    /**
481
-     * Gets the template for the ticket
482
-     *
483
-     * @return EE_Ticket_Template|EE_Base_Class
484
-     * @throws EE_Error
485
-     */
486
-    public function template()
487
-    {
488
-        return $this->get_first_related('Ticket_Template');
489
-    }
490
-
491
-
492
-    /**
493
-     * Simply returns an array of EE_Price objects that are taxes.
494
-     *
495
-     * @return EE_Price[]
496
-     * @throws EE_Error
497
-     */
498
-    public function get_ticket_taxes_for_admin()
499
-    {
500
-        return EE_Taxes::get_taxes_for_admin();
501
-    }
502
-
503
-
504
-    /**
505
-     * @return float
506
-     * @throws EE_Error
507
-     */
508
-    public function ticket_price()
509
-    {
510
-        return $this->get('TKT_price');
511
-    }
512
-
513
-
514
-    /**
515
-     * @return mixed
516
-     * @throws EE_Error
517
-     */
518
-    public function pretty_price()
519
-    {
520
-        return $this->get_pretty('TKT_price');
521
-    }
522
-
523
-
524
-    /**
525
-     * @return bool
526
-     * @throws EE_Error
527
-     */
528
-    public function is_free()
529
-    {
530
-        return $this->get_ticket_total_with_taxes() === (float) 0;
531
-    }
532
-
533
-
534
-    /**
535
-     * get_ticket_total_with_taxes
536
-     *
537
-     * @param bool $no_cache
538
-     * @return float
539
-     * @throws EE_Error
540
-     */
541
-    public function get_ticket_total_with_taxes($no_cache = false)
542
-    {
543
-        if ($this->_ticket_total_with_taxes === null || $no_cache) {
544
-            $this->_ticket_total_with_taxes = $this->get_ticket_subtotal() + $this->get_ticket_taxes_total_for_admin();
545
-        }
546
-        return (float) $this->_ticket_total_with_taxes;
547
-    }
548
-
549
-
550
-    public function ensure_TKT_Price_correct()
551
-    {
552
-        $this->set('TKT_price', EE_Taxes::get_subtotal_for_admin($this));
553
-        $this->save();
554
-    }
555
-
556
-
557
-    /**
558
-     * @return float
559
-     * @throws EE_Error
560
-     */
561
-    public function get_ticket_subtotal()
562
-    {
563
-        return EE_Taxes::get_subtotal_for_admin($this);
564
-    }
565
-
566
-
567
-    /**
568
-     * Returns the total taxes applied to this ticket
569
-     *
570
-     * @return float
571
-     * @throws EE_Error
572
-     */
573
-    public function get_ticket_taxes_total_for_admin()
574
-    {
575
-        return EE_Taxes::get_total_taxes_for_admin($this);
576
-    }
577
-
578
-
579
-    /**
580
-     * Sets name
581
-     *
582
-     * @param string $name
583
-     * @throws EE_Error
584
-     */
585
-    public function set_name($name)
586
-    {
587
-        $this->set('TKT_name', $name);
588
-    }
589
-
590
-
591
-    /**
592
-     * Gets description
593
-     *
594
-     * @return string
595
-     * @throws EE_Error
596
-     */
597
-    public function description()
598
-    {
599
-        return $this->get('TKT_description');
600
-    }
601
-
602
-
603
-    /**
604
-     * Sets description
605
-     *
606
-     * @param string $description
607
-     * @throws EE_Error
608
-     */
609
-    public function set_description($description)
610
-    {
611
-        $this->set('TKT_description', $description);
612
-    }
613
-
614
-
615
-    /**
616
-     * Gets start_date
617
-     *
618
-     * @param string $dt_frmt
619
-     * @param string $tm_frmt
620
-     * @return string
621
-     * @throws EE_Error
622
-     */
623
-    public function start_date($dt_frmt = '', $tm_frmt = '')
624
-    {
625
-        return $this->_get_datetime('TKT_start_date', $dt_frmt, $tm_frmt);
626
-    }
627
-
628
-
629
-    /**
630
-     * Sets start_date
631
-     *
632
-     * @param string $start_date
633
-     * @return void
634
-     * @throws EE_Error
635
-     */
636
-    public function set_start_date($start_date)
637
-    {
638
-        $this->_set_date_time('B', $start_date, 'TKT_start_date');
639
-    }
640
-
641
-
642
-    /**
643
-     * Gets end_date
644
-     *
645
-     * @param string $dt_frmt
646
-     * @param string $tm_frmt
647
-     * @return string
648
-     * @throws EE_Error
649
-     */
650
-    public function end_date($dt_frmt = '', $tm_frmt = '')
651
-    {
652
-        return $this->_get_datetime('TKT_end_date', $dt_frmt, $tm_frmt);
653
-    }
654
-
655
-
656
-    /**
657
-     * Sets end_date
658
-     *
659
-     * @param string $end_date
660
-     * @return void
661
-     * @throws EE_Error
662
-     */
663
-    public function set_end_date($end_date)
664
-    {
665
-        $this->_set_date_time('B', $end_date, 'TKT_end_date');
666
-    }
667
-
668
-
669
-    /**
670
-     * Sets sell until time
671
-     *
672
-     * @since 4.5.0
673
-     * @param string $time a string representation of the sell until time (ex 9am or 7:30pm)
674
-     * @throws EE_Error
675
-     */
676
-    public function set_end_time($time)
677
-    {
678
-        $this->_set_time_for($time, 'TKT_end_date');
679
-    }
680
-
681
-
682
-    /**
683
-     * Sets min
684
-     *
685
-     * @param int $min
686
-     * @return void
687
-     * @throws EE_Error
688
-     */
689
-    public function set_min($min)
690
-    {
691
-        $this->set('TKT_min', $min);
692
-    }
693
-
694
-
695
-    /**
696
-     * Gets max
697
-     *
698
-     * @return int
699
-     * @throws EE_Error
700
-     */
701
-    public function max()
702
-    {
703
-        return $this->get('TKT_max');
704
-    }
705
-
706
-
707
-    /**
708
-     * Sets max
709
-     *
710
-     * @param int $max
711
-     * @return void
712
-     * @throws EE_Error
713
-     */
714
-    public function set_max($max)
715
-    {
716
-        $this->set('TKT_max', $max);
717
-    }
718
-
719
-
720
-    /**
721
-     * Sets price
722
-     *
723
-     * @param float $price
724
-     * @return void
725
-     * @throws EE_Error
726
-     */
727
-    public function set_price($price)
728
-    {
729
-        $this->set('TKT_price', $price);
730
-    }
731
-
732
-
733
-    /**
734
-     * Gets sold
735
-     *
736
-     * @return int
737
-     * @throws EE_Error
738
-     */
739
-    public function sold()
740
-    {
741
-        return $this->get_raw('TKT_sold');
742
-    }
743
-
744
-
745
-    /**
746
-     * Sets sold
747
-     *
748
-     * @param int $sold
749
-     * @return void
750
-     * @throws EE_Error
751
-     */
752
-    public function set_sold($sold)
753
-    {
754
-        // sold can not go below zero
755
-        $sold = max(0, $sold);
756
-        $this->set('TKT_sold', $sold);
757
-    }
758
-
759
-
760
-    /**
761
-     * Increments sold by amount passed by $qty AND decrements the reserved count on both this ticket and its
762
-     * associated datetimes.
763
-     *
764
-     * @since 4.9.80.p
765
-     * @param int $qty
766
-     * @return boolean
767
-     * @throws EE_Error
768
-     * @throws InvalidArgumentException
769
-     * @throws InvalidDataTypeException
770
-     * @throws InvalidInterfaceException
771
-     * @throws ReflectionException
772
-     */
773
-    public function increaseSold($qty = 1)
774
-    {
775
-        $qty = absint($qty);
776
-        // increment sold and decrement reserved datetime quantities simultaneously
777
-        // don't worry about failures, because they must have already had a spot reserved
778
-        $this->increaseSoldForDatetimes($qty);
779
-        // Increment and decrement ticket quantities simultaneously
780
-        $success = $this->adjustNumericFieldsInDb(
781
-            [
782
-                'TKT_reserved' => $qty * -1,
783
-                'TKT_sold' => $qty
784
-            ]
785
-        );
786
-        do_action(
787
-            'AHEE__EE_Ticket__increase_sold',
788
-            $this,
789
-            $qty,
790
-            $this->sold(),
791
-            $success
792
-        );
793
-        return $success;
794
-    }
795
-
796
-    /**
797
-     * On each datetime related to this ticket, increases its sold count and decreases its reserved count by $qty.
798
-     *
799
-     * @since 4.9.80.p
800
-     * @param int $qty positive or negative. Positive means to increase sold counts (and decrease reserved counts),
801
-     *             Negative means to decreases old counts (and increase reserved counts).
802
-     * @param EE_Datetime[] $datetimes
803
-     * @throws EE_Error
804
-     * @throws InvalidArgumentException
805
-     * @throws InvalidDataTypeException
806
-     * @throws InvalidInterfaceException
807
-     * @throws ReflectionException
808
-     */
809
-    protected function increaseSoldForDatetimes($qty, array $datetimes = [])
810
-    {
811
-        $datetimes = ! empty($datetimes) ? $datetimes : $this->datetimes();
812
-        foreach ($datetimes as $datetime) {
813
-            $datetime->increaseSold($qty);
814
-        }
815
-    }
816
-
817
-
818
-
819
-    /**
820
-     * Decrements (subtracts) sold by amount passed by $qty on both the ticket and its related datetimes directly in the
821
-     * DB and then updates the model objects.
822
-     * Does not affect the reserved counts.
823
-     *
824
-     * @since 4.9.80.p
825
-     * @param int $qty
826
-     * @return boolean
827
-     * @throws EE_Error
828
-     * @throws InvalidArgumentException
829
-     * @throws InvalidDataTypeException
830
-     * @throws InvalidInterfaceException
831
-     * @throws ReflectionException
832
-     */
833
-    public function decreaseSold($qty = 1)
834
-    {
835
-        $qty = absint($qty);
836
-        $this->decreaseSoldForDatetimes($qty);
837
-        $success = $this->adjustNumericFieldsInDb(
838
-            [
839
-                'TKT_sold' => $qty * -1
840
-            ]
841
-        );
842
-        do_action(
843
-            'AHEE__EE_Ticket__decrease_sold',
844
-            $this,
845
-            $qty,
846
-            $this->sold(),
847
-            $success
848
-        );
849
-        return $success;
850
-    }
851
-
852
-
853
-    /**
854
-     * Decreases sold on related datetimes
855
-     *
856
-     * @since 4.9.80.p
857
-     * @param int $qty
858
-     * @param EE_Datetime[] $datetimes
859
-     * @return void
860
-     * @throws EE_Error
861
-     * @throws InvalidArgumentException
862
-     * @throws InvalidDataTypeException
863
-     * @throws InvalidInterfaceException
864
-     * @throws ReflectionException
865
-     */
866
-    protected function decreaseSoldForDatetimes($qty = 1, array $datetimes = [])
867
-    {
868
-        $datetimes = ! empty($datetimes) ? $datetimes : $this->datetimes();
869
-        if (is_array($datetimes)) {
870
-            foreach ($datetimes as $datetime) {
871
-                if ($datetime instanceof EE_Datetime) {
872
-                    $datetime->decreaseSold($qty);
873
-                }
874
-            }
875
-        }
876
-    }
877
-
878
-
879
-    /**
880
-     * Gets qty of reserved tickets
881
-     *
882
-     * @return int
883
-     * @throws EE_Error
884
-     */
885
-    public function reserved()
886
-    {
887
-        return $this->get_raw('TKT_reserved');
888
-    }
889
-
890
-
891
-    /**
892
-     * Sets reserved
893
-     *
894
-     * @param int $reserved
895
-     * @return void
896
-     * @throws EE_Error
897
-     */
898
-    public function set_reserved($reserved)
899
-    {
900
-        // reserved can not go below zero
901
-        $reserved = max(0, (int) $reserved);
902
-        $this->set('TKT_reserved', $reserved);
903
-    }
904
-
905
-
906
-    /**
907
-     * Increments reserved by amount passed by $qty, and persists it immediately to the database.
908
-     *
909
-     * @since 4.9.80.p
910
-     * @param int    $qty
911
-     * @param string $source
912
-     * @return bool whether we successfully reserved the ticket or not.
913
-     * @throws EE_Error
914
-     * @throws InvalidArgumentException
915
-     * @throws ReflectionException
916
-     * @throws InvalidDataTypeException
917
-     * @throws InvalidInterfaceException
918
-     */
919
-    public function increaseReserved($qty = 1, $source = 'unknown')
920
-    {
921
-        $qty = absint($qty);
922
-        do_action(
923
-            'AHEE__EE_Ticket__increase_reserved__begin',
924
-            $this,
925
-            $qty,
926
-            $source
927
-        );
928
-        $this->add_extra_meta(EE_Ticket::META_KEY_TICKET_RESERVATIONS, "{$qty} from {$source}");
929
-        $success = false;
930
-        $datetimes_adjusted_successfully = $this->increaseReservedForDatetimes($qty);
931
-        if ($datetimes_adjusted_successfully) {
932
-            $success = $this->incrementFieldConditionallyInDb(
933
-                'TKT_reserved',
934
-                'TKT_sold',
935
-                'TKT_qty',
936
-                $qty
937
-            );
938
-            if (! $success) {
939
-                // The datetimes were successfully bumped, but not the
940
-                // ticket. So we need to manually rollback the datetimes.
941
-                $this->decreaseReservedForDatetimes($qty);
942
-            }
943
-        }
944
-        do_action(
945
-            'AHEE__EE_Ticket__increase_reserved',
946
-            $this,
947
-            $qty,
948
-            $this->reserved(),
949
-            $success
950
-        );
951
-        return $success;
952
-    }
953
-
954
-
955
-    /**
956
-     * Increases reserved counts on related datetimes
957
-     *
958
-     * @since 4.9.80.p
959
-     * @param int $qty
960
-     * @param EE_Datetime[] $datetimes
961
-     * @return boolean indicating success
962
-     * @throws EE_Error
963
-     * @throws InvalidArgumentException
964
-     * @throws InvalidDataTypeException
965
-     * @throws InvalidInterfaceException
966
-     * @throws ReflectionException
967
-     */
968
-    protected function increaseReservedForDatetimes($qty = 1, array $datetimes = [])
969
-    {
970
-        $datetimes = ! empty($datetimes) ? $datetimes : $this->datetimes();
971
-        $datetimes_updated = [];
972
-        $limit_exceeded = false;
973
-        if (is_array($datetimes)) {
974
-            foreach ($datetimes as $datetime) {
975
-                if ($datetime instanceof EE_Datetime) {
976
-                    if ($datetime->increaseReserved($qty)) {
977
-                        $datetimes_updated[] = $datetime;
978
-                    } else {
979
-                        $limit_exceeded = true;
980
-                        break;
981
-                    }
982
-                }
983
-            }
984
-            // If somewhere along the way we detected a datetime whose
985
-            // limit was exceeded, do a manual rollback.
986
-            if ($limit_exceeded) {
987
-                $this->decreaseReservedForDatetimes($qty, $datetimes_updated);
988
-                return false;
989
-            }
990
-        }
991
-        return true;
992
-    }
993
-
994
-
995
-    /**
996
-     * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
997
-     *
998
-     * @since 4.9.80.p
999
-     * @param int    $qty
1000
-     * @param bool   $adjust_datetimes
1001
-     * @param string $source
1002
-     * @return boolean
1003
-     * @throws EE_Error
1004
-     * @throws InvalidArgumentException
1005
-     * @throws ReflectionException
1006
-     * @throws InvalidDataTypeException
1007
-     * @throws InvalidInterfaceException
1008
-     */
1009
-    public function decreaseReserved($qty = 1, $adjust_datetimes = true, $source = 'unknown')
1010
-    {
1011
-        $qty = absint($qty);
1012
-        $this->add_extra_meta(EE_Ticket::META_KEY_TICKET_RESERVATIONS, "-{$qty} from {$source}");
1013
-        if ($adjust_datetimes) {
1014
-            $this->decreaseReservedForDatetimes($qty);
1015
-        }
1016
-        $success = $this->adjustNumericFieldsInDb(
1017
-            [
1018
-                'TKT_reserved' => $qty * -1
1019
-            ]
1020
-        );
1021
-        do_action(
1022
-            'AHEE__EE_Ticket__decrease_reserved',
1023
-            $this,
1024
-            $qty,
1025
-            $this->reserved(),
1026
-            $success
1027
-        );
1028
-        return $success;
1029
-    }
1030
-
1031
-
1032
-    /**
1033
-     * Decreases the reserved count on the specified datetimes.
1034
-     *
1035
-     * @since 4.9.80.p
1036
-     * @param int           $qty
1037
-     * @param EE_Datetime[] $datetimes
1038
-     * @throws EE_Error
1039
-     * @throws InvalidArgumentException
1040
-     * @throws ReflectionException
1041
-     * @throws InvalidDataTypeException
1042
-     * @throws InvalidInterfaceException
1043
-     */
1044
-    protected function decreaseReservedForDatetimes($qty = 1, array $datetimes = [])
1045
-    {
1046
-        $datetimes = ! empty($datetimes) ? $datetimes : $this->datetimes();
1047
-        foreach ($datetimes as $datetime) {
1048
-            if ($datetime instanceof EE_Datetime) {
1049
-                $datetime->decreaseReserved($qty);
1050
-            }
1051
-        }
1052
-    }
1053
-
1054
-
1055
-    /**
1056
-     * Gets ticket quantity
1057
-     *
1058
-     * @param string $context     ticket quantity is somewhat subjective depending on the exact information sought
1059
-     *                            therefore $context can be one of three values: '', 'reg_limit', or 'saleable'
1060
-     *                            '' (default) quantity is the actual db value for TKT_qty, unaffected by other objects
1061
-     *                            REG LIMIT: caps qty based on DTT_reg_limit for ALL related datetimes
1062
-     *                            SALEABLE: also considers datetime sold and returns zero if ANY DTT is sold out, and
1063
-     *                            is therefore the truest measure of tickets that can be purchased at the moment
1064
-     * @return int
1065
-     * @throws EE_Error
1066
-     */
1067
-    public function qty($context = '')
1068
-    {
1069
-        switch ($context) {
1070
-            case 'reg_limit':
1071
-                return $this->real_quantity_on_ticket();
1072
-            case 'saleable':
1073
-                return $this->real_quantity_on_ticket('saleable');
1074
-            default:
1075
-                return $this->get_raw('TKT_qty');
1076
-        }
1077
-    }
1078
-
1079
-
1080
-    /**
1081
-     * Gets ticket quantity
1082
-     *
1083
-     * @param string $context     ticket quantity is somewhat subjective depending on the exact information sought
1084
-     *                            therefore $context can be one of two values: 'reg_limit', or 'saleable'
1085
-     *                            REG LIMIT: caps qty based on DTT_reg_limit for ALL related datetimes
1086
-     *                            SALEABLE: also considers datetime sold and returns zero if ANY DTT is sold out, and
1087
-     *                            is therefore the truest measure of tickets that can be purchased at the moment
1088
-     * @param  int   $DTT_ID      the primary key for a particular datetime.
1089
-     *                            set to 0 for all related datetimes
1090
-     * @return int
1091
-     * @throws EE_Error
1092
-     */
1093
-    public function real_quantity_on_ticket($context = 'reg_limit', $DTT_ID = 0)
1094
-    {
1095
-        $raw = $this->get_raw('TKT_qty');
1096
-        // return immediately if it's zero
1097
-        if ($raw === 0) {
1098
-            return $raw;
1099
-        }
1100
-        // echo "\n\n<br />Ticket: " . $this->name() . '<br />';
1101
-        // ensure qty doesn't exceed raw value for THIS ticket
1102
-        $qty = min(EE_INF, $raw);
1103
-        // echo "\n . qty: " . $qty . '<br />';
1104
-        // calculate this ticket's total sales and reservations
1105
-        $sold_and_reserved_for_this_ticket = $this->sold() + $this->reserved();
1106
-        // echo "\n . sold: " . $this->sold() . '<br />';
1107
-        // echo "\n . reserved: " . $this->reserved() . '<br />';
1108
-        // echo "\n . sold_and_reserved_for_this_ticket: " . $sold_and_reserved_for_this_ticket . '<br />';
1109
-        // first we need to calculate the maximum number of tickets available for the datetime
1110
-        // do we want data for one datetime or all of them ?
1111
-        $query_params = $DTT_ID ? array(array('DTT_ID' => $DTT_ID)) : array();
1112
-        $datetimes = $this->datetimes($query_params);
1113
-        if (is_array($datetimes) && ! empty($datetimes)) {
1114
-            foreach ($datetimes as $datetime) {
1115
-                if ($datetime instanceof EE_Datetime) {
1116
-                    $datetime->refresh_from_db();
1117
-                    // echo "\n . . datetime name: " . $datetime->name() . '<br />';
1118
-                    // echo "\n . . datetime ID: " . $datetime->ID() . '<br />';
1119
-                    // initialize with no restrictions for each datetime
1120
-                    // but adjust datetime qty based on datetime reg limit
1121
-                    $datetime_qty = min(EE_INF, $datetime->reg_limit());
1122
-                    // echo "\n . . . datetime reg_limit: " . $datetime->reg_limit() . '<br />';
1123
-                    // echo "\n . . . datetime_qty: " . $datetime_qty . '<br />';
1124
-                    // if we want the actual saleable amount, then we need to consider OTHER ticket sales
1125
-                    // and reservations for this datetime, that do NOT include sales and reservations
1126
-                    // for this ticket (so we add $this->sold() and $this->reserved() back in)
1127
-                    if ($context === 'saleable') {
1128
-                        $datetime_qty = max(
1129
-                            $datetime_qty - $datetime->sold_and_reserved() + $sold_and_reserved_for_this_ticket,
1130
-                            0
1131
-                        );
1132
-                        // echo "\n . . . datetime sold: " . $datetime->sold() . '<br />';
1133
-                        // echo "\n . . . datetime reserved: " . $datetime->reserved() . '<br />';
1134
-                        // echo "\n . . . datetime sold_and_reserved: " . $datetime->sold_and_reserved() . '<br />';
1135
-                        // echo "\n . . . datetime_qty: " . $datetime_qty . '<br />';
1136
-                        $datetime_qty = ! $datetime->sold_out() ? $datetime_qty : 0;
1137
-                        // echo "\n . . . datetime_qty: " . $datetime_qty . '<br />';
1138
-                    }
1139
-                    $qty = min($datetime_qty, $qty);
1140
-                    // echo "\n . . qty: " . $qty . '<br />';
1141
-                }
1142
-            }
1143
-        }
1144
-        // NOW that we know the  maximum number of tickets available for the datetime
1145
-        // we can finally factor in the details for this specific ticket
1146
-        if ($qty > 0 && $context === 'saleable') {
1147
-            // and subtract the sales for THIS ticket
1148
-            $qty = max($qty - $sold_and_reserved_for_this_ticket, 0);
1149
-            // echo "\n . qty: " . $qty . '<br />';
1150
-        }
1151
-        // echo "\nFINAL QTY: " . $qty . "<br /><br />";
1152
-        return $qty;
1153
-    }
1154
-
1155
-
1156
-    /**
1157
-     * Sets qty - IMPORTANT!!! Does NOT allow QTY to be set higher than the lowest reg limit of any related datetimes
1158
-     *
1159
-     * @param int $qty
1160
-     * @return void
1161
-     * @throws EE_Error
1162
-     */
1163
-    public function set_qty($qty)
1164
-    {
1165
-        $datetimes = $this->datetimes();
1166
-        foreach ($datetimes as $datetime) {
1167
-            if ($datetime instanceof EE_Datetime) {
1168
-                $qty = min($qty, $datetime->reg_limit());
1169
-            }
1170
-        }
1171
-        $this->set('TKT_qty', $qty);
1172
-    }
1173
-
1174
-
1175
-    /**
1176
-     * Gets uses
1177
-     *
1178
-     * @return int
1179
-     * @throws EE_Error
1180
-     */
1181
-    public function uses()
1182
-    {
1183
-        return $this->get('TKT_uses');
1184
-    }
1185
-
1186
-
1187
-    /**
1188
-     * Sets uses
1189
-     *
1190
-     * @param int $uses
1191
-     * @return void
1192
-     * @throws EE_Error
1193
-     */
1194
-    public function set_uses($uses)
1195
-    {
1196
-        $this->set('TKT_uses', $uses);
1197
-    }
1198
-
1199
-
1200
-    /**
1201
-     * returns whether ticket is required or not.
1202
-     *
1203
-     * @return boolean
1204
-     * @throws EE_Error
1205
-     */
1206
-    public function required()
1207
-    {
1208
-        return $this->get('TKT_required');
1209
-    }
1210
-
1211
-
1212
-    /**
1213
-     * sets the TKT_required property
1214
-     *
1215
-     * @param boolean $required
1216
-     * @return void
1217
-     * @throws EE_Error
1218
-     */
1219
-    public function set_required($required)
1220
-    {
1221
-        $this->set('TKT_required', $required);
1222
-    }
1223
-
1224
-
1225
-    /**
1226
-     * Gets taxable
1227
-     *
1228
-     * @return boolean
1229
-     * @throws EE_Error
1230
-     */
1231
-    public function taxable()
1232
-    {
1233
-        return $this->get('TKT_taxable');
1234
-    }
1235
-
1236
-
1237
-    /**
1238
-     * Sets taxable
1239
-     *
1240
-     * @param boolean $taxable
1241
-     * @return void
1242
-     * @throws EE_Error
1243
-     */
1244
-    public function set_taxable($taxable)
1245
-    {
1246
-        $this->set('TKT_taxable', $taxable);
1247
-    }
1248
-
1249
-
1250
-    /**
1251
-     * Gets is_default
1252
-     *
1253
-     * @return boolean
1254
-     * @throws EE_Error
1255
-     */
1256
-    public function is_default()
1257
-    {
1258
-        return $this->get('TKT_is_default');
1259
-    }
1260
-
1261
-
1262
-    /**
1263
-     * Sets is_default
1264
-     *
1265
-     * @param boolean $is_default
1266
-     * @return void
1267
-     * @throws EE_Error
1268
-     */
1269
-    public function set_is_default($is_default)
1270
-    {
1271
-        $this->set('TKT_is_default', $is_default);
1272
-    }
1273
-
1274
-
1275
-    /**
1276
-     * Gets order
1277
-     *
1278
-     * @return int
1279
-     * @throws EE_Error
1280
-     */
1281
-    public function order()
1282
-    {
1283
-        return $this->get('TKT_order');
1284
-    }
1285
-
1286
-
1287
-    /**
1288
-     * Sets order
1289
-     *
1290
-     * @param int $order
1291
-     * @return void
1292
-     * @throws EE_Error
1293
-     */
1294
-    public function set_order($order)
1295
-    {
1296
-        $this->set('TKT_order', $order);
1297
-    }
1298
-
1299
-
1300
-    /**
1301
-     * Gets row
1302
-     *
1303
-     * @return int
1304
-     * @throws EE_Error
1305
-     */
1306
-    public function row()
1307
-    {
1308
-        return $this->get('TKT_row');
1309
-    }
1310
-
1311
-
1312
-    /**
1313
-     * Sets row
1314
-     *
1315
-     * @param int $row
1316
-     * @return void
1317
-     * @throws EE_Error
1318
-     */
1319
-    public function set_row($row)
1320
-    {
1321
-        $this->set('TKT_row', $row);
1322
-    }
1323
-
1324
-
1325
-    /**
1326
-     * Gets deleted
1327
-     *
1328
-     * @return boolean
1329
-     * @throws EE_Error
1330
-     */
1331
-    public function deleted()
1332
-    {
1333
-        return $this->get('TKT_deleted');
1334
-    }
1335
-
1336
-
1337
-    /**
1338
-     * Sets deleted
1339
-     *
1340
-     * @param boolean $deleted
1341
-     * @return void
1342
-     * @throws EE_Error
1343
-     */
1344
-    public function set_deleted($deleted)
1345
-    {
1346
-        $this->set('TKT_deleted', $deleted);
1347
-    }
1348
-
1349
-
1350
-    /**
1351
-     * Gets parent
1352
-     *
1353
-     * @return int
1354
-     * @throws EE_Error
1355
-     */
1356
-    public function parent_ID()
1357
-    {
1358
-        return $this->get('TKT_parent');
1359
-    }
1360
-
1361
-
1362
-    /**
1363
-     * Sets parent
1364
-     *
1365
-     * @param int $parent
1366
-     * @return void
1367
-     * @throws EE_Error
1368
-     */
1369
-    public function set_parent_ID($parent)
1370
-    {
1371
-        $this->set('TKT_parent', $parent);
1372
-    }
1373
-
1374
-
1375
-    /**
1376
-     * Gets a string which is handy for showing in gateways etc that describes the ticket.
1377
-     *
1378
-     * @return string
1379
-     * @throws EE_Error
1380
-     */
1381
-    public function name_and_info()
1382
-    {
1383
-        $times = array();
1384
-        foreach ($this->datetimes() as $datetime) {
1385
-            $times[] = $datetime->start_date_and_time();
1386
-        }
1387
-        return $this->name() . ' @ ' . implode(', ', $times) . ' for ' . $this->pretty_price();
1388
-    }
1389
-
1390
-
1391
-    /**
1392
-     * Gets name
1393
-     *
1394
-     * @return string
1395
-     * @throws EE_Error
1396
-     */
1397
-    public function name()
1398
-    {
1399
-        return $this->get('TKT_name');
1400
-    }
1401
-
1402
-
1403
-    /**
1404
-     * Gets price
1405
-     *
1406
-     * @return float
1407
-     * @throws EE_Error
1408
-     */
1409
-    public function price()
1410
-    {
1411
-        return $this->get('TKT_price');
1412
-    }
1413
-
1414
-
1415
-    /**
1416
-     * Gets all the registrations for this ticket
1417
-     *
1418
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1419
-     * @return EE_Registration[]|EE_Base_Class[]
1420
-     * @throws EE_Error
1421
-     */
1422
-    public function registrations($query_params = array())
1423
-    {
1424
-        return $this->get_many_related('Registration', $query_params);
1425
-    }
1426
-
1427
-
1428
-    /**
1429
-     * Updates the TKT_sold attribute (and saves) based on the number of APPROVED registrations for this ticket.
1430
-     *
1431
-     * @return int
1432
-     * @throws EE_Error
1433
-     */
1434
-    public function update_tickets_sold()
1435
-    {
1436
-        $count_regs_for_this_ticket = $this->count_registrations(
1437
-            array(
1438
-                array(
1439
-                    'STS_ID'      => EEM_Registration::status_id_approved,
1440
-                    'REG_deleted' => 0,
1441
-                ),
1442
-            )
1443
-        );
1444
-        $this->set_sold($count_regs_for_this_ticket);
1445
-        $this->save();
1446
-        return $count_regs_for_this_ticket;
1447
-    }
1448
-
1449
-
1450
-    /**
1451
-     * Counts the registrations for this ticket
1452
-     *
1453
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1454
-     * @return int
1455
-     */
1456
-    public function count_registrations($query_params = array())
1457
-    {
1458
-        return $this->count_related('Registration', $query_params);
1459
-    }
1460
-
1461
-
1462
-    /**
1463
-     * Implementation for EEI_Has_Icon interface method.
1464
-     *
1465
-     * @see EEI_Visual_Representation for comments
1466
-     * @return string
1467
-     */
1468
-    public function get_icon()
1469
-    {
1470
-        return '<span class="dashicons dashicons-tickets-alt"></span>';
1471
-    }
1472
-
1473
-
1474
-    /**
1475
-     * Implementation of the EEI_Event_Relation interface method
1476
-     *
1477
-     * @see EEI_Event_Relation for comments
1478
-     * @return EE_Event
1479
-     * @throws EE_Error
1480
-     * @throws UnexpectedEntityException
1481
-     */
1482
-    public function get_related_event()
1483
-    {
1484
-        // get one datetime to use for getting the event
1485
-        $datetime = $this->first_datetime();
1486
-        if (! $datetime instanceof \EE_Datetime) {
1487
-            throw new UnexpectedEntityException(
1488
-                $datetime,
1489
-                'EE_Datetime',
1490
-                sprintf(
1491
-                    __('The ticket (%s) is not associated with any valid datetimes.', 'event_espresso'),
1492
-                    $this->name()
1493
-                )
1494
-            );
1495
-        }
1496
-        $event = $datetime->event();
1497
-        if (! $event instanceof \EE_Event) {
1498
-            throw new UnexpectedEntityException(
1499
-                $event,
1500
-                'EE_Event',
1501
-                sprintf(
1502
-                    __('The ticket (%s) is not associated with a valid event.', 'event_espresso'),
1503
-                    $this->name()
1504
-                )
1505
-            );
1506
-        }
1507
-        return $event;
1508
-    }
1509
-
1510
-
1511
-    /**
1512
-     * Implementation of the EEI_Event_Relation interface method
1513
-     *
1514
-     * @see EEI_Event_Relation for comments
1515
-     * @return string
1516
-     * @throws UnexpectedEntityException
1517
-     * @throws EE_Error
1518
-     */
1519
-    public function get_event_name()
1520
-    {
1521
-        $event = $this->get_related_event();
1522
-        return $event instanceof EE_Event ? $event->name() : '';
1523
-    }
1524
-
1525
-
1526
-    /**
1527
-     * Implementation of the EEI_Event_Relation interface method
1528
-     *
1529
-     * @see EEI_Event_Relation for comments
1530
-     * @return int
1531
-     * @throws UnexpectedEntityException
1532
-     * @throws EE_Error
1533
-     */
1534
-    public function get_event_ID()
1535
-    {
1536
-        $event = $this->get_related_event();
1537
-        return $event instanceof EE_Event ? $event->ID() : 0;
1538
-    }
1539
-
1540
-
1541
-    /**
1542
-     * This simply returns whether a ticket can be permanently deleted or not.
1543
-     * The criteria for determining this is whether the ticket has any related registrations.
1544
-     * If there are none then it can be permanently deleted.
1545
-     *
1546
-     * @return bool
1547
-     */
1548
-    public function is_permanently_deleteable()
1549
-    {
1550
-        return $this->count_registrations() === 0;
1551
-    }
1552
-
1553
-
1554
-    /*******************************************************************
17
+	/**
18
+	 * TicKet Sold out:
19
+	 * constant used by ticket_status() to indicate that a ticket is sold out
20
+	 * and no longer available for purchase
21
+	 */
22
+	const sold_out = 'TKS';
23
+
24
+	/**
25
+	 * TicKet Expired:
26
+	 * constant used by ticket_status() to indicate that a ticket is expired
27
+	 * and no longer available for purchase
28
+	 */
29
+	const expired = 'TKE';
30
+
31
+	/**
32
+	 * TicKet Archived:
33
+	 * constant used by ticket_status() to indicate that a ticket is archived
34
+	 * and no longer available for purchase
35
+	 */
36
+	const archived = 'TKA';
37
+
38
+	/**
39
+	 * TicKet Pending:
40
+	 * constant used by ticket_status() to indicate that a ticket is pending
41
+	 * and is NOT YET available for purchase
42
+	 */
43
+	const pending = 'TKP';
44
+
45
+	/**
46
+	 * TicKet On sale:
47
+	 * constant used by ticket_status() to indicate that a ticket is On Sale
48
+	 * and IS available for purchase
49
+	 */
50
+	const onsale = 'TKO';
51
+
52
+	/**
53
+	 * extra meta key for tracking ticket reservations
54
+	 *
55
+	 * @type string
56
+	 */
57
+	const META_KEY_TICKET_RESERVATIONS = 'ticket_reservations';
58
+
59
+	/**
60
+	 * cached result from method of the same name
61
+	 *
62
+	 * @var float $_ticket_total_with_taxes
63
+	 */
64
+	private $_ticket_total_with_taxes;
65
+
66
+
67
+	/**
68
+	 * @param array  $props_n_values          incoming values
69
+	 * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
70
+	 *                                        used.)
71
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
72
+	 *                                        date_format and the second value is the time format
73
+	 * @return EE_Ticket
74
+	 * @throws EE_Error
75
+	 */
76
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
77
+	{
78
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
79
+		return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
80
+	}
81
+
82
+
83
+	/**
84
+	 * @param array  $props_n_values  incoming values from the database
85
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
86
+	 *                                the website will be used.
87
+	 * @return EE_Ticket
88
+	 * @throws EE_Error
89
+	 */
90
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null)
91
+	{
92
+		return new self($props_n_values, true, $timezone);
93
+	}
94
+
95
+
96
+	/**
97
+	 * @return bool
98
+	 * @throws EE_Error
99
+	 */
100
+	public function parent()
101
+	{
102
+		return $this->get('TKT_parent');
103
+	}
104
+
105
+
106
+	/**
107
+	 * return if a ticket has quantities available for purchase
108
+	 *
109
+	 * @param  int $DTT_ID the primary key for a particular datetime
110
+	 * @return boolean
111
+	 * @throws EE_Error
112
+	 */
113
+	public function available($DTT_ID = 0)
114
+	{
115
+		// are we checking availability for a particular datetime ?
116
+		if ($DTT_ID) {
117
+			// get that datetime object
118
+			$datetime = $this->get_first_related('Datetime', array(array('DTT_ID' => $DTT_ID)));
119
+			// if  ticket sales for this datetime have exceeded the reg limit...
120
+			if ($datetime instanceof EE_Datetime && $datetime->sold_out()) {
121
+				return false;
122
+			}
123
+		}
124
+		// datetime is still open for registration, but is this ticket sold out ?
125
+		return $this->qty() < 1 || $this->qty() > $this->sold() ? true : false;
126
+	}
127
+
128
+
129
+	/**
130
+	 * Using the start date and end date this method calculates whether the ticket is On Sale, Pending, or Expired
131
+	 *
132
+	 * @param bool        $display   true = we'll return a localized string, otherwise we just return the value of the
133
+	 *                               relevant status const
134
+	 * @param bool | null $remaining if it is already known that tickets are available, then simply pass a bool to save
135
+	 *               further processing
136
+	 * @return mixed status int if the display string isn't requested
137
+	 * @throws EE_Error
138
+	 */
139
+	public function ticket_status($display = false, $remaining = null)
140
+	{
141
+		$remaining = is_bool($remaining) ? $remaining : $this->is_remaining();
142
+		if (! $remaining) {
143
+			return $display ? EEH_Template::pretty_status(EE_Ticket::sold_out, false, 'sentence') : EE_Ticket::sold_out;
144
+		}
145
+		if ($this->get('TKT_deleted')) {
146
+			return $display ? EEH_Template::pretty_status(EE_Ticket::archived, false, 'sentence') : EE_Ticket::archived;
147
+		}
148
+		if ($this->is_expired()) {
149
+			return $display ? EEH_Template::pretty_status(EE_Ticket::expired, false, 'sentence') : EE_Ticket::expired;
150
+		}
151
+		if ($this->is_pending()) {
152
+			return $display ? EEH_Template::pretty_status(EE_Ticket::pending, false, 'sentence') : EE_Ticket::pending;
153
+		}
154
+		if ($this->is_on_sale()) {
155
+			return $display ? EEH_Template::pretty_status(EE_Ticket::onsale, false, 'sentence') : EE_Ticket::onsale;
156
+		}
157
+		return '';
158
+	}
159
+
160
+
161
+	/**
162
+	 * The purpose of this method is to simply return a boolean for whether there are any tickets remaining for sale
163
+	 * considering ALL the factors used for figuring that out.
164
+	 *
165
+	 * @access public
166
+	 * @param  int $DTT_ID if an int above 0 is included here then we get a specific dtt.
167
+	 * @return boolean         true = tickets remaining, false not.
168
+	 * @throws EE_Error
169
+	 */
170
+	public function is_remaining($DTT_ID = 0)
171
+	{
172
+		$num_remaining = $this->remaining($DTT_ID);
173
+		if ($num_remaining === 0) {
174
+			return false;
175
+		}
176
+		if ($num_remaining > 0 && $num_remaining < $this->min()) {
177
+			return false;
178
+		}
179
+		return true;
180
+	}
181
+
182
+
183
+	/**
184
+	 * return the total number of tickets available for purchase
185
+	 *
186
+	 * @param  int $DTT_ID the primary key for a particular datetime.
187
+	 *                     set to 0 for all related datetimes
188
+	 * @return int
189
+	 * @throws EE_Error
190
+	 */
191
+	public function remaining($DTT_ID = 0)
192
+	{
193
+		return $this->real_quantity_on_ticket('saleable', $DTT_ID);
194
+	}
195
+
196
+
197
+	/**
198
+	 * Gets min
199
+	 *
200
+	 * @return int
201
+	 * @throws EE_Error
202
+	 */
203
+	public function min()
204
+	{
205
+		return $this->get('TKT_min');
206
+	}
207
+
208
+
209
+	/**
210
+	 * return if a ticket is no longer available cause its available dates have expired.
211
+	 *
212
+	 * @return boolean
213
+	 * @throws EE_Error
214
+	 */
215
+	public function is_expired()
216
+	{
217
+		return ($this->get_raw('TKT_end_date') < time());
218
+	}
219
+
220
+
221
+	/**
222
+	 * Return if a ticket is yet to go on sale or not
223
+	 *
224
+	 * @return boolean
225
+	 * @throws EE_Error
226
+	 */
227
+	public function is_pending()
228
+	{
229
+		return ($this->get_raw('TKT_start_date') > time());
230
+	}
231
+
232
+
233
+	/**
234
+	 * Return if a ticket is on sale or not
235
+	 *
236
+	 * @return boolean
237
+	 * @throws EE_Error
238
+	 */
239
+	public function is_on_sale()
240
+	{
241
+		return ($this->get_raw('TKT_start_date') < time() && $this->get_raw('TKT_end_date') > time());
242
+	}
243
+
244
+
245
+	/**
246
+	 * This returns the chronologically last datetime that this ticket is associated with
247
+	 *
248
+	 * @param string $dt_frmt
249
+	 * @param string $conjunction - conjunction junction what's your function ? this string joins the start date with
250
+	 *                            the end date ie: Jan 01 "to" Dec 31
251
+	 * @return string
252
+	 * @throws EE_Error
253
+	 */
254
+	public function date_range($dt_frmt = '', $conjunction = ' - ')
255
+	{
256
+		$dt_frmt = ! empty($dt_frmt) ? $dt_frmt : $this->_dt_frmt;
257
+		$first_date = $this->first_datetime() instanceof EE_Datetime ? $this->first_datetime()->get_i18n_datetime('DTT_EVT_start', $dt_frmt)
258
+			: '';
259
+		$last_date = $this->last_datetime() instanceof EE_Datetime ? $this->last_datetime()->get_i18n_datetime('DTT_EVT_end', $dt_frmt) : '';
260
+
261
+		return $first_date && $last_date ? $first_date . $conjunction . $last_date : '';
262
+	}
263
+
264
+
265
+	/**
266
+	 * This returns the chronologically first datetime that this ticket is associated with
267
+	 *
268
+	 * @return EE_Datetime
269
+	 * @throws EE_Error
270
+	 */
271
+	public function first_datetime()
272
+	{
273
+		$datetimes = $this->datetimes(array('limit' => 1));
274
+		return reset($datetimes);
275
+	}
276
+
277
+
278
+	/**
279
+	 * Gets all the datetimes this ticket can be used for attending.
280
+	 * Unless otherwise specified, orders datetimes by start date.
281
+	 *
282
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
283
+	 * @return EE_Datetime[]|EE_Base_Class[]
284
+	 * @throws EE_Error
285
+	 */
286
+	public function datetimes($query_params = array())
287
+	{
288
+		if (! isset($query_params['order_by'])) {
289
+			$query_params['order_by']['DTT_order'] = 'ASC';
290
+		}
291
+		return $this->get_many_related('Datetime', $query_params);
292
+	}
293
+
294
+
295
+	/**
296
+	 * This returns the chronologically last datetime that this ticket is associated with
297
+	 *
298
+	 * @return EE_Datetime
299
+	 * @throws EE_Error
300
+	 */
301
+	public function last_datetime()
302
+	{
303
+		$datetimes = $this->datetimes(array('limit' => 1, 'order_by' => array('DTT_EVT_start' => 'DESC')));
304
+		return end($datetimes);
305
+	}
306
+
307
+
308
+	/**
309
+	 * This returns the total tickets sold depending on the given parameters.
310
+	 *
311
+	 * @param  string $what   Can be one of two options: 'ticket', 'datetime'.
312
+	 *                        'ticket' = total ticket sales for all datetimes this ticket is related to
313
+	 *                        'datetime' = total ticket sales for a specified datetime (required $dtt_id)
314
+	 *                        'datetime' = total ticket sales in the datetime_ticket table.
315
+	 *                        If $dtt_id is not given then we return an array of sales indexed by datetime.
316
+	 *                        If $dtt_id IS given then we return the tickets sold for that given datetime.
317
+	 * @param  int    $dtt_id [optional] include the dtt_id with $what = 'datetime'.
318
+	 * @return mixed (array|int)          how many tickets have sold
319
+	 * @throws EE_Error
320
+	 */
321
+	public function tickets_sold($what = 'ticket', $dtt_id = null)
322
+	{
323
+		$total = 0;
324
+		$tickets_sold = $this->_all_tickets_sold();
325
+		switch ($what) {
326
+			case 'ticket':
327
+				return $tickets_sold['ticket'];
328
+				break;
329
+			case 'datetime':
330
+				if (empty($tickets_sold['datetime'])) {
331
+					return $total;
332
+				}
333
+				if (! empty($dtt_id) && ! isset($tickets_sold['datetime'][ $dtt_id ])) {
334
+					EE_Error::add_error(
335
+						__(
336
+							'You\'ve requested the amount of tickets sold for a given ticket and datetime, however there are no records for the datetime id you included.  Are you SURE that is a datetime related to this ticket?',
337
+							'event_espresso'
338
+						),
339
+						__FILE__,
340
+						__FUNCTION__,
341
+						__LINE__
342
+					);
343
+					return $total;
344
+				}
345
+				return empty($dtt_id) ? $tickets_sold['datetime'] : $tickets_sold['datetime'][ $dtt_id ];
346
+				break;
347
+			default:
348
+				return $total;
349
+		}
350
+	}
351
+
352
+
353
+	/**
354
+	 * This returns an array indexed by datetime_id for tickets sold with this ticket.
355
+	 *
356
+	 * @return EE_Ticket[]
357
+	 * @throws EE_Error
358
+	 */
359
+	protected function _all_tickets_sold()
360
+	{
361
+		$datetimes = $this->get_many_related('Datetime');
362
+		$tickets_sold = array();
363
+		if (! empty($datetimes)) {
364
+			foreach ($datetimes as $datetime) {
365
+				$tickets_sold['datetime'][ $datetime->ID() ] = $datetime->get('DTT_sold');
366
+			}
367
+		}
368
+		// Tickets sold
369
+		$tickets_sold['ticket'] = $this->sold();
370
+		return $tickets_sold;
371
+	}
372
+
373
+
374
+	/**
375
+	 * This returns the base price object for the ticket.
376
+	 *
377
+	 * @param  bool $return_array whether to return as an array indexed by price id or just the object.
378
+	 * @return EE_Price|EE_Base_Class|EE_Price[]|EE_Base_Class[]
379
+	 * @throws EE_Error
380
+	 */
381
+	public function base_price($return_array = false)
382
+	{
383
+		$_where = array('Price_Type.PBT_ID' => EEM_Price_Type::base_type_base_price);
384
+		return $return_array
385
+			? $this->get_many_related('Price', array($_where))
386
+			: $this->get_first_related('Price', array($_where));
387
+	}
388
+
389
+
390
+	/**
391
+	 * This returns ONLY the price modifiers for the ticket (i.e. no taxes or base price)
392
+	 *
393
+	 * @access public
394
+	 * @return EE_Price[]
395
+	 * @throws EE_Error
396
+	 */
397
+	public function price_modifiers()
398
+	{
399
+		$query_params = array(
400
+			0 => array(
401
+				'Price_Type.PBT_ID' => array(
402
+					'NOT IN',
403
+					array(EEM_Price_Type::base_type_base_price, EEM_Price_Type::base_type_tax),
404
+				),
405
+			),
406
+		);
407
+		return $this->prices($query_params);
408
+	}
409
+
410
+
411
+	/**
412
+	 * Gets all the prices that combine to form the final price of this ticket
413
+	 *
414
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
415
+	 * @return EE_Price[]|EE_Base_Class[]
416
+	 * @throws EE_Error
417
+	 */
418
+	public function prices($query_params = array())
419
+	{
420
+		return $this->get_many_related('Price', $query_params);
421
+	}
422
+
423
+
424
+	/**
425
+	 * Gets all the ticket applicabilities (ie, relations between datetimes and tickets)
426
+	 *
427
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
428
+	 * @return EE_Datetime_Ticket|EE_Base_Class[]
429
+	 * @throws EE_Error
430
+	 */
431
+	public function datetime_tickets($query_params = array())
432
+	{
433
+		return $this->get_many_related('Datetime_Ticket', $query_params);
434
+	}
435
+
436
+
437
+	/**
438
+	 * Gets all the datetimes from the db ordered by DTT_order
439
+	 *
440
+	 * @param boolean $show_expired
441
+	 * @param boolean $show_deleted
442
+	 * @return EE_Datetime[]
443
+	 * @throws EE_Error
444
+	 */
445
+	public function datetimes_ordered($show_expired = true, $show_deleted = false)
446
+	{
447
+		return EEM_Datetime::instance($this->_timezone)->get_datetimes_for_ticket_ordered_by_DTT_order(
448
+			$this->ID(),
449
+			$show_expired,
450
+			$show_deleted
451
+		);
452
+	}
453
+
454
+
455
+	/**
456
+	 * Gets ID
457
+	 *
458
+	 * @return string
459
+	 * @throws EE_Error
460
+	 */
461
+	public function ID()
462
+	{
463
+		return $this->get('TKT_ID');
464
+	}
465
+
466
+
467
+	/**
468
+	 * get the author of the ticket.
469
+	 *
470
+	 * @since 4.5.0
471
+	 * @return int
472
+	 * @throws EE_Error
473
+	 */
474
+	public function wp_user()
475
+	{
476
+		return $this->get('TKT_wp_user');
477
+	}
478
+
479
+
480
+	/**
481
+	 * Gets the template for the ticket
482
+	 *
483
+	 * @return EE_Ticket_Template|EE_Base_Class
484
+	 * @throws EE_Error
485
+	 */
486
+	public function template()
487
+	{
488
+		return $this->get_first_related('Ticket_Template');
489
+	}
490
+
491
+
492
+	/**
493
+	 * Simply returns an array of EE_Price objects that are taxes.
494
+	 *
495
+	 * @return EE_Price[]
496
+	 * @throws EE_Error
497
+	 */
498
+	public function get_ticket_taxes_for_admin()
499
+	{
500
+		return EE_Taxes::get_taxes_for_admin();
501
+	}
502
+
503
+
504
+	/**
505
+	 * @return float
506
+	 * @throws EE_Error
507
+	 */
508
+	public function ticket_price()
509
+	{
510
+		return $this->get('TKT_price');
511
+	}
512
+
513
+
514
+	/**
515
+	 * @return mixed
516
+	 * @throws EE_Error
517
+	 */
518
+	public function pretty_price()
519
+	{
520
+		return $this->get_pretty('TKT_price');
521
+	}
522
+
523
+
524
+	/**
525
+	 * @return bool
526
+	 * @throws EE_Error
527
+	 */
528
+	public function is_free()
529
+	{
530
+		return $this->get_ticket_total_with_taxes() === (float) 0;
531
+	}
532
+
533
+
534
+	/**
535
+	 * get_ticket_total_with_taxes
536
+	 *
537
+	 * @param bool $no_cache
538
+	 * @return float
539
+	 * @throws EE_Error
540
+	 */
541
+	public function get_ticket_total_with_taxes($no_cache = false)
542
+	{
543
+		if ($this->_ticket_total_with_taxes === null || $no_cache) {
544
+			$this->_ticket_total_with_taxes = $this->get_ticket_subtotal() + $this->get_ticket_taxes_total_for_admin();
545
+		}
546
+		return (float) $this->_ticket_total_with_taxes;
547
+	}
548
+
549
+
550
+	public function ensure_TKT_Price_correct()
551
+	{
552
+		$this->set('TKT_price', EE_Taxes::get_subtotal_for_admin($this));
553
+		$this->save();
554
+	}
555
+
556
+
557
+	/**
558
+	 * @return float
559
+	 * @throws EE_Error
560
+	 */
561
+	public function get_ticket_subtotal()
562
+	{
563
+		return EE_Taxes::get_subtotal_for_admin($this);
564
+	}
565
+
566
+
567
+	/**
568
+	 * Returns the total taxes applied to this ticket
569
+	 *
570
+	 * @return float
571
+	 * @throws EE_Error
572
+	 */
573
+	public function get_ticket_taxes_total_for_admin()
574
+	{
575
+		return EE_Taxes::get_total_taxes_for_admin($this);
576
+	}
577
+
578
+
579
+	/**
580
+	 * Sets name
581
+	 *
582
+	 * @param string $name
583
+	 * @throws EE_Error
584
+	 */
585
+	public function set_name($name)
586
+	{
587
+		$this->set('TKT_name', $name);
588
+	}
589
+
590
+
591
+	/**
592
+	 * Gets description
593
+	 *
594
+	 * @return string
595
+	 * @throws EE_Error
596
+	 */
597
+	public function description()
598
+	{
599
+		return $this->get('TKT_description');
600
+	}
601
+
602
+
603
+	/**
604
+	 * Sets description
605
+	 *
606
+	 * @param string $description
607
+	 * @throws EE_Error
608
+	 */
609
+	public function set_description($description)
610
+	{
611
+		$this->set('TKT_description', $description);
612
+	}
613
+
614
+
615
+	/**
616
+	 * Gets start_date
617
+	 *
618
+	 * @param string $dt_frmt
619
+	 * @param string $tm_frmt
620
+	 * @return string
621
+	 * @throws EE_Error
622
+	 */
623
+	public function start_date($dt_frmt = '', $tm_frmt = '')
624
+	{
625
+		return $this->_get_datetime('TKT_start_date', $dt_frmt, $tm_frmt);
626
+	}
627
+
628
+
629
+	/**
630
+	 * Sets start_date
631
+	 *
632
+	 * @param string $start_date
633
+	 * @return void
634
+	 * @throws EE_Error
635
+	 */
636
+	public function set_start_date($start_date)
637
+	{
638
+		$this->_set_date_time('B', $start_date, 'TKT_start_date');
639
+	}
640
+
641
+
642
+	/**
643
+	 * Gets end_date
644
+	 *
645
+	 * @param string $dt_frmt
646
+	 * @param string $tm_frmt
647
+	 * @return string
648
+	 * @throws EE_Error
649
+	 */
650
+	public function end_date($dt_frmt = '', $tm_frmt = '')
651
+	{
652
+		return $this->_get_datetime('TKT_end_date', $dt_frmt, $tm_frmt);
653
+	}
654
+
655
+
656
+	/**
657
+	 * Sets end_date
658
+	 *
659
+	 * @param string $end_date
660
+	 * @return void
661
+	 * @throws EE_Error
662
+	 */
663
+	public function set_end_date($end_date)
664
+	{
665
+		$this->_set_date_time('B', $end_date, 'TKT_end_date');
666
+	}
667
+
668
+
669
+	/**
670
+	 * Sets sell until time
671
+	 *
672
+	 * @since 4.5.0
673
+	 * @param string $time a string representation of the sell until time (ex 9am or 7:30pm)
674
+	 * @throws EE_Error
675
+	 */
676
+	public function set_end_time($time)
677
+	{
678
+		$this->_set_time_for($time, 'TKT_end_date');
679
+	}
680
+
681
+
682
+	/**
683
+	 * Sets min
684
+	 *
685
+	 * @param int $min
686
+	 * @return void
687
+	 * @throws EE_Error
688
+	 */
689
+	public function set_min($min)
690
+	{
691
+		$this->set('TKT_min', $min);
692
+	}
693
+
694
+
695
+	/**
696
+	 * Gets max
697
+	 *
698
+	 * @return int
699
+	 * @throws EE_Error
700
+	 */
701
+	public function max()
702
+	{
703
+		return $this->get('TKT_max');
704
+	}
705
+
706
+
707
+	/**
708
+	 * Sets max
709
+	 *
710
+	 * @param int $max
711
+	 * @return void
712
+	 * @throws EE_Error
713
+	 */
714
+	public function set_max($max)
715
+	{
716
+		$this->set('TKT_max', $max);
717
+	}
718
+
719
+
720
+	/**
721
+	 * Sets price
722
+	 *
723
+	 * @param float $price
724
+	 * @return void
725
+	 * @throws EE_Error
726
+	 */
727
+	public function set_price($price)
728
+	{
729
+		$this->set('TKT_price', $price);
730
+	}
731
+
732
+
733
+	/**
734
+	 * Gets sold
735
+	 *
736
+	 * @return int
737
+	 * @throws EE_Error
738
+	 */
739
+	public function sold()
740
+	{
741
+		return $this->get_raw('TKT_sold');
742
+	}
743
+
744
+
745
+	/**
746
+	 * Sets sold
747
+	 *
748
+	 * @param int $sold
749
+	 * @return void
750
+	 * @throws EE_Error
751
+	 */
752
+	public function set_sold($sold)
753
+	{
754
+		// sold can not go below zero
755
+		$sold = max(0, $sold);
756
+		$this->set('TKT_sold', $sold);
757
+	}
758
+
759
+
760
+	/**
761
+	 * Increments sold by amount passed by $qty AND decrements the reserved count on both this ticket and its
762
+	 * associated datetimes.
763
+	 *
764
+	 * @since 4.9.80.p
765
+	 * @param int $qty
766
+	 * @return boolean
767
+	 * @throws EE_Error
768
+	 * @throws InvalidArgumentException
769
+	 * @throws InvalidDataTypeException
770
+	 * @throws InvalidInterfaceException
771
+	 * @throws ReflectionException
772
+	 */
773
+	public function increaseSold($qty = 1)
774
+	{
775
+		$qty = absint($qty);
776
+		// increment sold and decrement reserved datetime quantities simultaneously
777
+		// don't worry about failures, because they must have already had a spot reserved
778
+		$this->increaseSoldForDatetimes($qty);
779
+		// Increment and decrement ticket quantities simultaneously
780
+		$success = $this->adjustNumericFieldsInDb(
781
+			[
782
+				'TKT_reserved' => $qty * -1,
783
+				'TKT_sold' => $qty
784
+			]
785
+		);
786
+		do_action(
787
+			'AHEE__EE_Ticket__increase_sold',
788
+			$this,
789
+			$qty,
790
+			$this->sold(),
791
+			$success
792
+		);
793
+		return $success;
794
+	}
795
+
796
+	/**
797
+	 * On each datetime related to this ticket, increases its sold count and decreases its reserved count by $qty.
798
+	 *
799
+	 * @since 4.9.80.p
800
+	 * @param int $qty positive or negative. Positive means to increase sold counts (and decrease reserved counts),
801
+	 *             Negative means to decreases old counts (and increase reserved counts).
802
+	 * @param EE_Datetime[] $datetimes
803
+	 * @throws EE_Error
804
+	 * @throws InvalidArgumentException
805
+	 * @throws InvalidDataTypeException
806
+	 * @throws InvalidInterfaceException
807
+	 * @throws ReflectionException
808
+	 */
809
+	protected function increaseSoldForDatetimes($qty, array $datetimes = [])
810
+	{
811
+		$datetimes = ! empty($datetimes) ? $datetimes : $this->datetimes();
812
+		foreach ($datetimes as $datetime) {
813
+			$datetime->increaseSold($qty);
814
+		}
815
+	}
816
+
817
+
818
+
819
+	/**
820
+	 * Decrements (subtracts) sold by amount passed by $qty on both the ticket and its related datetimes directly in the
821
+	 * DB and then updates the model objects.
822
+	 * Does not affect the reserved counts.
823
+	 *
824
+	 * @since 4.9.80.p
825
+	 * @param int $qty
826
+	 * @return boolean
827
+	 * @throws EE_Error
828
+	 * @throws InvalidArgumentException
829
+	 * @throws InvalidDataTypeException
830
+	 * @throws InvalidInterfaceException
831
+	 * @throws ReflectionException
832
+	 */
833
+	public function decreaseSold($qty = 1)
834
+	{
835
+		$qty = absint($qty);
836
+		$this->decreaseSoldForDatetimes($qty);
837
+		$success = $this->adjustNumericFieldsInDb(
838
+			[
839
+				'TKT_sold' => $qty * -1
840
+			]
841
+		);
842
+		do_action(
843
+			'AHEE__EE_Ticket__decrease_sold',
844
+			$this,
845
+			$qty,
846
+			$this->sold(),
847
+			$success
848
+		);
849
+		return $success;
850
+	}
851
+
852
+
853
+	/**
854
+	 * Decreases sold on related datetimes
855
+	 *
856
+	 * @since 4.9.80.p
857
+	 * @param int $qty
858
+	 * @param EE_Datetime[] $datetimes
859
+	 * @return void
860
+	 * @throws EE_Error
861
+	 * @throws InvalidArgumentException
862
+	 * @throws InvalidDataTypeException
863
+	 * @throws InvalidInterfaceException
864
+	 * @throws ReflectionException
865
+	 */
866
+	protected function decreaseSoldForDatetimes($qty = 1, array $datetimes = [])
867
+	{
868
+		$datetimes = ! empty($datetimes) ? $datetimes : $this->datetimes();
869
+		if (is_array($datetimes)) {
870
+			foreach ($datetimes as $datetime) {
871
+				if ($datetime instanceof EE_Datetime) {
872
+					$datetime->decreaseSold($qty);
873
+				}
874
+			}
875
+		}
876
+	}
877
+
878
+
879
+	/**
880
+	 * Gets qty of reserved tickets
881
+	 *
882
+	 * @return int
883
+	 * @throws EE_Error
884
+	 */
885
+	public function reserved()
886
+	{
887
+		return $this->get_raw('TKT_reserved');
888
+	}
889
+
890
+
891
+	/**
892
+	 * Sets reserved
893
+	 *
894
+	 * @param int $reserved
895
+	 * @return void
896
+	 * @throws EE_Error
897
+	 */
898
+	public function set_reserved($reserved)
899
+	{
900
+		// reserved can not go below zero
901
+		$reserved = max(0, (int) $reserved);
902
+		$this->set('TKT_reserved', $reserved);
903
+	}
904
+
905
+
906
+	/**
907
+	 * Increments reserved by amount passed by $qty, and persists it immediately to the database.
908
+	 *
909
+	 * @since 4.9.80.p
910
+	 * @param int    $qty
911
+	 * @param string $source
912
+	 * @return bool whether we successfully reserved the ticket or not.
913
+	 * @throws EE_Error
914
+	 * @throws InvalidArgumentException
915
+	 * @throws ReflectionException
916
+	 * @throws InvalidDataTypeException
917
+	 * @throws InvalidInterfaceException
918
+	 */
919
+	public function increaseReserved($qty = 1, $source = 'unknown')
920
+	{
921
+		$qty = absint($qty);
922
+		do_action(
923
+			'AHEE__EE_Ticket__increase_reserved__begin',
924
+			$this,
925
+			$qty,
926
+			$source
927
+		);
928
+		$this->add_extra_meta(EE_Ticket::META_KEY_TICKET_RESERVATIONS, "{$qty} from {$source}");
929
+		$success = false;
930
+		$datetimes_adjusted_successfully = $this->increaseReservedForDatetimes($qty);
931
+		if ($datetimes_adjusted_successfully) {
932
+			$success = $this->incrementFieldConditionallyInDb(
933
+				'TKT_reserved',
934
+				'TKT_sold',
935
+				'TKT_qty',
936
+				$qty
937
+			);
938
+			if (! $success) {
939
+				// The datetimes were successfully bumped, but not the
940
+				// ticket. So we need to manually rollback the datetimes.
941
+				$this->decreaseReservedForDatetimes($qty);
942
+			}
943
+		}
944
+		do_action(
945
+			'AHEE__EE_Ticket__increase_reserved',
946
+			$this,
947
+			$qty,
948
+			$this->reserved(),
949
+			$success
950
+		);
951
+		return $success;
952
+	}
953
+
954
+
955
+	/**
956
+	 * Increases reserved counts on related datetimes
957
+	 *
958
+	 * @since 4.9.80.p
959
+	 * @param int $qty
960
+	 * @param EE_Datetime[] $datetimes
961
+	 * @return boolean indicating success
962
+	 * @throws EE_Error
963
+	 * @throws InvalidArgumentException
964
+	 * @throws InvalidDataTypeException
965
+	 * @throws InvalidInterfaceException
966
+	 * @throws ReflectionException
967
+	 */
968
+	protected function increaseReservedForDatetimes($qty = 1, array $datetimes = [])
969
+	{
970
+		$datetimes = ! empty($datetimes) ? $datetimes : $this->datetimes();
971
+		$datetimes_updated = [];
972
+		$limit_exceeded = false;
973
+		if (is_array($datetimes)) {
974
+			foreach ($datetimes as $datetime) {
975
+				if ($datetime instanceof EE_Datetime) {
976
+					if ($datetime->increaseReserved($qty)) {
977
+						$datetimes_updated[] = $datetime;
978
+					} else {
979
+						$limit_exceeded = true;
980
+						break;
981
+					}
982
+				}
983
+			}
984
+			// If somewhere along the way we detected a datetime whose
985
+			// limit was exceeded, do a manual rollback.
986
+			if ($limit_exceeded) {
987
+				$this->decreaseReservedForDatetimes($qty, $datetimes_updated);
988
+				return false;
989
+			}
990
+		}
991
+		return true;
992
+	}
993
+
994
+
995
+	/**
996
+	 * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
997
+	 *
998
+	 * @since 4.9.80.p
999
+	 * @param int    $qty
1000
+	 * @param bool   $adjust_datetimes
1001
+	 * @param string $source
1002
+	 * @return boolean
1003
+	 * @throws EE_Error
1004
+	 * @throws InvalidArgumentException
1005
+	 * @throws ReflectionException
1006
+	 * @throws InvalidDataTypeException
1007
+	 * @throws InvalidInterfaceException
1008
+	 */
1009
+	public function decreaseReserved($qty = 1, $adjust_datetimes = true, $source = 'unknown')
1010
+	{
1011
+		$qty = absint($qty);
1012
+		$this->add_extra_meta(EE_Ticket::META_KEY_TICKET_RESERVATIONS, "-{$qty} from {$source}");
1013
+		if ($adjust_datetimes) {
1014
+			$this->decreaseReservedForDatetimes($qty);
1015
+		}
1016
+		$success = $this->adjustNumericFieldsInDb(
1017
+			[
1018
+				'TKT_reserved' => $qty * -1
1019
+			]
1020
+		);
1021
+		do_action(
1022
+			'AHEE__EE_Ticket__decrease_reserved',
1023
+			$this,
1024
+			$qty,
1025
+			$this->reserved(),
1026
+			$success
1027
+		);
1028
+		return $success;
1029
+	}
1030
+
1031
+
1032
+	/**
1033
+	 * Decreases the reserved count on the specified datetimes.
1034
+	 *
1035
+	 * @since 4.9.80.p
1036
+	 * @param int           $qty
1037
+	 * @param EE_Datetime[] $datetimes
1038
+	 * @throws EE_Error
1039
+	 * @throws InvalidArgumentException
1040
+	 * @throws ReflectionException
1041
+	 * @throws InvalidDataTypeException
1042
+	 * @throws InvalidInterfaceException
1043
+	 */
1044
+	protected function decreaseReservedForDatetimes($qty = 1, array $datetimes = [])
1045
+	{
1046
+		$datetimes = ! empty($datetimes) ? $datetimes : $this->datetimes();
1047
+		foreach ($datetimes as $datetime) {
1048
+			if ($datetime instanceof EE_Datetime) {
1049
+				$datetime->decreaseReserved($qty);
1050
+			}
1051
+		}
1052
+	}
1053
+
1054
+
1055
+	/**
1056
+	 * Gets ticket quantity
1057
+	 *
1058
+	 * @param string $context     ticket quantity is somewhat subjective depending on the exact information sought
1059
+	 *                            therefore $context can be one of three values: '', 'reg_limit', or 'saleable'
1060
+	 *                            '' (default) quantity is the actual db value for TKT_qty, unaffected by other objects
1061
+	 *                            REG LIMIT: caps qty based on DTT_reg_limit for ALL related datetimes
1062
+	 *                            SALEABLE: also considers datetime sold and returns zero if ANY DTT is sold out, and
1063
+	 *                            is therefore the truest measure of tickets that can be purchased at the moment
1064
+	 * @return int
1065
+	 * @throws EE_Error
1066
+	 */
1067
+	public function qty($context = '')
1068
+	{
1069
+		switch ($context) {
1070
+			case 'reg_limit':
1071
+				return $this->real_quantity_on_ticket();
1072
+			case 'saleable':
1073
+				return $this->real_quantity_on_ticket('saleable');
1074
+			default:
1075
+				return $this->get_raw('TKT_qty');
1076
+		}
1077
+	}
1078
+
1079
+
1080
+	/**
1081
+	 * Gets ticket quantity
1082
+	 *
1083
+	 * @param string $context     ticket quantity is somewhat subjective depending on the exact information sought
1084
+	 *                            therefore $context can be one of two values: 'reg_limit', or 'saleable'
1085
+	 *                            REG LIMIT: caps qty based on DTT_reg_limit for ALL related datetimes
1086
+	 *                            SALEABLE: also considers datetime sold and returns zero if ANY DTT is sold out, and
1087
+	 *                            is therefore the truest measure of tickets that can be purchased at the moment
1088
+	 * @param  int   $DTT_ID      the primary key for a particular datetime.
1089
+	 *                            set to 0 for all related datetimes
1090
+	 * @return int
1091
+	 * @throws EE_Error
1092
+	 */
1093
+	public function real_quantity_on_ticket($context = 'reg_limit', $DTT_ID = 0)
1094
+	{
1095
+		$raw = $this->get_raw('TKT_qty');
1096
+		// return immediately if it's zero
1097
+		if ($raw === 0) {
1098
+			return $raw;
1099
+		}
1100
+		// echo "\n\n<br />Ticket: " . $this->name() . '<br />';
1101
+		// ensure qty doesn't exceed raw value for THIS ticket
1102
+		$qty = min(EE_INF, $raw);
1103
+		// echo "\n . qty: " . $qty . '<br />';
1104
+		// calculate this ticket's total sales and reservations
1105
+		$sold_and_reserved_for_this_ticket = $this->sold() + $this->reserved();
1106
+		// echo "\n . sold: " . $this->sold() . '<br />';
1107
+		// echo "\n . reserved: " . $this->reserved() . '<br />';
1108
+		// echo "\n . sold_and_reserved_for_this_ticket: " . $sold_and_reserved_for_this_ticket . '<br />';
1109
+		// first we need to calculate the maximum number of tickets available for the datetime
1110
+		// do we want data for one datetime or all of them ?
1111
+		$query_params = $DTT_ID ? array(array('DTT_ID' => $DTT_ID)) : array();
1112
+		$datetimes = $this->datetimes($query_params);
1113
+		if (is_array($datetimes) && ! empty($datetimes)) {
1114
+			foreach ($datetimes as $datetime) {
1115
+				if ($datetime instanceof EE_Datetime) {
1116
+					$datetime->refresh_from_db();
1117
+					// echo "\n . . datetime name: " . $datetime->name() . '<br />';
1118
+					// echo "\n . . datetime ID: " . $datetime->ID() . '<br />';
1119
+					// initialize with no restrictions for each datetime
1120
+					// but adjust datetime qty based on datetime reg limit
1121
+					$datetime_qty = min(EE_INF, $datetime->reg_limit());
1122
+					// echo "\n . . . datetime reg_limit: " . $datetime->reg_limit() . '<br />';
1123
+					// echo "\n . . . datetime_qty: " . $datetime_qty . '<br />';
1124
+					// if we want the actual saleable amount, then we need to consider OTHER ticket sales
1125
+					// and reservations for this datetime, that do NOT include sales and reservations
1126
+					// for this ticket (so we add $this->sold() and $this->reserved() back in)
1127
+					if ($context === 'saleable') {
1128
+						$datetime_qty = max(
1129
+							$datetime_qty - $datetime->sold_and_reserved() + $sold_and_reserved_for_this_ticket,
1130
+							0
1131
+						);
1132
+						// echo "\n . . . datetime sold: " . $datetime->sold() . '<br />';
1133
+						// echo "\n . . . datetime reserved: " . $datetime->reserved() . '<br />';
1134
+						// echo "\n . . . datetime sold_and_reserved: " . $datetime->sold_and_reserved() . '<br />';
1135
+						// echo "\n . . . datetime_qty: " . $datetime_qty . '<br />';
1136
+						$datetime_qty = ! $datetime->sold_out() ? $datetime_qty : 0;
1137
+						// echo "\n . . . datetime_qty: " . $datetime_qty . '<br />';
1138
+					}
1139
+					$qty = min($datetime_qty, $qty);
1140
+					// echo "\n . . qty: " . $qty . '<br />';
1141
+				}
1142
+			}
1143
+		}
1144
+		// NOW that we know the  maximum number of tickets available for the datetime
1145
+		// we can finally factor in the details for this specific ticket
1146
+		if ($qty > 0 && $context === 'saleable') {
1147
+			// and subtract the sales for THIS ticket
1148
+			$qty = max($qty - $sold_and_reserved_for_this_ticket, 0);
1149
+			// echo "\n . qty: " . $qty . '<br />';
1150
+		}
1151
+		// echo "\nFINAL QTY: " . $qty . "<br /><br />";
1152
+		return $qty;
1153
+	}
1154
+
1155
+
1156
+	/**
1157
+	 * Sets qty - IMPORTANT!!! Does NOT allow QTY to be set higher than the lowest reg limit of any related datetimes
1158
+	 *
1159
+	 * @param int $qty
1160
+	 * @return void
1161
+	 * @throws EE_Error
1162
+	 */
1163
+	public function set_qty($qty)
1164
+	{
1165
+		$datetimes = $this->datetimes();
1166
+		foreach ($datetimes as $datetime) {
1167
+			if ($datetime instanceof EE_Datetime) {
1168
+				$qty = min($qty, $datetime->reg_limit());
1169
+			}
1170
+		}
1171
+		$this->set('TKT_qty', $qty);
1172
+	}
1173
+
1174
+
1175
+	/**
1176
+	 * Gets uses
1177
+	 *
1178
+	 * @return int
1179
+	 * @throws EE_Error
1180
+	 */
1181
+	public function uses()
1182
+	{
1183
+		return $this->get('TKT_uses');
1184
+	}
1185
+
1186
+
1187
+	/**
1188
+	 * Sets uses
1189
+	 *
1190
+	 * @param int $uses
1191
+	 * @return void
1192
+	 * @throws EE_Error
1193
+	 */
1194
+	public function set_uses($uses)
1195
+	{
1196
+		$this->set('TKT_uses', $uses);
1197
+	}
1198
+
1199
+
1200
+	/**
1201
+	 * returns whether ticket is required or not.
1202
+	 *
1203
+	 * @return boolean
1204
+	 * @throws EE_Error
1205
+	 */
1206
+	public function required()
1207
+	{
1208
+		return $this->get('TKT_required');
1209
+	}
1210
+
1211
+
1212
+	/**
1213
+	 * sets the TKT_required property
1214
+	 *
1215
+	 * @param boolean $required
1216
+	 * @return void
1217
+	 * @throws EE_Error
1218
+	 */
1219
+	public function set_required($required)
1220
+	{
1221
+		$this->set('TKT_required', $required);
1222
+	}
1223
+
1224
+
1225
+	/**
1226
+	 * Gets taxable
1227
+	 *
1228
+	 * @return boolean
1229
+	 * @throws EE_Error
1230
+	 */
1231
+	public function taxable()
1232
+	{
1233
+		return $this->get('TKT_taxable');
1234
+	}
1235
+
1236
+
1237
+	/**
1238
+	 * Sets taxable
1239
+	 *
1240
+	 * @param boolean $taxable
1241
+	 * @return void
1242
+	 * @throws EE_Error
1243
+	 */
1244
+	public function set_taxable($taxable)
1245
+	{
1246
+		$this->set('TKT_taxable', $taxable);
1247
+	}
1248
+
1249
+
1250
+	/**
1251
+	 * Gets is_default
1252
+	 *
1253
+	 * @return boolean
1254
+	 * @throws EE_Error
1255
+	 */
1256
+	public function is_default()
1257
+	{
1258
+		return $this->get('TKT_is_default');
1259
+	}
1260
+
1261
+
1262
+	/**
1263
+	 * Sets is_default
1264
+	 *
1265
+	 * @param boolean $is_default
1266
+	 * @return void
1267
+	 * @throws EE_Error
1268
+	 */
1269
+	public function set_is_default($is_default)
1270
+	{
1271
+		$this->set('TKT_is_default', $is_default);
1272
+	}
1273
+
1274
+
1275
+	/**
1276
+	 * Gets order
1277
+	 *
1278
+	 * @return int
1279
+	 * @throws EE_Error
1280
+	 */
1281
+	public function order()
1282
+	{
1283
+		return $this->get('TKT_order');
1284
+	}
1285
+
1286
+
1287
+	/**
1288
+	 * Sets order
1289
+	 *
1290
+	 * @param int $order
1291
+	 * @return void
1292
+	 * @throws EE_Error
1293
+	 */
1294
+	public function set_order($order)
1295
+	{
1296
+		$this->set('TKT_order', $order);
1297
+	}
1298
+
1299
+
1300
+	/**
1301
+	 * Gets row
1302
+	 *
1303
+	 * @return int
1304
+	 * @throws EE_Error
1305
+	 */
1306
+	public function row()
1307
+	{
1308
+		return $this->get('TKT_row');
1309
+	}
1310
+
1311
+
1312
+	/**
1313
+	 * Sets row
1314
+	 *
1315
+	 * @param int $row
1316
+	 * @return void
1317
+	 * @throws EE_Error
1318
+	 */
1319
+	public function set_row($row)
1320
+	{
1321
+		$this->set('TKT_row', $row);
1322
+	}
1323
+
1324
+
1325
+	/**
1326
+	 * Gets deleted
1327
+	 *
1328
+	 * @return boolean
1329
+	 * @throws EE_Error
1330
+	 */
1331
+	public function deleted()
1332
+	{
1333
+		return $this->get('TKT_deleted');
1334
+	}
1335
+
1336
+
1337
+	/**
1338
+	 * Sets deleted
1339
+	 *
1340
+	 * @param boolean $deleted
1341
+	 * @return void
1342
+	 * @throws EE_Error
1343
+	 */
1344
+	public function set_deleted($deleted)
1345
+	{
1346
+		$this->set('TKT_deleted', $deleted);
1347
+	}
1348
+
1349
+
1350
+	/**
1351
+	 * Gets parent
1352
+	 *
1353
+	 * @return int
1354
+	 * @throws EE_Error
1355
+	 */
1356
+	public function parent_ID()
1357
+	{
1358
+		return $this->get('TKT_parent');
1359
+	}
1360
+
1361
+
1362
+	/**
1363
+	 * Sets parent
1364
+	 *
1365
+	 * @param int $parent
1366
+	 * @return void
1367
+	 * @throws EE_Error
1368
+	 */
1369
+	public function set_parent_ID($parent)
1370
+	{
1371
+		$this->set('TKT_parent', $parent);
1372
+	}
1373
+
1374
+
1375
+	/**
1376
+	 * Gets a string which is handy for showing in gateways etc that describes the ticket.
1377
+	 *
1378
+	 * @return string
1379
+	 * @throws EE_Error
1380
+	 */
1381
+	public function name_and_info()
1382
+	{
1383
+		$times = array();
1384
+		foreach ($this->datetimes() as $datetime) {
1385
+			$times[] = $datetime->start_date_and_time();
1386
+		}
1387
+		return $this->name() . ' @ ' . implode(', ', $times) . ' for ' . $this->pretty_price();
1388
+	}
1389
+
1390
+
1391
+	/**
1392
+	 * Gets name
1393
+	 *
1394
+	 * @return string
1395
+	 * @throws EE_Error
1396
+	 */
1397
+	public function name()
1398
+	{
1399
+		return $this->get('TKT_name');
1400
+	}
1401
+
1402
+
1403
+	/**
1404
+	 * Gets price
1405
+	 *
1406
+	 * @return float
1407
+	 * @throws EE_Error
1408
+	 */
1409
+	public function price()
1410
+	{
1411
+		return $this->get('TKT_price');
1412
+	}
1413
+
1414
+
1415
+	/**
1416
+	 * Gets all the registrations for this ticket
1417
+	 *
1418
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1419
+	 * @return EE_Registration[]|EE_Base_Class[]
1420
+	 * @throws EE_Error
1421
+	 */
1422
+	public function registrations($query_params = array())
1423
+	{
1424
+		return $this->get_many_related('Registration', $query_params);
1425
+	}
1426
+
1427
+
1428
+	/**
1429
+	 * Updates the TKT_sold attribute (and saves) based on the number of APPROVED registrations for this ticket.
1430
+	 *
1431
+	 * @return int
1432
+	 * @throws EE_Error
1433
+	 */
1434
+	public function update_tickets_sold()
1435
+	{
1436
+		$count_regs_for_this_ticket = $this->count_registrations(
1437
+			array(
1438
+				array(
1439
+					'STS_ID'      => EEM_Registration::status_id_approved,
1440
+					'REG_deleted' => 0,
1441
+				),
1442
+			)
1443
+		);
1444
+		$this->set_sold($count_regs_for_this_ticket);
1445
+		$this->save();
1446
+		return $count_regs_for_this_ticket;
1447
+	}
1448
+
1449
+
1450
+	/**
1451
+	 * Counts the registrations for this ticket
1452
+	 *
1453
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1454
+	 * @return int
1455
+	 */
1456
+	public function count_registrations($query_params = array())
1457
+	{
1458
+		return $this->count_related('Registration', $query_params);
1459
+	}
1460
+
1461
+
1462
+	/**
1463
+	 * Implementation for EEI_Has_Icon interface method.
1464
+	 *
1465
+	 * @see EEI_Visual_Representation for comments
1466
+	 * @return string
1467
+	 */
1468
+	public function get_icon()
1469
+	{
1470
+		return '<span class="dashicons dashicons-tickets-alt"></span>';
1471
+	}
1472
+
1473
+
1474
+	/**
1475
+	 * Implementation of the EEI_Event_Relation interface method
1476
+	 *
1477
+	 * @see EEI_Event_Relation for comments
1478
+	 * @return EE_Event
1479
+	 * @throws EE_Error
1480
+	 * @throws UnexpectedEntityException
1481
+	 */
1482
+	public function get_related_event()
1483
+	{
1484
+		// get one datetime to use for getting the event
1485
+		$datetime = $this->first_datetime();
1486
+		if (! $datetime instanceof \EE_Datetime) {
1487
+			throw new UnexpectedEntityException(
1488
+				$datetime,
1489
+				'EE_Datetime',
1490
+				sprintf(
1491
+					__('The ticket (%s) is not associated with any valid datetimes.', 'event_espresso'),
1492
+					$this->name()
1493
+				)
1494
+			);
1495
+		}
1496
+		$event = $datetime->event();
1497
+		if (! $event instanceof \EE_Event) {
1498
+			throw new UnexpectedEntityException(
1499
+				$event,
1500
+				'EE_Event',
1501
+				sprintf(
1502
+					__('The ticket (%s) is not associated with a valid event.', 'event_espresso'),
1503
+					$this->name()
1504
+				)
1505
+			);
1506
+		}
1507
+		return $event;
1508
+	}
1509
+
1510
+
1511
+	/**
1512
+	 * Implementation of the EEI_Event_Relation interface method
1513
+	 *
1514
+	 * @see EEI_Event_Relation for comments
1515
+	 * @return string
1516
+	 * @throws UnexpectedEntityException
1517
+	 * @throws EE_Error
1518
+	 */
1519
+	public function get_event_name()
1520
+	{
1521
+		$event = $this->get_related_event();
1522
+		return $event instanceof EE_Event ? $event->name() : '';
1523
+	}
1524
+
1525
+
1526
+	/**
1527
+	 * Implementation of the EEI_Event_Relation interface method
1528
+	 *
1529
+	 * @see EEI_Event_Relation for comments
1530
+	 * @return int
1531
+	 * @throws UnexpectedEntityException
1532
+	 * @throws EE_Error
1533
+	 */
1534
+	public function get_event_ID()
1535
+	{
1536
+		$event = $this->get_related_event();
1537
+		return $event instanceof EE_Event ? $event->ID() : 0;
1538
+	}
1539
+
1540
+
1541
+	/**
1542
+	 * This simply returns whether a ticket can be permanently deleted or not.
1543
+	 * The criteria for determining this is whether the ticket has any related registrations.
1544
+	 * If there are none then it can be permanently deleted.
1545
+	 *
1546
+	 * @return bool
1547
+	 */
1548
+	public function is_permanently_deleteable()
1549
+	{
1550
+		return $this->count_registrations() === 0;
1551
+	}
1552
+
1553
+
1554
+	/*******************************************************************
1555 1555
      ***********************  DEPRECATED METHODS  **********************
1556 1556
      *******************************************************************/
1557 1557
 
1558 1558
 
1559
-    /**
1560
-     * Increments sold by amount passed by $qty AND decrements the reserved count on both this ticket and its
1561
-     * associated datetimes.
1562
-     *
1563
-     * @deprecated 4.9.80.p
1564
-     * @param int $qty
1565
-     * @return void
1566
-     * @throws EE_Error
1567
-     * @throws InvalidArgumentException
1568
-     * @throws InvalidDataTypeException
1569
-     * @throws InvalidInterfaceException
1570
-     * @throws ReflectionException
1571
-     */
1572
-    public function increase_sold($qty = 1)
1573
-    {
1574
-        EE_Error::doing_it_wrong(
1575
-            __FUNCTION__,
1576
-            esc_html__('Please use EE_Ticket::increaseSold() instead', 'event_espresso'),
1577
-            '4.9.80.p',
1578
-            '5.0.0.p'
1579
-        );
1580
-        $this->increaseSold($qty);
1581
-    }
1582
-
1583
-
1584
-    /**
1585
-     * On each datetime related to this ticket, increases its sold count and decreases its reserved count by $qty.
1586
-     *
1587
-     * @deprecated 4.9.80.p
1588
-     * @param int $qty positive or negative. Positive means to increase sold counts (and decrease reserved counts),
1589
-     *                 Negative means to decreases old counts (and increase reserved counts).
1590
-     * @throws EE_Error
1591
-     * @throws InvalidArgumentException
1592
-     * @throws InvalidDataTypeException
1593
-     * @throws InvalidInterfaceException
1594
-     * @throws ReflectionException
1595
-     */
1596
-    protected function _increase_sold_for_datetimes($qty)
1597
-    {
1598
-        EE_Error::doing_it_wrong(
1599
-            __FUNCTION__,
1600
-            esc_html__('Please use EE_Ticket::increaseSoldForDatetimes() instead', 'event_espresso'),
1601
-            '4.9.80.p',
1602
-            '5.0.0.p'
1603
-        );
1604
-        $this->increaseSoldForDatetimes($qty);
1605
-    }
1606
-
1607
-
1608
-    /**
1609
-     * Decrements (subtracts) sold by amount passed by $qty on both the ticket and its related datetimes directly in the
1610
-     * DB and then updates the model objects.
1611
-     * Does not affect the reserved counts.
1612
-     *
1613
-     * @deprecated 4.9.80.p
1614
-     * @param int $qty
1615
-     * @return void
1616
-     * @throws EE_Error
1617
-     * @throws InvalidArgumentException
1618
-     * @throws InvalidDataTypeException
1619
-     * @throws InvalidInterfaceException
1620
-     * @throws ReflectionException
1621
-     */
1622
-    public function decrease_sold($qty = 1)
1623
-    {
1624
-        EE_Error::doing_it_wrong(
1625
-            __FUNCTION__,
1626
-            esc_html__('Please use EE_Ticket::decreaseSold() instead', 'event_espresso'),
1627
-            '4.9.80.p',
1628
-            '5.0.0.p'
1629
-        );
1630
-        $this->decreaseSold($qty);
1631
-    }
1632
-
1633
-
1634
-    /**
1635
-     * Decreases sold on related datetimes
1636
-     *
1637
-     * @deprecated 4.9.80.p
1638
-     * @param int $qty
1639
-     * @return void
1640
-     * @throws EE_Error
1641
-     * @throws InvalidArgumentException
1642
-     * @throws InvalidDataTypeException
1643
-     * @throws InvalidInterfaceException
1644
-     * @throws ReflectionException
1645
-     */
1646
-    protected function _decrease_sold_for_datetimes($qty = 1)
1647
-    {
1648
-        EE_Error::doing_it_wrong(
1649
-            __FUNCTION__,
1650
-            esc_html__('Please use EE_Ticket::decreaseSoldForDatetimes() instead', 'event_espresso'),
1651
-            '4.9.80.p',
1652
-            '5.0.0.p'
1653
-        );
1654
-        $this->decreaseSoldForDatetimes($qty);
1655
-    }
1656
-
1657
-
1658
-    /**
1659
-     * Increments reserved by amount passed by $qty, and persists it immediately to the database.
1660
-     *
1661
-     * @deprecated 4.9.80.p
1662
-     * @param int    $qty
1663
-     * @param string $source
1664
-     * @return bool whether we successfully reserved the ticket or not.
1665
-     * @throws EE_Error
1666
-     * @throws InvalidArgumentException
1667
-     * @throws ReflectionException
1668
-     * @throws InvalidDataTypeException
1669
-     * @throws InvalidInterfaceException
1670
-     */
1671
-    public function increase_reserved($qty = 1, $source = 'unknown')
1672
-    {
1673
-        EE_Error::doing_it_wrong(
1674
-            __FUNCTION__,
1675
-            esc_html__('Please use EE_Ticket::increaseReserved() instead', 'event_espresso'),
1676
-            '4.9.80.p',
1677
-            '5.0.0.p'
1678
-        );
1679
-        return $this->increaseReserved($qty);
1680
-    }
1681
-
1682
-
1683
-    /**
1684
-     * Increases sold on related datetimes
1685
-     *
1686
-     * @deprecated 4.9.80.p
1687
-     * @param int $qty
1688
-     * @return boolean indicating success
1689
-     * @throws EE_Error
1690
-     * @throws InvalidArgumentException
1691
-     * @throws InvalidDataTypeException
1692
-     * @throws InvalidInterfaceException
1693
-     * @throws ReflectionException
1694
-     */
1695
-    protected function _increase_reserved_for_datetimes($qty = 1)
1696
-    {
1697
-        EE_Error::doing_it_wrong(
1698
-            __FUNCTION__,
1699
-            esc_html__('Please use EE_Ticket::increaseReservedForDatetimes() instead', 'event_espresso'),
1700
-            '4.9.80.p',
1701
-            '5.0.0.p'
1702
-        );
1703
-        return $this->increaseReservedForDatetimes($qty);
1704
-    }
1705
-
1706
-
1707
-    /**
1708
-     * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
1709
-     *
1710
-     * @deprecated 4.9.80.p
1711
-     * @param int    $qty
1712
-     * @param bool   $adjust_datetimes
1713
-     * @param string $source
1714
-     * @return void
1715
-     * @throws EE_Error
1716
-     * @throws InvalidArgumentException
1717
-     * @throws ReflectionException
1718
-     * @throws InvalidDataTypeException
1719
-     * @throws InvalidInterfaceException
1720
-     */
1721
-    public function decrease_reserved($qty = 1, $adjust_datetimes = true, $source = 'unknown')
1722
-    {
1723
-        EE_Error::doing_it_wrong(
1724
-            __FUNCTION__,
1725
-            esc_html__('Please use EE_Ticket::decreaseReserved() instead', 'event_espresso'),
1726
-            '4.9.80.p',
1727
-            '5.0.0.p'
1728
-        );
1729
-        $this->decreaseReserved($qty);
1730
-    }
1731
-
1732
-
1733
-    /**
1734
-     * Decreases reserved on related datetimes
1735
-     *
1736
-     * @deprecated 4.9.80.p
1737
-     * @param int $qty
1738
-     * @return void
1739
-     * @throws EE_Error
1740
-     * @throws InvalidArgumentException
1741
-     * @throws ReflectionException
1742
-     * @throws InvalidDataTypeException
1743
-     * @throws InvalidInterfaceException
1744
-     */
1745
-    protected function _decrease_reserved_for_datetimes($qty = 1)
1746
-    {
1747
-        EE_Error::doing_it_wrong(
1748
-            __FUNCTION__,
1749
-            esc_html__('Please use EE_Ticket::decreaseReservedForDatetimes() instead', 'event_espresso'),
1750
-            '4.9.80.p',
1751
-            '5.0.0.p'
1752
-        );
1753
-        $this->decreaseReservedForDatetimes($qty);
1754
-    }
1559
+	/**
1560
+	 * Increments sold by amount passed by $qty AND decrements the reserved count on both this ticket and its
1561
+	 * associated datetimes.
1562
+	 *
1563
+	 * @deprecated 4.9.80.p
1564
+	 * @param int $qty
1565
+	 * @return void
1566
+	 * @throws EE_Error
1567
+	 * @throws InvalidArgumentException
1568
+	 * @throws InvalidDataTypeException
1569
+	 * @throws InvalidInterfaceException
1570
+	 * @throws ReflectionException
1571
+	 */
1572
+	public function increase_sold($qty = 1)
1573
+	{
1574
+		EE_Error::doing_it_wrong(
1575
+			__FUNCTION__,
1576
+			esc_html__('Please use EE_Ticket::increaseSold() instead', 'event_espresso'),
1577
+			'4.9.80.p',
1578
+			'5.0.0.p'
1579
+		);
1580
+		$this->increaseSold($qty);
1581
+	}
1582
+
1583
+
1584
+	/**
1585
+	 * On each datetime related to this ticket, increases its sold count and decreases its reserved count by $qty.
1586
+	 *
1587
+	 * @deprecated 4.9.80.p
1588
+	 * @param int $qty positive or negative. Positive means to increase sold counts (and decrease reserved counts),
1589
+	 *                 Negative means to decreases old counts (and increase reserved counts).
1590
+	 * @throws EE_Error
1591
+	 * @throws InvalidArgumentException
1592
+	 * @throws InvalidDataTypeException
1593
+	 * @throws InvalidInterfaceException
1594
+	 * @throws ReflectionException
1595
+	 */
1596
+	protected function _increase_sold_for_datetimes($qty)
1597
+	{
1598
+		EE_Error::doing_it_wrong(
1599
+			__FUNCTION__,
1600
+			esc_html__('Please use EE_Ticket::increaseSoldForDatetimes() instead', 'event_espresso'),
1601
+			'4.9.80.p',
1602
+			'5.0.0.p'
1603
+		);
1604
+		$this->increaseSoldForDatetimes($qty);
1605
+	}
1606
+
1607
+
1608
+	/**
1609
+	 * Decrements (subtracts) sold by amount passed by $qty on both the ticket and its related datetimes directly in the
1610
+	 * DB and then updates the model objects.
1611
+	 * Does not affect the reserved counts.
1612
+	 *
1613
+	 * @deprecated 4.9.80.p
1614
+	 * @param int $qty
1615
+	 * @return void
1616
+	 * @throws EE_Error
1617
+	 * @throws InvalidArgumentException
1618
+	 * @throws InvalidDataTypeException
1619
+	 * @throws InvalidInterfaceException
1620
+	 * @throws ReflectionException
1621
+	 */
1622
+	public function decrease_sold($qty = 1)
1623
+	{
1624
+		EE_Error::doing_it_wrong(
1625
+			__FUNCTION__,
1626
+			esc_html__('Please use EE_Ticket::decreaseSold() instead', 'event_espresso'),
1627
+			'4.9.80.p',
1628
+			'5.0.0.p'
1629
+		);
1630
+		$this->decreaseSold($qty);
1631
+	}
1632
+
1633
+
1634
+	/**
1635
+	 * Decreases sold on related datetimes
1636
+	 *
1637
+	 * @deprecated 4.9.80.p
1638
+	 * @param int $qty
1639
+	 * @return void
1640
+	 * @throws EE_Error
1641
+	 * @throws InvalidArgumentException
1642
+	 * @throws InvalidDataTypeException
1643
+	 * @throws InvalidInterfaceException
1644
+	 * @throws ReflectionException
1645
+	 */
1646
+	protected function _decrease_sold_for_datetimes($qty = 1)
1647
+	{
1648
+		EE_Error::doing_it_wrong(
1649
+			__FUNCTION__,
1650
+			esc_html__('Please use EE_Ticket::decreaseSoldForDatetimes() instead', 'event_espresso'),
1651
+			'4.9.80.p',
1652
+			'5.0.0.p'
1653
+		);
1654
+		$this->decreaseSoldForDatetimes($qty);
1655
+	}
1656
+
1657
+
1658
+	/**
1659
+	 * Increments reserved by amount passed by $qty, and persists it immediately to the database.
1660
+	 *
1661
+	 * @deprecated 4.9.80.p
1662
+	 * @param int    $qty
1663
+	 * @param string $source
1664
+	 * @return bool whether we successfully reserved the ticket or not.
1665
+	 * @throws EE_Error
1666
+	 * @throws InvalidArgumentException
1667
+	 * @throws ReflectionException
1668
+	 * @throws InvalidDataTypeException
1669
+	 * @throws InvalidInterfaceException
1670
+	 */
1671
+	public function increase_reserved($qty = 1, $source = 'unknown')
1672
+	{
1673
+		EE_Error::doing_it_wrong(
1674
+			__FUNCTION__,
1675
+			esc_html__('Please use EE_Ticket::increaseReserved() instead', 'event_espresso'),
1676
+			'4.9.80.p',
1677
+			'5.0.0.p'
1678
+		);
1679
+		return $this->increaseReserved($qty);
1680
+	}
1681
+
1682
+
1683
+	/**
1684
+	 * Increases sold on related datetimes
1685
+	 *
1686
+	 * @deprecated 4.9.80.p
1687
+	 * @param int $qty
1688
+	 * @return boolean indicating success
1689
+	 * @throws EE_Error
1690
+	 * @throws InvalidArgumentException
1691
+	 * @throws InvalidDataTypeException
1692
+	 * @throws InvalidInterfaceException
1693
+	 * @throws ReflectionException
1694
+	 */
1695
+	protected function _increase_reserved_for_datetimes($qty = 1)
1696
+	{
1697
+		EE_Error::doing_it_wrong(
1698
+			__FUNCTION__,
1699
+			esc_html__('Please use EE_Ticket::increaseReservedForDatetimes() instead', 'event_espresso'),
1700
+			'4.9.80.p',
1701
+			'5.0.0.p'
1702
+		);
1703
+		return $this->increaseReservedForDatetimes($qty);
1704
+	}
1705
+
1706
+
1707
+	/**
1708
+	 * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
1709
+	 *
1710
+	 * @deprecated 4.9.80.p
1711
+	 * @param int    $qty
1712
+	 * @param bool   $adjust_datetimes
1713
+	 * @param string $source
1714
+	 * @return void
1715
+	 * @throws EE_Error
1716
+	 * @throws InvalidArgumentException
1717
+	 * @throws ReflectionException
1718
+	 * @throws InvalidDataTypeException
1719
+	 * @throws InvalidInterfaceException
1720
+	 */
1721
+	public function decrease_reserved($qty = 1, $adjust_datetimes = true, $source = 'unknown')
1722
+	{
1723
+		EE_Error::doing_it_wrong(
1724
+			__FUNCTION__,
1725
+			esc_html__('Please use EE_Ticket::decreaseReserved() instead', 'event_espresso'),
1726
+			'4.9.80.p',
1727
+			'5.0.0.p'
1728
+		);
1729
+		$this->decreaseReserved($qty);
1730
+	}
1731
+
1732
+
1733
+	/**
1734
+	 * Decreases reserved on related datetimes
1735
+	 *
1736
+	 * @deprecated 4.9.80.p
1737
+	 * @param int $qty
1738
+	 * @return void
1739
+	 * @throws EE_Error
1740
+	 * @throws InvalidArgumentException
1741
+	 * @throws ReflectionException
1742
+	 * @throws InvalidDataTypeException
1743
+	 * @throws InvalidInterfaceException
1744
+	 */
1745
+	protected function _decrease_reserved_for_datetimes($qty = 1)
1746
+	{
1747
+		EE_Error::doing_it_wrong(
1748
+			__FUNCTION__,
1749
+			esc_html__('Please use EE_Ticket::decreaseReservedForDatetimes() instead', 'event_espresso'),
1750
+			'4.9.80.p',
1751
+			'5.0.0.p'
1752
+		);
1753
+		$this->decreaseReservedForDatetimes($qty);
1754
+	}
1755 1755
 }
Please login to merge, or discard this patch.
core/EE_Capabilities.core.php 1 patch
Indentation   +1369 added lines, -1369 removed lines patch added patch discarded remove patch
@@ -14,981 +14,981 @@  discard block
 block discarded – undo
14 14
 final class EE_Capabilities extends EE_Base
15 15
 {
16 16
 
17
-    /**
18
-     * the name of the wp option used to store caps previously initialized
19
-     */
20
-    const option_name = 'ee_caps_initialized';
21
-
22
-    /**
23
-     * instance of EE_Capabilities object
24
-     *
25
-     * @var EE_Capabilities
26
-     */
27
-    private static $_instance;
28
-
29
-
30
-    /**
31
-     * This is a map of caps that correspond to a default WP_Role.
32
-     * Array is indexed by Role and values are ee capabilities.
33
-     *
34
-     * @since 4.5.0
35
-     *
36
-     * @var array
37
-     */
38
-    private $capabilities_map = array();
39
-
40
-    /**
41
-     * This used to hold an array of EE_Meta_Capability_Map objects
42
-     * that define the granular capabilities mapped to for a user depending on context.
43
-     *
44
-     * @var EE_Meta_Capability_Map[]
45
-     */
46
-    private $_meta_caps = array();
47
-
48
-    /**
49
-     * The internal $capabilities_map needs to be initialized before it can be used.
50
-     * This flag tracks whether that has happened or not.
51
-     * But for this to work, we need three states to indicate:
52
-     *      initialization has not occurred at all
53
-     *      initialization has started but is not complete
54
-     *      initialization is complete
55
-     * The reason this is needed is because the addCaps() method
56
-     * normally requires the $capabilities_map to be initialized,
57
-     * but is also used during the initialization process.
58
-     * So:
59
-     *      If initialized === null, init_caps() will be called before any other methods will run.
60
-     *      If initialized === false, then init_caps() is in the process of running it's logic.
61
-     *      If initialized === true, then init_caps() has completed the initialization process.
62
-     *
63
-     * @var boolean|null $initialized
64
-     */
65
-    private $initialized;
66
-
67
-    /**
68
-     * @var boolean $reset
69
-     */
70
-    private $reset = false;
71
-
72
-
73
-    /**
74
-     * singleton method used to instantiate class object
75
-     *
76
-     * @since 4.5.0
77
-     *
78
-     * @return EE_Capabilities
79
-     */
80
-    public static function instance()
81
-    {
82
-        // check if instantiated, and if not do so.
83
-        if (! self::$_instance instanceof EE_Capabilities) {
84
-            self::$_instance = new self();
85
-        }
86
-        return self::$_instance;
87
-    }
88
-
89
-
90
-    /**
91
-     * private constructor
92
-     *
93
-     * @since 4.5.0
94
-     */
95
-    private function __construct()
96
-    {
97
-    }
98
-
99
-
100
-    /**
101
-     * This delays the initialization of the capabilities class until EE_System core is loaded and ready.
102
-     *
103
-     * @param bool $reset allows for resetting the default capabilities saved on roles.  Note that this doesn't
104
-     *                    actually REMOVE any capabilities from existing roles, it just resaves defaults roles and
105
-     *                    ensures that they are up to date.
106
-     *
107
-     * @since 4.5.0
108
-     * @return bool
109
-     * @throws EE_Error
110
-     */
111
-    public function init_caps($reset = false)
112
-    {
113
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
114
-            return false;
115
-        }
116
-        $this->reset = filter_var($reset, FILTER_VALIDATE_BOOLEAN);
117
-        // if reset, then completely delete the cache option and clear the $capabilities_map property.
118
-        if ($this->reset) {
119
-            $this->initialized = null;
120
-            $this->capabilities_map = array();
121
-            delete_option(self::option_name);
122
-        }
123
-        if ($this->initialized === null) {
124
-            $this->initialized = false;
125
-            do_action(
126
-                'AHEE__EE_Capabilities__init_caps__before_initialization',
127
-                $this->reset
128
-            );
129
-            $this->addCaps($this->_init_caps_map());
130
-            $this->_set_meta_caps();
131
-            do_action(
132
-                'AHEE__EE_Capabilities__init_caps__after_initialization',
133
-                $this->capabilities_map
134
-            );
135
-            $this->initialized = true;
136
-        }
137
-        // reset $this->reset so that it's not stuck on true if init_caps() gets called again
138
-        $this->reset = false;
139
-        return true;
140
-    }
141
-
142
-
143
-    /**
144
-     * This sets the meta caps property.
145
-     *
146
-     * @since 4.5.0
147
-     * @return void
148
-     * @throws EE_Error
149
-     */
150
-    private function _set_meta_caps()
151
-    {
152
-        // get default meta caps and filter the returned array
153
-        $this->_meta_caps = apply_filters(
154
-            'FHEE__EE_Capabilities___set_meta_caps__meta_caps',
155
-            $this->_get_default_meta_caps_array()
156
-        );
157
-        // add filter for map_meta_caps but only if models can query.
158
-        if (! has_filter('map_meta_cap', array($this, 'map_meta_caps'))) {
159
-            add_filter('map_meta_cap', array($this, 'map_meta_caps'), 10, 4);
160
-        }
161
-    }
162
-
163
-
164
-    /**
165
-     * This builds and returns the default meta_caps array only once.
166
-     *
167
-     * @since  4.8.28.rc.012
168
-     * @return array
169
-     * @throws EE_Error
170
-     */
171
-    private function _get_default_meta_caps_array()
172
-    {
173
-        static $default_meta_caps = array();
174
-        // make sure we're only ever initializing the default _meta_caps array once if it's empty.
175
-        if (empty($default_meta_caps)) {
176
-            $default_meta_caps = array(
177
-                // edits
178
-                new EE_Meta_Capability_Map_Edit(
179
-                    'ee_edit_event',
180
-                    array('Event', 'ee_edit_published_events', 'ee_edit_others_events', 'ee_edit_private_events')
181
-                ),
182
-                new EE_Meta_Capability_Map_Edit(
183
-                    'ee_edit_venue',
184
-                    array('Venue', 'ee_edit_published_venues', 'ee_edit_others_venues', 'ee_edit_private_venues')
185
-                ),
186
-                new EE_Meta_Capability_Map_Edit(
187
-                    'ee_edit_registration',
188
-                    array('Registration', '', 'ee_edit_others_registrations', '')
189
-                ),
190
-                new EE_Meta_Capability_Map_Edit(
191
-                    'ee_edit_checkin',
192
-                    array('Registration', '', 'ee_edit_others_checkins', '')
193
-                ),
194
-                new EE_Meta_Capability_Map_Messages_Cap(
195
-                    'ee_edit_message',
196
-                    array('Message_Template_Group', '', 'ee_edit_others_messages', 'ee_edit_global_messages')
197
-                ),
198
-                new EE_Meta_Capability_Map_Edit(
199
-                    'ee_edit_default_ticket',
200
-                    array('Ticket', '', 'ee_edit_others_default_tickets', '')
201
-                ),
202
-                new EE_Meta_Capability_Map_Registration_Form_Cap(
203
-                    'ee_edit_question',
204
-                    array('Question', '', '', 'ee_edit_system_questions')
205
-                ),
206
-                new EE_Meta_Capability_Map_Registration_Form_Cap(
207
-                    'ee_edit_question_group',
208
-                    array('Question_Group', '', '', 'ee_edit_system_question_groups')
209
-                ),
210
-                new EE_Meta_Capability_Map_Edit(
211
-                    'ee_edit_payment_method',
212
-                    array('Payment_Method', '', 'ee_edit_others_payment_methods', '')
213
-                ),
214
-                // reads
215
-                new EE_Meta_Capability_Map_Read(
216
-                    'ee_read_event',
217
-                    array('Event', '', 'ee_read_others_events', 'ee_read_private_events')
218
-                ),
219
-                new EE_Meta_Capability_Map_Read(
220
-                    'ee_read_venue',
221
-                    array('Venue', '', 'ee_read_others_venues', 'ee_read_private_venues')
222
-                ),
223
-                new EE_Meta_Capability_Map_Read(
224
-                    'ee_read_registration',
225
-                    array('Registration', '', 'ee_read_others_registrations', '')
226
-                ),
227
-                new EE_Meta_Capability_Map_Read(
228
-                    'ee_read_checkin',
229
-                    array('Registration', '', 'ee_read_others_checkins', '')
230
-                ),
231
-                new EE_Meta_Capability_Map_Messages_Cap(
232
-                    'ee_read_message',
233
-                    array('Message_Template_Group', '', 'ee_read_others_messages', 'ee_read_global_messages')
234
-                ),
235
-                new EE_Meta_Capability_Map_Read(
236
-                    'ee_read_default_ticket',
237
-                    array('Ticket', '', 'ee_read_others_default_tickets', '')
238
-                ),
239
-                new EE_Meta_Capability_Map_Read(
240
-                    'ee_read_payment_method',
241
-                    array('Payment_Method', '', 'ee_read_others_payment_methods', '')
242
-                ),
243
-                // deletes
244
-                new EE_Meta_Capability_Map_Delete(
245
-                    'ee_delete_event',
246
-                    array(
247
-                        'Event',
248
-                        'ee_delete_published_events',
249
-                        'ee_delete_others_events',
250
-                        'ee_delete_private_events',
251
-                    )
252
-                ),
253
-                new EE_Meta_Capability_Map_Delete(
254
-                    'ee_delete_venue',
255
-                    array(
256
-                        'Venue',
257
-                        'ee_delete_published_venues',
258
-                        'ee_delete_others_venues',
259
-                        'ee_delete_private_venues',
260
-                    )
261
-                ),
262
-                new EE_Meta_Capability_Map_Delete(
263
-                    'ee_delete_registration',
264
-                    array('Registration', '', 'ee_delete_others_registrations', '')
265
-                ),
266
-                new EE_Meta_Capability_Map_Delete(
267
-                    'ee_delete_checkin',
268
-                    array('Registration', '', 'ee_delete_others_checkins', '')
269
-                ),
270
-                new EE_Meta_Capability_Map_Messages_Cap(
271
-                    'ee_delete_message',
272
-                    array('Message_Template_Group', '', 'ee_delete_others_messages', 'ee_delete_global_messages')
273
-                ),
274
-                new EE_Meta_Capability_Map_Delete(
275
-                    'ee_delete_default_ticket',
276
-                    array('Ticket', '', 'ee_delete_others_default_tickets', '')
277
-                ),
278
-                new EE_Meta_Capability_Map_Registration_Form_Cap(
279
-                    'ee_delete_question',
280
-                    array('Question', '', '', 'delete_system_questions')
281
-                ),
282
-                new EE_Meta_Capability_Map_Registration_Form_Cap(
283
-                    'ee_delete_question_group',
284
-                    array('Question_Group', '', '', 'delete_system_question_groups')
285
-                ),
286
-                new EE_Meta_Capability_Map_Delete(
287
-                    'ee_delete_payment_method',
288
-                    array('Payment_Method', '', 'ee_delete_others_payment_methods', '')
289
-                ),
290
-            );
291
-        }
292
-        return $default_meta_caps;
293
-    }
294
-
295
-
296
-    /**
297
-     * This is the callback for the wp map_meta_caps() function which allows for ensuring certain caps that act as a
298
-     * "meta" for other caps ( i.e. ee_edit_event is a meta for ee_edit_others_events ) work as expected.
299
-     *
300
-     * The actual logic is carried out by implementer classes in their definition of _map_meta_caps.
301
-     *
302
-     * @since 4.5.0
303
-     * @see   wp-includes/capabilities.php
304
-     *
305
-     * @param array  $caps    actual users capabilities
306
-     * @param string $cap     initial capability name that is being checked (the "map" key)
307
-     * @param int    $user_id The user id
308
-     * @param array  $args    Adds context to the cap. Typically the object ID.
309
-     * @return array actual users capabilities
310
-     * @throws EE_Error
311
-     */
312
-    public function map_meta_caps($caps, $cap, $user_id, $args)
313
-    {
314
-        if (did_action('AHEE__EE_System__load_espresso_addons__complete')) {
315
-            // loop through our _meta_caps array
316
-            foreach ($this->_meta_caps as $meta_map) {
317
-                if (! $meta_map instanceof EE_Meta_Capability_Map) {
318
-                    continue;
319
-                }
320
-                // don't load models if there is no object ID in the args
321
-                if (! empty($args[0])) {
322
-                    $meta_map->ensure_is_model();
323
-                }
324
-                $caps = $meta_map->map_meta_caps($caps, $cap, $user_id, $args);
325
-            }
326
-        }
327
-        return $caps;
328
-    }
329
-
330
-
331
-    /**
332
-     * This sets up and returns the initial capabilities map for Event Espresso
333
-     * Note this array is filtered.
334
-     * It is assumed that all available EE capabilities are assigned to the administrator role.
335
-     *
336
-     * @since 4.5.0
337
-     *
338
-     * @return array
339
-     */
340
-    private function _init_caps_map()
341
-    {
342
-        return apply_filters(
343
-            'FHEE__EE_Capabilities__init_caps_map__caps',
344
-            array(
345
-                'administrator'           => array(
346
-                    // basic access
347
-                    'ee_read_ee',
348
-                    // gateways
349
-                    /**
350
-                     * note that with payment method capabilities, although we've implemented
351
-                     * capability mapping which will be used for accessing payment methods owned by
352
-                     * other users.  This is not fully implemented yet in the payment method ui.
353
-                     * Currently only the "plural" caps are in active use.
354
-                     * (Specific payment method caps are in use as well).
355
-                     **/
356
-                    'ee_manage_gateways',
357
-                    'ee_read_payment_methods',
358
-                    'ee_read_others_payment_methods',
359
-                    'ee_edit_payment_methods',
360
-                    'ee_edit_others_payment_methods',
361
-                    'ee_delete_payment_methods',
362
-                    // events
363
-                    'ee_publish_events',
364
-                    'ee_read_private_events',
365
-                    'ee_read_others_events',
366
-                    'ee_read_events',
367
-                    'ee_edit_events',
368
-                    'ee_edit_published_events',
369
-                    'ee_edit_others_events',
370
-                    'ee_edit_private_events',
371
-                    'ee_delete_published_events',
372
-                    'ee_delete_private_events',
373
-                    'ee_delete_events',
374
-                    'ee_delete_others_events',
375
-                    // event categories
376
-                    'ee_manage_event_categories',
377
-                    'ee_edit_event_category',
378
-                    'ee_delete_event_category',
379
-                    'ee_assign_event_category',
380
-                    // venues
381
-                    'ee_publish_venues',
382
-                    'ee_read_venues',
383
-                    'ee_read_others_venues',
384
-                    'ee_read_private_venues',
385
-                    'ee_edit_venues',
386
-                    'ee_edit_others_venues',
387
-                    'ee_edit_published_venues',
388
-                    'ee_edit_private_venues',
389
-                    'ee_delete_venues',
390
-                    'ee_delete_others_venues',
391
-                    'ee_delete_private_venues',
392
-                    'ee_delete_published_venues',
393
-                    // venue categories
394
-                    'ee_manage_venue_categories',
395
-                    'ee_edit_venue_category',
396
-                    'ee_delete_venue_category',
397
-                    'ee_assign_venue_category',
398
-                    // contacts
399
-                    'ee_read_contacts',
400
-                    'ee_edit_contacts',
401
-                    'ee_delete_contacts',
402
-                    // registrations
403
-                    'ee_read_registrations',
404
-                    'ee_read_others_registrations',
405
-                    'ee_edit_registrations',
406
-                    'ee_edit_others_registrations',
407
-                    'ee_delete_registrations',
408
-                    'ee_delete_others_registrations',
409
-                    // checkins
410
-                    'ee_read_others_checkins',
411
-                    'ee_read_checkins',
412
-                    'ee_edit_checkins',
413
-                    'ee_edit_others_checkins',
414
-                    'ee_delete_checkins',
415
-                    'ee_delete_others_checkins',
416
-                    // transactions && payments
417
-                    'ee_read_transaction',
418
-                    'ee_read_transactions',
419
-                    'ee_edit_payments',
420
-                    'ee_delete_payments',
421
-                    // messages
422
-                    'ee_read_messages',
423
-                    'ee_read_others_messages',
424
-                    'ee_read_global_messages',
425
-                    'ee_edit_global_messages',
426
-                    'ee_edit_messages',
427
-                    'ee_edit_others_messages',
428
-                    'ee_delete_messages',
429
-                    'ee_delete_others_messages',
430
-                    'ee_delete_global_messages',
431
-                    'ee_send_message',
432
-                    // tickets
433
-                    'ee_read_default_tickets',
434
-                    'ee_read_others_default_tickets',
435
-                    'ee_edit_default_tickets',
436
-                    'ee_edit_others_default_tickets',
437
-                    'ee_delete_default_tickets',
438
-                    'ee_delete_others_default_tickets',
439
-                    // prices
440
-                    'ee_edit_default_price',
441
-                    'ee_edit_default_prices',
442
-                    'ee_delete_default_price',
443
-                    'ee_delete_default_prices',
444
-                    'ee_edit_default_price_type',
445
-                    'ee_edit_default_price_types',
446
-                    'ee_delete_default_price_type',
447
-                    'ee_delete_default_price_types',
448
-                    'ee_read_default_prices',
449
-                    'ee_read_default_price_types',
450
-                    // registration form
451
-                    'ee_edit_questions',
452
-                    'ee_edit_system_questions',
453
-                    'ee_read_questions',
454
-                    'ee_delete_questions',
455
-                    'ee_edit_question_groups',
456
-                    'ee_read_question_groups',
457
-                    'ee_edit_system_question_groups',
458
-                    'ee_delete_question_groups',
459
-                    // event_type taxonomy
460
-                    'ee_assign_event_type',
461
-                    'ee_manage_event_types',
462
-                    'ee_edit_event_type',
463
-                    'ee_delete_event_type',
464
-                ),
465
-                'ee_events_administrator' => array(
466
-                    // core wp caps
467
-                    'read',
468
-                    'read_private_pages',
469
-                    'read_private_posts',
470
-                    'edit_users',
471
-                    'edit_posts',
472
-                    'edit_pages',
473
-                    'edit_published_posts',
474
-                    'edit_published_pages',
475
-                    'edit_private_pages',
476
-                    'edit_private_posts',
477
-                    'edit_others_posts',
478
-                    'edit_others_pages',
479
-                    'publish_posts',
480
-                    'publish_pages',
481
-                    'delete_posts',
482
-                    'delete_pages',
483
-                    'delete_private_pages',
484
-                    'delete_private_posts',
485
-                    'delete_published_pages',
486
-                    'delete_published_posts',
487
-                    'delete_others_posts',
488
-                    'delete_others_pages',
489
-                    'manage_categories',
490
-                    'manage_links',
491
-                    'moderate_comments',
492
-                    'unfiltered_html',
493
-                    'upload_files',
494
-                    'export',
495
-                    'import',
496
-                    'list_users',
497
-                    'level_1', // required if user with this role shows up in author dropdowns
498
-                    // basic ee access
499
-                    'ee_read_ee',
500
-                    // events
501
-                    'ee_publish_events',
502
-                    'ee_read_private_events',
503
-                    'ee_read_others_events',
504
-                    'ee_read_event',
505
-                    'ee_read_events',
506
-                    'ee_edit_event',
507
-                    'ee_edit_events',
508
-                    'ee_edit_published_events',
509
-                    'ee_edit_others_events',
510
-                    'ee_edit_private_events',
511
-                    'ee_delete_published_events',
512
-                    'ee_delete_private_events',
513
-                    'ee_delete_event',
514
-                    'ee_delete_events',
515
-                    'ee_delete_others_events',
516
-                    // event categories
517
-                    'ee_manage_event_categories',
518
-                    'ee_edit_event_category',
519
-                    'ee_delete_event_category',
520
-                    'ee_assign_event_category',
521
-                    // venues
522
-                    'ee_publish_venues',
523
-                    'ee_read_venue',
524
-                    'ee_read_venues',
525
-                    'ee_read_others_venues',
526
-                    'ee_read_private_venues',
527
-                    'ee_edit_venue',
528
-                    'ee_edit_venues',
529
-                    'ee_edit_others_venues',
530
-                    'ee_edit_published_venues',
531
-                    'ee_edit_private_venues',
532
-                    'ee_delete_venue',
533
-                    'ee_delete_venues',
534
-                    'ee_delete_others_venues',
535
-                    'ee_delete_private_venues',
536
-                    'ee_delete_published_venues',
537
-                    // venue categories
538
-                    'ee_manage_venue_categories',
539
-                    'ee_edit_venue_category',
540
-                    'ee_delete_venue_category',
541
-                    'ee_assign_venue_category',
542
-                    // contacts
543
-                    'ee_read_contacts',
544
-                    'ee_edit_contacts',
545
-                    'ee_delete_contacts',
546
-                    // registrations
547
-                    'ee_read_registrations',
548
-                    'ee_read_others_registrations',
549
-                    'ee_edit_registration',
550
-                    'ee_edit_registrations',
551
-                    'ee_edit_others_registrations',
552
-                    'ee_delete_registration',
553
-                    'ee_delete_registrations',
554
-                    'ee_delete_others_registrations',
555
-                    // checkins
556
-                    'ee_read_others_checkins',
557
-                    'ee_read_checkins',
558
-                    'ee_edit_checkins',
559
-                    'ee_edit_others_checkins',
560
-                    'ee_delete_checkins',
561
-                    'ee_delete_others_checkins',
562
-                    // transactions && payments
563
-                    'ee_read_transaction',
564
-                    'ee_read_transactions',
565
-                    'ee_edit_payments',
566
-                    'ee_delete_payments',
567
-                    // messages
568
-                    'ee_read_messages',
569
-                    'ee_read_others_messages',
570
-                    'ee_read_global_messages',
571
-                    'ee_edit_global_messages',
572
-                    'ee_edit_messages',
573
-                    'ee_edit_others_messages',
574
-                    'ee_delete_messages',
575
-                    'ee_delete_others_messages',
576
-                    'ee_delete_global_messages',
577
-                    'ee_send_message',
578
-                    // tickets
579
-                    'ee_read_default_tickets',
580
-                    'ee_read_others_default_tickets',
581
-                    'ee_edit_default_tickets',
582
-                    'ee_edit_others_default_tickets',
583
-                    'ee_delete_default_tickets',
584
-                    'ee_delete_others_default_tickets',
585
-                    // prices
586
-                    'ee_edit_default_price',
587
-                    'ee_edit_default_prices',
588
-                    'ee_delete_default_price',
589
-                    'ee_delete_default_prices',
590
-                    'ee_edit_default_price_type',
591
-                    'ee_edit_default_price_types',
592
-                    'ee_delete_default_price_type',
593
-                    'ee_delete_default_price_types',
594
-                    'ee_read_default_prices',
595
-                    'ee_read_default_price_types',
596
-                    // registration form
597
-                    'ee_edit_questions',
598
-                    'ee_edit_system_questions',
599
-                    'ee_read_questions',
600
-                    'ee_delete_questions',
601
-                    'ee_edit_question_groups',
602
-                    'ee_read_question_groups',
603
-                    'ee_edit_system_question_groups',
604
-                    'ee_delete_question_groups',
605
-                    // event_type taxonomy
606
-                    'ee_assign_event_type',
607
-                    'ee_manage_event_types',
608
-                    'ee_edit_event_type',
609
-                    'ee_delete_event_type',
610
-                ),
611
-            )
612
-        );
613
-    }
614
-
615
-
616
-    /**
617
-     * @return bool
618
-     * @throws EE_Error
619
-     */
620
-    private function setupCapabilitiesMap()
621
-    {
622
-        // if the initialization process hasn't even started, then we need to call init_caps()
623
-        if ($this->initialized === null) {
624
-            return $this->init_caps();
625
-        }
626
-        // unless resetting, get caps from db if we haven't already
627
-        $this->capabilities_map = $this->reset || ! empty($this->capabilities_map)
628
-            ? $this->capabilities_map
629
-            : get_option(self::option_name, array());
630
-        return true;
631
-    }
632
-
633
-
634
-    /**
635
-     * @param bool $update
636
-     * @return bool
637
-     */
638
-    private function updateCapabilitiesMap($update = true)
639
-    {
640
-        return $update ? update_option(self::option_name, $this->capabilities_map) : false;
641
-    }
642
-
643
-
644
-    /**
645
-     * Adds capabilities to roles.
646
-     *
647
-     * @since 4.9.42
648
-     * @param array $capabilities_to_add array of capabilities to add, indexed by roles.
649
-     *                                   Note that this should ONLY be called on activation hook
650
-     *                                   otherwise the caps will be added on every request.
651
-     * @return bool
652
-     * @throws \EE_Error
653
-     */
654
-    public function addCaps(array $capabilities_to_add)
655
-    {
656
-        // don't do anything if the capabilities map can not be initialized
657
-        if (! $this->setupCapabilitiesMap()) {
658
-            return false;
659
-        }
660
-        // and filter the array so others can get in on the fun during resets
661
-        $capabilities_to_add = apply_filters(
662
-            'FHEE__EE_Capabilities__addCaps__capabilities_to_add',
663
-            $capabilities_to_add,
664
-            $this->reset,
665
-            $this->capabilities_map
666
-        );
667
-        $update_capabilities_map = false;
668
-        // if not reset, see what caps are new for each role. if they're new, add them.
669
-        foreach ($capabilities_to_add as $role => $caps_for_role) {
670
-            if (is_array($caps_for_role)) {
671
-                foreach ($caps_for_role as $cap) {
672
-                    if (! $this->capHasBeenAddedToRole($role, $cap)
673
-                        && $this->add_cap_to_role($role, $cap, true, false)
674
-                    ) {
675
-                        $update_capabilities_map = true;
676
-                    }
677
-                }
678
-            }
679
-        }
680
-        // now let's just save the cap that has been set but only if there's been a change.
681
-        $updated = $this->updateCapabilitiesMap($update_capabilities_map);
682
-        $this->flushWpUser($updated);
683
-        do_action('AHEE__EE_Capabilities__addCaps__complete', $this->capabilities_map, $updated);
684
-        return $updated;
685
-    }
686
-
687
-
688
-    /**
689
-     * Loops through the capabilities map and removes the role caps specified by the incoming array
690
-     *
691
-     * @param array $caps_map map of capabilities to be removed (indexed by roles)
692
-     * @return bool
693
-     * @throws \EE_Error
694
-     */
695
-    public function removeCaps($caps_map)
696
-    {
697
-        // don't do anything if the capabilities map can not be initialized
698
-        if (! $this->setupCapabilitiesMap()) {
699
-            return false;
700
-        }
701
-        $update_capabilities_map = false;
702
-        foreach ($caps_map as $role => $caps_for_role) {
703
-            if (is_array($caps_for_role)) {
704
-                foreach ($caps_for_role as $cap) {
705
-                    if ($this->capHasBeenAddedToRole($role, $cap)
706
-                        && $this->remove_cap_from_role($role, $cap, false)
707
-                    ) {
708
-                        $update_capabilities_map = true;
709
-                    }
710
-                }
711
-            }
712
-        }
713
-        // maybe resave the caps
714
-        $updated = $this->updateCapabilitiesMap($update_capabilities_map);
715
-        $this->flushWpUser($updated);
716
-        return $updated;
717
-    }
718
-
719
-
720
-    /**
721
-     * This ensures that the WP User object cached on the $current_user global in WP has the latest capabilities from
722
-     * the roles on that user.
723
-     *
724
-     * @param bool $flush Default is to flush the WP_User object.  If false, then this method effectively does nothing.
725
-     */
726
-    private function flushWpUser($flush = true)
727
-    {
728
-        if ($flush) {
729
-            $user = wp_get_current_user();
730
-            if ($user instanceof WP_User) {
731
-                $user->get_role_caps();
732
-            }
733
-        }
734
-    }
735
-
736
-
737
-    /**
738
-     * This method sets a capability on a role.  Note this should only be done on activation, or if you have something
739
-     * specific to prevent the cap from being added on every page load (adding caps are persistent to the db). Note.
740
-     * this is a wrapper for $wp_role->add_cap()
741
-     *
742
-     * @see   wp-includes/capabilities.php
743
-     * @since 4.5.0
744
-     * @param string|WP_Role $role  A WordPress role the capability is being added to
745
-     * @param string         $cap   The capability being added to the role
746
-     * @param bool           $grant Whether to grant access to this cap on this role.
747
-     * @param bool           $update_capabilities_map
748
-     * @return bool
749
-     * @throws \EE_Error
750
-     */
751
-    public function add_cap_to_role($role, $cap, $grant = true, $update_capabilities_map = true)
752
-    {
753
-        // capture incoming value for $role because we may need it to create a new WP_Role
754
-        $orig_role = $role;
755
-        $role = $role instanceof WP_Role ? $role : get_role($role);
756
-        // if the role isn't available then we create it.
757
-        if (! $role instanceof WP_Role) {
758
-            // if a plugin wants to create a specific role name then they should create the role before
759
-            // EE_Capabilities does.  Otherwise this function will create the role name from the slug:
760
-            // - removes any `ee_` namespacing from the start of the slug.
761
-            // - replaces `_` with ` ` (empty space).
762
-            // - sentence case on the resulting string.
763
-            $role_label = ucwords(str_replace(array('ee_', '_'), array('', ' '), $orig_role));
764
-            $role = add_role($orig_role, $role_label);
765
-        }
766
-        if ($role instanceof WP_Role) {
767
-            // don't do anything if the capabilities map can not be initialized
768
-            if (! $this->setupCapabilitiesMap()) {
769
-                return false;
770
-            }
771
-            if (! $this->capHasBeenAddedToRole($role->name, $cap)) {
772
-                $role->add_cap($cap, $grant);
773
-                $this->capabilities_map[ $role->name ][] = $cap;
774
-                $this->updateCapabilitiesMap($update_capabilities_map);
775
-                return true;
776
-            }
777
-        }
778
-        return false;
779
-    }
780
-
781
-
782
-    /**
783
-     * Functions similarly to add_cap_to_role except removes cap from given role.
784
-     * Wrapper for $wp_role->remove_cap()
785
-     *
786
-     * @see   wp-includes/capabilities.php
787
-     * @since 4.5.0
788
-     * @param string|WP_Role $role A WordPress role the capability is being removed from.
789
-     * @param string         $cap  The capability being removed
790
-     * @param bool           $update_capabilities_map
791
-     * @return bool
792
-     * @throws \EE_Error
793
-     */
794
-    public function remove_cap_from_role($role, $cap, $update_capabilities_map = true)
795
-    {
796
-        // don't do anything if the capabilities map can not be initialized
797
-        if (! $this->setupCapabilitiesMap()) {
798
-            return false;
799
-        }
800
-
801
-        $role = $role instanceof WP_Role ? $role : get_role($role);
802
-        if ($role instanceof WP_Role && $index = $this->capHasBeenAddedToRole($role->name, $cap, true)) {
803
-            $role->remove_cap($cap);
804
-            unset($this->capabilities_map[ $role->name ][ $index ]);
805
-            $this->updateCapabilitiesMap($update_capabilities_map);
806
-            return true;
807
-        }
808
-        return false;
809
-    }
810
-
811
-
812
-    /**
813
-     * @param string $role_name
814
-     * @param string $cap
815
-     * @param bool   $get_index
816
-     * @return bool|mixed
817
-     */
818
-    private function capHasBeenAddedToRole($role_name = '', $cap = '', $get_index = false)
819
-    {
820
-        if (isset($this->capabilities_map[ $role_name ])
821
-            && ($index = array_search($cap, $this->capabilities_map[ $role_name ], true)) !== false
822
-        ) {
823
-            return $get_index ? $index : true;
824
-        }
825
-        return false;
826
-    }
827
-
828
-
829
-    /**
830
-     * Wrapper for the native WP current_user_can() method.
831
-     * This is provided as a handy method for a couple things:
832
-     * 1. Using the context string it allows for targeted filtering by addons for a specific check (without having to
833
-     * write those filters wherever current_user_can is called).
834
-     * 2. Explicit passing of $id from a given context ( useful in the cases of map_meta_cap filters )
835
-     *
836
-     * @since 4.5.0
837
-     *
838
-     * @param string $cap     The cap being checked.
839
-     * @param string $context The context where the current_user_can is being called from.
840
-     * @param int    $id      Optional. Id for item where current_user_can is being called from (used in map_meta_cap()
841
-     *                        filters.
842
-     *
843
-     * @return bool  Whether user can or not.
844
-     */
845
-    public function current_user_can($cap, $context, $id = 0)
846
-    {
847
-        // apply filters (both a global on just the cap, and context specific.  Global overrides context specific)
848
-        $filtered_cap = apply_filters('FHEE__EE_Capabilities__current_user_can__cap__' . $context, $cap, $id);
849
-        $filtered_cap = apply_filters(
850
-            'FHEE__EE_Capabilities__current_user_can__cap',
851
-            $filtered_cap,
852
-            $context,
853
-            $cap,
854
-            $id
855
-        );
856
-        return ! empty($id)
857
-            ? current_user_can($filtered_cap, $id)
858
-            : current_user_can($filtered_cap);
859
-    }
860
-
861
-
862
-    /**
863
-     * This is a wrapper for the WP user_can() function and follows the same style as the other wrappers in this class.
864
-     *
865
-     * @param int|WP_User $user    Either the user_id or a WP_User object
866
-     * @param string      $cap     The capability string being checked
867
-     * @param string      $context The context where the user_can is being called from (used in filters).
868
-     * @param int         $id      Optional. Id for item where user_can is being called from ( used in map_meta_cap()
869
-     *                             filters)
870
-     *
871
-     * @return bool Whether user can or not.
872
-     */
873
-    public function user_can($user, $cap, $context, $id = 0)
874
-    {
875
-        // apply filters (both a global on just the cap, and context specific.  Global overrides context specific)
876
-        $filtered_cap = apply_filters('FHEE__EE_Capabilities__user_can__cap__' . $context, $cap, $user, $id);
877
-        $filtered_cap = apply_filters(
878
-            'FHEE__EE_Capabilities__user_can__cap',
879
-            $filtered_cap,
880
-            $context,
881
-            $cap,
882
-            $user,
883
-            $id
884
-        );
885
-        return ! empty($id)
886
-            ? user_can($user, $filtered_cap, $id)
887
-            : user_can($user, $filtered_cap);
888
-    }
889
-
890
-
891
-    /**
892
-     * Wrapper for the native WP current_user_can_for_blog() method.
893
-     * This is provided as a handy method for a couple things:
894
-     * 1. Using the context string it allows for targeted filtering by addons for a specific check (without having to
895
-     * write those filters wherever current_user_can is called).
896
-     * 2. Explicit passing of $id from a given context ( useful in the cases of map_meta_cap filters )
897
-     *
898
-     * @since 4.5.0
899
-     *
900
-     * @param int    $blog_id The blog id that is being checked for.
901
-     * @param string $cap     The cap being checked.
902
-     * @param string $context The context where the current_user_can is being called from.
903
-     * @param int    $id      Optional. Id for item where current_user_can is being called from (used in map_meta_cap()
904
-     *                        filters.
905
-     *
906
-     * @return bool  Whether user can or not.
907
-     */
908
-    public function current_user_can_for_blog($blog_id, $cap, $context, $id = 0)
909
-    {
910
-        $user_can = ! empty($id)
911
-            ? current_user_can_for_blog($blog_id, $cap, $id)
912
-            : current_user_can($blog_id, $cap);
913
-        // apply filters (both a global on just the cap, and context specific.  Global overrides context specific)
914
-        $user_can = apply_filters(
915
-            'FHEE__EE_Capabilities__current_user_can_for_blog__user_can__' . $context,
916
-            $user_can,
917
-            $blog_id,
918
-            $cap,
919
-            $id
920
-        );
921
-        $user_can = apply_filters(
922
-            'FHEE__EE_Capabilities__current_user_can_for_blog__user_can',
923
-            $user_can,
924
-            $context,
925
-            $blog_id,
926
-            $cap,
927
-            $id
928
-        );
929
-        return $user_can;
930
-    }
931
-
932
-
933
-    /**
934
-     * This helper method just returns an array of registered EE capabilities.
935
-     *
936
-     * @since 4.5.0
937
-     * @param string $role If empty then the entire role/capability map is returned.
938
-     *                     Otherwise just the capabilities for the given role are returned.
939
-     * @return array
940
-     * @throws EE_Error
941
-     */
942
-    public function get_ee_capabilities($role = 'administrator')
943
-    {
944
-        if (! $this->initialized) {
945
-            $this->init_caps();
946
-        }
947
-        if (empty($role)) {
948
-            return $this->capabilities_map;
949
-        }
950
-        return isset($this->capabilities_map[ $role ])
951
-            ? $this->capabilities_map[ $role ]
952
-            : array();
953
-    }
954
-
955
-
956
-    /**
957
-     * @deprecated 4.9.42
958
-     * @param bool  $reset      If you need to reset Event Espresso's capabilities,
959
-     *                          then please use the init_caps() method with the "$reset" parameter set to "true"
960
-     * @param array $caps_map   Optional.
961
-     *                          Can be used to send a custom map of roles and capabilities for setting them up.
962
-     *                          Note that this should ONLY be called on activation hook or some other one-time
963
-     *                          task otherwise the caps will be added on every request.
964
-     * @return void
965
-     * @throws EE_Error
966
-     */
967
-    public function init_role_caps($reset = false, $caps_map = array())
968
-    {
969
-        // If this method is called directly and reset is set as 'true',
970
-        // then display a doing it wrong notice, because we want resets to go through init_caps()
971
-        // to guarantee that everything is set up correctly.
972
-        // This prevents the capabilities map getting reset incorrectly by direct calls to this method.
973
-        if ($reset) {
974
-            EE_Error::doing_it_wrong(
975
-                __METHOD__,
976
-                sprintf(
977
-                    esc_html__(
978
-                        'The "%1$s" parameter for the "%2$s" method is deprecated. If you need to reset Event Espresso\'s capabilities, then please use the "%3$s" method with the "%1$s" parameter set to "%4$s".',
979
-                        'event_espresso'
980
-                    ),
981
-                    '$reset',
982
-                    __METHOD__ . '()',
983
-                    'EE_Capabilities::init_caps()',
984
-                    'true'
985
-                ),
986
-                '4.9.42',
987
-                '5.0.0'
988
-            );
989
-        }
990
-        $this->addCaps($caps_map);
991
-    }
17
+	/**
18
+	 * the name of the wp option used to store caps previously initialized
19
+	 */
20
+	const option_name = 'ee_caps_initialized';
21
+
22
+	/**
23
+	 * instance of EE_Capabilities object
24
+	 *
25
+	 * @var EE_Capabilities
26
+	 */
27
+	private static $_instance;
28
+
29
+
30
+	/**
31
+	 * This is a map of caps that correspond to a default WP_Role.
32
+	 * Array is indexed by Role and values are ee capabilities.
33
+	 *
34
+	 * @since 4.5.0
35
+	 *
36
+	 * @var array
37
+	 */
38
+	private $capabilities_map = array();
39
+
40
+	/**
41
+	 * This used to hold an array of EE_Meta_Capability_Map objects
42
+	 * that define the granular capabilities mapped to for a user depending on context.
43
+	 *
44
+	 * @var EE_Meta_Capability_Map[]
45
+	 */
46
+	private $_meta_caps = array();
47
+
48
+	/**
49
+	 * The internal $capabilities_map needs to be initialized before it can be used.
50
+	 * This flag tracks whether that has happened or not.
51
+	 * But for this to work, we need three states to indicate:
52
+	 *      initialization has not occurred at all
53
+	 *      initialization has started but is not complete
54
+	 *      initialization is complete
55
+	 * The reason this is needed is because the addCaps() method
56
+	 * normally requires the $capabilities_map to be initialized,
57
+	 * but is also used during the initialization process.
58
+	 * So:
59
+	 *      If initialized === null, init_caps() will be called before any other methods will run.
60
+	 *      If initialized === false, then init_caps() is in the process of running it's logic.
61
+	 *      If initialized === true, then init_caps() has completed the initialization process.
62
+	 *
63
+	 * @var boolean|null $initialized
64
+	 */
65
+	private $initialized;
66
+
67
+	/**
68
+	 * @var boolean $reset
69
+	 */
70
+	private $reset = false;
71
+
72
+
73
+	/**
74
+	 * singleton method used to instantiate class object
75
+	 *
76
+	 * @since 4.5.0
77
+	 *
78
+	 * @return EE_Capabilities
79
+	 */
80
+	public static function instance()
81
+	{
82
+		// check if instantiated, and if not do so.
83
+		if (! self::$_instance instanceof EE_Capabilities) {
84
+			self::$_instance = new self();
85
+		}
86
+		return self::$_instance;
87
+	}
88
+
89
+
90
+	/**
91
+	 * private constructor
92
+	 *
93
+	 * @since 4.5.0
94
+	 */
95
+	private function __construct()
96
+	{
97
+	}
98
+
99
+
100
+	/**
101
+	 * This delays the initialization of the capabilities class until EE_System core is loaded and ready.
102
+	 *
103
+	 * @param bool $reset allows for resetting the default capabilities saved on roles.  Note that this doesn't
104
+	 *                    actually REMOVE any capabilities from existing roles, it just resaves defaults roles and
105
+	 *                    ensures that they are up to date.
106
+	 *
107
+	 * @since 4.5.0
108
+	 * @return bool
109
+	 * @throws EE_Error
110
+	 */
111
+	public function init_caps($reset = false)
112
+	{
113
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
114
+			return false;
115
+		}
116
+		$this->reset = filter_var($reset, FILTER_VALIDATE_BOOLEAN);
117
+		// if reset, then completely delete the cache option and clear the $capabilities_map property.
118
+		if ($this->reset) {
119
+			$this->initialized = null;
120
+			$this->capabilities_map = array();
121
+			delete_option(self::option_name);
122
+		}
123
+		if ($this->initialized === null) {
124
+			$this->initialized = false;
125
+			do_action(
126
+				'AHEE__EE_Capabilities__init_caps__before_initialization',
127
+				$this->reset
128
+			);
129
+			$this->addCaps($this->_init_caps_map());
130
+			$this->_set_meta_caps();
131
+			do_action(
132
+				'AHEE__EE_Capabilities__init_caps__after_initialization',
133
+				$this->capabilities_map
134
+			);
135
+			$this->initialized = true;
136
+		}
137
+		// reset $this->reset so that it's not stuck on true if init_caps() gets called again
138
+		$this->reset = false;
139
+		return true;
140
+	}
141
+
142
+
143
+	/**
144
+	 * This sets the meta caps property.
145
+	 *
146
+	 * @since 4.5.0
147
+	 * @return void
148
+	 * @throws EE_Error
149
+	 */
150
+	private function _set_meta_caps()
151
+	{
152
+		// get default meta caps and filter the returned array
153
+		$this->_meta_caps = apply_filters(
154
+			'FHEE__EE_Capabilities___set_meta_caps__meta_caps',
155
+			$this->_get_default_meta_caps_array()
156
+		);
157
+		// add filter for map_meta_caps but only if models can query.
158
+		if (! has_filter('map_meta_cap', array($this, 'map_meta_caps'))) {
159
+			add_filter('map_meta_cap', array($this, 'map_meta_caps'), 10, 4);
160
+		}
161
+	}
162
+
163
+
164
+	/**
165
+	 * This builds and returns the default meta_caps array only once.
166
+	 *
167
+	 * @since  4.8.28.rc.012
168
+	 * @return array
169
+	 * @throws EE_Error
170
+	 */
171
+	private function _get_default_meta_caps_array()
172
+	{
173
+		static $default_meta_caps = array();
174
+		// make sure we're only ever initializing the default _meta_caps array once if it's empty.
175
+		if (empty($default_meta_caps)) {
176
+			$default_meta_caps = array(
177
+				// edits
178
+				new EE_Meta_Capability_Map_Edit(
179
+					'ee_edit_event',
180
+					array('Event', 'ee_edit_published_events', 'ee_edit_others_events', 'ee_edit_private_events')
181
+				),
182
+				new EE_Meta_Capability_Map_Edit(
183
+					'ee_edit_venue',
184
+					array('Venue', 'ee_edit_published_venues', 'ee_edit_others_venues', 'ee_edit_private_venues')
185
+				),
186
+				new EE_Meta_Capability_Map_Edit(
187
+					'ee_edit_registration',
188
+					array('Registration', '', 'ee_edit_others_registrations', '')
189
+				),
190
+				new EE_Meta_Capability_Map_Edit(
191
+					'ee_edit_checkin',
192
+					array('Registration', '', 'ee_edit_others_checkins', '')
193
+				),
194
+				new EE_Meta_Capability_Map_Messages_Cap(
195
+					'ee_edit_message',
196
+					array('Message_Template_Group', '', 'ee_edit_others_messages', 'ee_edit_global_messages')
197
+				),
198
+				new EE_Meta_Capability_Map_Edit(
199
+					'ee_edit_default_ticket',
200
+					array('Ticket', '', 'ee_edit_others_default_tickets', '')
201
+				),
202
+				new EE_Meta_Capability_Map_Registration_Form_Cap(
203
+					'ee_edit_question',
204
+					array('Question', '', '', 'ee_edit_system_questions')
205
+				),
206
+				new EE_Meta_Capability_Map_Registration_Form_Cap(
207
+					'ee_edit_question_group',
208
+					array('Question_Group', '', '', 'ee_edit_system_question_groups')
209
+				),
210
+				new EE_Meta_Capability_Map_Edit(
211
+					'ee_edit_payment_method',
212
+					array('Payment_Method', '', 'ee_edit_others_payment_methods', '')
213
+				),
214
+				// reads
215
+				new EE_Meta_Capability_Map_Read(
216
+					'ee_read_event',
217
+					array('Event', '', 'ee_read_others_events', 'ee_read_private_events')
218
+				),
219
+				new EE_Meta_Capability_Map_Read(
220
+					'ee_read_venue',
221
+					array('Venue', '', 'ee_read_others_venues', 'ee_read_private_venues')
222
+				),
223
+				new EE_Meta_Capability_Map_Read(
224
+					'ee_read_registration',
225
+					array('Registration', '', 'ee_read_others_registrations', '')
226
+				),
227
+				new EE_Meta_Capability_Map_Read(
228
+					'ee_read_checkin',
229
+					array('Registration', '', 'ee_read_others_checkins', '')
230
+				),
231
+				new EE_Meta_Capability_Map_Messages_Cap(
232
+					'ee_read_message',
233
+					array('Message_Template_Group', '', 'ee_read_others_messages', 'ee_read_global_messages')
234
+				),
235
+				new EE_Meta_Capability_Map_Read(
236
+					'ee_read_default_ticket',
237
+					array('Ticket', '', 'ee_read_others_default_tickets', '')
238
+				),
239
+				new EE_Meta_Capability_Map_Read(
240
+					'ee_read_payment_method',
241
+					array('Payment_Method', '', 'ee_read_others_payment_methods', '')
242
+				),
243
+				// deletes
244
+				new EE_Meta_Capability_Map_Delete(
245
+					'ee_delete_event',
246
+					array(
247
+						'Event',
248
+						'ee_delete_published_events',
249
+						'ee_delete_others_events',
250
+						'ee_delete_private_events',
251
+					)
252
+				),
253
+				new EE_Meta_Capability_Map_Delete(
254
+					'ee_delete_venue',
255
+					array(
256
+						'Venue',
257
+						'ee_delete_published_venues',
258
+						'ee_delete_others_venues',
259
+						'ee_delete_private_venues',
260
+					)
261
+				),
262
+				new EE_Meta_Capability_Map_Delete(
263
+					'ee_delete_registration',
264
+					array('Registration', '', 'ee_delete_others_registrations', '')
265
+				),
266
+				new EE_Meta_Capability_Map_Delete(
267
+					'ee_delete_checkin',
268
+					array('Registration', '', 'ee_delete_others_checkins', '')
269
+				),
270
+				new EE_Meta_Capability_Map_Messages_Cap(
271
+					'ee_delete_message',
272
+					array('Message_Template_Group', '', 'ee_delete_others_messages', 'ee_delete_global_messages')
273
+				),
274
+				new EE_Meta_Capability_Map_Delete(
275
+					'ee_delete_default_ticket',
276
+					array('Ticket', '', 'ee_delete_others_default_tickets', '')
277
+				),
278
+				new EE_Meta_Capability_Map_Registration_Form_Cap(
279
+					'ee_delete_question',
280
+					array('Question', '', '', 'delete_system_questions')
281
+				),
282
+				new EE_Meta_Capability_Map_Registration_Form_Cap(
283
+					'ee_delete_question_group',
284
+					array('Question_Group', '', '', 'delete_system_question_groups')
285
+				),
286
+				new EE_Meta_Capability_Map_Delete(
287
+					'ee_delete_payment_method',
288
+					array('Payment_Method', '', 'ee_delete_others_payment_methods', '')
289
+				),
290
+			);
291
+		}
292
+		return $default_meta_caps;
293
+	}
294
+
295
+
296
+	/**
297
+	 * This is the callback for the wp map_meta_caps() function which allows for ensuring certain caps that act as a
298
+	 * "meta" for other caps ( i.e. ee_edit_event is a meta for ee_edit_others_events ) work as expected.
299
+	 *
300
+	 * The actual logic is carried out by implementer classes in their definition of _map_meta_caps.
301
+	 *
302
+	 * @since 4.5.0
303
+	 * @see   wp-includes/capabilities.php
304
+	 *
305
+	 * @param array  $caps    actual users capabilities
306
+	 * @param string $cap     initial capability name that is being checked (the "map" key)
307
+	 * @param int    $user_id The user id
308
+	 * @param array  $args    Adds context to the cap. Typically the object ID.
309
+	 * @return array actual users capabilities
310
+	 * @throws EE_Error
311
+	 */
312
+	public function map_meta_caps($caps, $cap, $user_id, $args)
313
+	{
314
+		if (did_action('AHEE__EE_System__load_espresso_addons__complete')) {
315
+			// loop through our _meta_caps array
316
+			foreach ($this->_meta_caps as $meta_map) {
317
+				if (! $meta_map instanceof EE_Meta_Capability_Map) {
318
+					continue;
319
+				}
320
+				// don't load models if there is no object ID in the args
321
+				if (! empty($args[0])) {
322
+					$meta_map->ensure_is_model();
323
+				}
324
+				$caps = $meta_map->map_meta_caps($caps, $cap, $user_id, $args);
325
+			}
326
+		}
327
+		return $caps;
328
+	}
329
+
330
+
331
+	/**
332
+	 * This sets up and returns the initial capabilities map for Event Espresso
333
+	 * Note this array is filtered.
334
+	 * It is assumed that all available EE capabilities are assigned to the administrator role.
335
+	 *
336
+	 * @since 4.5.0
337
+	 *
338
+	 * @return array
339
+	 */
340
+	private function _init_caps_map()
341
+	{
342
+		return apply_filters(
343
+			'FHEE__EE_Capabilities__init_caps_map__caps',
344
+			array(
345
+				'administrator'           => array(
346
+					// basic access
347
+					'ee_read_ee',
348
+					// gateways
349
+					/**
350
+					 * note that with payment method capabilities, although we've implemented
351
+					 * capability mapping which will be used for accessing payment methods owned by
352
+					 * other users.  This is not fully implemented yet in the payment method ui.
353
+					 * Currently only the "plural" caps are in active use.
354
+					 * (Specific payment method caps are in use as well).
355
+					 **/
356
+					'ee_manage_gateways',
357
+					'ee_read_payment_methods',
358
+					'ee_read_others_payment_methods',
359
+					'ee_edit_payment_methods',
360
+					'ee_edit_others_payment_methods',
361
+					'ee_delete_payment_methods',
362
+					// events
363
+					'ee_publish_events',
364
+					'ee_read_private_events',
365
+					'ee_read_others_events',
366
+					'ee_read_events',
367
+					'ee_edit_events',
368
+					'ee_edit_published_events',
369
+					'ee_edit_others_events',
370
+					'ee_edit_private_events',
371
+					'ee_delete_published_events',
372
+					'ee_delete_private_events',
373
+					'ee_delete_events',
374
+					'ee_delete_others_events',
375
+					// event categories
376
+					'ee_manage_event_categories',
377
+					'ee_edit_event_category',
378
+					'ee_delete_event_category',
379
+					'ee_assign_event_category',
380
+					// venues
381
+					'ee_publish_venues',
382
+					'ee_read_venues',
383
+					'ee_read_others_venues',
384
+					'ee_read_private_venues',
385
+					'ee_edit_venues',
386
+					'ee_edit_others_venues',
387
+					'ee_edit_published_venues',
388
+					'ee_edit_private_venues',
389
+					'ee_delete_venues',
390
+					'ee_delete_others_venues',
391
+					'ee_delete_private_venues',
392
+					'ee_delete_published_venues',
393
+					// venue categories
394
+					'ee_manage_venue_categories',
395
+					'ee_edit_venue_category',
396
+					'ee_delete_venue_category',
397
+					'ee_assign_venue_category',
398
+					// contacts
399
+					'ee_read_contacts',
400
+					'ee_edit_contacts',
401
+					'ee_delete_contacts',
402
+					// registrations
403
+					'ee_read_registrations',
404
+					'ee_read_others_registrations',
405
+					'ee_edit_registrations',
406
+					'ee_edit_others_registrations',
407
+					'ee_delete_registrations',
408
+					'ee_delete_others_registrations',
409
+					// checkins
410
+					'ee_read_others_checkins',
411
+					'ee_read_checkins',
412
+					'ee_edit_checkins',
413
+					'ee_edit_others_checkins',
414
+					'ee_delete_checkins',
415
+					'ee_delete_others_checkins',
416
+					// transactions && payments
417
+					'ee_read_transaction',
418
+					'ee_read_transactions',
419
+					'ee_edit_payments',
420
+					'ee_delete_payments',
421
+					// messages
422
+					'ee_read_messages',
423
+					'ee_read_others_messages',
424
+					'ee_read_global_messages',
425
+					'ee_edit_global_messages',
426
+					'ee_edit_messages',
427
+					'ee_edit_others_messages',
428
+					'ee_delete_messages',
429
+					'ee_delete_others_messages',
430
+					'ee_delete_global_messages',
431
+					'ee_send_message',
432
+					// tickets
433
+					'ee_read_default_tickets',
434
+					'ee_read_others_default_tickets',
435
+					'ee_edit_default_tickets',
436
+					'ee_edit_others_default_tickets',
437
+					'ee_delete_default_tickets',
438
+					'ee_delete_others_default_tickets',
439
+					// prices
440
+					'ee_edit_default_price',
441
+					'ee_edit_default_prices',
442
+					'ee_delete_default_price',
443
+					'ee_delete_default_prices',
444
+					'ee_edit_default_price_type',
445
+					'ee_edit_default_price_types',
446
+					'ee_delete_default_price_type',
447
+					'ee_delete_default_price_types',
448
+					'ee_read_default_prices',
449
+					'ee_read_default_price_types',
450
+					// registration form
451
+					'ee_edit_questions',
452
+					'ee_edit_system_questions',
453
+					'ee_read_questions',
454
+					'ee_delete_questions',
455
+					'ee_edit_question_groups',
456
+					'ee_read_question_groups',
457
+					'ee_edit_system_question_groups',
458
+					'ee_delete_question_groups',
459
+					// event_type taxonomy
460
+					'ee_assign_event_type',
461
+					'ee_manage_event_types',
462
+					'ee_edit_event_type',
463
+					'ee_delete_event_type',
464
+				),
465
+				'ee_events_administrator' => array(
466
+					// core wp caps
467
+					'read',
468
+					'read_private_pages',
469
+					'read_private_posts',
470
+					'edit_users',
471
+					'edit_posts',
472
+					'edit_pages',
473
+					'edit_published_posts',
474
+					'edit_published_pages',
475
+					'edit_private_pages',
476
+					'edit_private_posts',
477
+					'edit_others_posts',
478
+					'edit_others_pages',
479
+					'publish_posts',
480
+					'publish_pages',
481
+					'delete_posts',
482
+					'delete_pages',
483
+					'delete_private_pages',
484
+					'delete_private_posts',
485
+					'delete_published_pages',
486
+					'delete_published_posts',
487
+					'delete_others_posts',
488
+					'delete_others_pages',
489
+					'manage_categories',
490
+					'manage_links',
491
+					'moderate_comments',
492
+					'unfiltered_html',
493
+					'upload_files',
494
+					'export',
495
+					'import',
496
+					'list_users',
497
+					'level_1', // required if user with this role shows up in author dropdowns
498
+					// basic ee access
499
+					'ee_read_ee',
500
+					// events
501
+					'ee_publish_events',
502
+					'ee_read_private_events',
503
+					'ee_read_others_events',
504
+					'ee_read_event',
505
+					'ee_read_events',
506
+					'ee_edit_event',
507
+					'ee_edit_events',
508
+					'ee_edit_published_events',
509
+					'ee_edit_others_events',
510
+					'ee_edit_private_events',
511
+					'ee_delete_published_events',
512
+					'ee_delete_private_events',
513
+					'ee_delete_event',
514
+					'ee_delete_events',
515
+					'ee_delete_others_events',
516
+					// event categories
517
+					'ee_manage_event_categories',
518
+					'ee_edit_event_category',
519
+					'ee_delete_event_category',
520
+					'ee_assign_event_category',
521
+					// venues
522
+					'ee_publish_venues',
523
+					'ee_read_venue',
524
+					'ee_read_venues',
525
+					'ee_read_others_venues',
526
+					'ee_read_private_venues',
527
+					'ee_edit_venue',
528
+					'ee_edit_venues',
529
+					'ee_edit_others_venues',
530
+					'ee_edit_published_venues',
531
+					'ee_edit_private_venues',
532
+					'ee_delete_venue',
533
+					'ee_delete_venues',
534
+					'ee_delete_others_venues',
535
+					'ee_delete_private_venues',
536
+					'ee_delete_published_venues',
537
+					// venue categories
538
+					'ee_manage_venue_categories',
539
+					'ee_edit_venue_category',
540
+					'ee_delete_venue_category',
541
+					'ee_assign_venue_category',
542
+					// contacts
543
+					'ee_read_contacts',
544
+					'ee_edit_contacts',
545
+					'ee_delete_contacts',
546
+					// registrations
547
+					'ee_read_registrations',
548
+					'ee_read_others_registrations',
549
+					'ee_edit_registration',
550
+					'ee_edit_registrations',
551
+					'ee_edit_others_registrations',
552
+					'ee_delete_registration',
553
+					'ee_delete_registrations',
554
+					'ee_delete_others_registrations',
555
+					// checkins
556
+					'ee_read_others_checkins',
557
+					'ee_read_checkins',
558
+					'ee_edit_checkins',
559
+					'ee_edit_others_checkins',
560
+					'ee_delete_checkins',
561
+					'ee_delete_others_checkins',
562
+					// transactions && payments
563
+					'ee_read_transaction',
564
+					'ee_read_transactions',
565
+					'ee_edit_payments',
566
+					'ee_delete_payments',
567
+					// messages
568
+					'ee_read_messages',
569
+					'ee_read_others_messages',
570
+					'ee_read_global_messages',
571
+					'ee_edit_global_messages',
572
+					'ee_edit_messages',
573
+					'ee_edit_others_messages',
574
+					'ee_delete_messages',
575
+					'ee_delete_others_messages',
576
+					'ee_delete_global_messages',
577
+					'ee_send_message',
578
+					// tickets
579
+					'ee_read_default_tickets',
580
+					'ee_read_others_default_tickets',
581
+					'ee_edit_default_tickets',
582
+					'ee_edit_others_default_tickets',
583
+					'ee_delete_default_tickets',
584
+					'ee_delete_others_default_tickets',
585
+					// prices
586
+					'ee_edit_default_price',
587
+					'ee_edit_default_prices',
588
+					'ee_delete_default_price',
589
+					'ee_delete_default_prices',
590
+					'ee_edit_default_price_type',
591
+					'ee_edit_default_price_types',
592
+					'ee_delete_default_price_type',
593
+					'ee_delete_default_price_types',
594
+					'ee_read_default_prices',
595
+					'ee_read_default_price_types',
596
+					// registration form
597
+					'ee_edit_questions',
598
+					'ee_edit_system_questions',
599
+					'ee_read_questions',
600
+					'ee_delete_questions',
601
+					'ee_edit_question_groups',
602
+					'ee_read_question_groups',
603
+					'ee_edit_system_question_groups',
604
+					'ee_delete_question_groups',
605
+					// event_type taxonomy
606
+					'ee_assign_event_type',
607
+					'ee_manage_event_types',
608
+					'ee_edit_event_type',
609
+					'ee_delete_event_type',
610
+				),
611
+			)
612
+		);
613
+	}
614
+
615
+
616
+	/**
617
+	 * @return bool
618
+	 * @throws EE_Error
619
+	 */
620
+	private function setupCapabilitiesMap()
621
+	{
622
+		// if the initialization process hasn't even started, then we need to call init_caps()
623
+		if ($this->initialized === null) {
624
+			return $this->init_caps();
625
+		}
626
+		// unless resetting, get caps from db if we haven't already
627
+		$this->capabilities_map = $this->reset || ! empty($this->capabilities_map)
628
+			? $this->capabilities_map
629
+			: get_option(self::option_name, array());
630
+		return true;
631
+	}
632
+
633
+
634
+	/**
635
+	 * @param bool $update
636
+	 * @return bool
637
+	 */
638
+	private function updateCapabilitiesMap($update = true)
639
+	{
640
+		return $update ? update_option(self::option_name, $this->capabilities_map) : false;
641
+	}
642
+
643
+
644
+	/**
645
+	 * Adds capabilities to roles.
646
+	 *
647
+	 * @since 4.9.42
648
+	 * @param array $capabilities_to_add array of capabilities to add, indexed by roles.
649
+	 *                                   Note that this should ONLY be called on activation hook
650
+	 *                                   otherwise the caps will be added on every request.
651
+	 * @return bool
652
+	 * @throws \EE_Error
653
+	 */
654
+	public function addCaps(array $capabilities_to_add)
655
+	{
656
+		// don't do anything if the capabilities map can not be initialized
657
+		if (! $this->setupCapabilitiesMap()) {
658
+			return false;
659
+		}
660
+		// and filter the array so others can get in on the fun during resets
661
+		$capabilities_to_add = apply_filters(
662
+			'FHEE__EE_Capabilities__addCaps__capabilities_to_add',
663
+			$capabilities_to_add,
664
+			$this->reset,
665
+			$this->capabilities_map
666
+		);
667
+		$update_capabilities_map = false;
668
+		// if not reset, see what caps are new for each role. if they're new, add them.
669
+		foreach ($capabilities_to_add as $role => $caps_for_role) {
670
+			if (is_array($caps_for_role)) {
671
+				foreach ($caps_for_role as $cap) {
672
+					if (! $this->capHasBeenAddedToRole($role, $cap)
673
+						&& $this->add_cap_to_role($role, $cap, true, false)
674
+					) {
675
+						$update_capabilities_map = true;
676
+					}
677
+				}
678
+			}
679
+		}
680
+		// now let's just save the cap that has been set but only if there's been a change.
681
+		$updated = $this->updateCapabilitiesMap($update_capabilities_map);
682
+		$this->flushWpUser($updated);
683
+		do_action('AHEE__EE_Capabilities__addCaps__complete', $this->capabilities_map, $updated);
684
+		return $updated;
685
+	}
686
+
687
+
688
+	/**
689
+	 * Loops through the capabilities map and removes the role caps specified by the incoming array
690
+	 *
691
+	 * @param array $caps_map map of capabilities to be removed (indexed by roles)
692
+	 * @return bool
693
+	 * @throws \EE_Error
694
+	 */
695
+	public function removeCaps($caps_map)
696
+	{
697
+		// don't do anything if the capabilities map can not be initialized
698
+		if (! $this->setupCapabilitiesMap()) {
699
+			return false;
700
+		}
701
+		$update_capabilities_map = false;
702
+		foreach ($caps_map as $role => $caps_for_role) {
703
+			if (is_array($caps_for_role)) {
704
+				foreach ($caps_for_role as $cap) {
705
+					if ($this->capHasBeenAddedToRole($role, $cap)
706
+						&& $this->remove_cap_from_role($role, $cap, false)
707
+					) {
708
+						$update_capabilities_map = true;
709
+					}
710
+				}
711
+			}
712
+		}
713
+		// maybe resave the caps
714
+		$updated = $this->updateCapabilitiesMap($update_capabilities_map);
715
+		$this->flushWpUser($updated);
716
+		return $updated;
717
+	}
718
+
719
+
720
+	/**
721
+	 * This ensures that the WP User object cached on the $current_user global in WP has the latest capabilities from
722
+	 * the roles on that user.
723
+	 *
724
+	 * @param bool $flush Default is to flush the WP_User object.  If false, then this method effectively does nothing.
725
+	 */
726
+	private function flushWpUser($flush = true)
727
+	{
728
+		if ($flush) {
729
+			$user = wp_get_current_user();
730
+			if ($user instanceof WP_User) {
731
+				$user->get_role_caps();
732
+			}
733
+		}
734
+	}
735
+
736
+
737
+	/**
738
+	 * This method sets a capability on a role.  Note this should only be done on activation, or if you have something
739
+	 * specific to prevent the cap from being added on every page load (adding caps are persistent to the db). Note.
740
+	 * this is a wrapper for $wp_role->add_cap()
741
+	 *
742
+	 * @see   wp-includes/capabilities.php
743
+	 * @since 4.5.0
744
+	 * @param string|WP_Role $role  A WordPress role the capability is being added to
745
+	 * @param string         $cap   The capability being added to the role
746
+	 * @param bool           $grant Whether to grant access to this cap on this role.
747
+	 * @param bool           $update_capabilities_map
748
+	 * @return bool
749
+	 * @throws \EE_Error
750
+	 */
751
+	public function add_cap_to_role($role, $cap, $grant = true, $update_capabilities_map = true)
752
+	{
753
+		// capture incoming value for $role because we may need it to create a new WP_Role
754
+		$orig_role = $role;
755
+		$role = $role instanceof WP_Role ? $role : get_role($role);
756
+		// if the role isn't available then we create it.
757
+		if (! $role instanceof WP_Role) {
758
+			// if a plugin wants to create a specific role name then they should create the role before
759
+			// EE_Capabilities does.  Otherwise this function will create the role name from the slug:
760
+			// - removes any `ee_` namespacing from the start of the slug.
761
+			// - replaces `_` with ` ` (empty space).
762
+			// - sentence case on the resulting string.
763
+			$role_label = ucwords(str_replace(array('ee_', '_'), array('', ' '), $orig_role));
764
+			$role = add_role($orig_role, $role_label);
765
+		}
766
+		if ($role instanceof WP_Role) {
767
+			// don't do anything if the capabilities map can not be initialized
768
+			if (! $this->setupCapabilitiesMap()) {
769
+				return false;
770
+			}
771
+			if (! $this->capHasBeenAddedToRole($role->name, $cap)) {
772
+				$role->add_cap($cap, $grant);
773
+				$this->capabilities_map[ $role->name ][] = $cap;
774
+				$this->updateCapabilitiesMap($update_capabilities_map);
775
+				return true;
776
+			}
777
+		}
778
+		return false;
779
+	}
780
+
781
+
782
+	/**
783
+	 * Functions similarly to add_cap_to_role except removes cap from given role.
784
+	 * Wrapper for $wp_role->remove_cap()
785
+	 *
786
+	 * @see   wp-includes/capabilities.php
787
+	 * @since 4.5.0
788
+	 * @param string|WP_Role $role A WordPress role the capability is being removed from.
789
+	 * @param string         $cap  The capability being removed
790
+	 * @param bool           $update_capabilities_map
791
+	 * @return bool
792
+	 * @throws \EE_Error
793
+	 */
794
+	public function remove_cap_from_role($role, $cap, $update_capabilities_map = true)
795
+	{
796
+		// don't do anything if the capabilities map can not be initialized
797
+		if (! $this->setupCapabilitiesMap()) {
798
+			return false;
799
+		}
800
+
801
+		$role = $role instanceof WP_Role ? $role : get_role($role);
802
+		if ($role instanceof WP_Role && $index = $this->capHasBeenAddedToRole($role->name, $cap, true)) {
803
+			$role->remove_cap($cap);
804
+			unset($this->capabilities_map[ $role->name ][ $index ]);
805
+			$this->updateCapabilitiesMap($update_capabilities_map);
806
+			return true;
807
+		}
808
+		return false;
809
+	}
810
+
811
+
812
+	/**
813
+	 * @param string $role_name
814
+	 * @param string $cap
815
+	 * @param bool   $get_index
816
+	 * @return bool|mixed
817
+	 */
818
+	private function capHasBeenAddedToRole($role_name = '', $cap = '', $get_index = false)
819
+	{
820
+		if (isset($this->capabilities_map[ $role_name ])
821
+			&& ($index = array_search($cap, $this->capabilities_map[ $role_name ], true)) !== false
822
+		) {
823
+			return $get_index ? $index : true;
824
+		}
825
+		return false;
826
+	}
827
+
828
+
829
+	/**
830
+	 * Wrapper for the native WP current_user_can() method.
831
+	 * This is provided as a handy method for a couple things:
832
+	 * 1. Using the context string it allows for targeted filtering by addons for a specific check (without having to
833
+	 * write those filters wherever current_user_can is called).
834
+	 * 2. Explicit passing of $id from a given context ( useful in the cases of map_meta_cap filters )
835
+	 *
836
+	 * @since 4.5.0
837
+	 *
838
+	 * @param string $cap     The cap being checked.
839
+	 * @param string $context The context where the current_user_can is being called from.
840
+	 * @param int    $id      Optional. Id for item where current_user_can is being called from (used in map_meta_cap()
841
+	 *                        filters.
842
+	 *
843
+	 * @return bool  Whether user can or not.
844
+	 */
845
+	public function current_user_can($cap, $context, $id = 0)
846
+	{
847
+		// apply filters (both a global on just the cap, and context specific.  Global overrides context specific)
848
+		$filtered_cap = apply_filters('FHEE__EE_Capabilities__current_user_can__cap__' . $context, $cap, $id);
849
+		$filtered_cap = apply_filters(
850
+			'FHEE__EE_Capabilities__current_user_can__cap',
851
+			$filtered_cap,
852
+			$context,
853
+			$cap,
854
+			$id
855
+		);
856
+		return ! empty($id)
857
+			? current_user_can($filtered_cap, $id)
858
+			: current_user_can($filtered_cap);
859
+	}
860
+
861
+
862
+	/**
863
+	 * This is a wrapper for the WP user_can() function and follows the same style as the other wrappers in this class.
864
+	 *
865
+	 * @param int|WP_User $user    Either the user_id or a WP_User object
866
+	 * @param string      $cap     The capability string being checked
867
+	 * @param string      $context The context where the user_can is being called from (used in filters).
868
+	 * @param int         $id      Optional. Id for item where user_can is being called from ( used in map_meta_cap()
869
+	 *                             filters)
870
+	 *
871
+	 * @return bool Whether user can or not.
872
+	 */
873
+	public function user_can($user, $cap, $context, $id = 0)
874
+	{
875
+		// apply filters (both a global on just the cap, and context specific.  Global overrides context specific)
876
+		$filtered_cap = apply_filters('FHEE__EE_Capabilities__user_can__cap__' . $context, $cap, $user, $id);
877
+		$filtered_cap = apply_filters(
878
+			'FHEE__EE_Capabilities__user_can__cap',
879
+			$filtered_cap,
880
+			$context,
881
+			$cap,
882
+			$user,
883
+			$id
884
+		);
885
+		return ! empty($id)
886
+			? user_can($user, $filtered_cap, $id)
887
+			: user_can($user, $filtered_cap);
888
+	}
889
+
890
+
891
+	/**
892
+	 * Wrapper for the native WP current_user_can_for_blog() method.
893
+	 * This is provided as a handy method for a couple things:
894
+	 * 1. Using the context string it allows for targeted filtering by addons for a specific check (without having to
895
+	 * write those filters wherever current_user_can is called).
896
+	 * 2. Explicit passing of $id from a given context ( useful in the cases of map_meta_cap filters )
897
+	 *
898
+	 * @since 4.5.0
899
+	 *
900
+	 * @param int    $blog_id The blog id that is being checked for.
901
+	 * @param string $cap     The cap being checked.
902
+	 * @param string $context The context where the current_user_can is being called from.
903
+	 * @param int    $id      Optional. Id for item where current_user_can is being called from (used in map_meta_cap()
904
+	 *                        filters.
905
+	 *
906
+	 * @return bool  Whether user can or not.
907
+	 */
908
+	public function current_user_can_for_blog($blog_id, $cap, $context, $id = 0)
909
+	{
910
+		$user_can = ! empty($id)
911
+			? current_user_can_for_blog($blog_id, $cap, $id)
912
+			: current_user_can($blog_id, $cap);
913
+		// apply filters (both a global on just the cap, and context specific.  Global overrides context specific)
914
+		$user_can = apply_filters(
915
+			'FHEE__EE_Capabilities__current_user_can_for_blog__user_can__' . $context,
916
+			$user_can,
917
+			$blog_id,
918
+			$cap,
919
+			$id
920
+		);
921
+		$user_can = apply_filters(
922
+			'FHEE__EE_Capabilities__current_user_can_for_blog__user_can',
923
+			$user_can,
924
+			$context,
925
+			$blog_id,
926
+			$cap,
927
+			$id
928
+		);
929
+		return $user_can;
930
+	}
931
+
932
+
933
+	/**
934
+	 * This helper method just returns an array of registered EE capabilities.
935
+	 *
936
+	 * @since 4.5.0
937
+	 * @param string $role If empty then the entire role/capability map is returned.
938
+	 *                     Otherwise just the capabilities for the given role are returned.
939
+	 * @return array
940
+	 * @throws EE_Error
941
+	 */
942
+	public function get_ee_capabilities($role = 'administrator')
943
+	{
944
+		if (! $this->initialized) {
945
+			$this->init_caps();
946
+		}
947
+		if (empty($role)) {
948
+			return $this->capabilities_map;
949
+		}
950
+		return isset($this->capabilities_map[ $role ])
951
+			? $this->capabilities_map[ $role ]
952
+			: array();
953
+	}
954
+
955
+
956
+	/**
957
+	 * @deprecated 4.9.42
958
+	 * @param bool  $reset      If you need to reset Event Espresso's capabilities,
959
+	 *                          then please use the init_caps() method with the "$reset" parameter set to "true"
960
+	 * @param array $caps_map   Optional.
961
+	 *                          Can be used to send a custom map of roles and capabilities for setting them up.
962
+	 *                          Note that this should ONLY be called on activation hook or some other one-time
963
+	 *                          task otherwise the caps will be added on every request.
964
+	 * @return void
965
+	 * @throws EE_Error
966
+	 */
967
+	public function init_role_caps($reset = false, $caps_map = array())
968
+	{
969
+		// If this method is called directly and reset is set as 'true',
970
+		// then display a doing it wrong notice, because we want resets to go through init_caps()
971
+		// to guarantee that everything is set up correctly.
972
+		// This prevents the capabilities map getting reset incorrectly by direct calls to this method.
973
+		if ($reset) {
974
+			EE_Error::doing_it_wrong(
975
+				__METHOD__,
976
+				sprintf(
977
+					esc_html__(
978
+						'The "%1$s" parameter for the "%2$s" method is deprecated. If you need to reset Event Espresso\'s capabilities, then please use the "%3$s" method with the "%1$s" parameter set to "%4$s".',
979
+						'event_espresso'
980
+					),
981
+					'$reset',
982
+					__METHOD__ . '()',
983
+					'EE_Capabilities::init_caps()',
984
+					'true'
985
+				),
986
+				'4.9.42',
987
+				'5.0.0'
988
+			);
989
+		}
990
+		$this->addCaps($caps_map);
991
+	}
992 992
 }
993 993
 
994 994
 
@@ -1005,142 +1005,142 @@  discard block
 block discarded – undo
1005 1005
 abstract class EE_Meta_Capability_Map
1006 1006
 {
1007 1007
 
1008
-    public $meta_cap;
1009
-
1010
-    /**
1011
-     * @var EEM_Base
1012
-     */
1013
-    protected $_model;
1014
-
1015
-    protected $_model_name;
1016
-
1017
-    public $published_cap = '';
1018
-
1019
-    public $others_cap = '';
1020
-
1021
-    public $private_cap = '';
1022
-
1023
-
1024
-    /**
1025
-     * constructor.
1026
-     * Receives the setup arguments for the map.
1027
-     *
1028
-     * @since                        4.5.0
1029
-     *
1030
-     * @param string $meta_cap   What meta capability is this mapping.
1031
-     * @param array  $map_values array {
1032
-     *                           //array of values that MUST match a count of 4.  It's okay to send an empty string for
1033
-     *                           capabilities that don't get mapped to.
1034
-     *
1035
-     * @type         $map_values [0] string A string representing the model name. Required.  String's
1036
-     *                               should always be used when Menu Maps are registered via the
1037
-     *                               plugin API as models are not allowed to be instantiated when
1038
-     *                               in maintenance mode 2 (migrations).
1039
-     * @type         $map_values [1] string represents the capability used for published. Optional.
1040
-     * @type         $map_values [2] string represents the capability used for "others". Optional.
1041
-     * @type         $map_values [3] string represents the capability used for private. Optional.
1042
-     *                               }
1043
-     * @throws EE_Error
1044
-     */
1045
-    public function __construct($meta_cap, $map_values)
1046
-    {
1047
-        $this->meta_cap = $meta_cap;
1048
-        // verify there are four args in the $map_values array;
1049
-        if (count($map_values) !== 4) {
1050
-            throw new EE_Error(
1051
-                sprintf(
1052
-                    __(
1053
-                        'Incoming $map_values array should have a count of four values in it.  This is what was given: %s',
1054
-                        'event_espresso'
1055
-                    ),
1056
-                    '<br>' . print_r($map_values, true)
1057
-                )
1058
-            );
1059
-        }
1060
-        // set properties
1061
-        $this->_model = null;
1062
-        $this->_model_name = $map_values[0];
1063
-        $this->published_cap = (string) $map_values[1];
1064
-        $this->others_cap = (string) $map_values[2];
1065
-        $this->private_cap = (string) $map_values[3];
1066
-    }
1067
-
1068
-    /**
1069
-     * Makes it so this object stops filtering caps
1070
-     */
1071
-    public function remove_filters()
1072
-    {
1073
-        remove_filter('map_meta_cap', array($this, 'map_meta_caps'), 10);
1074
-    }
1075
-
1076
-
1077
-    /**
1078
-     * This method ensures that the $model property is converted from the model name string to a proper EEM_Base class
1079
-     *
1080
-     * @since 4.5.0
1081
-     * @throws EE_Error
1082
-     *
1083
-     * @return void
1084
-     */
1085
-    public function ensure_is_model()
1086
-    {
1087
-        // is it already instantiated?
1088
-        if ($this->_model instanceof EEM_Base) {
1089
-            return;
1090
-        }
1091
-        // ensure model name is string
1092
-        $this->_model_name = (string) $this->_model_name;
1093
-        // error proof if the name has EEM in it
1094
-        $this->_model_name = str_replace('EEM', '', $this->_model_name);
1095
-        $this->_model = EE_Registry::instance()->load_model($this->_model_name);
1096
-        if (! $this->_model instanceof EEM_Base) {
1097
-            throw new EE_Error(
1098
-                sprintf(
1099
-                    __(
1100
-                        'This string passed in to %s to represent a EEM_Base model class was not able to be used to instantiate the class.   Please ensure that the string is a match for the EEM_Base model name (not including the EEM_ part). This was given: %s',
1101
-                        'event_espresso'
1102
-                    ),
1103
-                    get_class($this),
1104
-                    $this->_model
1105
-                )
1106
-            );
1107
-        }
1108
-    }
1109
-
1110
-
1111
-    /**
1112
-     *
1113
-     * @see   EE_Meta_Capability_Map::_map_meta_caps() for docs on params.
1114
-     * @since 4.6.x
1115
-     *
1116
-     * @param $caps
1117
-     * @param $cap
1118
-     * @param $user_id
1119
-     * @param $args
1120
-     *
1121
-     * @return array
1122
-     */
1123
-    public function map_meta_caps($caps, $cap, $user_id, $args)
1124
-    {
1125
-        return $this->_map_meta_caps($caps, $cap, $user_id, $args);
1126
-    }
1127
-
1128
-
1129
-    /**
1130
-     * This is the callback for the wp map_meta_caps() function which allows for ensuring certain caps that act as a
1131
-     * "meta" for other caps ( i.e. ee_edit_event is a meta for ee_edit_others_events ) work as expected.
1132
-     *
1133
-     * @since 4.5.0
1134
-     * @see   wp-includes/capabilities.php
1135
-     *
1136
-     * @param array  $caps    actual users capabilities
1137
-     * @param string $cap     initial capability name that is being checked (the "map" key)
1138
-     * @param int    $user_id The user id
1139
-     * @param array  $args    Adds context to the cap. Typically the object ID.
1140
-     *
1141
-     * @return array   actual users capabilities
1142
-     */
1143
-    abstract protected function _map_meta_caps($caps, $cap, $user_id, $args);
1008
+	public $meta_cap;
1009
+
1010
+	/**
1011
+	 * @var EEM_Base
1012
+	 */
1013
+	protected $_model;
1014
+
1015
+	protected $_model_name;
1016
+
1017
+	public $published_cap = '';
1018
+
1019
+	public $others_cap = '';
1020
+
1021
+	public $private_cap = '';
1022
+
1023
+
1024
+	/**
1025
+	 * constructor.
1026
+	 * Receives the setup arguments for the map.
1027
+	 *
1028
+	 * @since                        4.5.0
1029
+	 *
1030
+	 * @param string $meta_cap   What meta capability is this mapping.
1031
+	 * @param array  $map_values array {
1032
+	 *                           //array of values that MUST match a count of 4.  It's okay to send an empty string for
1033
+	 *                           capabilities that don't get mapped to.
1034
+	 *
1035
+	 * @type         $map_values [0] string A string representing the model name. Required.  String's
1036
+	 *                               should always be used when Menu Maps are registered via the
1037
+	 *                               plugin API as models are not allowed to be instantiated when
1038
+	 *                               in maintenance mode 2 (migrations).
1039
+	 * @type         $map_values [1] string represents the capability used for published. Optional.
1040
+	 * @type         $map_values [2] string represents the capability used for "others". Optional.
1041
+	 * @type         $map_values [3] string represents the capability used for private. Optional.
1042
+	 *                               }
1043
+	 * @throws EE_Error
1044
+	 */
1045
+	public function __construct($meta_cap, $map_values)
1046
+	{
1047
+		$this->meta_cap = $meta_cap;
1048
+		// verify there are four args in the $map_values array;
1049
+		if (count($map_values) !== 4) {
1050
+			throw new EE_Error(
1051
+				sprintf(
1052
+					__(
1053
+						'Incoming $map_values array should have a count of four values in it.  This is what was given: %s',
1054
+						'event_espresso'
1055
+					),
1056
+					'<br>' . print_r($map_values, true)
1057
+				)
1058
+			);
1059
+		}
1060
+		// set properties
1061
+		$this->_model = null;
1062
+		$this->_model_name = $map_values[0];
1063
+		$this->published_cap = (string) $map_values[1];
1064
+		$this->others_cap = (string) $map_values[2];
1065
+		$this->private_cap = (string) $map_values[3];
1066
+	}
1067
+
1068
+	/**
1069
+	 * Makes it so this object stops filtering caps
1070
+	 */
1071
+	public function remove_filters()
1072
+	{
1073
+		remove_filter('map_meta_cap', array($this, 'map_meta_caps'), 10);
1074
+	}
1075
+
1076
+
1077
+	/**
1078
+	 * This method ensures that the $model property is converted from the model name string to a proper EEM_Base class
1079
+	 *
1080
+	 * @since 4.5.0
1081
+	 * @throws EE_Error
1082
+	 *
1083
+	 * @return void
1084
+	 */
1085
+	public function ensure_is_model()
1086
+	{
1087
+		// is it already instantiated?
1088
+		if ($this->_model instanceof EEM_Base) {
1089
+			return;
1090
+		}
1091
+		// ensure model name is string
1092
+		$this->_model_name = (string) $this->_model_name;
1093
+		// error proof if the name has EEM in it
1094
+		$this->_model_name = str_replace('EEM', '', $this->_model_name);
1095
+		$this->_model = EE_Registry::instance()->load_model($this->_model_name);
1096
+		if (! $this->_model instanceof EEM_Base) {
1097
+			throw new EE_Error(
1098
+				sprintf(
1099
+					__(
1100
+						'This string passed in to %s to represent a EEM_Base model class was not able to be used to instantiate the class.   Please ensure that the string is a match for the EEM_Base model name (not including the EEM_ part). This was given: %s',
1101
+						'event_espresso'
1102
+					),
1103
+					get_class($this),
1104
+					$this->_model
1105
+				)
1106
+			);
1107
+		}
1108
+	}
1109
+
1110
+
1111
+	/**
1112
+	 *
1113
+	 * @see   EE_Meta_Capability_Map::_map_meta_caps() for docs on params.
1114
+	 * @since 4.6.x
1115
+	 *
1116
+	 * @param $caps
1117
+	 * @param $cap
1118
+	 * @param $user_id
1119
+	 * @param $args
1120
+	 *
1121
+	 * @return array
1122
+	 */
1123
+	public function map_meta_caps($caps, $cap, $user_id, $args)
1124
+	{
1125
+		return $this->_map_meta_caps($caps, $cap, $user_id, $args);
1126
+	}
1127
+
1128
+
1129
+	/**
1130
+	 * This is the callback for the wp map_meta_caps() function which allows for ensuring certain caps that act as a
1131
+	 * "meta" for other caps ( i.e. ee_edit_event is a meta for ee_edit_others_events ) work as expected.
1132
+	 *
1133
+	 * @since 4.5.0
1134
+	 * @see   wp-includes/capabilities.php
1135
+	 *
1136
+	 * @param array  $caps    actual users capabilities
1137
+	 * @param string $cap     initial capability name that is being checked (the "map" key)
1138
+	 * @param int    $user_id The user id
1139
+	 * @param array  $args    Adds context to the cap. Typically the object ID.
1140
+	 *
1141
+	 * @return array   actual users capabilities
1142
+	 */
1143
+	abstract protected function _map_meta_caps($caps, $cap, $user_id, $args);
1144 1144
 }
1145 1145
 
1146 1146
 
@@ -1156,81 +1156,81 @@  discard block
 block discarded – undo
1156 1156
 class EE_Meta_Capability_Map_Edit extends EE_Meta_Capability_Map
1157 1157
 {
1158 1158
 
1159
-    /**
1160
-     * This is the callback for the wp map_meta_caps() function which allows for ensuring certain caps that act as a
1161
-     * "meta" for other caps ( i.e. ee_edit_event is a meta for ee_edit_others_events ) work as expected.
1162
-     *
1163
-     * @since 4.5.0
1164
-     * @see   wp-includes/capabilities.php
1165
-     *
1166
-     * @param array  $caps    actual users capabilities
1167
-     * @param string $cap     initial capability name that is being checked (the "map" key)
1168
-     * @param int    $user_id The user id
1169
-     * @param array  $args    Adds context to the cap. Typically the object ID.
1170
-     *
1171
-     * @return array   actual users capabilities
1172
-     */
1173
-    protected function _map_meta_caps($caps, $cap, $user_id, $args)
1174
-    {
1175
-        // only process if we're checking our mapped_cap
1176
-        if ($cap !== $this->meta_cap) {
1177
-            return $caps;
1178
-        }
1179
-
1180
-        // okay it is a meta cap so let's first remove that cap from the $caps array.
1181
-        if (($key = array_search($cap, $caps)) !== false) {
1182
-            unset($caps[ $key ]);
1183
-        }
1184
-
1185
-        // cast $user_id to int for later explicit comparisons
1186
-        $user_id = (int) $user_id;
1187
-
1188
-        /** @var EE_Base_Class $obj */
1189
-        $obj = ! empty($args[0]) ? $this->_model->get_one_by_ID($args[0]) : null;
1190
-        // if no obj then let's just do cap
1191
-        if (! $obj instanceof EE_Base_Class) {
1192
-            $caps[] = 'do_not_allow';
1193
-            return $caps;
1194
-        }
1195
-        $caps[] = $cap . 's';
1196
-        if ($obj instanceof EE_CPT_Base) {
1197
-            // if the item author is set and the user is the author...
1198
-            if ($obj->wp_user() && $user_id === $obj->wp_user()) {
1199
-                // if obj is published...
1200
-                if ($obj->status() === 'publish') {
1201
-                    $caps[] = $this->published_cap;
1202
-                }
1203
-            } else {
1204
-                // the user is trying to edit someone else's obj
1205
-                if (! empty($this->others_cap)) {
1206
-                    $caps[] = $this->others_cap;
1207
-                }
1208
-                if (! empty($this->published_cap) && $obj->status() === 'publish') {
1209
-                    $caps[] = $this->published_cap;
1210
-                } elseif (! empty($this->private_cap) && $obj->status() === 'private') {
1211
-                    $caps[] = $this->private_cap;
1212
-                }
1213
-            }
1214
-        } else {
1215
-            // not a cpt object so handled differently
1216
-            $has_cap = false;
1217
-            try {
1218
-                $has_cap = method_exists($obj, 'wp_user')
1219
-                           && $obj->wp_user()
1220
-                           && $obj->wp_user() === $user_id;
1221
-            } catch (Exception $e) {
1222
-                if (WP_DEBUG) {
1223
-                    EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1224
-                }
1225
-            }
1226
-            if (! $has_cap) {
1227
-                if (! empty($this->others_cap)) {
1228
-                    $caps[] = $this->others_cap;
1229
-                }
1230
-            }
1231
-        }
1232
-        return $caps;
1233
-    }
1159
+	/**
1160
+	 * This is the callback for the wp map_meta_caps() function which allows for ensuring certain caps that act as a
1161
+	 * "meta" for other caps ( i.e. ee_edit_event is a meta for ee_edit_others_events ) work as expected.
1162
+	 *
1163
+	 * @since 4.5.0
1164
+	 * @see   wp-includes/capabilities.php
1165
+	 *
1166
+	 * @param array  $caps    actual users capabilities
1167
+	 * @param string $cap     initial capability name that is being checked (the "map" key)
1168
+	 * @param int    $user_id The user id
1169
+	 * @param array  $args    Adds context to the cap. Typically the object ID.
1170
+	 *
1171
+	 * @return array   actual users capabilities
1172
+	 */
1173
+	protected function _map_meta_caps($caps, $cap, $user_id, $args)
1174
+	{
1175
+		// only process if we're checking our mapped_cap
1176
+		if ($cap !== $this->meta_cap) {
1177
+			return $caps;
1178
+		}
1179
+
1180
+		// okay it is a meta cap so let's first remove that cap from the $caps array.
1181
+		if (($key = array_search($cap, $caps)) !== false) {
1182
+			unset($caps[ $key ]);
1183
+		}
1184
+
1185
+		// cast $user_id to int for later explicit comparisons
1186
+		$user_id = (int) $user_id;
1187
+
1188
+		/** @var EE_Base_Class $obj */
1189
+		$obj = ! empty($args[0]) ? $this->_model->get_one_by_ID($args[0]) : null;
1190
+		// if no obj then let's just do cap
1191
+		if (! $obj instanceof EE_Base_Class) {
1192
+			$caps[] = 'do_not_allow';
1193
+			return $caps;
1194
+		}
1195
+		$caps[] = $cap . 's';
1196
+		if ($obj instanceof EE_CPT_Base) {
1197
+			// if the item author is set and the user is the author...
1198
+			if ($obj->wp_user() && $user_id === $obj->wp_user()) {
1199
+				// if obj is published...
1200
+				if ($obj->status() === 'publish') {
1201
+					$caps[] = $this->published_cap;
1202
+				}
1203
+			} else {
1204
+				// the user is trying to edit someone else's obj
1205
+				if (! empty($this->others_cap)) {
1206
+					$caps[] = $this->others_cap;
1207
+				}
1208
+				if (! empty($this->published_cap) && $obj->status() === 'publish') {
1209
+					$caps[] = $this->published_cap;
1210
+				} elseif (! empty($this->private_cap) && $obj->status() === 'private') {
1211
+					$caps[] = $this->private_cap;
1212
+				}
1213
+			}
1214
+		} else {
1215
+			// not a cpt object so handled differently
1216
+			$has_cap = false;
1217
+			try {
1218
+				$has_cap = method_exists($obj, 'wp_user')
1219
+						   && $obj->wp_user()
1220
+						   && $obj->wp_user() === $user_id;
1221
+			} catch (Exception $e) {
1222
+				if (WP_DEBUG) {
1223
+					EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1224
+				}
1225
+			}
1226
+			if (! $has_cap) {
1227
+				if (! empty($this->others_cap)) {
1228
+					$caps[] = $this->others_cap;
1229
+				}
1230
+			}
1231
+		}
1232
+		return $caps;
1233
+	}
1234 1234
 }
1235 1235
 
1236 1236
 
@@ -1247,24 +1247,24 @@  discard block
 block discarded – undo
1247 1247
 class EE_Meta_Capability_Map_Delete extends EE_Meta_Capability_Map_Edit
1248 1248
 {
1249 1249
 
1250
-    /**
1251
-     * This is the callback for the wp map_meta_caps() function which allows for ensuring certain caps that act as a
1252
-     * "meta" for other caps ( i.e. ee_edit_event is a meta for ee_edit_others_events ) work as expected.
1253
-     *
1254
-     * @since 4.5.0
1255
-     * @see   wp-includes/capabilities.php
1256
-     *
1257
-     * @param array  $caps    actual users capabilities
1258
-     * @param string $cap     initial capability name that is being checked (the "map" key)
1259
-     * @param int    $user_id The user id
1260
-     * @param array  $args    Adds context to the cap. Typically the object ID.
1261
-     *
1262
-     * @return array   actual users capabilities
1263
-     */
1264
-    protected function _map_meta_caps($caps, $cap, $user_id, $args)
1265
-    {
1266
-        return parent::_map_meta_caps($caps, $cap, $user_id, $args);
1267
-    }
1250
+	/**
1251
+	 * This is the callback for the wp map_meta_caps() function which allows for ensuring certain caps that act as a
1252
+	 * "meta" for other caps ( i.e. ee_edit_event is a meta for ee_edit_others_events ) work as expected.
1253
+	 *
1254
+	 * @since 4.5.0
1255
+	 * @see   wp-includes/capabilities.php
1256
+	 *
1257
+	 * @param array  $caps    actual users capabilities
1258
+	 * @param string $cap     initial capability name that is being checked (the "map" key)
1259
+	 * @param int    $user_id The user id
1260
+	 * @param array  $args    Adds context to the cap. Typically the object ID.
1261
+	 *
1262
+	 * @return array   actual users capabilities
1263
+	 */
1264
+	protected function _map_meta_caps($caps, $cap, $user_id, $args)
1265
+	{
1266
+		return parent::_map_meta_caps($caps, $cap, $user_id, $args);
1267
+	}
1268 1268
 }
1269 1269
 
1270 1270
 
@@ -1280,85 +1280,85 @@  discard block
 block discarded – undo
1280 1280
 class EE_Meta_Capability_Map_Read extends EE_Meta_Capability_Map
1281 1281
 {
1282 1282
 
1283
-    /**
1284
-     * This is the callback for the wp map_meta_caps() function which allows for ensuring certain caps that act as a
1285
-     * "meta" for other caps ( i.e. ee_edit_event is a meta for ee_edit_others_events ) work as expected.
1286
-     *
1287
-     * @since 4.5.0
1288
-     * @see   wp-includes/capabilities.php
1289
-     *
1290
-     * @param array  $caps    actual users capabilities
1291
-     * @param string $cap     initial capability name that is being checked (the "map" key)
1292
-     * @param int    $user_id The user id
1293
-     * @param array  $args    Adds context to the cap. Typically the object ID.
1294
-     *
1295
-     * @return array   actual users capabilities
1296
-     */
1297
-    protected function _map_meta_caps($caps, $cap, $user_id, $args)
1298
-    {
1299
-        // only process if we're checking our mapped cap;
1300
-        if ($cap !== $this->meta_cap) {
1301
-            return $caps;
1302
-        }
1303
-
1304
-        // okay it is a meta cap so let's first remove that cap from the $caps array.
1305
-        if (($key = array_search($cap, $caps)) !== false) {
1306
-            unset($caps[ $key ]);
1307
-        }
1308
-
1309
-        // cast $user_id to int for later explicit comparisons
1310
-        $user_id = (int) $user_id;
1311
-
1312
-        $obj = ! empty($args[0]) ? $this->_model->get_one_by_ID($args[0]) : null;
1313
-        // if no obj then let's just do cap
1314
-        if (! $obj instanceof EE_Base_Class) {
1315
-            $caps[] = 'do_not_allow';
1316
-            return $caps;
1317
-        }
1318
-
1319
-        $caps[] = $cap . 's';
1320
-        if ($obj instanceof EE_CPT_Base) {
1321
-            $status_obj = get_post_status_object($obj->status());
1322
-            if ($status_obj->public) {
1323
-                return $caps;
1324
-            }
1325
-            // if the item author is set and the user is not the author...
1326
-            if ($obj->wp_user() && $obj->wp_user() !== $user_id) {
1327
-                if (! empty($this->others_cap)) {
1328
-                    $caps[] = $this->others_cap;
1329
-                }
1330
-            }
1331
-            // yes this means that if users created the private post, they are able to see it regardless of private cap.
1332
-            if ($status_obj->private
1333
-                && ! empty($this->private_cap)
1334
-                && $obj->wp_user() !== $user_id
1335
-            ) {
1336
-                // the user is trying to view a private object for an object they don't own.
1337
-                $caps[] = $this->private_cap;
1338
-            }
1339
-        } else {
1340
-            // not a cpt object so handled differently
1341
-            $has_cap = false;
1342
-            try {
1343
-                $has_cap = method_exists($obj, 'wp_user')
1344
-                           && $obj->wp_user()
1345
-                           && $obj->wp_user() === $user_id;
1346
-            } catch (Exception $e) {
1347
-                if (WP_DEBUG) {
1348
-                    EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1349
-                }
1350
-            }
1351
-            if (! $has_cap) {
1352
-                if (! empty($this->private_cap)) {
1353
-                    $caps[] = $this->private_cap;
1354
-                }
1355
-                if (! empty($this->others_cap)) {
1356
-                    $caps[] = $this->others_cap;
1357
-                }
1358
-            }
1359
-        }
1360
-        return $caps;
1361
-    }
1283
+	/**
1284
+	 * This is the callback for the wp map_meta_caps() function which allows for ensuring certain caps that act as a
1285
+	 * "meta" for other caps ( i.e. ee_edit_event is a meta for ee_edit_others_events ) work as expected.
1286
+	 *
1287
+	 * @since 4.5.0
1288
+	 * @see   wp-includes/capabilities.php
1289
+	 *
1290
+	 * @param array  $caps    actual users capabilities
1291
+	 * @param string $cap     initial capability name that is being checked (the "map" key)
1292
+	 * @param int    $user_id The user id
1293
+	 * @param array  $args    Adds context to the cap. Typically the object ID.
1294
+	 *
1295
+	 * @return array   actual users capabilities
1296
+	 */
1297
+	protected function _map_meta_caps($caps, $cap, $user_id, $args)
1298
+	{
1299
+		// only process if we're checking our mapped cap;
1300
+		if ($cap !== $this->meta_cap) {
1301
+			return $caps;
1302
+		}
1303
+
1304
+		// okay it is a meta cap so let's first remove that cap from the $caps array.
1305
+		if (($key = array_search($cap, $caps)) !== false) {
1306
+			unset($caps[ $key ]);
1307
+		}
1308
+
1309
+		// cast $user_id to int for later explicit comparisons
1310
+		$user_id = (int) $user_id;
1311
+
1312
+		$obj = ! empty($args[0]) ? $this->_model->get_one_by_ID($args[0]) : null;
1313
+		// if no obj then let's just do cap
1314
+		if (! $obj instanceof EE_Base_Class) {
1315
+			$caps[] = 'do_not_allow';
1316
+			return $caps;
1317
+		}
1318
+
1319
+		$caps[] = $cap . 's';
1320
+		if ($obj instanceof EE_CPT_Base) {
1321
+			$status_obj = get_post_status_object($obj->status());
1322
+			if ($status_obj->public) {
1323
+				return $caps;
1324
+			}
1325
+			// if the item author is set and the user is not the author...
1326
+			if ($obj->wp_user() && $obj->wp_user() !== $user_id) {
1327
+				if (! empty($this->others_cap)) {
1328
+					$caps[] = $this->others_cap;
1329
+				}
1330
+			}
1331
+			// yes this means that if users created the private post, they are able to see it regardless of private cap.
1332
+			if ($status_obj->private
1333
+				&& ! empty($this->private_cap)
1334
+				&& $obj->wp_user() !== $user_id
1335
+			) {
1336
+				// the user is trying to view a private object for an object they don't own.
1337
+				$caps[] = $this->private_cap;
1338
+			}
1339
+		} else {
1340
+			// not a cpt object so handled differently
1341
+			$has_cap = false;
1342
+			try {
1343
+				$has_cap = method_exists($obj, 'wp_user')
1344
+						   && $obj->wp_user()
1345
+						   && $obj->wp_user() === $user_id;
1346
+			} catch (Exception $e) {
1347
+				if (WP_DEBUG) {
1348
+					EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1349
+				}
1350
+			}
1351
+			if (! $has_cap) {
1352
+				if (! empty($this->private_cap)) {
1353
+					$caps[] = $this->private_cap;
1354
+				}
1355
+				if (! empty($this->others_cap)) {
1356
+					$caps[] = $this->others_cap;
1357
+				}
1358
+			}
1359
+		}
1360
+		return $caps;
1361
+	}
1362 1362
 }
1363 1363
 
1364 1364
 
@@ -1375,56 +1375,56 @@  discard block
 block discarded – undo
1375 1375
 class EE_Meta_Capability_Map_Messages_Cap extends EE_Meta_Capability_Map
1376 1376
 {
1377 1377
 
1378
-    /**
1379
-     * This is the callback for the wp map_meta_caps() function which allows for ensuring certain caps that act as a
1380
-     * "meta" for other caps ( i.e. ee_edit_event is a meta for ee_edit_others_events ) work as expected.
1381
-     *
1382
-     * @since 4.5.0
1383
-     * @see   wp-includes/capabilities.php
1384
-     *
1385
-     * @param array  $caps    actual users capabilities
1386
-     * @param string $cap     initial capability name that is being checked (the "map" key)
1387
-     * @param int    $user_id The user id
1388
-     * @param array  $args    Adds context to the cap. Typically the object ID.
1389
-     *
1390
-     * @return array   actual users capabilities
1391
-     */
1392
-    protected function _map_meta_caps($caps, $cap, $user_id, $args)
1393
-    {
1394
-        // only process if we're checking our mapped_cap
1395
-        if ($cap !== $this->meta_cap) {
1396
-            return $caps;
1397
-        }
1398
-
1399
-        // okay it is a meta cap so let's first remove that cap from the $caps array.
1400
-        if (($key = array_search($cap, $caps)) !== false) {
1401
-            unset($caps[ $key ]);
1402
-        }
1403
-
1404
-        // cast $user_id to int for later explicit comparisons
1405
-        $user_id = (int) $user_id;
1406
-
1407
-        $obj = ! empty($args[0]) ? $this->_model->get_one_by_ID($args[0]) : null;
1408
-        // if no obj then let's just do cap
1409
-        if (! $obj instanceof EE_Message_Template_Group) {
1410
-            $caps[] = 'do_not_allow';
1411
-            return $caps;
1412
-        }
1413
-        $caps[] = $cap . 's';
1414
-        $is_global = $obj->is_global();
1415
-        if ($obj->wp_user() && $obj->wp_user() === $user_id) {
1416
-            if ($is_global) {
1417
-                $caps[] = $this->private_cap;
1418
-            }
1419
-        } else {
1420
-            if ($is_global) {
1421
-                $caps[] = $this->private_cap;
1422
-            } else {
1423
-                $caps[] = $this->others_cap;
1424
-            }
1425
-        }
1426
-        return $caps;
1427
-    }
1378
+	/**
1379
+	 * This is the callback for the wp map_meta_caps() function which allows for ensuring certain caps that act as a
1380
+	 * "meta" for other caps ( i.e. ee_edit_event is a meta for ee_edit_others_events ) work as expected.
1381
+	 *
1382
+	 * @since 4.5.0
1383
+	 * @see   wp-includes/capabilities.php
1384
+	 *
1385
+	 * @param array  $caps    actual users capabilities
1386
+	 * @param string $cap     initial capability name that is being checked (the "map" key)
1387
+	 * @param int    $user_id The user id
1388
+	 * @param array  $args    Adds context to the cap. Typically the object ID.
1389
+	 *
1390
+	 * @return array   actual users capabilities
1391
+	 */
1392
+	protected function _map_meta_caps($caps, $cap, $user_id, $args)
1393
+	{
1394
+		// only process if we're checking our mapped_cap
1395
+		if ($cap !== $this->meta_cap) {
1396
+			return $caps;
1397
+		}
1398
+
1399
+		// okay it is a meta cap so let's first remove that cap from the $caps array.
1400
+		if (($key = array_search($cap, $caps)) !== false) {
1401
+			unset($caps[ $key ]);
1402
+		}
1403
+
1404
+		// cast $user_id to int for later explicit comparisons
1405
+		$user_id = (int) $user_id;
1406
+
1407
+		$obj = ! empty($args[0]) ? $this->_model->get_one_by_ID($args[0]) : null;
1408
+		// if no obj then let's just do cap
1409
+		if (! $obj instanceof EE_Message_Template_Group) {
1410
+			$caps[] = 'do_not_allow';
1411
+			return $caps;
1412
+		}
1413
+		$caps[] = $cap . 's';
1414
+		$is_global = $obj->is_global();
1415
+		if ($obj->wp_user() && $obj->wp_user() === $user_id) {
1416
+			if ($is_global) {
1417
+				$caps[] = $this->private_cap;
1418
+			}
1419
+		} else {
1420
+			if ($is_global) {
1421
+				$caps[] = $this->private_cap;
1422
+			} else {
1423
+				$caps[] = $this->others_cap;
1424
+			}
1425
+		}
1426
+		return $caps;
1427
+	}
1428 1428
 }
1429 1429
 
1430 1430
 
@@ -1441,40 +1441,40 @@  discard block
 block discarded – undo
1441 1441
 class EE_Meta_Capability_Map_Registration_Form_Cap extends EE_Meta_Capability_Map
1442 1442
 {
1443 1443
 
1444
-    /**
1445
-     * This is the callback for the wp map_meta_caps() function which allows for ensuring certain caps that act as a
1446
-     * "meta" for other caps ( i.e. ee_edit_event is a meta for ee_edit_others_events ) work as expected.
1447
-     *
1448
-     * @since 4.5.0
1449
-     * @see   wp-includes/capabilities.php
1450
-     * @param array  $caps    actual users capabilities
1451
-     * @param string $cap     initial capability name that is being checked (the "map" key)
1452
-     * @param int    $user_id The user id
1453
-     * @param array  $args    Adds context to the cap. Typically the object ID.
1454
-     * @return array   actual users capabilities
1455
-     */
1456
-    protected function _map_meta_caps($caps, $cap, $user_id, $args)
1457
-    {
1458
-        // only process if we're checking our mapped_cap
1459
-        if ($cap !== $this->meta_cap) {
1460
-            return $caps;
1461
-        }
1462
-        // okay it is a meta cap so let's first remove that cap from the $caps array.
1463
-        if (($key = array_search($cap, $caps)) !== false) {
1464
-            unset($caps[ $key ]);
1465
-        }
1466
-        $obj = ! empty($args[0]) ? $this->_model->get_one_by_ID($args[0]) : null;
1467
-        // if no obj then let's just do cap
1468
-        if (! $obj instanceof EE_Base_Class) {
1469
-            $caps[] = 'do_not_allow';
1470
-            return $caps;
1471
-        }
1472
-        $caps[] = $cap . 's';
1473
-        $is_system = $obj instanceof EE_Question_Group ? $obj->system_group() : false;
1474
-        $is_system = $obj instanceof EE_Question ? $obj->is_system_question() : $is_system;
1475
-        if ($is_system) {
1476
-            $caps[] = $this->private_cap;
1477
-        }
1478
-        return $caps;
1479
-    }
1444
+	/**
1445
+	 * This is the callback for the wp map_meta_caps() function which allows for ensuring certain caps that act as a
1446
+	 * "meta" for other caps ( i.e. ee_edit_event is a meta for ee_edit_others_events ) work as expected.
1447
+	 *
1448
+	 * @since 4.5.0
1449
+	 * @see   wp-includes/capabilities.php
1450
+	 * @param array  $caps    actual users capabilities
1451
+	 * @param string $cap     initial capability name that is being checked (the "map" key)
1452
+	 * @param int    $user_id The user id
1453
+	 * @param array  $args    Adds context to the cap. Typically the object ID.
1454
+	 * @return array   actual users capabilities
1455
+	 */
1456
+	protected function _map_meta_caps($caps, $cap, $user_id, $args)
1457
+	{
1458
+		// only process if we're checking our mapped_cap
1459
+		if ($cap !== $this->meta_cap) {
1460
+			return $caps;
1461
+		}
1462
+		// okay it is a meta cap so let's first remove that cap from the $caps array.
1463
+		if (($key = array_search($cap, $caps)) !== false) {
1464
+			unset($caps[ $key ]);
1465
+		}
1466
+		$obj = ! empty($args[0]) ? $this->_model->get_one_by_ID($args[0]) : null;
1467
+		// if no obj then let's just do cap
1468
+		if (! $obj instanceof EE_Base_Class) {
1469
+			$caps[] = 'do_not_allow';
1470
+			return $caps;
1471
+		}
1472
+		$caps[] = $cap . 's';
1473
+		$is_system = $obj instanceof EE_Question_Group ? $obj->system_group() : false;
1474
+		$is_system = $obj instanceof EE_Question ? $obj->is_system_question() : $is_system;
1475
+		if ($is_system) {
1476
+			$caps[] = $this->private_cap;
1477
+		}
1478
+		return $caps;
1479
+	}
1480 1480
 }
Please login to merge, or discard this patch.
admin_pages/registrations/Registrations_Admin_Page.core.php 1 patch
Indentation   +3824 added lines, -3824 removed lines patch added patch discarded remove patch
@@ -19,2396 +19,2396 @@  discard block
 block discarded – undo
19 19
 class Registrations_Admin_Page extends EE_Admin_Page_CPT
20 20
 {
21 21
 
22
-    /**
23
-     * @var EE_Registration
24
-     */
25
-    private $_registration;
26
-
27
-    /**
28
-     * @var EE_Event
29
-     */
30
-    private $_reg_event;
31
-
32
-    /**
33
-     * @var EE_Session
34
-     */
35
-    private $_session;
36
-
37
-    private static $_reg_status;
38
-
39
-    /**
40
-     * Form for displaying the custom questions for this registration.
41
-     * This gets used a few times throughout the request so its best to cache it
42
-     *
43
-     * @var EE_Registration_Custom_Questions_Form
44
-     */
45
-    protected $_reg_custom_questions_form = null;
46
-
47
-
48
-    /**
49
-     *        constructor
50
-     *
51
-     * @Constructor
52
-     * @access public
53
-     * @param bool $routing
54
-     * @return Registrations_Admin_Page
55
-     */
56
-    public function __construct($routing = true)
57
-    {
58
-        parent::__construct($routing);
59
-        add_action('wp_loaded', array($this, 'wp_loaded'));
60
-    }
61
-
62
-
63
-    public function wp_loaded()
64
-    {
65
-        // when adding a new registration...
66
-        if (isset($this->_req_data['action']) && $this->_req_data['action'] === 'new_registration') {
67
-            EE_System::do_not_cache();
68
-            if (! isset($this->_req_data['processing_registration'])
69
-                || absint($this->_req_data['processing_registration']) !== 1
70
-            ) {
71
-                // and it's NOT the attendee information reg step
72
-                // force cookie expiration by setting time to last week
73
-                setcookie('ee_registration_added', 0, time() - WEEK_IN_SECONDS, '/');
74
-                // and update the global
75
-                $_COOKIE['ee_registration_added'] = 0;
76
-            }
77
-        }
78
-    }
79
-
80
-
81
-    protected function _init_page_props()
82
-    {
83
-        $this->page_slug = REG_PG_SLUG;
84
-        $this->_admin_base_url = REG_ADMIN_URL;
85
-        $this->_admin_base_path = REG_ADMIN;
86
-        $this->page_label = esc_html__('Registrations', 'event_espresso');
87
-        $this->_cpt_routes = array(
88
-            'add_new_attendee' => 'espresso_attendees',
89
-            'edit_attendee'    => 'espresso_attendees',
90
-            'insert_attendee'  => 'espresso_attendees',
91
-            'update_attendee'  => 'espresso_attendees',
92
-        );
93
-        $this->_cpt_model_names = array(
94
-            'add_new_attendee' => 'EEM_Attendee',
95
-            'edit_attendee'    => 'EEM_Attendee',
96
-        );
97
-        $this->_cpt_edit_routes = array(
98
-            'espresso_attendees' => 'edit_attendee',
99
-        );
100
-        $this->_pagenow_map = array(
101
-            'add_new_attendee' => 'post-new.php',
102
-            'edit_attendee'    => 'post.php',
103
-            'trash'            => 'post.php',
104
-        );
105
-        add_action('edit_form_after_title', array($this, 'after_title_form_fields'), 10);
106
-        // add filters so that the comment urls don't take users to a confusing 404 page
107
-        add_filter('get_comment_link', array($this, 'clear_comment_link'), 10, 3);
108
-    }
109
-
110
-
111
-    public function clear_comment_link($link, $comment, $args)
112
-    {
113
-        // gotta make sure this only happens on this route
114
-        $post_type = get_post_type($comment->comment_post_ID);
115
-        if ($post_type === 'espresso_attendees') {
116
-            return '#commentsdiv';
117
-        }
118
-        return $link;
119
-    }
120
-
121
-
122
-    protected function _ajax_hooks()
123
-    {
124
-        // todo: all hooks for registrations ajax goes in here
125
-        add_action('wp_ajax_toggle_checkin_status', array($this, 'toggle_checkin_status'));
126
-    }
127
-
128
-
129
-    protected function _define_page_props()
130
-    {
131
-        $this->_admin_page_title = $this->page_label;
132
-        $this->_labels = array(
133
-            'buttons'                      => array(
134
-                'add-registrant'      => esc_html__('Add New Registration', 'event_espresso'),
135
-                'add-attendee'        => esc_html__('Add Contact', 'event_espresso'),
136
-                'edit'                => esc_html__('Edit Contact', 'event_espresso'),
137
-                'report'              => esc_html__("Event Registrations CSV Report", "event_espresso"),
138
-                'report_all'          => esc_html__('All Registrations CSV Report', 'event_espresso'),
139
-                'report_filtered'     => esc_html__('Filtered CSV Report', 'event_espresso'),
140
-                'contact_list_report' => esc_html__('Contact List Report', 'event_espresso'),
141
-                'contact_list_export' => esc_html__("Export Data", "event_espresso"),
142
-            ),
143
-            'publishbox'                   => array(
144
-                'add_new_attendee' => esc_html__("Add Contact Record", 'event_espresso'),
145
-                'edit_attendee'    => esc_html__("Update Contact Record", 'event_espresso'),
146
-            ),
147
-            'hide_add_button_on_cpt_route' => array(
148
-                'edit_attendee' => true,
149
-            ),
150
-        );
151
-    }
152
-
153
-
154
-    /**
155
-     *        grab url requests and route them
156
-     *
157
-     * @access private
158
-     * @return void
159
-     */
160
-    public function _set_page_routes()
161
-    {
162
-        $this->_get_registration_status_array();
163
-        $reg_id = ! empty($this->_req_data['_REG_ID']) && ! is_array($this->_req_data['_REG_ID'])
164
-            ? $this->_req_data['_REG_ID'] : 0;
165
-        $reg_id = empty($reg_id) && ! empty($this->_req_data['reg_status_change_form']['REG_ID'])
166
-            ? $this->_req_data['reg_status_change_form']['REG_ID']
167
-            : $reg_id;
168
-        $att_id = ! empty($this->_req_data['ATT_ID']) && ! is_array($this->_req_data['ATT_ID'])
169
-            ? $this->_req_data['ATT_ID'] : 0;
170
-        $att_id = ! empty($this->_req_data['post']) && ! is_array($this->_req_data['post'])
171
-            ? $this->_req_data['post']
172
-            : $att_id;
173
-        $this->_page_routes = array(
174
-            'default'                             => array(
175
-                'func'       => '_registrations_overview_list_table',
176
-                'capability' => 'ee_read_registrations',
177
-            ),
178
-            'view_registration'                   => array(
179
-                'func'       => '_registration_details',
180
-                'capability' => 'ee_read_registration',
181
-                'obj_id'     => $reg_id,
182
-            ),
183
-            'edit_registration'                   => array(
184
-                'func'               => '_update_attendee_registration_form',
185
-                'noheader'           => true,
186
-                'headers_sent_route' => 'view_registration',
187
-                'capability'         => 'ee_edit_registration',
188
-                'obj_id'             => $reg_id,
189
-                '_REG_ID'            => $reg_id,
190
-            ),
191
-            'trash_registrations'                 => array(
192
-                'func'       => '_trash_or_restore_registrations',
193
-                'args'       => array('trash' => true),
194
-                'noheader'   => true,
195
-                'capability' => 'ee_delete_registrations',
196
-            ),
197
-            'restore_registrations'               => array(
198
-                'func'       => '_trash_or_restore_registrations',
199
-                'args'       => array('trash' => false),
200
-                'noheader'   => true,
201
-                'capability' => 'ee_delete_registrations',
202
-            ),
203
-            'delete_registrations'                => array(
204
-                'func'       => '_delete_registrations',
205
-                'noheader'   => true,
206
-                'capability' => 'ee_delete_registrations',
207
-            ),
208
-            'new_registration'                    => array(
209
-                'func'       => 'new_registration',
210
-                'capability' => 'ee_edit_registrations',
211
-            ),
212
-            'process_reg_step'                    => array(
213
-                'func'       => 'process_reg_step',
214
-                'noheader'   => true,
215
-                'capability' => 'ee_edit_registrations',
216
-            ),
217
-            'redirect_to_txn'                     => array(
218
-                'func'       => 'redirect_to_txn',
219
-                'noheader'   => true,
220
-                'capability' => 'ee_edit_registrations',
221
-            ),
222
-            'change_reg_status'                   => array(
223
-                'func'       => '_change_reg_status',
224
-                'noheader'   => true,
225
-                'capability' => 'ee_edit_registration',
226
-                'obj_id'     => $reg_id,
227
-            ),
228
-            'approve_registration'                => array(
229
-                'func'       => 'approve_registration',
230
-                'noheader'   => true,
231
-                'capability' => 'ee_edit_registration',
232
-                'obj_id'     => $reg_id,
233
-            ),
234
-            'approve_and_notify_registration'     => array(
235
-                'func'       => 'approve_registration',
236
-                'noheader'   => true,
237
-                'args'       => array(true),
238
-                'capability' => 'ee_edit_registration',
239
-                'obj_id'     => $reg_id,
240
-            ),
241
-            'approve_registrations'               => array(
242
-                'func'       => 'bulk_action_on_registrations',
243
-                'noheader'   => true,
244
-                'capability' => 'ee_edit_registrations',
245
-                'args'       => array('approve'),
246
-            ),
247
-            'approve_and_notify_registrations'    => array(
248
-                'func'       => 'bulk_action_on_registrations',
249
-                'noheader'   => true,
250
-                'capability' => 'ee_edit_registrations',
251
-                'args'       => array('approve', true),
252
-            ),
253
-            'decline_registration'                => array(
254
-                'func'       => 'decline_registration',
255
-                'noheader'   => true,
256
-                'capability' => 'ee_edit_registration',
257
-                'obj_id'     => $reg_id,
258
-            ),
259
-            'decline_and_notify_registration'     => array(
260
-                'func'       => 'decline_registration',
261
-                'noheader'   => true,
262
-                'args'       => array(true),
263
-                'capability' => 'ee_edit_registration',
264
-                'obj_id'     => $reg_id,
265
-            ),
266
-            'decline_registrations'               => array(
267
-                'func'       => 'bulk_action_on_registrations',
268
-                'noheader'   => true,
269
-                'capability' => 'ee_edit_registrations',
270
-                'args'       => array('decline'),
271
-            ),
272
-            'decline_and_notify_registrations'    => array(
273
-                'func'       => 'bulk_action_on_registrations',
274
-                'noheader'   => true,
275
-                'capability' => 'ee_edit_registrations',
276
-                'args'       => array('decline', true),
277
-            ),
278
-            'pending_registration'                => array(
279
-                'func'       => 'pending_registration',
280
-                'noheader'   => true,
281
-                'capability' => 'ee_edit_registration',
282
-                'obj_id'     => $reg_id,
283
-            ),
284
-            'pending_and_notify_registration'     => array(
285
-                'func'       => 'pending_registration',
286
-                'noheader'   => true,
287
-                'args'       => array(true),
288
-                'capability' => 'ee_edit_registration',
289
-                'obj_id'     => $reg_id,
290
-            ),
291
-            'pending_registrations'               => array(
292
-                'func'       => 'bulk_action_on_registrations',
293
-                'noheader'   => true,
294
-                'capability' => 'ee_edit_registrations',
295
-                'args'       => array('pending'),
296
-            ),
297
-            'pending_and_notify_registrations'    => array(
298
-                'func'       => 'bulk_action_on_registrations',
299
-                'noheader'   => true,
300
-                'capability' => 'ee_edit_registrations',
301
-                'args'       => array('pending', true),
302
-            ),
303
-            'no_approve_registration'             => array(
304
-                'func'       => 'not_approve_registration',
305
-                'noheader'   => true,
306
-                'capability' => 'ee_edit_registration',
307
-                'obj_id'     => $reg_id,
308
-            ),
309
-            'no_approve_and_notify_registration'  => array(
310
-                'func'       => 'not_approve_registration',
311
-                'noheader'   => true,
312
-                'args'       => array(true),
313
-                'capability' => 'ee_edit_registration',
314
-                'obj_id'     => $reg_id,
315
-            ),
316
-            'no_approve_registrations'            => array(
317
-                'func'       => 'bulk_action_on_registrations',
318
-                'noheader'   => true,
319
-                'capability' => 'ee_edit_registrations',
320
-                'args'       => array('not_approve'),
321
-            ),
322
-            'no_approve_and_notify_registrations' => array(
323
-                'func'       => 'bulk_action_on_registrations',
324
-                'noheader'   => true,
325
-                'capability' => 'ee_edit_registrations',
326
-                'args'       => array('not_approve', true),
327
-            ),
328
-            'cancel_registration'                 => array(
329
-                'func'       => 'cancel_registration',
330
-                'noheader'   => true,
331
-                'capability' => 'ee_edit_registration',
332
-                'obj_id'     => $reg_id,
333
-            ),
334
-            'cancel_and_notify_registration'      => array(
335
-                'func'       => 'cancel_registration',
336
-                'noheader'   => true,
337
-                'args'       => array(true),
338
-                'capability' => 'ee_edit_registration',
339
-                'obj_id'     => $reg_id,
340
-            ),
341
-            'cancel_registrations'                => array(
342
-                'func'       => 'bulk_action_on_registrations',
343
-                'noheader'   => true,
344
-                'capability' => 'ee_edit_registrations',
345
-                'args'       => array('cancel'),
346
-            ),
347
-            'cancel_and_notify_registrations'     => array(
348
-                'func'       => 'bulk_action_on_registrations',
349
-                'noheader'   => true,
350
-                'capability' => 'ee_edit_registrations',
351
-                'args'       => array('cancel', true),
352
-            ),
353
-            'wait_list_registration'              => array(
354
-                'func'       => 'wait_list_registration',
355
-                'noheader'   => true,
356
-                'capability' => 'ee_edit_registration',
357
-                'obj_id'     => $reg_id,
358
-            ),
359
-            'wait_list_and_notify_registration'   => array(
360
-                'func'       => 'wait_list_registration',
361
-                'noheader'   => true,
362
-                'args'       => array(true),
363
-                'capability' => 'ee_edit_registration',
364
-                'obj_id'     => $reg_id,
365
-            ),
366
-            'contact_list'                        => array(
367
-                'func'       => '_attendee_contact_list_table',
368
-                'capability' => 'ee_read_contacts',
369
-            ),
370
-            'add_new_attendee'                    => array(
371
-                'func' => '_create_new_cpt_item',
372
-                'args' => array(
373
-                    'new_attendee' => true,
374
-                    'capability'   => 'ee_edit_contacts',
375
-                ),
376
-            ),
377
-            'edit_attendee'                       => array(
378
-                'func'       => '_edit_cpt_item',
379
-                'capability' => 'ee_edit_contacts',
380
-                'obj_id'     => $att_id,
381
-            ),
382
-            'duplicate_attendee'                  => array(
383
-                'func'       => '_duplicate_attendee',
384
-                'noheader'   => true,
385
-                'capability' => 'ee_edit_contacts',
386
-                'obj_id'     => $att_id,
387
-            ),
388
-            'insert_attendee'                     => array(
389
-                'func'       => '_insert_or_update_attendee',
390
-                'args'       => array(
391
-                    'new_attendee' => true,
392
-                ),
393
-                'noheader'   => true,
394
-                'capability' => 'ee_edit_contacts',
395
-            ),
396
-            'update_attendee'                     => array(
397
-                'func'       => '_insert_or_update_attendee',
398
-                'args'       => array(
399
-                    'new_attendee' => false,
400
-                ),
401
-                'noheader'   => true,
402
-                'capability' => 'ee_edit_contacts',
403
-                'obj_id'     => $att_id,
404
-            ),
405
-            'trash_attendees'                     => array(
406
-                'func'       => '_trash_or_restore_attendees',
407
-                'args'       => array(
408
-                    'trash' => 'true',
409
-                ),
410
-                'noheader'   => true,
411
-                'capability' => 'ee_delete_contacts',
412
-            ),
413
-            'trash_attendee'                      => array(
414
-                'func'       => '_trash_or_restore_attendees',
415
-                'args'       => array(
416
-                    'trash' => true,
417
-                ),
418
-                'noheader'   => true,
419
-                'capability' => 'ee_delete_contacts',
420
-                'obj_id'     => $att_id,
421
-            ),
422
-            'restore_attendees'                   => array(
423
-                'func'       => '_trash_or_restore_attendees',
424
-                'args'       => array(
425
-                    'trash' => false,
426
-                ),
427
-                'noheader'   => true,
428
-                'capability' => 'ee_delete_contacts',
429
-                'obj_id'     => $att_id,
430
-            ),
431
-            'resend_registration'                 => array(
432
-                'func'       => '_resend_registration',
433
-                'noheader'   => true,
434
-                'capability' => 'ee_send_message',
435
-            ),
436
-            'registrations_report'                => array(
437
-                'func'       => '_registrations_report',
438
-                'noheader'   => true,
439
-                'capability' => 'ee_read_registrations',
440
-            ),
441
-            'contact_list_export'                 => array(
442
-                'func'       => '_contact_list_export',
443
-                'noheader'   => true,
444
-                'capability' => 'export',
445
-            ),
446
-            'contact_list_report'                 => array(
447
-                'func'       => '_contact_list_report',
448
-                'noheader'   => true,
449
-                'capability' => 'ee_read_contacts',
450
-            ),
451
-        );
452
-    }
453
-
454
-
455
-    protected function _set_page_config()
456
-    {
457
-        $this->_page_config = array(
458
-            'default'           => array(
459
-                'nav'           => array(
460
-                    'label' => esc_html__('Overview', 'event_espresso'),
461
-                    'order' => 5,
462
-                ),
463
-                'help_tabs'     => array(
464
-                    'registrations_overview_help_tab'                       => array(
465
-                        'title'    => esc_html__('Registrations Overview', 'event_espresso'),
466
-                        'filename' => 'registrations_overview',
467
-                    ),
468
-                    'registrations_overview_table_column_headings_help_tab' => array(
469
-                        'title'    => esc_html__('Registrations Table Column Headings', 'event_espresso'),
470
-                        'filename' => 'registrations_overview_table_column_headings',
471
-                    ),
472
-                    'registrations_overview_filters_help_tab'               => array(
473
-                        'title'    => esc_html__('Registration Filters', 'event_espresso'),
474
-                        'filename' => 'registrations_overview_filters',
475
-                    ),
476
-                    'registrations_overview_views_help_tab'                 => array(
477
-                        'title'    => esc_html__('Registration Views', 'event_espresso'),
478
-                        'filename' => 'registrations_overview_views',
479
-                    ),
480
-                    'registrations_regoverview_other_help_tab'              => array(
481
-                        'title'    => esc_html__('Registrations Other', 'event_espresso'),
482
-                        'filename' => 'registrations_overview_other',
483
-                    ),
484
-                ),
485
-                'help_tour'     => array('Registration_Overview_Help_Tour'),
486
-                'qtips'         => array('Registration_List_Table_Tips'),
487
-                'list_table'    => 'EE_Registrations_List_Table',
488
-                'require_nonce' => false,
489
-            ),
490
-            'view_registration' => array(
491
-                'nav'           => array(
492
-                    'label'      => esc_html__('REG Details', 'event_espresso'),
493
-                    'order'      => 15,
494
-                    'url'        => isset($this->_req_data['_REG_ID'])
495
-                        ? add_query_arg(array('_REG_ID' => $this->_req_data['_REG_ID']), $this->_current_page_view_url)
496
-                        : $this->_admin_base_url,
497
-                    'persistent' => false,
498
-                ),
499
-                'help_tabs'     => array(
500
-                    'registrations_details_help_tab'                    => array(
501
-                        'title'    => esc_html__('Registration Details', 'event_espresso'),
502
-                        'filename' => 'registrations_details',
503
-                    ),
504
-                    'registrations_details_table_help_tab'              => array(
505
-                        'title'    => esc_html__('Registration Details Table', 'event_espresso'),
506
-                        'filename' => 'registrations_details_table',
507
-                    ),
508
-                    'registrations_details_form_answers_help_tab'       => array(
509
-                        'title'    => esc_html__('Registration Form Answers', 'event_espresso'),
510
-                        'filename' => 'registrations_details_form_answers',
511
-                    ),
512
-                    'registrations_details_registrant_details_help_tab' => array(
513
-                        'title'    => esc_html__('Contact Details', 'event_espresso'),
514
-                        'filename' => 'registrations_details_registrant_details',
515
-                    ),
516
-                ),
517
-                'help_tour'     => array('Registration_Details_Help_Tour'),
518
-                'metaboxes'     => array_merge(
519
-                    $this->_default_espresso_metaboxes,
520
-                    array('_registration_details_metaboxes')
521
-                ),
522
-                'require_nonce' => false,
523
-            ),
524
-            'new_registration'  => array(
525
-                'nav'           => array(
526
-                    'label'      => esc_html__('Add New Registration', 'event_espresso'),
527
-                    'url'        => '#',
528
-                    'order'      => 15,
529
-                    'persistent' => false,
530
-                ),
531
-                'metaboxes'     => $this->_default_espresso_metaboxes,
532
-                'labels'        => array(
533
-                    'publishbox' => esc_html__('Save Registration', 'event_espresso'),
534
-                ),
535
-                'require_nonce' => false,
536
-            ),
537
-            'add_new_attendee'  => array(
538
-                'nav'           => array(
539
-                    'label'      => esc_html__('Add Contact', 'event_espresso'),
540
-                    'order'      => 15,
541
-                    'persistent' => false,
542
-                ),
543
-                'metaboxes'     => array_merge(
544
-                    $this->_default_espresso_metaboxes,
545
-                    array('_publish_post_box', 'attendee_editor_metaboxes')
546
-                ),
547
-                'require_nonce' => false,
548
-            ),
549
-            'edit_attendee'     => array(
550
-                'nav'           => array(
551
-                    'label'      => esc_html__('Edit Contact', 'event_espresso'),
552
-                    'order'      => 15,
553
-                    'persistent' => false,
554
-                    'url'        => isset($this->_req_data['ATT_ID'])
555
-                        ? add_query_arg(array('ATT_ID' => $this->_req_data['ATT_ID']), $this->_current_page_view_url)
556
-                        : $this->_admin_base_url,
557
-                ),
558
-                'metaboxes'     => array('attendee_editor_metaboxes'),
559
-                'require_nonce' => false,
560
-            ),
561
-            'contact_list'      => array(
562
-                'nav'           => array(
563
-                    'label' => esc_html__('Contact List', 'event_espresso'),
564
-                    'order' => 20,
565
-                ),
566
-                'list_table'    => 'EE_Attendee_Contact_List_Table',
567
-                'help_tabs'     => array(
568
-                    'registrations_contact_list_help_tab'                       => array(
569
-                        'title'    => esc_html__('Registrations Contact List', 'event_espresso'),
570
-                        'filename' => 'registrations_contact_list',
571
-                    ),
572
-                    'registrations_contact-list_table_column_headings_help_tab' => array(
573
-                        'title'    => esc_html__('Contact List Table Column Headings', 'event_espresso'),
574
-                        'filename' => 'registrations_contact_list_table_column_headings',
575
-                    ),
576
-                    'registrations_contact_list_views_help_tab'                 => array(
577
-                        'title'    => esc_html__('Contact List Views', 'event_espresso'),
578
-                        'filename' => 'registrations_contact_list_views',
579
-                    ),
580
-                    'registrations_contact_list_other_help_tab'                 => array(
581
-                        'title'    => esc_html__('Contact List Other', 'event_espresso'),
582
-                        'filename' => 'registrations_contact_list_other',
583
-                    ),
584
-                ),
585
-                'help_tour'     => array('Contact_List_Help_Tour'),
586
-                'metaboxes'     => array(),
587
-                'require_nonce' => false,
588
-            ),
589
-            // override default cpt routes
590
-            'create_new'        => '',
591
-            'edit'              => '',
592
-        );
593
-    }
594
-
595
-
596
-    /**
597
-     * The below methods aren't used by this class currently
598
-     */
599
-    protected function _add_screen_options()
600
-    {
601
-    }
602
-
603
-
604
-    protected function _add_feature_pointers()
605
-    {
606
-    }
607
-
608
-
609
-    public function admin_init()
610
-    {
611
-        EE_Registry::$i18n_js_strings['update_att_qstns'] = esc_html__(
612
-            'click "Update Registration Questions" to save your changes',
613
-            'event_espresso'
614
-        );
615
-    }
616
-
617
-
618
-    public function admin_notices()
619
-    {
620
-    }
621
-
622
-
623
-    public function admin_footer_scripts()
624
-    {
625
-    }
626
-
627
-
628
-    /**
629
-     *        get list of registration statuses
630
-     *
631
-     * @access private
632
-     * @return void
633
-     * @throws EE_Error
634
-     */
635
-    private function _get_registration_status_array()
636
-    {
637
-        self::$_reg_status = EEM_Registration::reg_status_array(array(), true);
638
-    }
639
-
640
-
641
-    protected function _add_screen_options_default()
642
-    {
643
-        $this->_per_page_screen_option();
644
-    }
645
-
646
-
647
-    protected function _add_screen_options_contact_list()
648
-    {
649
-        $page_title = $this->_admin_page_title;
650
-        $this->_admin_page_title = esc_html__("Contacts", 'event_espresso');
651
-        $this->_per_page_screen_option();
652
-        $this->_admin_page_title = $page_title;
653
-    }
654
-
655
-
656
-    public function load_scripts_styles()
657
-    {
658
-        // style
659
-        wp_register_style(
660
-            'espresso_reg',
661
-            REG_ASSETS_URL . 'espresso_registrations_admin.css',
662
-            array('ee-admin-css'),
663
-            EVENT_ESPRESSO_VERSION
664
-        );
665
-        wp_enqueue_style('espresso_reg');
666
-        // script
667
-        wp_register_script(
668
-            'espresso_reg',
669
-            REG_ASSETS_URL . 'espresso_registrations_admin.js',
670
-            array('jquery-ui-datepicker', 'jquery-ui-draggable', 'ee_admin_js'),
671
-            EVENT_ESPRESSO_VERSION,
672
-            true
673
-        );
674
-        wp_enqueue_script('espresso_reg');
675
-    }
676
-
677
-
678
-    public function load_scripts_styles_edit_attendee()
679
-    {
680
-        // stuff to only show up on our attendee edit details page.
681
-        $attendee_details_translations = array(
682
-            'att_publish_text' => sprintf(
683
-                esc_html__('Created on: <b>%1$s</b>', 'event_espresso'),
684
-                $this->_cpt_model_obj->get_datetime('ATT_created')
685
-            ),
686
-        );
687
-        wp_localize_script('espresso_reg', 'ATTENDEE_DETAILS', $attendee_details_translations);
688
-        wp_enqueue_script('jquery-validate');
689
-    }
690
-
691
-
692
-    public function load_scripts_styles_view_registration()
693
-    {
694
-        // styles
695
-        wp_enqueue_style('espresso-ui-theme');
696
-        // scripts
697
-        $this->_get_reg_custom_questions_form($this->_registration->ID());
698
-        $this->_reg_custom_questions_form->wp_enqueue_scripts(true);
699
-    }
700
-
701
-
702
-    public function load_scripts_styles_contact_list()
703
-    {
704
-        wp_dequeue_style('espresso_reg');
705
-        wp_register_style(
706
-            'espresso_att',
707
-            REG_ASSETS_URL . 'espresso_attendees_admin.css',
708
-            array('ee-admin-css'),
709
-            EVENT_ESPRESSO_VERSION
710
-        );
711
-        wp_enqueue_style('espresso_att');
712
-    }
713
-
714
-
715
-    public function load_scripts_styles_new_registration()
716
-    {
717
-        wp_register_script(
718
-            'ee-spco-for-admin',
719
-            REG_ASSETS_URL . 'spco_for_admin.js',
720
-            array('underscore', 'jquery'),
721
-            EVENT_ESPRESSO_VERSION,
722
-            true
723
-        );
724
-        wp_enqueue_script('ee-spco-for-admin');
725
-        add_filter('FHEE__EED_Ticket_Selector__load_tckt_slctr_assets', '__return_true');
726
-        EE_Form_Section_Proper::wp_enqueue_scripts();
727
-        EED_Ticket_Selector::load_tckt_slctr_assets();
728
-        EE_Datepicker_Input::enqueue_styles_and_scripts();
729
-    }
730
-
731
-
732
-    public function AHEE__EE_Admin_Page__route_admin_request_resend_registration()
733
-    {
734
-        add_filter('FHEE_load_EE_messages', '__return_true');
735
-    }
736
-
737
-
738
-    public function AHEE__EE_Admin_Page__route_admin_request_approve_registration()
739
-    {
740
-        add_filter('FHEE_load_EE_messages', '__return_true');
741
-    }
742
-
743
-
744
-    protected function _set_list_table_views_default()
745
-    {
746
-        // for notification related bulk actions we need to make sure only active messengers have an option.
747
-        EED_Messages::set_autoloaders();
748
-        /** @type EE_Message_Resource_Manager $message_resource_manager */
749
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
750
-        $active_mts = $message_resource_manager->list_of_active_message_types();
751
-        // key= bulk_action_slug, value= message type.
752
-        $match_array = array(
753
-            'approve_registrations'    => 'registration',
754
-            'decline_registrations'    => 'declined_registration',
755
-            'pending_registrations'    => 'pending_approval',
756
-            'no_approve_registrations' => 'not_approved_registration',
757
-            'cancel_registrations'     => 'cancelled_registration',
758
-        );
759
-        $can_send = EE_Registry::instance()->CAP->current_user_can(
760
-            'ee_send_message',
761
-            'batch_send_messages'
762
-        );
763
-        /** setup reg status bulk actions **/
764
-        $def_reg_status_actions['approve_registrations'] = esc_html__('Approve Registrations', 'event_espresso');
765
-        if ($can_send && in_array($match_array['approve_registrations'], $active_mts, true)) {
766
-            $def_reg_status_actions['approve_and_notify_registrations'] = esc_html__(
767
-                'Approve and Notify Registrations',
768
-                'event_espresso'
769
-            );
770
-        }
771
-        $def_reg_status_actions['decline_registrations'] = esc_html__('Decline Registrations', 'event_espresso');
772
-        if ($can_send && in_array($match_array['decline_registrations'], $active_mts, true)) {
773
-            $def_reg_status_actions['decline_and_notify_registrations'] = esc_html__(
774
-                'Decline and Notify Registrations',
775
-                'event_espresso'
776
-            );
777
-        }
778
-        $def_reg_status_actions['pending_registrations'] = esc_html__(
779
-            'Set Registrations to Pending Payment',
780
-            'event_espresso'
781
-        );
782
-        if ($can_send && in_array($match_array['pending_registrations'], $active_mts, true)) {
783
-            $def_reg_status_actions['pending_and_notify_registrations'] = esc_html__(
784
-                'Set Registrations to Pending Payment and Notify',
785
-                'event_espresso'
786
-            );
787
-        }
788
-        $def_reg_status_actions['no_approve_registrations'] = esc_html__(
789
-            'Set Registrations to Not Approved',
790
-            'event_espresso'
791
-        );
792
-        if ($can_send && in_array($match_array['no_approve_registrations'], $active_mts, true)) {
793
-            $def_reg_status_actions['no_approve_and_notify_registrations'] = esc_html__(
794
-                'Set Registrations to Not Approved and Notify',
795
-                'event_espresso'
796
-            );
797
-        }
798
-        $def_reg_status_actions['cancel_registrations'] = esc_html__('Cancel Registrations', 'event_espresso');
799
-        if ($can_send && in_array($match_array['cancel_registrations'], $active_mts, true)) {
800
-            $def_reg_status_actions['cancel_and_notify_registrations'] = esc_html__(
801
-                'Cancel Registrations and Notify',
802
-                'event_espresso'
803
-            );
804
-        }
805
-        $def_reg_status_actions = apply_filters(
806
-            'FHEE__Registrations_Admin_Page___set_list_table_views_default__def_reg_status_actions_array',
807
-            $def_reg_status_actions,
808
-            $active_mts,
809
-            $can_send
810
-        );
811
-
812
-        $this->_views = array(
813
-            'all'   => array(
814
-                'slug'        => 'all',
815
-                'label'       => esc_html__('View All Registrations', 'event_espresso'),
816
-                'count'       => 0,
817
-                'bulk_action' => array_merge(
818
-                    $def_reg_status_actions,
819
-                    array(
820
-                        'trash_registrations' => esc_html__('Trash Registrations', 'event_espresso'),
821
-                    )
822
-                ),
823
-            ),
824
-            'month' => array(
825
-                'slug'        => 'month',
826
-                'label'       => esc_html__('This Month', 'event_espresso'),
827
-                'count'       => 0,
828
-                'bulk_action' => array_merge(
829
-                    $def_reg_status_actions,
830
-                    array(
831
-                        'trash_registrations' => esc_html__('Trash Registrations', 'event_espresso'),
832
-                    )
833
-                ),
834
-            ),
835
-            'today' => array(
836
-                'slug'        => 'today',
837
-                'label'       => sprintf(
838
-                    esc_html__('Today - %s', 'event_espresso'),
839
-                    date('M d, Y', current_time('timestamp'))
840
-                ),
841
-                'count'       => 0,
842
-                'bulk_action' => array_merge(
843
-                    $def_reg_status_actions,
844
-                    array(
845
-                        'trash_registrations' => esc_html__('Trash Registrations', 'event_espresso'),
846
-                    )
847
-                ),
848
-            ),
849
-        );
850
-        if (EE_Registry::instance()->CAP->current_user_can(
851
-            'ee_delete_registrations',
852
-            'espresso_registrations_delete_registration'
853
-        )) {
854
-            $this->_views['incomplete'] = array(
855
-                'slug'        => 'incomplete',
856
-                'label'       => esc_html__('Incomplete', 'event_espresso'),
857
-                'count'       => 0,
858
-                'bulk_action' => array(
859
-                    'trash_registrations' => esc_html__('Trash Registrations', 'event_espresso'),
860
-                ),
861
-            );
862
-            $this->_views['trash'] = array(
863
-                'slug'        => 'trash',
864
-                'label'       => esc_html__('Trash', 'event_espresso'),
865
-                'count'       => 0,
866
-                'bulk_action' => array(
867
-                    'restore_registrations' => esc_html__('Restore Registrations', 'event_espresso'),
868
-                    'delete_registrations'  => esc_html__('Delete Registrations Permanently', 'event_espresso'),
869
-                ),
870
-            );
871
-        }
872
-    }
873
-
874
-
875
-    protected function _set_list_table_views_contact_list()
876
-    {
877
-        $this->_views = array(
878
-            'in_use' => array(
879
-                'slug'        => 'in_use',
880
-                'label'       => esc_html__('In Use', 'event_espresso'),
881
-                'count'       => 0,
882
-                'bulk_action' => array(
883
-                    'trash_attendees' => esc_html__('Move to Trash', 'event_espresso'),
884
-                ),
885
-            ),
886
-        );
887
-        if (EE_Registry::instance()->CAP->current_user_can(
888
-            'ee_delete_contacts',
889
-            'espresso_registrations_trash_attendees'
890
-        )
891
-        ) {
892
-            $this->_views['trash'] = array(
893
-                'slug'        => 'trash',
894
-                'label'       => esc_html__('Trash', 'event_espresso'),
895
-                'count'       => 0,
896
-                'bulk_action' => array(
897
-                    'restore_attendees' => esc_html__('Restore from Trash', 'event_espresso'),
898
-                ),
899
-            );
900
-        }
901
-    }
902
-
903
-
904
-    protected function _registration_legend_items()
905
-    {
906
-        $fc_items = array(
907
-            'star-icon'        => array(
908
-                'class' => 'dashicons dashicons-star-filled lt-blue-icon ee-icon-size-8',
909
-                'desc'  => esc_html__('This is the Primary Registrant', 'event_espresso'),
910
-            ),
911
-            'view_details'     => array(
912
-                'class' => 'dashicons dashicons-clipboard',
913
-                'desc'  => esc_html__('View Registration Details', 'event_espresso'),
914
-            ),
915
-            'edit_attendee'    => array(
916
-                'class' => 'ee-icon ee-icon-user-edit ee-icon-size-16',
917
-                'desc'  => esc_html__('Edit Contact Details', 'event_espresso'),
918
-            ),
919
-            'view_transaction' => array(
920
-                'class' => 'dashicons dashicons-cart',
921
-                'desc'  => esc_html__('View Transaction Details', 'event_espresso'),
922
-            ),
923
-            'view_invoice'     => array(
924
-                'class' => 'dashicons dashicons-media-spreadsheet',
925
-                'desc'  => esc_html__('View Transaction Invoice', 'event_espresso'),
926
-            ),
927
-        );
928
-        if (EE_Registry::instance()->CAP->current_user_can(
929
-            'ee_send_message',
930
-            'espresso_registrations_resend_registration'
931
-        )) {
932
-            $fc_items['resend_registration'] = array(
933
-                'class' => 'dashicons dashicons-email-alt',
934
-                'desc'  => esc_html__('Resend Registration Details', 'event_espresso'),
935
-            );
936
-        } else {
937
-            $fc_items['blank'] = array('class' => 'blank', 'desc' => '');
938
-        }
939
-        if (EE_Registry::instance()->CAP->current_user_can(
940
-            'ee_read_global_messages',
941
-            'view_filtered_messages'
942
-        )) {
943
-            $related_for_icon = EEH_MSG_Template::get_message_action_icon('see_notifications_for');
944
-            if (isset($related_for_icon['css_class']) && isset($related_for_icon['label'])) {
945
-                $fc_items['view_related_messages'] = array(
946
-                    'class' => $related_for_icon['css_class'],
947
-                    'desc'  => $related_for_icon['label'],
948
-                );
949
-            }
950
-        }
951
-        $sc_items = array(
952
-            'approved_status'   => array(
953
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_approved,
954
-                'desc'  => EEH_Template::pretty_status(
955
-                    EEM_Registration::status_id_approved,
956
-                    false,
957
-                    'sentence'
958
-                ),
959
-            ),
960
-            'pending_status'    => array(
961
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_pending_payment,
962
-                'desc'  => EEH_Template::pretty_status(
963
-                    EEM_Registration::status_id_pending_payment,
964
-                    false,
965
-                    'sentence'
966
-                ),
967
-            ),
968
-            'wait_list'         => array(
969
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_wait_list,
970
-                'desc'  => EEH_Template::pretty_status(
971
-                    EEM_Registration::status_id_wait_list,
972
-                    false,
973
-                    'sentence'
974
-                ),
975
-            ),
976
-            'incomplete_status' => array(
977
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_incomplete,
978
-                'desc'  => EEH_Template::pretty_status(
979
-                    EEM_Registration::status_id_incomplete,
980
-                    false,
981
-                    'sentence'
982
-                ),
983
-            ),
984
-            'not_approved'      => array(
985
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_not_approved,
986
-                'desc'  => EEH_Template::pretty_status(
987
-                    EEM_Registration::status_id_not_approved,
988
-                    false,
989
-                    'sentence'
990
-                ),
991
-            ),
992
-            'declined_status'   => array(
993
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_declined,
994
-                'desc'  => EEH_Template::pretty_status(
995
-                    EEM_Registration::status_id_declined,
996
-                    false,
997
-                    'sentence'
998
-                ),
999
-            ),
1000
-            'cancelled_status'  => array(
1001
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_cancelled,
1002
-                'desc'  => EEH_Template::pretty_status(
1003
-                    EEM_Registration::status_id_cancelled,
1004
-                    false,
1005
-                    'sentence'
1006
-                ),
1007
-            ),
1008
-        );
1009
-        return array_merge($fc_items, $sc_items);
1010
-    }
1011
-
1012
-
1013
-
1014
-    /***************************************        REGISTRATION OVERVIEW        **************************************/
1015
-    /**
1016
-     * @throws \EE_Error
1017
-     */
1018
-    protected function _registrations_overview_list_table()
1019
-    {
1020
-        $this->_template_args['admin_page_header'] = '';
1021
-        $EVT_ID = ! empty($this->_req_data['event_id'])
1022
-            ? absint($this->_req_data['event_id'])
1023
-            : 0;
1024
-        $ATT_ID = ! empty($this->_req_data['ATT_ID'])
1025
-            ? absint($this->_req_data['ATT_ID'])
1026
-            : 0;
1027
-        if ($ATT_ID) {
1028
-            $attendee = EEM_Attendee::instance()->get_one_by_ID($ATT_ID);
1029
-            if ($attendee instanceof EE_Attendee) {
1030
-                $this->_template_args['admin_page_header'] = sprintf(
1031
-                    esc_html__(
1032
-                        '%1$s Viewing registrations for %2$s%3$s',
1033
-                        'event_espresso'
1034
-                    ),
1035
-                    '<h3 style="line-height:1.5em;">',
1036
-                    '<a href="' . EE_Admin_Page::add_query_args_and_nonce(
1037
-                        array(
1038
-                            'action' => 'edit_attendee',
1039
-                            'post'   => $ATT_ID,
1040
-                        ),
1041
-                        REG_ADMIN_URL
1042
-                    ) . '">' . $attendee->full_name() . '</a>',
1043
-                    '</h3>'
1044
-                );
1045
-            }
1046
-        }
1047
-        if ($EVT_ID) {
1048
-            if (EE_Registry::instance()->CAP->current_user_can(
1049
-                'ee_edit_registrations',
1050
-                'espresso_registrations_new_registration',
1051
-                $EVT_ID
1052
-            )) {
1053
-                $this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
1054
-                    'new_registration',
1055
-                    'add-registrant',
1056
-                    array('event_id' => $EVT_ID),
1057
-                    'add-new-h2'
1058
-                );
1059
-            }
1060
-            $event = EEM_Event::instance()->get_one_by_ID($EVT_ID);
1061
-            if ($event instanceof EE_Event) {
1062
-                $this->_template_args['admin_page_header'] = sprintf(
1063
-                    esc_html__(
1064
-                        '%s Viewing registrations for the event: %s%s',
1065
-                        'event_espresso'
1066
-                    ),
1067
-                    '<h3 style="line-height:1.5em;">',
1068
-                    '<br /><a href="'
1069
-                    . EE_Admin_Page::add_query_args_and_nonce(
1070
-                        array(
1071
-                            'action' => 'edit',
1072
-                            'post'   => $event->ID(),
1073
-                        ),
1074
-                        EVENTS_ADMIN_URL
1075
-                    )
1076
-                    . '">&nbsp;'
1077
-                    . $event->get('EVT_name')
1078
-                    . '&nbsp;</a>&nbsp;',
1079
-                    '</h3>'
1080
-                );
1081
-            }
1082
-            $DTT_ID = ! empty($this->_req_data['datetime_id']) ? absint($this->_req_data['datetime_id']) : 0;
1083
-            $datetime = EEM_Datetime::instance()->get_one_by_ID($DTT_ID);
1084
-            if ($datetime instanceof EE_Datetime && $this->_template_args['admin_page_header'] !== '') {
1085
-                $this->_template_args['admin_page_header'] = substr(
1086
-                    $this->_template_args['admin_page_header'],
1087
-                    0,
1088
-                    -5
1089
-                );
1090
-                $this->_template_args['admin_page_header'] .= ' &nbsp;<span class="drk-grey-text">';
1091
-                $this->_template_args['admin_page_header'] .= '<span class="dashicons dashicons-calendar"></span>';
1092
-                $this->_template_args['admin_page_header'] .= $datetime->name();
1093
-                $this->_template_args['admin_page_header'] .= ' ( ' . $datetime->start_date() . ' )';
1094
-                $this->_template_args['admin_page_header'] .= '</span></h3>';
1095
-            }
1096
-        }
1097
-        $this->_template_args['after_list_table'] = $this->_display_legend($this->_registration_legend_items());
1098
-        $this->display_admin_list_table_page_with_no_sidebar();
1099
-    }
1100
-
1101
-
1102
-    /**
1103
-     * This sets the _registration property for the registration details screen
1104
-     *
1105
-     * @access private
1106
-     * @return bool
1107
-     * @throws EE_Error
1108
-     * @throws InvalidArgumentException
1109
-     * @throws InvalidDataTypeException
1110
-     * @throws InvalidInterfaceException
1111
-     */
1112
-    private function _set_registration_object()
1113
-    {
1114
-        // get out if we've already set the object
1115
-        if ($this->_registration instanceof EE_Registration) {
1116
-            return true;
1117
-        }
1118
-        $REG = EEM_Registration::instance();
1119
-        $REG_ID = (! empty($this->_req_data['_REG_ID'])) ? absint($this->_req_data['_REG_ID']) : false;
1120
-        if ($this->_registration = $REG->get_one_by_ID($REG_ID)) {
1121
-            return true;
1122
-        } else {
1123
-            $error_msg = sprintf(
1124
-                esc_html__(
1125
-                    'An error occurred and the details for Registration ID #%s could not be retrieved.',
1126
-                    'event_espresso'
1127
-                ),
1128
-                $REG_ID
1129
-            );
1130
-            EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
1131
-            $this->_registration = null;
1132
-            return false;
1133
-        }
1134
-    }
1135
-
1136
-
1137
-    /**
1138
-     * Used to retrieve registrations for the list table.
1139
-     *
1140
-     * @param int  $per_page
1141
-     * @param bool $count
1142
-     * @param bool $this_month
1143
-     * @param bool $today
1144
-     * @return EE_Registration[]|int
1145
-     * @throws EE_Error
1146
-     * @throws InvalidArgumentException
1147
-     * @throws InvalidDataTypeException
1148
-     * @throws InvalidInterfaceException
1149
-     */
1150
-    public function get_registrations(
1151
-        $per_page = 10,
1152
-        $count = false,
1153
-        $this_month = false,
1154
-        $today = false
1155
-    ) {
1156
-        if ($this_month) {
1157
-            $this->_req_data['status'] = 'month';
1158
-        }
1159
-        if ($today) {
1160
-            $this->_req_data['status'] = 'today';
1161
-        }
1162
-        $query_params = $this->_get_registration_query_parameters($this->_req_data, $per_page, $count);
1163
-        /**
1164
-         * Override the default groupby added by EEM_Base so that sorts with multiple order bys work as expected
1165
-         *
1166
-         * @link https://events.codebasehq.com/projects/event-espresso/tickets/10093
1167
-         * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1168
-         *                             or if you have the development copy of EE you can view this at the path:
1169
-         *                             /docs/G--Model-System/model-query-params.md
1170
-         */
1171
-        $query_params['group_by'] = '';
1172
-
1173
-        return $count
1174
-            ? EEM_Registration::instance()->count($query_params)
1175
-            /** @type EE_Registration[] */
1176
-            : EEM_Registration::instance()->get_all($query_params);
1177
-    }
1178
-
1179
-
1180
-    /**
1181
-     * Retrieves the query parameters to be used by the Registration model for getting registrations.
1182
-     * Note: this listens to values on the request for some of the query parameters.
1183
-     *
1184
-     * @param array $request
1185
-     * @param int   $per_page
1186
-     * @param bool  $count
1187
-     * @return array
1188
-     * @throws EE_Error
1189
-     */
1190
-    protected function _get_registration_query_parameters(
1191
-        $request = array(),
1192
-        $per_page = 10,
1193
-        $count = false
1194
-    ) {
1195
-
1196
-        $query_params = array(
1197
-            0                          => $this->_get_where_conditions_for_registrations_query(
1198
-                $request
1199
-            ),
1200
-            'caps'                     => EEM_Registration::caps_read_admin,
1201
-            'default_where_conditions' => 'this_model_only',
1202
-        );
1203
-        if (! $count) {
1204
-            $query_params = array_merge(
1205
-                $query_params,
1206
-                $this->_get_orderby_for_registrations_query(),
1207
-                $this->_get_limit($per_page)
1208
-            );
1209
-        }
1210
-
1211
-        return $query_params;
1212
-    }
1213
-
1214
-
1215
-    /**
1216
-     * This will add ATT_ID to the provided $where array for EE model query parameters.
1217
-     *
1218
-     * @param array $request usually the same as $this->_req_data but not necessarily
1219
-     * @return array
1220
-     */
1221
-    protected function addAttendeeIdToWhereConditions(array $request)
1222
-    {
1223
-        $where = array();
1224
-        if (! empty($request['ATT_ID'])) {
1225
-            $where['ATT_ID'] = absint($request['ATT_ID']);
1226
-        }
1227
-        return $where;
1228
-    }
1229
-
1230
-
1231
-    /**
1232
-     * This will add EVT_ID to the provided $where array for EE model query parameters.
1233
-     *
1234
-     * @param array $request usually the same as $this->_req_data but not necessarily
1235
-     * @return array
1236
-     */
1237
-    protected function _add_event_id_to_where_conditions(array $request)
1238
-    {
1239
-        $where = array();
1240
-        if (! empty($request['event_id'])) {
1241
-            $where['EVT_ID'] = absint($request['event_id']);
1242
-        }
1243
-        return $where;
1244
-    }
1245
-
1246
-
1247
-    /**
1248
-     * Adds category ID if it exists in the request to the where conditions for the registrations query.
1249
-     *
1250
-     * @param array $request usually the same as $this->_req_data but not necessarily
1251
-     * @return array
1252
-     */
1253
-    protected function _add_category_id_to_where_conditions(array $request)
1254
-    {
1255
-        $where = array();
1256
-        if (! empty($request['EVT_CAT']) && (int) $request['EVT_CAT'] !== -1) {
1257
-            $where['Event.Term_Taxonomy.term_id'] = absint($request['EVT_CAT']);
1258
-        }
1259
-        return $where;
1260
-    }
1261
-
1262
-
1263
-    /**
1264
-     * Adds the datetime ID if it exists in the request to the where conditions for the registrations query.
1265
-     *
1266
-     * @param array $request usually the same as $this->_req_data but not necessarily
1267
-     * @return array
1268
-     */
1269
-    protected function _add_datetime_id_to_where_conditions(array $request)
1270
-    {
1271
-        $where = array();
1272
-        if (! empty($request['datetime_id'])) {
1273
-            $where['Ticket.Datetime.DTT_ID'] = absint($request['datetime_id']);
1274
-        }
1275
-        if (! empty($request['DTT_ID'])) {
1276
-            $where['Ticket.Datetime.DTT_ID'] = absint($request['DTT_ID']);
1277
-        }
1278
-        return $where;
1279
-    }
1280
-
1281
-
1282
-    /**
1283
-     * Adds the correct registration status to the where conditions for the registrations query.
1284
-     *
1285
-     * @param array $request usually the same as $this->_req_data but not necessarily
1286
-     * @return array
1287
-     */
1288
-    protected function _add_registration_status_to_where_conditions(array $request)
1289
-    {
1290
-        $where = array();
1291
-        $view = EEH_Array::is_set($request, 'status', '');
1292
-        $registration_status = ! empty($request['_reg_status'])
1293
-            ? sanitize_text_field($request['_reg_status'])
1294
-            : '';
1295
-
1296
-        /*
22
+	/**
23
+	 * @var EE_Registration
24
+	 */
25
+	private $_registration;
26
+
27
+	/**
28
+	 * @var EE_Event
29
+	 */
30
+	private $_reg_event;
31
+
32
+	/**
33
+	 * @var EE_Session
34
+	 */
35
+	private $_session;
36
+
37
+	private static $_reg_status;
38
+
39
+	/**
40
+	 * Form for displaying the custom questions for this registration.
41
+	 * This gets used a few times throughout the request so its best to cache it
42
+	 *
43
+	 * @var EE_Registration_Custom_Questions_Form
44
+	 */
45
+	protected $_reg_custom_questions_form = null;
46
+
47
+
48
+	/**
49
+	 *        constructor
50
+	 *
51
+	 * @Constructor
52
+	 * @access public
53
+	 * @param bool $routing
54
+	 * @return Registrations_Admin_Page
55
+	 */
56
+	public function __construct($routing = true)
57
+	{
58
+		parent::__construct($routing);
59
+		add_action('wp_loaded', array($this, 'wp_loaded'));
60
+	}
61
+
62
+
63
+	public function wp_loaded()
64
+	{
65
+		// when adding a new registration...
66
+		if (isset($this->_req_data['action']) && $this->_req_data['action'] === 'new_registration') {
67
+			EE_System::do_not_cache();
68
+			if (! isset($this->_req_data['processing_registration'])
69
+				|| absint($this->_req_data['processing_registration']) !== 1
70
+			) {
71
+				// and it's NOT the attendee information reg step
72
+				// force cookie expiration by setting time to last week
73
+				setcookie('ee_registration_added', 0, time() - WEEK_IN_SECONDS, '/');
74
+				// and update the global
75
+				$_COOKIE['ee_registration_added'] = 0;
76
+			}
77
+		}
78
+	}
79
+
80
+
81
+	protected function _init_page_props()
82
+	{
83
+		$this->page_slug = REG_PG_SLUG;
84
+		$this->_admin_base_url = REG_ADMIN_URL;
85
+		$this->_admin_base_path = REG_ADMIN;
86
+		$this->page_label = esc_html__('Registrations', 'event_espresso');
87
+		$this->_cpt_routes = array(
88
+			'add_new_attendee' => 'espresso_attendees',
89
+			'edit_attendee'    => 'espresso_attendees',
90
+			'insert_attendee'  => 'espresso_attendees',
91
+			'update_attendee'  => 'espresso_attendees',
92
+		);
93
+		$this->_cpt_model_names = array(
94
+			'add_new_attendee' => 'EEM_Attendee',
95
+			'edit_attendee'    => 'EEM_Attendee',
96
+		);
97
+		$this->_cpt_edit_routes = array(
98
+			'espresso_attendees' => 'edit_attendee',
99
+		);
100
+		$this->_pagenow_map = array(
101
+			'add_new_attendee' => 'post-new.php',
102
+			'edit_attendee'    => 'post.php',
103
+			'trash'            => 'post.php',
104
+		);
105
+		add_action('edit_form_after_title', array($this, 'after_title_form_fields'), 10);
106
+		// add filters so that the comment urls don't take users to a confusing 404 page
107
+		add_filter('get_comment_link', array($this, 'clear_comment_link'), 10, 3);
108
+	}
109
+
110
+
111
+	public function clear_comment_link($link, $comment, $args)
112
+	{
113
+		// gotta make sure this only happens on this route
114
+		$post_type = get_post_type($comment->comment_post_ID);
115
+		if ($post_type === 'espresso_attendees') {
116
+			return '#commentsdiv';
117
+		}
118
+		return $link;
119
+	}
120
+
121
+
122
+	protected function _ajax_hooks()
123
+	{
124
+		// todo: all hooks for registrations ajax goes in here
125
+		add_action('wp_ajax_toggle_checkin_status', array($this, 'toggle_checkin_status'));
126
+	}
127
+
128
+
129
+	protected function _define_page_props()
130
+	{
131
+		$this->_admin_page_title = $this->page_label;
132
+		$this->_labels = array(
133
+			'buttons'                      => array(
134
+				'add-registrant'      => esc_html__('Add New Registration', 'event_espresso'),
135
+				'add-attendee'        => esc_html__('Add Contact', 'event_espresso'),
136
+				'edit'                => esc_html__('Edit Contact', 'event_espresso'),
137
+				'report'              => esc_html__("Event Registrations CSV Report", "event_espresso"),
138
+				'report_all'          => esc_html__('All Registrations CSV Report', 'event_espresso'),
139
+				'report_filtered'     => esc_html__('Filtered CSV Report', 'event_espresso'),
140
+				'contact_list_report' => esc_html__('Contact List Report', 'event_espresso'),
141
+				'contact_list_export' => esc_html__("Export Data", "event_espresso"),
142
+			),
143
+			'publishbox'                   => array(
144
+				'add_new_attendee' => esc_html__("Add Contact Record", 'event_espresso'),
145
+				'edit_attendee'    => esc_html__("Update Contact Record", 'event_espresso'),
146
+			),
147
+			'hide_add_button_on_cpt_route' => array(
148
+				'edit_attendee' => true,
149
+			),
150
+		);
151
+	}
152
+
153
+
154
+	/**
155
+	 *        grab url requests and route them
156
+	 *
157
+	 * @access private
158
+	 * @return void
159
+	 */
160
+	public function _set_page_routes()
161
+	{
162
+		$this->_get_registration_status_array();
163
+		$reg_id = ! empty($this->_req_data['_REG_ID']) && ! is_array($this->_req_data['_REG_ID'])
164
+			? $this->_req_data['_REG_ID'] : 0;
165
+		$reg_id = empty($reg_id) && ! empty($this->_req_data['reg_status_change_form']['REG_ID'])
166
+			? $this->_req_data['reg_status_change_form']['REG_ID']
167
+			: $reg_id;
168
+		$att_id = ! empty($this->_req_data['ATT_ID']) && ! is_array($this->_req_data['ATT_ID'])
169
+			? $this->_req_data['ATT_ID'] : 0;
170
+		$att_id = ! empty($this->_req_data['post']) && ! is_array($this->_req_data['post'])
171
+			? $this->_req_data['post']
172
+			: $att_id;
173
+		$this->_page_routes = array(
174
+			'default'                             => array(
175
+				'func'       => '_registrations_overview_list_table',
176
+				'capability' => 'ee_read_registrations',
177
+			),
178
+			'view_registration'                   => array(
179
+				'func'       => '_registration_details',
180
+				'capability' => 'ee_read_registration',
181
+				'obj_id'     => $reg_id,
182
+			),
183
+			'edit_registration'                   => array(
184
+				'func'               => '_update_attendee_registration_form',
185
+				'noheader'           => true,
186
+				'headers_sent_route' => 'view_registration',
187
+				'capability'         => 'ee_edit_registration',
188
+				'obj_id'             => $reg_id,
189
+				'_REG_ID'            => $reg_id,
190
+			),
191
+			'trash_registrations'                 => array(
192
+				'func'       => '_trash_or_restore_registrations',
193
+				'args'       => array('trash' => true),
194
+				'noheader'   => true,
195
+				'capability' => 'ee_delete_registrations',
196
+			),
197
+			'restore_registrations'               => array(
198
+				'func'       => '_trash_or_restore_registrations',
199
+				'args'       => array('trash' => false),
200
+				'noheader'   => true,
201
+				'capability' => 'ee_delete_registrations',
202
+			),
203
+			'delete_registrations'                => array(
204
+				'func'       => '_delete_registrations',
205
+				'noheader'   => true,
206
+				'capability' => 'ee_delete_registrations',
207
+			),
208
+			'new_registration'                    => array(
209
+				'func'       => 'new_registration',
210
+				'capability' => 'ee_edit_registrations',
211
+			),
212
+			'process_reg_step'                    => array(
213
+				'func'       => 'process_reg_step',
214
+				'noheader'   => true,
215
+				'capability' => 'ee_edit_registrations',
216
+			),
217
+			'redirect_to_txn'                     => array(
218
+				'func'       => 'redirect_to_txn',
219
+				'noheader'   => true,
220
+				'capability' => 'ee_edit_registrations',
221
+			),
222
+			'change_reg_status'                   => array(
223
+				'func'       => '_change_reg_status',
224
+				'noheader'   => true,
225
+				'capability' => 'ee_edit_registration',
226
+				'obj_id'     => $reg_id,
227
+			),
228
+			'approve_registration'                => array(
229
+				'func'       => 'approve_registration',
230
+				'noheader'   => true,
231
+				'capability' => 'ee_edit_registration',
232
+				'obj_id'     => $reg_id,
233
+			),
234
+			'approve_and_notify_registration'     => array(
235
+				'func'       => 'approve_registration',
236
+				'noheader'   => true,
237
+				'args'       => array(true),
238
+				'capability' => 'ee_edit_registration',
239
+				'obj_id'     => $reg_id,
240
+			),
241
+			'approve_registrations'               => array(
242
+				'func'       => 'bulk_action_on_registrations',
243
+				'noheader'   => true,
244
+				'capability' => 'ee_edit_registrations',
245
+				'args'       => array('approve'),
246
+			),
247
+			'approve_and_notify_registrations'    => array(
248
+				'func'       => 'bulk_action_on_registrations',
249
+				'noheader'   => true,
250
+				'capability' => 'ee_edit_registrations',
251
+				'args'       => array('approve', true),
252
+			),
253
+			'decline_registration'                => array(
254
+				'func'       => 'decline_registration',
255
+				'noheader'   => true,
256
+				'capability' => 'ee_edit_registration',
257
+				'obj_id'     => $reg_id,
258
+			),
259
+			'decline_and_notify_registration'     => array(
260
+				'func'       => 'decline_registration',
261
+				'noheader'   => true,
262
+				'args'       => array(true),
263
+				'capability' => 'ee_edit_registration',
264
+				'obj_id'     => $reg_id,
265
+			),
266
+			'decline_registrations'               => array(
267
+				'func'       => 'bulk_action_on_registrations',
268
+				'noheader'   => true,
269
+				'capability' => 'ee_edit_registrations',
270
+				'args'       => array('decline'),
271
+			),
272
+			'decline_and_notify_registrations'    => array(
273
+				'func'       => 'bulk_action_on_registrations',
274
+				'noheader'   => true,
275
+				'capability' => 'ee_edit_registrations',
276
+				'args'       => array('decline', true),
277
+			),
278
+			'pending_registration'                => array(
279
+				'func'       => 'pending_registration',
280
+				'noheader'   => true,
281
+				'capability' => 'ee_edit_registration',
282
+				'obj_id'     => $reg_id,
283
+			),
284
+			'pending_and_notify_registration'     => array(
285
+				'func'       => 'pending_registration',
286
+				'noheader'   => true,
287
+				'args'       => array(true),
288
+				'capability' => 'ee_edit_registration',
289
+				'obj_id'     => $reg_id,
290
+			),
291
+			'pending_registrations'               => array(
292
+				'func'       => 'bulk_action_on_registrations',
293
+				'noheader'   => true,
294
+				'capability' => 'ee_edit_registrations',
295
+				'args'       => array('pending'),
296
+			),
297
+			'pending_and_notify_registrations'    => array(
298
+				'func'       => 'bulk_action_on_registrations',
299
+				'noheader'   => true,
300
+				'capability' => 'ee_edit_registrations',
301
+				'args'       => array('pending', true),
302
+			),
303
+			'no_approve_registration'             => array(
304
+				'func'       => 'not_approve_registration',
305
+				'noheader'   => true,
306
+				'capability' => 'ee_edit_registration',
307
+				'obj_id'     => $reg_id,
308
+			),
309
+			'no_approve_and_notify_registration'  => array(
310
+				'func'       => 'not_approve_registration',
311
+				'noheader'   => true,
312
+				'args'       => array(true),
313
+				'capability' => 'ee_edit_registration',
314
+				'obj_id'     => $reg_id,
315
+			),
316
+			'no_approve_registrations'            => array(
317
+				'func'       => 'bulk_action_on_registrations',
318
+				'noheader'   => true,
319
+				'capability' => 'ee_edit_registrations',
320
+				'args'       => array('not_approve'),
321
+			),
322
+			'no_approve_and_notify_registrations' => array(
323
+				'func'       => 'bulk_action_on_registrations',
324
+				'noheader'   => true,
325
+				'capability' => 'ee_edit_registrations',
326
+				'args'       => array('not_approve', true),
327
+			),
328
+			'cancel_registration'                 => array(
329
+				'func'       => 'cancel_registration',
330
+				'noheader'   => true,
331
+				'capability' => 'ee_edit_registration',
332
+				'obj_id'     => $reg_id,
333
+			),
334
+			'cancel_and_notify_registration'      => array(
335
+				'func'       => 'cancel_registration',
336
+				'noheader'   => true,
337
+				'args'       => array(true),
338
+				'capability' => 'ee_edit_registration',
339
+				'obj_id'     => $reg_id,
340
+			),
341
+			'cancel_registrations'                => array(
342
+				'func'       => 'bulk_action_on_registrations',
343
+				'noheader'   => true,
344
+				'capability' => 'ee_edit_registrations',
345
+				'args'       => array('cancel'),
346
+			),
347
+			'cancel_and_notify_registrations'     => array(
348
+				'func'       => 'bulk_action_on_registrations',
349
+				'noheader'   => true,
350
+				'capability' => 'ee_edit_registrations',
351
+				'args'       => array('cancel', true),
352
+			),
353
+			'wait_list_registration'              => array(
354
+				'func'       => 'wait_list_registration',
355
+				'noheader'   => true,
356
+				'capability' => 'ee_edit_registration',
357
+				'obj_id'     => $reg_id,
358
+			),
359
+			'wait_list_and_notify_registration'   => array(
360
+				'func'       => 'wait_list_registration',
361
+				'noheader'   => true,
362
+				'args'       => array(true),
363
+				'capability' => 'ee_edit_registration',
364
+				'obj_id'     => $reg_id,
365
+			),
366
+			'contact_list'                        => array(
367
+				'func'       => '_attendee_contact_list_table',
368
+				'capability' => 'ee_read_contacts',
369
+			),
370
+			'add_new_attendee'                    => array(
371
+				'func' => '_create_new_cpt_item',
372
+				'args' => array(
373
+					'new_attendee' => true,
374
+					'capability'   => 'ee_edit_contacts',
375
+				),
376
+			),
377
+			'edit_attendee'                       => array(
378
+				'func'       => '_edit_cpt_item',
379
+				'capability' => 'ee_edit_contacts',
380
+				'obj_id'     => $att_id,
381
+			),
382
+			'duplicate_attendee'                  => array(
383
+				'func'       => '_duplicate_attendee',
384
+				'noheader'   => true,
385
+				'capability' => 'ee_edit_contacts',
386
+				'obj_id'     => $att_id,
387
+			),
388
+			'insert_attendee'                     => array(
389
+				'func'       => '_insert_or_update_attendee',
390
+				'args'       => array(
391
+					'new_attendee' => true,
392
+				),
393
+				'noheader'   => true,
394
+				'capability' => 'ee_edit_contacts',
395
+			),
396
+			'update_attendee'                     => array(
397
+				'func'       => '_insert_or_update_attendee',
398
+				'args'       => array(
399
+					'new_attendee' => false,
400
+				),
401
+				'noheader'   => true,
402
+				'capability' => 'ee_edit_contacts',
403
+				'obj_id'     => $att_id,
404
+			),
405
+			'trash_attendees'                     => array(
406
+				'func'       => '_trash_or_restore_attendees',
407
+				'args'       => array(
408
+					'trash' => 'true',
409
+				),
410
+				'noheader'   => true,
411
+				'capability' => 'ee_delete_contacts',
412
+			),
413
+			'trash_attendee'                      => array(
414
+				'func'       => '_trash_or_restore_attendees',
415
+				'args'       => array(
416
+					'trash' => true,
417
+				),
418
+				'noheader'   => true,
419
+				'capability' => 'ee_delete_contacts',
420
+				'obj_id'     => $att_id,
421
+			),
422
+			'restore_attendees'                   => array(
423
+				'func'       => '_trash_or_restore_attendees',
424
+				'args'       => array(
425
+					'trash' => false,
426
+				),
427
+				'noheader'   => true,
428
+				'capability' => 'ee_delete_contacts',
429
+				'obj_id'     => $att_id,
430
+			),
431
+			'resend_registration'                 => array(
432
+				'func'       => '_resend_registration',
433
+				'noheader'   => true,
434
+				'capability' => 'ee_send_message',
435
+			),
436
+			'registrations_report'                => array(
437
+				'func'       => '_registrations_report',
438
+				'noheader'   => true,
439
+				'capability' => 'ee_read_registrations',
440
+			),
441
+			'contact_list_export'                 => array(
442
+				'func'       => '_contact_list_export',
443
+				'noheader'   => true,
444
+				'capability' => 'export',
445
+			),
446
+			'contact_list_report'                 => array(
447
+				'func'       => '_contact_list_report',
448
+				'noheader'   => true,
449
+				'capability' => 'ee_read_contacts',
450
+			),
451
+		);
452
+	}
453
+
454
+
455
+	protected function _set_page_config()
456
+	{
457
+		$this->_page_config = array(
458
+			'default'           => array(
459
+				'nav'           => array(
460
+					'label' => esc_html__('Overview', 'event_espresso'),
461
+					'order' => 5,
462
+				),
463
+				'help_tabs'     => array(
464
+					'registrations_overview_help_tab'                       => array(
465
+						'title'    => esc_html__('Registrations Overview', 'event_espresso'),
466
+						'filename' => 'registrations_overview',
467
+					),
468
+					'registrations_overview_table_column_headings_help_tab' => array(
469
+						'title'    => esc_html__('Registrations Table Column Headings', 'event_espresso'),
470
+						'filename' => 'registrations_overview_table_column_headings',
471
+					),
472
+					'registrations_overview_filters_help_tab'               => array(
473
+						'title'    => esc_html__('Registration Filters', 'event_espresso'),
474
+						'filename' => 'registrations_overview_filters',
475
+					),
476
+					'registrations_overview_views_help_tab'                 => array(
477
+						'title'    => esc_html__('Registration Views', 'event_espresso'),
478
+						'filename' => 'registrations_overview_views',
479
+					),
480
+					'registrations_regoverview_other_help_tab'              => array(
481
+						'title'    => esc_html__('Registrations Other', 'event_espresso'),
482
+						'filename' => 'registrations_overview_other',
483
+					),
484
+				),
485
+				'help_tour'     => array('Registration_Overview_Help_Tour'),
486
+				'qtips'         => array('Registration_List_Table_Tips'),
487
+				'list_table'    => 'EE_Registrations_List_Table',
488
+				'require_nonce' => false,
489
+			),
490
+			'view_registration' => array(
491
+				'nav'           => array(
492
+					'label'      => esc_html__('REG Details', 'event_espresso'),
493
+					'order'      => 15,
494
+					'url'        => isset($this->_req_data['_REG_ID'])
495
+						? add_query_arg(array('_REG_ID' => $this->_req_data['_REG_ID']), $this->_current_page_view_url)
496
+						: $this->_admin_base_url,
497
+					'persistent' => false,
498
+				),
499
+				'help_tabs'     => array(
500
+					'registrations_details_help_tab'                    => array(
501
+						'title'    => esc_html__('Registration Details', 'event_espresso'),
502
+						'filename' => 'registrations_details',
503
+					),
504
+					'registrations_details_table_help_tab'              => array(
505
+						'title'    => esc_html__('Registration Details Table', 'event_espresso'),
506
+						'filename' => 'registrations_details_table',
507
+					),
508
+					'registrations_details_form_answers_help_tab'       => array(
509
+						'title'    => esc_html__('Registration Form Answers', 'event_espresso'),
510
+						'filename' => 'registrations_details_form_answers',
511
+					),
512
+					'registrations_details_registrant_details_help_tab' => array(
513
+						'title'    => esc_html__('Contact Details', 'event_espresso'),
514
+						'filename' => 'registrations_details_registrant_details',
515
+					),
516
+				),
517
+				'help_tour'     => array('Registration_Details_Help_Tour'),
518
+				'metaboxes'     => array_merge(
519
+					$this->_default_espresso_metaboxes,
520
+					array('_registration_details_metaboxes')
521
+				),
522
+				'require_nonce' => false,
523
+			),
524
+			'new_registration'  => array(
525
+				'nav'           => array(
526
+					'label'      => esc_html__('Add New Registration', 'event_espresso'),
527
+					'url'        => '#',
528
+					'order'      => 15,
529
+					'persistent' => false,
530
+				),
531
+				'metaboxes'     => $this->_default_espresso_metaboxes,
532
+				'labels'        => array(
533
+					'publishbox' => esc_html__('Save Registration', 'event_espresso'),
534
+				),
535
+				'require_nonce' => false,
536
+			),
537
+			'add_new_attendee'  => array(
538
+				'nav'           => array(
539
+					'label'      => esc_html__('Add Contact', 'event_espresso'),
540
+					'order'      => 15,
541
+					'persistent' => false,
542
+				),
543
+				'metaboxes'     => array_merge(
544
+					$this->_default_espresso_metaboxes,
545
+					array('_publish_post_box', 'attendee_editor_metaboxes')
546
+				),
547
+				'require_nonce' => false,
548
+			),
549
+			'edit_attendee'     => array(
550
+				'nav'           => array(
551
+					'label'      => esc_html__('Edit Contact', 'event_espresso'),
552
+					'order'      => 15,
553
+					'persistent' => false,
554
+					'url'        => isset($this->_req_data['ATT_ID'])
555
+						? add_query_arg(array('ATT_ID' => $this->_req_data['ATT_ID']), $this->_current_page_view_url)
556
+						: $this->_admin_base_url,
557
+				),
558
+				'metaboxes'     => array('attendee_editor_metaboxes'),
559
+				'require_nonce' => false,
560
+			),
561
+			'contact_list'      => array(
562
+				'nav'           => array(
563
+					'label' => esc_html__('Contact List', 'event_espresso'),
564
+					'order' => 20,
565
+				),
566
+				'list_table'    => 'EE_Attendee_Contact_List_Table',
567
+				'help_tabs'     => array(
568
+					'registrations_contact_list_help_tab'                       => array(
569
+						'title'    => esc_html__('Registrations Contact List', 'event_espresso'),
570
+						'filename' => 'registrations_contact_list',
571
+					),
572
+					'registrations_contact-list_table_column_headings_help_tab' => array(
573
+						'title'    => esc_html__('Contact List Table Column Headings', 'event_espresso'),
574
+						'filename' => 'registrations_contact_list_table_column_headings',
575
+					),
576
+					'registrations_contact_list_views_help_tab'                 => array(
577
+						'title'    => esc_html__('Contact List Views', 'event_espresso'),
578
+						'filename' => 'registrations_contact_list_views',
579
+					),
580
+					'registrations_contact_list_other_help_tab'                 => array(
581
+						'title'    => esc_html__('Contact List Other', 'event_espresso'),
582
+						'filename' => 'registrations_contact_list_other',
583
+					),
584
+				),
585
+				'help_tour'     => array('Contact_List_Help_Tour'),
586
+				'metaboxes'     => array(),
587
+				'require_nonce' => false,
588
+			),
589
+			// override default cpt routes
590
+			'create_new'        => '',
591
+			'edit'              => '',
592
+		);
593
+	}
594
+
595
+
596
+	/**
597
+	 * The below methods aren't used by this class currently
598
+	 */
599
+	protected function _add_screen_options()
600
+	{
601
+	}
602
+
603
+
604
+	protected function _add_feature_pointers()
605
+	{
606
+	}
607
+
608
+
609
+	public function admin_init()
610
+	{
611
+		EE_Registry::$i18n_js_strings['update_att_qstns'] = esc_html__(
612
+			'click "Update Registration Questions" to save your changes',
613
+			'event_espresso'
614
+		);
615
+	}
616
+
617
+
618
+	public function admin_notices()
619
+	{
620
+	}
621
+
622
+
623
+	public function admin_footer_scripts()
624
+	{
625
+	}
626
+
627
+
628
+	/**
629
+	 *        get list of registration statuses
630
+	 *
631
+	 * @access private
632
+	 * @return void
633
+	 * @throws EE_Error
634
+	 */
635
+	private function _get_registration_status_array()
636
+	{
637
+		self::$_reg_status = EEM_Registration::reg_status_array(array(), true);
638
+	}
639
+
640
+
641
+	protected function _add_screen_options_default()
642
+	{
643
+		$this->_per_page_screen_option();
644
+	}
645
+
646
+
647
+	protected function _add_screen_options_contact_list()
648
+	{
649
+		$page_title = $this->_admin_page_title;
650
+		$this->_admin_page_title = esc_html__("Contacts", 'event_espresso');
651
+		$this->_per_page_screen_option();
652
+		$this->_admin_page_title = $page_title;
653
+	}
654
+
655
+
656
+	public function load_scripts_styles()
657
+	{
658
+		// style
659
+		wp_register_style(
660
+			'espresso_reg',
661
+			REG_ASSETS_URL . 'espresso_registrations_admin.css',
662
+			array('ee-admin-css'),
663
+			EVENT_ESPRESSO_VERSION
664
+		);
665
+		wp_enqueue_style('espresso_reg');
666
+		// script
667
+		wp_register_script(
668
+			'espresso_reg',
669
+			REG_ASSETS_URL . 'espresso_registrations_admin.js',
670
+			array('jquery-ui-datepicker', 'jquery-ui-draggable', 'ee_admin_js'),
671
+			EVENT_ESPRESSO_VERSION,
672
+			true
673
+		);
674
+		wp_enqueue_script('espresso_reg');
675
+	}
676
+
677
+
678
+	public function load_scripts_styles_edit_attendee()
679
+	{
680
+		// stuff to only show up on our attendee edit details page.
681
+		$attendee_details_translations = array(
682
+			'att_publish_text' => sprintf(
683
+				esc_html__('Created on: <b>%1$s</b>', 'event_espresso'),
684
+				$this->_cpt_model_obj->get_datetime('ATT_created')
685
+			),
686
+		);
687
+		wp_localize_script('espresso_reg', 'ATTENDEE_DETAILS', $attendee_details_translations);
688
+		wp_enqueue_script('jquery-validate');
689
+	}
690
+
691
+
692
+	public function load_scripts_styles_view_registration()
693
+	{
694
+		// styles
695
+		wp_enqueue_style('espresso-ui-theme');
696
+		// scripts
697
+		$this->_get_reg_custom_questions_form($this->_registration->ID());
698
+		$this->_reg_custom_questions_form->wp_enqueue_scripts(true);
699
+	}
700
+
701
+
702
+	public function load_scripts_styles_contact_list()
703
+	{
704
+		wp_dequeue_style('espresso_reg');
705
+		wp_register_style(
706
+			'espresso_att',
707
+			REG_ASSETS_URL . 'espresso_attendees_admin.css',
708
+			array('ee-admin-css'),
709
+			EVENT_ESPRESSO_VERSION
710
+		);
711
+		wp_enqueue_style('espresso_att');
712
+	}
713
+
714
+
715
+	public function load_scripts_styles_new_registration()
716
+	{
717
+		wp_register_script(
718
+			'ee-spco-for-admin',
719
+			REG_ASSETS_URL . 'spco_for_admin.js',
720
+			array('underscore', 'jquery'),
721
+			EVENT_ESPRESSO_VERSION,
722
+			true
723
+		);
724
+		wp_enqueue_script('ee-spco-for-admin');
725
+		add_filter('FHEE__EED_Ticket_Selector__load_tckt_slctr_assets', '__return_true');
726
+		EE_Form_Section_Proper::wp_enqueue_scripts();
727
+		EED_Ticket_Selector::load_tckt_slctr_assets();
728
+		EE_Datepicker_Input::enqueue_styles_and_scripts();
729
+	}
730
+
731
+
732
+	public function AHEE__EE_Admin_Page__route_admin_request_resend_registration()
733
+	{
734
+		add_filter('FHEE_load_EE_messages', '__return_true');
735
+	}
736
+
737
+
738
+	public function AHEE__EE_Admin_Page__route_admin_request_approve_registration()
739
+	{
740
+		add_filter('FHEE_load_EE_messages', '__return_true');
741
+	}
742
+
743
+
744
+	protected function _set_list_table_views_default()
745
+	{
746
+		// for notification related bulk actions we need to make sure only active messengers have an option.
747
+		EED_Messages::set_autoloaders();
748
+		/** @type EE_Message_Resource_Manager $message_resource_manager */
749
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
750
+		$active_mts = $message_resource_manager->list_of_active_message_types();
751
+		// key= bulk_action_slug, value= message type.
752
+		$match_array = array(
753
+			'approve_registrations'    => 'registration',
754
+			'decline_registrations'    => 'declined_registration',
755
+			'pending_registrations'    => 'pending_approval',
756
+			'no_approve_registrations' => 'not_approved_registration',
757
+			'cancel_registrations'     => 'cancelled_registration',
758
+		);
759
+		$can_send = EE_Registry::instance()->CAP->current_user_can(
760
+			'ee_send_message',
761
+			'batch_send_messages'
762
+		);
763
+		/** setup reg status bulk actions **/
764
+		$def_reg_status_actions['approve_registrations'] = esc_html__('Approve Registrations', 'event_espresso');
765
+		if ($can_send && in_array($match_array['approve_registrations'], $active_mts, true)) {
766
+			$def_reg_status_actions['approve_and_notify_registrations'] = esc_html__(
767
+				'Approve and Notify Registrations',
768
+				'event_espresso'
769
+			);
770
+		}
771
+		$def_reg_status_actions['decline_registrations'] = esc_html__('Decline Registrations', 'event_espresso');
772
+		if ($can_send && in_array($match_array['decline_registrations'], $active_mts, true)) {
773
+			$def_reg_status_actions['decline_and_notify_registrations'] = esc_html__(
774
+				'Decline and Notify Registrations',
775
+				'event_espresso'
776
+			);
777
+		}
778
+		$def_reg_status_actions['pending_registrations'] = esc_html__(
779
+			'Set Registrations to Pending Payment',
780
+			'event_espresso'
781
+		);
782
+		if ($can_send && in_array($match_array['pending_registrations'], $active_mts, true)) {
783
+			$def_reg_status_actions['pending_and_notify_registrations'] = esc_html__(
784
+				'Set Registrations to Pending Payment and Notify',
785
+				'event_espresso'
786
+			);
787
+		}
788
+		$def_reg_status_actions['no_approve_registrations'] = esc_html__(
789
+			'Set Registrations to Not Approved',
790
+			'event_espresso'
791
+		);
792
+		if ($can_send && in_array($match_array['no_approve_registrations'], $active_mts, true)) {
793
+			$def_reg_status_actions['no_approve_and_notify_registrations'] = esc_html__(
794
+				'Set Registrations to Not Approved and Notify',
795
+				'event_espresso'
796
+			);
797
+		}
798
+		$def_reg_status_actions['cancel_registrations'] = esc_html__('Cancel Registrations', 'event_espresso');
799
+		if ($can_send && in_array($match_array['cancel_registrations'], $active_mts, true)) {
800
+			$def_reg_status_actions['cancel_and_notify_registrations'] = esc_html__(
801
+				'Cancel Registrations and Notify',
802
+				'event_espresso'
803
+			);
804
+		}
805
+		$def_reg_status_actions = apply_filters(
806
+			'FHEE__Registrations_Admin_Page___set_list_table_views_default__def_reg_status_actions_array',
807
+			$def_reg_status_actions,
808
+			$active_mts,
809
+			$can_send
810
+		);
811
+
812
+		$this->_views = array(
813
+			'all'   => array(
814
+				'slug'        => 'all',
815
+				'label'       => esc_html__('View All Registrations', 'event_espresso'),
816
+				'count'       => 0,
817
+				'bulk_action' => array_merge(
818
+					$def_reg_status_actions,
819
+					array(
820
+						'trash_registrations' => esc_html__('Trash Registrations', 'event_espresso'),
821
+					)
822
+				),
823
+			),
824
+			'month' => array(
825
+				'slug'        => 'month',
826
+				'label'       => esc_html__('This Month', 'event_espresso'),
827
+				'count'       => 0,
828
+				'bulk_action' => array_merge(
829
+					$def_reg_status_actions,
830
+					array(
831
+						'trash_registrations' => esc_html__('Trash Registrations', 'event_espresso'),
832
+					)
833
+				),
834
+			),
835
+			'today' => array(
836
+				'slug'        => 'today',
837
+				'label'       => sprintf(
838
+					esc_html__('Today - %s', 'event_espresso'),
839
+					date('M d, Y', current_time('timestamp'))
840
+				),
841
+				'count'       => 0,
842
+				'bulk_action' => array_merge(
843
+					$def_reg_status_actions,
844
+					array(
845
+						'trash_registrations' => esc_html__('Trash Registrations', 'event_espresso'),
846
+					)
847
+				),
848
+			),
849
+		);
850
+		if (EE_Registry::instance()->CAP->current_user_can(
851
+			'ee_delete_registrations',
852
+			'espresso_registrations_delete_registration'
853
+		)) {
854
+			$this->_views['incomplete'] = array(
855
+				'slug'        => 'incomplete',
856
+				'label'       => esc_html__('Incomplete', 'event_espresso'),
857
+				'count'       => 0,
858
+				'bulk_action' => array(
859
+					'trash_registrations' => esc_html__('Trash Registrations', 'event_espresso'),
860
+				),
861
+			);
862
+			$this->_views['trash'] = array(
863
+				'slug'        => 'trash',
864
+				'label'       => esc_html__('Trash', 'event_espresso'),
865
+				'count'       => 0,
866
+				'bulk_action' => array(
867
+					'restore_registrations' => esc_html__('Restore Registrations', 'event_espresso'),
868
+					'delete_registrations'  => esc_html__('Delete Registrations Permanently', 'event_espresso'),
869
+				),
870
+			);
871
+		}
872
+	}
873
+
874
+
875
+	protected function _set_list_table_views_contact_list()
876
+	{
877
+		$this->_views = array(
878
+			'in_use' => array(
879
+				'slug'        => 'in_use',
880
+				'label'       => esc_html__('In Use', 'event_espresso'),
881
+				'count'       => 0,
882
+				'bulk_action' => array(
883
+					'trash_attendees' => esc_html__('Move to Trash', 'event_espresso'),
884
+				),
885
+			),
886
+		);
887
+		if (EE_Registry::instance()->CAP->current_user_can(
888
+			'ee_delete_contacts',
889
+			'espresso_registrations_trash_attendees'
890
+		)
891
+		) {
892
+			$this->_views['trash'] = array(
893
+				'slug'        => 'trash',
894
+				'label'       => esc_html__('Trash', 'event_espresso'),
895
+				'count'       => 0,
896
+				'bulk_action' => array(
897
+					'restore_attendees' => esc_html__('Restore from Trash', 'event_espresso'),
898
+				),
899
+			);
900
+		}
901
+	}
902
+
903
+
904
+	protected function _registration_legend_items()
905
+	{
906
+		$fc_items = array(
907
+			'star-icon'        => array(
908
+				'class' => 'dashicons dashicons-star-filled lt-blue-icon ee-icon-size-8',
909
+				'desc'  => esc_html__('This is the Primary Registrant', 'event_espresso'),
910
+			),
911
+			'view_details'     => array(
912
+				'class' => 'dashicons dashicons-clipboard',
913
+				'desc'  => esc_html__('View Registration Details', 'event_espresso'),
914
+			),
915
+			'edit_attendee'    => array(
916
+				'class' => 'ee-icon ee-icon-user-edit ee-icon-size-16',
917
+				'desc'  => esc_html__('Edit Contact Details', 'event_espresso'),
918
+			),
919
+			'view_transaction' => array(
920
+				'class' => 'dashicons dashicons-cart',
921
+				'desc'  => esc_html__('View Transaction Details', 'event_espresso'),
922
+			),
923
+			'view_invoice'     => array(
924
+				'class' => 'dashicons dashicons-media-spreadsheet',
925
+				'desc'  => esc_html__('View Transaction Invoice', 'event_espresso'),
926
+			),
927
+		);
928
+		if (EE_Registry::instance()->CAP->current_user_can(
929
+			'ee_send_message',
930
+			'espresso_registrations_resend_registration'
931
+		)) {
932
+			$fc_items['resend_registration'] = array(
933
+				'class' => 'dashicons dashicons-email-alt',
934
+				'desc'  => esc_html__('Resend Registration Details', 'event_espresso'),
935
+			);
936
+		} else {
937
+			$fc_items['blank'] = array('class' => 'blank', 'desc' => '');
938
+		}
939
+		if (EE_Registry::instance()->CAP->current_user_can(
940
+			'ee_read_global_messages',
941
+			'view_filtered_messages'
942
+		)) {
943
+			$related_for_icon = EEH_MSG_Template::get_message_action_icon('see_notifications_for');
944
+			if (isset($related_for_icon['css_class']) && isset($related_for_icon['label'])) {
945
+				$fc_items['view_related_messages'] = array(
946
+					'class' => $related_for_icon['css_class'],
947
+					'desc'  => $related_for_icon['label'],
948
+				);
949
+			}
950
+		}
951
+		$sc_items = array(
952
+			'approved_status'   => array(
953
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_approved,
954
+				'desc'  => EEH_Template::pretty_status(
955
+					EEM_Registration::status_id_approved,
956
+					false,
957
+					'sentence'
958
+				),
959
+			),
960
+			'pending_status'    => array(
961
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_pending_payment,
962
+				'desc'  => EEH_Template::pretty_status(
963
+					EEM_Registration::status_id_pending_payment,
964
+					false,
965
+					'sentence'
966
+				),
967
+			),
968
+			'wait_list'         => array(
969
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_wait_list,
970
+				'desc'  => EEH_Template::pretty_status(
971
+					EEM_Registration::status_id_wait_list,
972
+					false,
973
+					'sentence'
974
+				),
975
+			),
976
+			'incomplete_status' => array(
977
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_incomplete,
978
+				'desc'  => EEH_Template::pretty_status(
979
+					EEM_Registration::status_id_incomplete,
980
+					false,
981
+					'sentence'
982
+				),
983
+			),
984
+			'not_approved'      => array(
985
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_not_approved,
986
+				'desc'  => EEH_Template::pretty_status(
987
+					EEM_Registration::status_id_not_approved,
988
+					false,
989
+					'sentence'
990
+				),
991
+			),
992
+			'declined_status'   => array(
993
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_declined,
994
+				'desc'  => EEH_Template::pretty_status(
995
+					EEM_Registration::status_id_declined,
996
+					false,
997
+					'sentence'
998
+				),
999
+			),
1000
+			'cancelled_status'  => array(
1001
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_cancelled,
1002
+				'desc'  => EEH_Template::pretty_status(
1003
+					EEM_Registration::status_id_cancelled,
1004
+					false,
1005
+					'sentence'
1006
+				),
1007
+			),
1008
+		);
1009
+		return array_merge($fc_items, $sc_items);
1010
+	}
1011
+
1012
+
1013
+
1014
+	/***************************************        REGISTRATION OVERVIEW        **************************************/
1015
+	/**
1016
+	 * @throws \EE_Error
1017
+	 */
1018
+	protected function _registrations_overview_list_table()
1019
+	{
1020
+		$this->_template_args['admin_page_header'] = '';
1021
+		$EVT_ID = ! empty($this->_req_data['event_id'])
1022
+			? absint($this->_req_data['event_id'])
1023
+			: 0;
1024
+		$ATT_ID = ! empty($this->_req_data['ATT_ID'])
1025
+			? absint($this->_req_data['ATT_ID'])
1026
+			: 0;
1027
+		if ($ATT_ID) {
1028
+			$attendee = EEM_Attendee::instance()->get_one_by_ID($ATT_ID);
1029
+			if ($attendee instanceof EE_Attendee) {
1030
+				$this->_template_args['admin_page_header'] = sprintf(
1031
+					esc_html__(
1032
+						'%1$s Viewing registrations for %2$s%3$s',
1033
+						'event_espresso'
1034
+					),
1035
+					'<h3 style="line-height:1.5em;">',
1036
+					'<a href="' . EE_Admin_Page::add_query_args_and_nonce(
1037
+						array(
1038
+							'action' => 'edit_attendee',
1039
+							'post'   => $ATT_ID,
1040
+						),
1041
+						REG_ADMIN_URL
1042
+					) . '">' . $attendee->full_name() . '</a>',
1043
+					'</h3>'
1044
+				);
1045
+			}
1046
+		}
1047
+		if ($EVT_ID) {
1048
+			if (EE_Registry::instance()->CAP->current_user_can(
1049
+				'ee_edit_registrations',
1050
+				'espresso_registrations_new_registration',
1051
+				$EVT_ID
1052
+			)) {
1053
+				$this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
1054
+					'new_registration',
1055
+					'add-registrant',
1056
+					array('event_id' => $EVT_ID),
1057
+					'add-new-h2'
1058
+				);
1059
+			}
1060
+			$event = EEM_Event::instance()->get_one_by_ID($EVT_ID);
1061
+			if ($event instanceof EE_Event) {
1062
+				$this->_template_args['admin_page_header'] = sprintf(
1063
+					esc_html__(
1064
+						'%s Viewing registrations for the event: %s%s',
1065
+						'event_espresso'
1066
+					),
1067
+					'<h3 style="line-height:1.5em;">',
1068
+					'<br /><a href="'
1069
+					. EE_Admin_Page::add_query_args_and_nonce(
1070
+						array(
1071
+							'action' => 'edit',
1072
+							'post'   => $event->ID(),
1073
+						),
1074
+						EVENTS_ADMIN_URL
1075
+					)
1076
+					. '">&nbsp;'
1077
+					. $event->get('EVT_name')
1078
+					. '&nbsp;</a>&nbsp;',
1079
+					'</h3>'
1080
+				);
1081
+			}
1082
+			$DTT_ID = ! empty($this->_req_data['datetime_id']) ? absint($this->_req_data['datetime_id']) : 0;
1083
+			$datetime = EEM_Datetime::instance()->get_one_by_ID($DTT_ID);
1084
+			if ($datetime instanceof EE_Datetime && $this->_template_args['admin_page_header'] !== '') {
1085
+				$this->_template_args['admin_page_header'] = substr(
1086
+					$this->_template_args['admin_page_header'],
1087
+					0,
1088
+					-5
1089
+				);
1090
+				$this->_template_args['admin_page_header'] .= ' &nbsp;<span class="drk-grey-text">';
1091
+				$this->_template_args['admin_page_header'] .= '<span class="dashicons dashicons-calendar"></span>';
1092
+				$this->_template_args['admin_page_header'] .= $datetime->name();
1093
+				$this->_template_args['admin_page_header'] .= ' ( ' . $datetime->start_date() . ' )';
1094
+				$this->_template_args['admin_page_header'] .= '</span></h3>';
1095
+			}
1096
+		}
1097
+		$this->_template_args['after_list_table'] = $this->_display_legend($this->_registration_legend_items());
1098
+		$this->display_admin_list_table_page_with_no_sidebar();
1099
+	}
1100
+
1101
+
1102
+	/**
1103
+	 * This sets the _registration property for the registration details screen
1104
+	 *
1105
+	 * @access private
1106
+	 * @return bool
1107
+	 * @throws EE_Error
1108
+	 * @throws InvalidArgumentException
1109
+	 * @throws InvalidDataTypeException
1110
+	 * @throws InvalidInterfaceException
1111
+	 */
1112
+	private function _set_registration_object()
1113
+	{
1114
+		// get out if we've already set the object
1115
+		if ($this->_registration instanceof EE_Registration) {
1116
+			return true;
1117
+		}
1118
+		$REG = EEM_Registration::instance();
1119
+		$REG_ID = (! empty($this->_req_data['_REG_ID'])) ? absint($this->_req_data['_REG_ID']) : false;
1120
+		if ($this->_registration = $REG->get_one_by_ID($REG_ID)) {
1121
+			return true;
1122
+		} else {
1123
+			$error_msg = sprintf(
1124
+				esc_html__(
1125
+					'An error occurred and the details for Registration ID #%s could not be retrieved.',
1126
+					'event_espresso'
1127
+				),
1128
+				$REG_ID
1129
+			);
1130
+			EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
1131
+			$this->_registration = null;
1132
+			return false;
1133
+		}
1134
+	}
1135
+
1136
+
1137
+	/**
1138
+	 * Used to retrieve registrations for the list table.
1139
+	 *
1140
+	 * @param int  $per_page
1141
+	 * @param bool $count
1142
+	 * @param bool $this_month
1143
+	 * @param bool $today
1144
+	 * @return EE_Registration[]|int
1145
+	 * @throws EE_Error
1146
+	 * @throws InvalidArgumentException
1147
+	 * @throws InvalidDataTypeException
1148
+	 * @throws InvalidInterfaceException
1149
+	 */
1150
+	public function get_registrations(
1151
+		$per_page = 10,
1152
+		$count = false,
1153
+		$this_month = false,
1154
+		$today = false
1155
+	) {
1156
+		if ($this_month) {
1157
+			$this->_req_data['status'] = 'month';
1158
+		}
1159
+		if ($today) {
1160
+			$this->_req_data['status'] = 'today';
1161
+		}
1162
+		$query_params = $this->_get_registration_query_parameters($this->_req_data, $per_page, $count);
1163
+		/**
1164
+		 * Override the default groupby added by EEM_Base so that sorts with multiple order bys work as expected
1165
+		 *
1166
+		 * @link https://events.codebasehq.com/projects/event-espresso/tickets/10093
1167
+		 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1168
+		 *                             or if you have the development copy of EE you can view this at the path:
1169
+		 *                             /docs/G--Model-System/model-query-params.md
1170
+		 */
1171
+		$query_params['group_by'] = '';
1172
+
1173
+		return $count
1174
+			? EEM_Registration::instance()->count($query_params)
1175
+			/** @type EE_Registration[] */
1176
+			: EEM_Registration::instance()->get_all($query_params);
1177
+	}
1178
+
1179
+
1180
+	/**
1181
+	 * Retrieves the query parameters to be used by the Registration model for getting registrations.
1182
+	 * Note: this listens to values on the request for some of the query parameters.
1183
+	 *
1184
+	 * @param array $request
1185
+	 * @param int   $per_page
1186
+	 * @param bool  $count
1187
+	 * @return array
1188
+	 * @throws EE_Error
1189
+	 */
1190
+	protected function _get_registration_query_parameters(
1191
+		$request = array(),
1192
+		$per_page = 10,
1193
+		$count = false
1194
+	) {
1195
+
1196
+		$query_params = array(
1197
+			0                          => $this->_get_where_conditions_for_registrations_query(
1198
+				$request
1199
+			),
1200
+			'caps'                     => EEM_Registration::caps_read_admin,
1201
+			'default_where_conditions' => 'this_model_only',
1202
+		);
1203
+		if (! $count) {
1204
+			$query_params = array_merge(
1205
+				$query_params,
1206
+				$this->_get_orderby_for_registrations_query(),
1207
+				$this->_get_limit($per_page)
1208
+			);
1209
+		}
1210
+
1211
+		return $query_params;
1212
+	}
1213
+
1214
+
1215
+	/**
1216
+	 * This will add ATT_ID to the provided $where array for EE model query parameters.
1217
+	 *
1218
+	 * @param array $request usually the same as $this->_req_data but not necessarily
1219
+	 * @return array
1220
+	 */
1221
+	protected function addAttendeeIdToWhereConditions(array $request)
1222
+	{
1223
+		$where = array();
1224
+		if (! empty($request['ATT_ID'])) {
1225
+			$where['ATT_ID'] = absint($request['ATT_ID']);
1226
+		}
1227
+		return $where;
1228
+	}
1229
+
1230
+
1231
+	/**
1232
+	 * This will add EVT_ID to the provided $where array for EE model query parameters.
1233
+	 *
1234
+	 * @param array $request usually the same as $this->_req_data but not necessarily
1235
+	 * @return array
1236
+	 */
1237
+	protected function _add_event_id_to_where_conditions(array $request)
1238
+	{
1239
+		$where = array();
1240
+		if (! empty($request['event_id'])) {
1241
+			$where['EVT_ID'] = absint($request['event_id']);
1242
+		}
1243
+		return $where;
1244
+	}
1245
+
1246
+
1247
+	/**
1248
+	 * Adds category ID if it exists in the request to the where conditions for the registrations query.
1249
+	 *
1250
+	 * @param array $request usually the same as $this->_req_data but not necessarily
1251
+	 * @return array
1252
+	 */
1253
+	protected function _add_category_id_to_where_conditions(array $request)
1254
+	{
1255
+		$where = array();
1256
+		if (! empty($request['EVT_CAT']) && (int) $request['EVT_CAT'] !== -1) {
1257
+			$where['Event.Term_Taxonomy.term_id'] = absint($request['EVT_CAT']);
1258
+		}
1259
+		return $where;
1260
+	}
1261
+
1262
+
1263
+	/**
1264
+	 * Adds the datetime ID if it exists in the request to the where conditions for the registrations query.
1265
+	 *
1266
+	 * @param array $request usually the same as $this->_req_data but not necessarily
1267
+	 * @return array
1268
+	 */
1269
+	protected function _add_datetime_id_to_where_conditions(array $request)
1270
+	{
1271
+		$where = array();
1272
+		if (! empty($request['datetime_id'])) {
1273
+			$where['Ticket.Datetime.DTT_ID'] = absint($request['datetime_id']);
1274
+		}
1275
+		if (! empty($request['DTT_ID'])) {
1276
+			$where['Ticket.Datetime.DTT_ID'] = absint($request['DTT_ID']);
1277
+		}
1278
+		return $where;
1279
+	}
1280
+
1281
+
1282
+	/**
1283
+	 * Adds the correct registration status to the where conditions for the registrations query.
1284
+	 *
1285
+	 * @param array $request usually the same as $this->_req_data but not necessarily
1286
+	 * @return array
1287
+	 */
1288
+	protected function _add_registration_status_to_where_conditions(array $request)
1289
+	{
1290
+		$where = array();
1291
+		$view = EEH_Array::is_set($request, 'status', '');
1292
+		$registration_status = ! empty($request['_reg_status'])
1293
+			? sanitize_text_field($request['_reg_status'])
1294
+			: '';
1295
+
1296
+		/*
1297 1297
          * If filtering by registration status, then we show registrations matching that status.
1298 1298
          * If not filtering by specified status, then we show all registrations excluding incomplete registrations
1299 1299
          * UNLESS viewing trashed registrations.
1300 1300
          */
1301
-        if (! empty($registration_status)) {
1302
-            $where['STS_ID'] = $registration_status;
1303
-        } else {
1304
-            // make sure we exclude incomplete registrations, but only if not trashed.
1305
-            if ($view === 'trash') {
1306
-                $where['REG_deleted'] = true;
1307
-            } elseif ($view === 'incomplete') {
1308
-                $where['STS_ID'] = EEM_Registration::status_id_incomplete;
1309
-            } else {
1310
-                $where['STS_ID'] = array('!=', EEM_Registration::status_id_incomplete);
1311
-            }
1312
-        }
1313
-        return $where;
1314
-    }
1315
-
1316
-
1317
-    /**
1318
-     * Adds any provided date restraints to the where conditions for the registrations query.
1319
-     *
1320
-     * @param array $request usually the same as $this->_req_data but not necessarily
1321
-     * @return array
1322
-     * @throws EE_Error
1323
-     * @throws InvalidArgumentException
1324
-     * @throws InvalidDataTypeException
1325
-     * @throws InvalidInterfaceException
1326
-     */
1327
-    protected function _add_date_to_where_conditions(array $request)
1328
-    {
1329
-        $where = array();
1330
-        $view = EEH_Array::is_set($request, 'status', '');
1331
-        $month_range = ! empty($request['month_range'])
1332
-            ? sanitize_text_field($request['month_range'])
1333
-            : '';
1334
-        $retrieve_for_today = $view === 'today';
1335
-        $retrieve_for_this_month = $view === 'month';
1336
-
1337
-        if ($retrieve_for_today) {
1338
-            $now = date('Y-m-d', current_time('timestamp'));
1339
-            $where['REG_date'] = array(
1340
-                'BETWEEN',
1341
-                array(
1342
-                    EEM_Registration::instance()->convert_datetime_for_query(
1343
-                        'REG_date',
1344
-                        $now . ' 00:00:00',
1345
-                        'Y-m-d H:i:s'
1346
-                    ),
1347
-                    EEM_Registration::instance()->convert_datetime_for_query(
1348
-                        'REG_date',
1349
-                        $now . ' 23:59:59',
1350
-                        'Y-m-d H:i:s'
1351
-                    ),
1352
-                ),
1353
-            );
1354
-        } elseif ($retrieve_for_this_month) {
1355
-            $current_year_and_month = date('Y-m', current_time('timestamp'));
1356
-            $days_this_month = date('t', current_time('timestamp'));
1357
-            $where['REG_date'] = array(
1358
-                'BETWEEN',
1359
-                array(
1360
-                    EEM_Registration::instance()->convert_datetime_for_query(
1361
-                        'REG_date',
1362
-                        $current_year_and_month . '-01 00:00:00',
1363
-                        'Y-m-d H:i:s'
1364
-                    ),
1365
-                    EEM_Registration::instance()->convert_datetime_for_query(
1366
-                        'REG_date',
1367
-                        $current_year_and_month . '-' . $days_this_month . ' 23:59:59',
1368
-                        'Y-m-d H:i:s'
1369
-                    ),
1370
-                ),
1371
-            );
1372
-        } elseif ($month_range) {
1373
-            $pieces = explode(' ', $month_range, 3);
1374
-            $month_requested = ! empty($pieces[0])
1375
-                ? date('m', \EEH_DTT_Helper::first_of_month_timestamp($pieces[0]))
1376
-                : '';
1377
-            $year_requested = ! empty($pieces[1])
1378
-                ? $pieces[1]
1379
-                : '';
1380
-            // if there is not a month or year then we can't go further
1381
-            if ($month_requested && $year_requested) {
1382
-                $days_in_month = date('t', strtotime($year_requested . '-' . $month_requested . '-' . '01'));
1383
-                $where['REG_date'] = array(
1384
-                    'BETWEEN',
1385
-                    array(
1386
-                        EEM_Registration::instance()->convert_datetime_for_query(
1387
-                            'REG_date',
1388
-                            $year_requested . '-' . $month_requested . '-01 00:00:00',
1389
-                            'Y-m-d H:i:s'
1390
-                        ),
1391
-                        EEM_Registration::instance()->convert_datetime_for_query(
1392
-                            'REG_date',
1393
-                            $year_requested . '-' . $month_requested . '-' . $days_in_month . ' 23:59:59',
1394
-                            'Y-m-d H:i:s'
1395
-                        ),
1396
-                    ),
1397
-                );
1398
-            }
1399
-        }
1400
-        return $where;
1401
-    }
1402
-
1403
-
1404
-    /**
1405
-     * Adds any provided search restraints to the where conditions for the registrations query
1406
-     *
1407
-     * @param array $request usually the same as $this->_req_data but not necessarily
1408
-     * @return array
1409
-     */
1410
-    protected function _add_search_to_where_conditions(array $request)
1411
-    {
1412
-        $where = array();
1413
-        if (! empty($request['s'])) {
1414
-            $search_string = '%' . sanitize_text_field($request['s']) . '%';
1415
-            $where['OR*search_conditions'] = array(
1416
-                'Event.EVT_name'                          => array('LIKE', $search_string),
1417
-                'Event.EVT_desc'                          => array('LIKE', $search_string),
1418
-                'Event.EVT_short_desc'                    => array('LIKE', $search_string),
1419
-                'Attendee.ATT_full_name'                  => array('LIKE', $search_string),
1420
-                'Attendee.ATT_fname'                      => array('LIKE', $search_string),
1421
-                'Attendee.ATT_lname'                      => array('LIKE', $search_string),
1422
-                'Attendee.ATT_short_bio'                  => array('LIKE', $search_string),
1423
-                'Attendee.ATT_email'                      => array('LIKE', $search_string),
1424
-                'Attendee.ATT_address'                    => array('LIKE', $search_string),
1425
-                'Attendee.ATT_address2'                   => array('LIKE', $search_string),
1426
-                'Attendee.ATT_city'                       => array('LIKE', $search_string),
1427
-                'REG_final_price'                         => array('LIKE', $search_string),
1428
-                'REG_code'                                => array('LIKE', $search_string),
1429
-                'REG_count'                               => array('LIKE', $search_string),
1430
-                'REG_group_size'                          => array('LIKE', $search_string),
1431
-                'Ticket.TKT_name'                         => array('LIKE', $search_string),
1432
-                'Ticket.TKT_description'                  => array('LIKE', $search_string),
1433
-                'Transaction.Payment.PAY_txn_id_chq_nmbr' => array('LIKE', $search_string),
1434
-            );
1435
-        }
1436
-        return $where;
1437
-    }
1438
-
1439
-
1440
-    /**
1441
-     * Sets up the where conditions for the registrations query.
1442
-     *
1443
-     * @param array $request
1444
-     * @return array
1445
-     * @throws EE_Error
1446
-     */
1447
-    protected function _get_where_conditions_for_registrations_query($request)
1448
-    {
1449
-        return apply_filters(
1450
-            'FHEE__Registrations_Admin_Page___get_where_conditions_for_registrations_query',
1451
-            array_merge(
1452
-                $this->addAttendeeIdToWhereConditions($request),
1453
-                $this->_add_event_id_to_where_conditions($request),
1454
-                $this->_add_category_id_to_where_conditions($request),
1455
-                $this->_add_datetime_id_to_where_conditions($request),
1456
-                $this->_add_registration_status_to_where_conditions($request),
1457
-                $this->_add_date_to_where_conditions($request),
1458
-                $this->_add_search_to_where_conditions($request)
1459
-            ),
1460
-            $request
1461
-        );
1462
-    }
1463
-
1464
-
1465
-    /**
1466
-     * Sets up the orderby for the registrations query.
1467
-     *
1468
-     * @return array
1469
-     */
1470
-    protected function _get_orderby_for_registrations_query()
1471
-    {
1472
-        $orderby_field = ! empty($this->_req_data['orderby'])
1473
-            ? sanitize_text_field($this->_req_data['orderby'])
1474
-            : '_REG_date';
1475
-        switch ($orderby_field) {
1476
-            case '_REG_ID':
1477
-                $orderby = array('REG_ID');
1478
-                break;
1479
-            case '_Reg_status':
1480
-                $orderby = array('STS_ID');
1481
-                break;
1482
-            case 'ATT_fname':
1483
-                $orderby = array('Attendee.ATT_fname', 'Attendee.ATT_lname');
1484
-                break;
1485
-            case 'ATT_lname':
1486
-                $orderby = array('Attendee.ATT_lname', 'Attendee.ATT_fname');
1487
-                break;
1488
-            case 'event_name':
1489
-                $orderby = array('Event.EVT_name');
1490
-                break;
1491
-            case 'DTT_EVT_start':
1492
-                $orderby = array('Event.Datetime.DTT_EVT_start');
1493
-                break;
1494
-            case '_REG_date':
1495
-                $orderby = array('REG_date');
1496
-                break;
1497
-            default:
1498
-                $orderby = array($orderby_field);
1499
-                break;
1500
-        }
1501
-
1502
-        // order
1503
-        $order = ! empty($this->_req_data['order'])
1504
-            ? sanitize_text_field($this->_req_data['order'])
1505
-            : 'DESC';
1506
-        $orderby = array_combine(
1507
-            $orderby,
1508
-            array_fill(0, count($orderby), $order)
1509
-        );
1510
-        // because there are many registrations with the same date, define
1511
-        // a secondary way to order them, otherwise MySQL seems to be a bit random
1512
-        if (empty($orderby['REG_ID'])) {
1513
-            $orderby['REG_ID'] = $order;
1514
-        }
1515
-
1516
-        $orderby = apply_filters(
1517
-            'FHEE__Registrations_Admin_Page___get_orderby_for_registrations_query',
1518
-            $orderby,
1519
-            $this->_req_data
1520
-        );
1521
-
1522
-        return array('order_by' => $orderby);
1523
-    }
1524
-
1525
-
1526
-    /**
1527
-     * Sets up the limit for the registrations query.
1528
-     *
1529
-     * @param $per_page
1530
-     * @return array
1531
-     */
1532
-    protected function _get_limit($per_page)
1533
-    {
1534
-        $current_page = ! empty($this->_req_data['paged'])
1535
-            ? absint($this->_req_data['paged'])
1536
-            : 1;
1537
-        $per_page = ! empty($this->_req_data['perpage'])
1538
-            ? $this->_req_data['perpage']
1539
-            : $per_page;
1540
-
1541
-        // -1 means return all results so get out if that's set.
1542
-        if ((int) $per_page === -1) {
1543
-            return array();
1544
-        }
1545
-        $per_page = absint($per_page);
1546
-        $offset = ($current_page - 1) * $per_page;
1547
-        return array('limit' => array($offset, $per_page));
1548
-    }
1549
-
1550
-
1551
-    public function get_registration_status_array()
1552
-    {
1553
-        return self::$_reg_status;
1554
-    }
1555
-
1556
-
1557
-
1558
-
1559
-    /***************************************        REGISTRATION DETAILS        ***************************************/
1560
-    /**
1561
-     *        generates HTML for the View Registration Details Admin page
1562
-     *
1563
-     * @access protected
1564
-     * @return void
1565
-     * @throws DomainException
1566
-     * @throws EE_Error
1567
-     * @throws InvalidArgumentException
1568
-     * @throws InvalidDataTypeException
1569
-     * @throws InvalidInterfaceException
1570
-     * @throws EntityNotFoundException
1571
-     */
1572
-    protected function _registration_details()
1573
-    {
1574
-        $this->_template_args = array();
1575
-        $this->_set_registration_object();
1576
-        if (is_object($this->_registration)) {
1577
-            $transaction = $this->_registration->transaction()
1578
-                ? $this->_registration->transaction()
1579
-                : EE_Transaction::new_instance();
1580
-            $this->_session = $transaction->session_data();
1581
-            $event_id = $this->_registration->event_ID();
1582
-            $this->_template_args['reg_nmbr']['value'] = $this->_registration->ID();
1583
-            $this->_template_args['reg_nmbr']['label'] = esc_html__('Registration Number', 'event_espresso');
1584
-            $this->_template_args['reg_datetime']['value'] = $this->_registration->get_i18n_datetime('REG_date');
1585
-            $this->_template_args['reg_datetime']['label'] = esc_html__('Date', 'event_espresso');
1586
-            $this->_template_args['grand_total'] = $transaction->total();
1587
-            $this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
1588
-            // link back to overview
1589
-            $this->_template_args['reg_overview_url'] = REG_ADMIN_URL;
1590
-            $this->_template_args['registration'] = $this->_registration;
1591
-            $this->_template_args['filtered_registrations_link'] = EE_Admin_Page::add_query_args_and_nonce(
1592
-                array(
1593
-                    'action'   => 'default',
1594
-                    'event_id' => $event_id,
1595
-                ),
1596
-                REG_ADMIN_URL
1597
-            );
1598
-            $this->_template_args['filtered_transactions_link'] = EE_Admin_Page::add_query_args_and_nonce(
1599
-                array(
1600
-                    'action' => 'default',
1601
-                    'EVT_ID' => $event_id,
1602
-                    'page'   => 'espresso_transactions',
1603
-                ),
1604
-                admin_url('admin.php')
1605
-            );
1606
-            $this->_template_args['event_link'] = EE_Admin_Page::add_query_args_and_nonce(
1607
-                array(
1608
-                    'page'   => 'espresso_events',
1609
-                    'action' => 'edit',
1610
-                    'post'   => $event_id,
1611
-                ),
1612
-                admin_url('admin.php')
1613
-            );
1614
-            // next and previous links
1615
-            $next_reg = $this->_registration->next(
1616
-                null,
1617
-                array(),
1618
-                'REG_ID'
1619
-            );
1620
-            $this->_template_args['next_registration'] = $next_reg
1621
-                ? $this->_next_link(
1622
-                    EE_Admin_Page::add_query_args_and_nonce(
1623
-                        array(
1624
-                            'action'  => 'view_registration',
1625
-                            '_REG_ID' => $next_reg['REG_ID'],
1626
-                        ),
1627
-                        REG_ADMIN_URL
1628
-                    ),
1629
-                    'dashicons dashicons-arrow-right ee-icon-size-22'
1630
-                )
1631
-                : '';
1632
-            $previous_reg = $this->_registration->previous(
1633
-                null,
1634
-                array(),
1635
-                'REG_ID'
1636
-            );
1637
-            $this->_template_args['previous_registration'] = $previous_reg
1638
-                ? $this->_previous_link(
1639
-                    EE_Admin_Page::add_query_args_and_nonce(
1640
-                        array(
1641
-                            'action'  => 'view_registration',
1642
-                            '_REG_ID' => $previous_reg['REG_ID'],
1643
-                        ),
1644
-                        REG_ADMIN_URL
1645
-                    ),
1646
-                    'dashicons dashicons-arrow-left ee-icon-size-22'
1647
-                )
1648
-                : '';
1649
-            // grab header
1650
-            $template_path = REG_TEMPLATE_PATH . 'reg_admin_details_header.template.php';
1651
-            $this->_template_args['REG_ID'] = $this->_registration->ID();
1652
-            $this->_template_args['admin_page_header'] = EEH_Template::display_template(
1653
-                $template_path,
1654
-                $this->_template_args,
1655
-                true
1656
-            );
1657
-        } else {
1658
-            $this->_template_args['admin_page_header'] = $this->display_espresso_notices();
1659
-        }
1660
-        // the details template wrapper
1661
-        $this->display_admin_page_with_sidebar();
1662
-    }
1663
-
1664
-
1665
-    protected function _registration_details_metaboxes()
1666
-    {
1667
-        do_action('AHEE__Registrations_Admin_Page___registration_details_metabox__start', $this);
1668
-        $this->_set_registration_object();
1669
-        $attendee = $this->_registration instanceof EE_Registration ? $this->_registration->attendee() : null;
1670
-        add_meta_box(
1671
-            'edit-reg-status-mbox',
1672
-            esc_html__('Registration Status', 'event_espresso'),
1673
-            array($this, 'set_reg_status_buttons_metabox'),
1674
-            $this->wp_page_slug,
1675
-            'normal',
1676
-            'high'
1677
-        );
1678
-        add_meta_box(
1679
-            'edit-reg-details-mbox',
1680
-            esc_html__('Registration Details', 'event_espresso'),
1681
-            array($this, '_reg_details_meta_box'),
1682
-            $this->wp_page_slug,
1683
-            'normal',
1684
-            'high'
1685
-        );
1686
-        if ($attendee instanceof EE_Attendee
1687
-            && EE_Registry::instance()->CAP->current_user_can(
1688
-                'ee_read_registration',
1689
-                'edit-reg-questions-mbox',
1690
-                $this->_registration->ID()
1691
-            )
1692
-        ) {
1693
-            add_meta_box(
1694
-                'edit-reg-questions-mbox',
1695
-                esc_html__('Registration Form Answers', 'event_espresso'),
1696
-                array($this, '_reg_questions_meta_box'),
1697
-                $this->wp_page_slug,
1698
-                'normal',
1699
-                'high'
1700
-            );
1701
-        }
1702
-        add_meta_box(
1703
-            'edit-reg-registrant-mbox',
1704
-            esc_html__('Contact Details', 'event_espresso'),
1705
-            array($this, '_reg_registrant_side_meta_box'),
1706
-            $this->wp_page_slug,
1707
-            'side',
1708
-            'high'
1709
-        );
1710
-        if ($this->_registration->group_size() > 1) {
1711
-            add_meta_box(
1712
-                'edit-reg-attendees-mbox',
1713
-                esc_html__('Other Registrations in this Transaction', 'event_espresso'),
1714
-                array($this, '_reg_attendees_meta_box'),
1715
-                $this->wp_page_slug,
1716
-                'normal',
1717
-                'high'
1718
-            );
1719
-        }
1720
-    }
1721
-
1722
-
1723
-    /**
1724
-     * set_reg_status_buttons_metabox
1725
-     *
1726
-     * @access protected
1727
-     * @return string
1728
-     * @throws \EE_Error
1729
-     */
1730
-    public function set_reg_status_buttons_metabox()
1731
-    {
1732
-        $this->_set_registration_object();
1733
-        $change_reg_status_form = $this->_generate_reg_status_change_form();
1734
-        echo $change_reg_status_form->form_open(
1735
-            self::add_query_args_and_nonce(
1736
-                array(
1737
-                    'action' => 'change_reg_status',
1738
-                ),
1739
-                REG_ADMIN_URL
1740
-            )
1741
-        );
1742
-        echo $change_reg_status_form->get_html();
1743
-        echo $change_reg_status_form->form_close();
1744
-    }
1745
-
1746
-
1747
-    /**
1748
-     * @return EE_Form_Section_Proper
1749
-     * @throws EE_Error
1750
-     * @throws InvalidArgumentException
1751
-     * @throws InvalidDataTypeException
1752
-     * @throws InvalidInterfaceException
1753
-     * @throws \EventEspresso\core\exceptions\EntityNotFoundException
1754
-     */
1755
-    protected function _generate_reg_status_change_form()
1756
-    {
1757
-        $reg_status_change_form_array = array(
1758
-            'name'            => 'reg_status_change_form',
1759
-            'html_id'         => 'reg-status-change-form',
1760
-            'layout_strategy' => new EE_Admin_Two_Column_Layout(),
1761
-            'subsections'     => array(
1762
-                'return'             => new EE_Hidden_Input(
1763
-                    array(
1764
-                        'name'    => 'return',
1765
-                        'default' => 'view_registration',
1766
-                    )
1767
-                ),
1768
-                'REG_ID'             => new EE_Hidden_Input(
1769
-                    array(
1770
-                        'name'    => 'REG_ID',
1771
-                        'default' => $this->_registration->ID(),
1772
-                    )
1773
-                ),
1774
-                'current_status'     => new EE_Form_Section_HTML(
1775
-                    EEH_HTML::tr(
1776
-                        EEH_HTML::th(
1777
-                            EEH_HTML::label(
1778
-                                EEH_HTML::strong(
1779
-                                    esc_html__('Current Registration Status', 'event_espresso')
1780
-                                )
1781
-                            )
1782
-                        )
1783
-                        . EEH_HTML::td(
1784
-                            EEH_HTML::strong(
1785
-                                $this->_registration->pretty_status(),
1786
-                                '',
1787
-                                'status-' . $this->_registration->status_ID(),
1788
-                                'line-height: 1em; font-size: 1.5em; font-weight: bold;'
1789
-                            )
1790
-                        )
1791
-                    )
1792
-                )
1793
-            )
1794
-        );
1795
-        if (EE_Registry::instance()->CAP->current_user_can(
1796
-            'ee_edit_registration',
1797
-            'toggle_registration_status',
1798
-            $this->_registration->ID()
1799
-        )) {
1800
-            $reg_status_change_form_array['subsections']['reg_status'] = new EE_Select_Input(
1801
-                $this->_get_reg_statuses(),
1802
-                array(
1803
-                    'html_label_text' => esc_html__('Change Registration Status to', 'event_espresso'),
1804
-                    'default'         => $this->_registration->status_ID(),
1805
-                )
1806
-            );
1807
-            $reg_status_change_form_array['subsections']['send_notifications'] = new EE_Yes_No_Input(
1808
-                array(
1809
-                    'html_label_text' => esc_html__('Send Related Messages', 'event_espresso'),
1810
-                    'default'         => false,
1811
-                    'html_help_text'  => esc_html__(
1812
-                        'If set to "Yes", then the related messages will be sent to the registrant.',
1813
-                        'event_espresso'
1814
-                    )
1815
-                )
1816
-            );
1817
-            $reg_status_change_form_array['subsections']['submit'] = new EE_Submit_Input(
1818
-                array(
1819
-                    'html_class'      => 'button-primary',
1820
-                    'html_label_text' => '&nbsp;',
1821
-                    'default'         => esc_html__('Update Registration Status', 'event_espresso'),
1822
-                )
1823
-            );
1824
-        }
1825
-        return new EE_Form_Section_Proper($reg_status_change_form_array);
1826
-    }
1827
-
1828
-
1829
-    /**
1830
-     * Returns an array of all the buttons for the various statuses and switch status actions
1831
-     *
1832
-     * @return array
1833
-     * @throws EE_Error
1834
-     * @throws InvalidArgumentException
1835
-     * @throws InvalidDataTypeException
1836
-     * @throws InvalidInterfaceException
1837
-     * @throws EntityNotFoundException
1838
-     */
1839
-    protected function _get_reg_statuses()
1840
-    {
1841
-        $reg_status_array = EEM_Registration::instance()->reg_status_array();
1842
-        unset($reg_status_array[ EEM_Registration::status_id_incomplete ]);
1843
-        // get current reg status
1844
-        $current_status = $this->_registration->status_ID();
1845
-        // is registration for free event? This will determine whether to display the pending payment option
1846
-        if ($current_status !== EEM_Registration::status_id_pending_payment
1847
-            && EEH_Money::compare_floats($this->_registration->ticket()->price(), 0.00)
1848
-        ) {
1849
-            unset($reg_status_array[ EEM_Registration::status_id_pending_payment ]);
1850
-        }
1851
-        return EEM_Status::instance()->localized_status($reg_status_array, false, 'sentence');
1852
-    }
1853
-
1854
-
1855
-    /**
1856
-     * This method is used when using _REG_ID from request which may or may not be an array of reg_ids.
1857
-     *
1858
-     * @param bool $status REG status given for changing registrations to.
1859
-     * @param bool $notify Whether to send messages notifications or not.
1860
-     * @return array (array with reg_id(s) updated and whether update was successful.
1861
-     * @throws EE_Error
1862
-     * @throws InvalidArgumentException
1863
-     * @throws InvalidDataTypeException
1864
-     * @throws InvalidInterfaceException
1865
-     * @throws ReflectionException
1866
-     * @throws RuntimeException
1867
-     * @throws EntityNotFoundException
1868
-     */
1869
-    protected function _set_registration_status_from_request($status = false, $notify = false)
1870
-    {
1871
-        if (isset($this->_req_data['reg_status_change_form'])) {
1872
-            $REG_IDs = isset($this->_req_data['reg_status_change_form']['REG_ID'])
1873
-                ? (array) $this->_req_data['reg_status_change_form']['REG_ID']
1874
-                : array();
1875
-        } else {
1876
-            $REG_IDs = isset($this->_req_data['_REG_ID'])
1877
-                ? (array) $this->_req_data['_REG_ID']
1878
-                : array();
1879
-        }
1880
-        // sanitize $REG_IDs
1881
-        $REG_IDs = array_map('absint', $REG_IDs);
1882
-        // and remove empty entries
1883
-        $REG_IDs = array_filter($REG_IDs);
1884
-
1885
-        $result = $this->_set_registration_status($REG_IDs, $status, $notify);
1886
-
1887
-        /**
1888
-         * Set and filter $_req_data['_REG_ID'] for any potential future messages notifications.
1889
-         * Currently this value is used downstream by the _process_resend_registration method.
1890
-         *
1891
-         * @param int|array                $registration_ids The registration ids that have had their status changed successfully.
1892
-         * @param bool                     $status           The status registrations were changed to.
1893
-         * @param bool                     $success          If the status was changed successfully for all registrations.
1894
-         * @param Registrations_Admin_Page $admin_page_object
1895
-         */
1896
-        $this->_req_data['_REG_ID'] = apply_filters(
1897
-            'FHEE__Registrations_Admin_Page___set_registration_status_from_request__REG_IDs',
1898
-            $result['REG_ID'],
1899
-            $status,
1900
-            $result['success'],
1901
-            $this
1902
-        );
1903
-
1904
-        // notify?
1905
-        if ($notify
1906
-            && $result['success']
1907
-            && ! empty($this->_req_data['_REG_ID'])
1908
-            && EE_Registry::instance()->CAP->current_user_can(
1909
-                'ee_send_message',
1910
-                'espresso_registrations_resend_registration'
1911
-            )
1912
-        ) {
1913
-            $this->_process_resend_registration();
1914
-        }
1915
-        return $result;
1916
-    }
1917
-
1918
-
1919
-    /**
1920
-     * Set the registration status for the given reg_id (which may or may not be an array, it gets typecast to an
1921
-     * array). Note, this method does NOT take care of possible notifications.  That is required by calling code.
1922
-     *
1923
-     * @param array  $REG_IDs
1924
-     * @param string $status
1925
-     * @param bool   $notify  Used to indicate whether notification was requested or not.  This determines the context
1926
-     *                        slug sent with setting the registration status.
1927
-     * @return array (an array with 'success' key representing whether status change was successful, and 'REG_ID' as
1928
-     * @throws EE_Error
1929
-     * @throws InvalidArgumentException
1930
-     * @throws InvalidDataTypeException
1931
-     * @throws InvalidInterfaceException
1932
-     * @throws ReflectionException
1933
-     * @throws RuntimeException
1934
-     * @throws EntityNotFoundException
1935
-     */
1936
-    protected function _set_registration_status($REG_IDs = array(), $status = '', $notify = false)
1937
-    {
1938
-        $success = false;
1939
-        // typecast $REG_IDs
1940
-        $REG_IDs = (array) $REG_IDs;
1941
-        if (! empty($REG_IDs)) {
1942
-            $success = true;
1943
-            // set default status if none is passed
1944
-            $status = $status ? $status : EEM_Registration::status_id_pending_payment;
1945
-            $status_context = $notify
1946
-                ? Domain::CONTEXT_REGISTRATION_STATUS_CHANGE_REGISTRATION_ADMIN_NOTIFY
1947
-                : Domain::CONTEXT_REGISTRATION_STATUS_CHANGE_REGISTRATION_ADMIN;
1948
-            // loop through REG_ID's and change status
1949
-            foreach ($REG_IDs as $REG_ID) {
1950
-                $registration = EEM_Registration::instance()->get_one_by_ID($REG_ID);
1951
-                if ($registration instanceof EE_Registration) {
1952
-                    $registration->set_status(
1953
-                        $status,
1954
-                        false,
1955
-                        new Context(
1956
-                            $status_context,
1957
-                            esc_html__(
1958
-                                'Manually triggered status change on a Registration Admin Page route.',
1959
-                                'event_espresso'
1960
-                            )
1961
-                        )
1962
-                    );
1963
-                    $result = $registration->save();
1964
-                    // verifying explicit fails because update *may* just return 0 for 0 rows affected
1965
-                    $success = $result !== false ? $success : false;
1966
-                }
1967
-            }
1968
-        }
1969
-
1970
-        // return $success and processed registrations
1971
-        return array('REG_ID' => $REG_IDs, 'success' => $success);
1972
-    }
1973
-
1974
-
1975
-    /**
1976
-     * Common logic for setting up success message and redirecting to appropriate route
1977
-     *
1978
-     * @param  string $STS_ID status id for the registration changed to
1979
-     * @param   bool  $notify indicates whether the _set_registration_status_from_request does notifications or not.
1980
-     * @return void
1981
-     * @throws EE_Error
1982
-     */
1983
-    protected function _reg_status_change_return($STS_ID, $notify = false)
1984
-    {
1985
-        $result = ! empty($STS_ID) ? $this->_set_registration_status_from_request($STS_ID, $notify)
1986
-            : array('success' => false);
1987
-        $success = isset($result['success']) && $result['success'];
1988
-        // setup success message
1989
-        if ($success) {
1990
-            if (is_array($result['REG_ID']) && count($result['REG_ID']) === 1) {
1991
-                $msg = sprintf(
1992
-                    esc_html__('Registration status has been set to %s', 'event_espresso'),
1993
-                    EEH_Template::pretty_status($STS_ID, false, 'lower')
1994
-                );
1995
-            } else {
1996
-                $msg = sprintf(
1997
-                    esc_html__('Registrations have been set to %s.', 'event_espresso'),
1998
-                    EEH_Template::pretty_status($STS_ID, false, 'lower')
1999
-                );
2000
-            }
2001
-            EE_Error::add_success($msg);
2002
-        } else {
2003
-            EE_Error::add_error(
2004
-                esc_html__(
2005
-                    'Something went wrong, and the status was not changed',
2006
-                    'event_espresso'
2007
-                ),
2008
-                __FILE__,
2009
-                __LINE__,
2010
-                __FUNCTION__
2011
-            );
2012
-        }
2013
-        if (isset($this->_req_data['return']) && $this->_req_data['return'] == 'view_registration') {
2014
-            $route = array('action' => 'view_registration', '_REG_ID' => reset($result['REG_ID']));
2015
-        } else {
2016
-            $route = array('action' => 'default');
2017
-        }
2018
-        $route = $this->mergeExistingRequestParamsWithRedirectArgs($route);
2019
-        $this->_redirect_after_action($success, '', '', $route, true);
2020
-    }
2021
-
2022
-
2023
-    /**
2024
-     * incoming reg status change from reg details page.
2025
-     *
2026
-     * @return void
2027
-     */
2028
-    protected function _change_reg_status()
2029
-    {
2030
-        $this->_req_data['return'] = 'view_registration';
2031
-        // set notify based on whether the send notifications toggle is set or not
2032
-        $notify = ! empty($this->_req_data['reg_status_change_form']['send_notifications']);
2033
-        // $notify = ! empty( $this->_req_data['txn_reg_status_change']['send_notifications'] );
2034
-        $this->_req_data['reg_status_change_form']['reg_status'] = isset($this->_req_data['reg_status_change_form']['reg_status'])
2035
-            ? $this->_req_data['reg_status_change_form']['reg_status'] : '';
2036
-        switch ($this->_req_data['reg_status_change_form']['reg_status']) {
2037
-            case EEM_Registration::status_id_approved:
2038
-            case EEH_Template::pretty_status(EEM_Registration::status_id_approved, false, 'sentence'):
2039
-                $this->approve_registration($notify);
2040
-                break;
2041
-            case EEM_Registration::status_id_pending_payment:
2042
-            case EEH_Template::pretty_status(EEM_Registration::status_id_pending_payment, false, 'sentence'):
2043
-                $this->pending_registration($notify);
2044
-                break;
2045
-            case EEM_Registration::status_id_not_approved:
2046
-            case EEH_Template::pretty_status(EEM_Registration::status_id_not_approved, false, 'sentence'):
2047
-                $this->not_approve_registration($notify);
2048
-                break;
2049
-            case EEM_Registration::status_id_declined:
2050
-            case EEH_Template::pretty_status(EEM_Registration::status_id_declined, false, 'sentence'):
2051
-                $this->decline_registration($notify);
2052
-                break;
2053
-            case EEM_Registration::status_id_cancelled:
2054
-            case EEH_Template::pretty_status(EEM_Registration::status_id_cancelled, false, 'sentence'):
2055
-                $this->cancel_registration($notify);
2056
-                break;
2057
-            case EEM_Registration::status_id_wait_list:
2058
-            case EEH_Template::pretty_status(EEM_Registration::status_id_wait_list, false, 'sentence'):
2059
-                $this->wait_list_registration($notify);
2060
-                break;
2061
-            case EEM_Registration::status_id_incomplete:
2062
-            default:
2063
-                $result['success'] = false;
2064
-                unset($this->_req_data['return']);
2065
-                $this->_reg_status_change_return('', false);
2066
-                break;
2067
-        }
2068
-    }
2069
-
2070
-
2071
-    /**
2072
-     * Callback for bulk action routes.
2073
-     * Note: although we could just register the singular route callbacks for each bulk action route as well, this
2074
-     * method was chosen so there is one central place all the registration status bulk actions are going through.
2075
-     * Potentially, this provides an easier place to locate logic that is specific to these bulk actions (as opposed to
2076
-     * when an action is happening on just a single registration).
2077
-     *
2078
-     * @param      $action
2079
-     * @param bool $notify
2080
-     */
2081
-    protected function bulk_action_on_registrations($action, $notify = false)
2082
-    {
2083
-        do_action(
2084
-            'AHEE__Registrations_Admin_Page__bulk_action_on_registrations__before_execution',
2085
-            $this,
2086
-            $action,
2087
-            $notify
2088
-        );
2089
-        $method = $action . '_registration';
2090
-        if (method_exists($this, $method)) {
2091
-            $this->$method($notify);
2092
-        }
2093
-    }
2094
-
2095
-
2096
-    /**
2097
-     * approve_registration
2098
-     *
2099
-     * @access protected
2100
-     * @param bool $notify whether or not to notify the registrant about their approval.
2101
-     * @return void
2102
-     */
2103
-    protected function approve_registration($notify = false)
2104
-    {
2105
-        $this->_reg_status_change_return(EEM_Registration::status_id_approved, $notify);
2106
-    }
2107
-
2108
-
2109
-    /**
2110
-     *        decline_registration
2111
-     *
2112
-     * @access protected
2113
-     * @param bool $notify whether or not to notify the registrant about their status change.
2114
-     * @return void
2115
-     */
2116
-    protected function decline_registration($notify = false)
2117
-    {
2118
-        $this->_reg_status_change_return(EEM_Registration::status_id_declined, $notify);
2119
-    }
2120
-
2121
-
2122
-    /**
2123
-     *        cancel_registration
2124
-     *
2125
-     * @access protected
2126
-     * @param bool $notify whether or not to notify the registrant about their status change.
2127
-     * @return void
2128
-     */
2129
-    protected function cancel_registration($notify = false)
2130
-    {
2131
-        $this->_reg_status_change_return(EEM_Registration::status_id_cancelled, $notify);
2132
-    }
2133
-
2134
-
2135
-    /**
2136
-     *        not_approve_registration
2137
-     *
2138
-     * @access protected
2139
-     * @param bool $notify whether or not to notify the registrant about their status change.
2140
-     * @return void
2141
-     */
2142
-    protected function not_approve_registration($notify = false)
2143
-    {
2144
-        $this->_reg_status_change_return(EEM_Registration::status_id_not_approved, $notify);
2145
-    }
2146
-
2147
-
2148
-    /**
2149
-     *        decline_registration
2150
-     *
2151
-     * @access protected
2152
-     * @param bool $notify whether or not to notify the registrant about their status change.
2153
-     * @return void
2154
-     */
2155
-    protected function pending_registration($notify = false)
2156
-    {
2157
-        $this->_reg_status_change_return(EEM_Registration::status_id_pending_payment, $notify);
2158
-    }
2159
-
2160
-
2161
-    /**
2162
-     * waitlist_registration
2163
-     *
2164
-     * @access protected
2165
-     * @param bool $notify whether or not to notify the registrant about their status change.
2166
-     * @return void
2167
-     */
2168
-    protected function wait_list_registration($notify = false)
2169
-    {
2170
-        $this->_reg_status_change_return(EEM_Registration::status_id_wait_list, $notify);
2171
-    }
2172
-
2173
-
2174
-    /**
2175
-     *        generates HTML for the Registration main meta box
2176
-     *
2177
-     * @access public
2178
-     * @return void
2179
-     * @throws DomainException
2180
-     * @throws EE_Error
2181
-     * @throws InvalidArgumentException
2182
-     * @throws InvalidDataTypeException
2183
-     * @throws InvalidInterfaceException
2184
-     * @throws ReflectionException
2185
-     * @throws EntityNotFoundException
2186
-     */
2187
-    public function _reg_details_meta_box()
2188
-    {
2189
-        EEH_Autoloader::register_line_item_display_autoloaders();
2190
-        EEH_Autoloader::register_line_item_filter_autoloaders();
2191
-        EE_Registry::instance()->load_helper('Line_Item');
2192
-        $transaction = $this->_registration->transaction() ? $this->_registration->transaction()
2193
-            : EE_Transaction::new_instance();
2194
-        $this->_session = $transaction->session_data();
2195
-        $filters = new EE_Line_Item_Filter_Collection();
2196
-        // $filters->add( new EE_Non_Zero_Line_Item_Filter() );
2197
-        $filters->add(new EE_Single_Registration_Line_Item_Filter($this->_registration));
2198
-        $line_item_filter_processor = new EE_Line_Item_Filter_Processor(
2199
-            $filters,
2200
-            $transaction->total_line_item()
2201
-        );
2202
-        $filtered_line_item_tree = $line_item_filter_processor->process();
2203
-        $line_item_display = new EE_Line_Item_Display(
2204
-            'reg_admin_table',
2205
-            'EE_Admin_Table_Registration_Line_Item_Display_Strategy'
2206
-        );
2207
-        $this->_template_args['line_item_table'] = $line_item_display->display_line_item(
2208
-            $filtered_line_item_tree,
2209
-            array('EE_Registration' => $this->_registration)
2210
-        );
2211
-        $attendee = $this->_registration->attendee();
2212
-        if (EE_Registry::instance()->CAP->current_user_can(
2213
-            'ee_read_transaction',
2214
-            'espresso_transactions_view_transaction'
2215
-        )) {
2216
-            $this->_template_args['view_transaction_button'] = EEH_Template::get_button_or_link(
2217
-                EE_Admin_Page::add_query_args_and_nonce(
2218
-                    array(
2219
-                        'action' => 'view_transaction',
2220
-                        'TXN_ID' => $transaction->ID(),
2221
-                    ),
2222
-                    TXN_ADMIN_URL
2223
-                ),
2224
-                esc_html__(' View Transaction', 'event_espresso'),
2225
-                'button secondary-button right',
2226
-                'dashicons dashicons-cart'
2227
-            );
2228
-        } else {
2229
-            $this->_template_args['view_transaction_button'] = '';
2230
-        }
2231
-        if ($attendee instanceof EE_Attendee
2232
-            && EE_Registry::instance()->CAP->current_user_can(
2233
-                'ee_send_message',
2234
-                'espresso_registrations_resend_registration'
2235
-            )
2236
-        ) {
2237
-            $this->_template_args['resend_registration_button'] = EEH_Template::get_button_or_link(
2238
-                EE_Admin_Page::add_query_args_and_nonce(
2239
-                    array(
2240
-                        'action'      => 'resend_registration',
2241
-                        '_REG_ID'     => $this->_registration->ID(),
2242
-                        'redirect_to' => 'view_registration',
2243
-                    ),
2244
-                    REG_ADMIN_URL
2245
-                ),
2246
-                esc_html__(' Resend Registration', 'event_espresso'),
2247
-                'button secondary-button right',
2248
-                'dashicons dashicons-email-alt'
2249
-            );
2250
-        } else {
2251
-            $this->_template_args['resend_registration_button'] = '';
2252
-        }
2253
-        $this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
2254
-        $payment = $transaction->get_first_related('Payment');
2255
-        $payment = ! $payment instanceof EE_Payment
2256
-            ? EE_Payment::new_instance()
2257
-            : $payment;
2258
-        $payment_method = $payment->get_first_related('Payment_Method');
2259
-        $payment_method = ! $payment_method instanceof EE_Payment_Method
2260
-            ? EE_Payment_Method::new_instance()
2261
-            : $payment_method;
2262
-        $reg_details = array(
2263
-            'payment_method'       => $payment_method->name(),
2264
-            'response_msg'         => $payment->gateway_response(),
2265
-            'registration_id'      => $this->_registration->get('REG_code'),
2266
-            'registration_session' => $this->_registration->session_ID(),
2267
-            'ip_address'           => isset($this->_session['ip_address']) ? $this->_session['ip_address'] : '',
2268
-            'user_agent'           => isset($this->_session['user_agent']) ? $this->_session['user_agent'] : '',
2269
-        );
2270
-        if (isset($reg_details['registration_id'])) {
2271
-            $this->_template_args['reg_details']['registration_id']['value'] = $reg_details['registration_id'];
2272
-            $this->_template_args['reg_details']['registration_id']['label'] = esc_html__(
2273
-                'Registration ID',
2274
-                'event_espresso'
2275
-            );
2276
-            $this->_template_args['reg_details']['registration_id']['class'] = 'regular-text';
2277
-        }
2278
-        if (isset($reg_details['payment_method'])) {
2279
-            $this->_template_args['reg_details']['payment_method']['value'] = $reg_details['payment_method'];
2280
-            $this->_template_args['reg_details']['payment_method']['label'] = esc_html__(
2281
-                'Most Recent Payment Method',
2282
-                'event_espresso'
2283
-            );
2284
-            $this->_template_args['reg_details']['payment_method']['class'] = 'regular-text';
2285
-            $this->_template_args['reg_details']['response_msg']['value'] = $reg_details['response_msg'];
2286
-            $this->_template_args['reg_details']['response_msg']['label'] = esc_html__(
2287
-                'Payment method response',
2288
-                'event_espresso'
2289
-            );
2290
-            $this->_template_args['reg_details']['response_msg']['class'] = 'regular-text';
2291
-        }
2292
-        $this->_template_args['reg_details']['registration_session']['value'] = $reg_details['registration_session'];
2293
-        $this->_template_args['reg_details']['registration_session']['label'] = esc_html__(
2294
-            'Registration Session',
2295
-            'event_espresso'
2296
-        );
2297
-        $this->_template_args['reg_details']['registration_session']['class'] = 'regular-text';
2298
-        $this->_template_args['reg_details']['ip_address']['value'] = $reg_details['ip_address'];
2299
-        $this->_template_args['reg_details']['ip_address']['label'] = esc_html__(
2300
-            'Registration placed from IP',
2301
-            'event_espresso'
2302
-        );
2303
-        $this->_template_args['reg_details']['ip_address']['class'] = 'regular-text';
2304
-        $this->_template_args['reg_details']['user_agent']['value'] = $reg_details['user_agent'];
2305
-        $this->_template_args['reg_details']['user_agent']['label'] = esc_html__(
2306
-            'Registrant User Agent',
2307
-            'event_espresso'
2308
-        );
2309
-        $this->_template_args['reg_details']['user_agent']['class'] = 'large-text';
2310
-        $this->_template_args['event_link'] = EE_Admin_Page::add_query_args_and_nonce(
2311
-            array(
2312
-                'action'   => 'default',
2313
-                'event_id' => $this->_registration->event_ID(),
2314
-            ),
2315
-            REG_ADMIN_URL
2316
-        );
2317
-        $this->_template_args['REG_ID'] = $this->_registration->ID();
2318
-        $this->_template_args['event_id'] = $this->_registration->event_ID();
2319
-        $template_path =
2320
-            REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_reg_details.template.php';
2321
-        echo EEH_Template::display_template($template_path, $this->_template_args, true);
2322
-    }
2323
-
2324
-
2325
-    /**
2326
-     * generates HTML for the Registration Questions meta box.
2327
-     * If pre-4.8.32.rc.000 hooks are used, uses old methods (with its filters),
2328
-     * otherwise uses new forms system
2329
-     *
2330
-     * @access public
2331
-     * @return void
2332
-     * @throws DomainException
2333
-     * @throws EE_Error
2334
-     */
2335
-    public function _reg_questions_meta_box()
2336
-    {
2337
-        // allow someone to override this method entirely
2338
-        if (apply_filters(
2339
-            'FHEE__Registrations_Admin_Page___reg_questions_meta_box__do_default',
2340
-            true,
2341
-            $this,
2342
-            $this->_registration
2343
-        )) {
2344
-            $form = $this->_get_reg_custom_questions_form(
2345
-                $this->_registration->ID()
2346
-            );
2347
-            $this->_template_args['att_questions'] = count($form->subforms()) > 0
2348
-                ? $form->get_html_and_js()
2349
-                : '';
2350
-            $this->_template_args['reg_questions_form_action'] = 'edit_registration';
2351
-            $this->_template_args['REG_ID'] = $this->_registration->ID();
2352
-            $template_path =
2353
-                REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_reg_questions.template.php';
2354
-            echo EEH_Template::display_template($template_path, $this->_template_args, true);
2355
-        }
2356
-    }
2357
-
2358
-
2359
-    /**
2360
-     * form_before_question_group
2361
-     *
2362
-     * @deprecated    as of 4.8.32.rc.000
2363
-     * @access        public
2364
-     * @param        string $output
2365
-     * @return        string
2366
-     */
2367
-    public function form_before_question_group($output)
2368
-    {
2369
-        EE_Error::doing_it_wrong(
2370
-            __CLASS__ . '::' . __FUNCTION__,
2371
-            esc_html__(
2372
-                'This method would have been protected but was used on a filter callback so needed to be public. Please discontinue usage as it will be removed soon.',
2373
-                'event_espresso'
2374
-            ),
2375
-            '4.8.32.rc.000'
2376
-        );
2377
-        return '
1301
+		if (! empty($registration_status)) {
1302
+			$where['STS_ID'] = $registration_status;
1303
+		} else {
1304
+			// make sure we exclude incomplete registrations, but only if not trashed.
1305
+			if ($view === 'trash') {
1306
+				$where['REG_deleted'] = true;
1307
+			} elseif ($view === 'incomplete') {
1308
+				$where['STS_ID'] = EEM_Registration::status_id_incomplete;
1309
+			} else {
1310
+				$where['STS_ID'] = array('!=', EEM_Registration::status_id_incomplete);
1311
+			}
1312
+		}
1313
+		return $where;
1314
+	}
1315
+
1316
+
1317
+	/**
1318
+	 * Adds any provided date restraints to the where conditions for the registrations query.
1319
+	 *
1320
+	 * @param array $request usually the same as $this->_req_data but not necessarily
1321
+	 * @return array
1322
+	 * @throws EE_Error
1323
+	 * @throws InvalidArgumentException
1324
+	 * @throws InvalidDataTypeException
1325
+	 * @throws InvalidInterfaceException
1326
+	 */
1327
+	protected function _add_date_to_where_conditions(array $request)
1328
+	{
1329
+		$where = array();
1330
+		$view = EEH_Array::is_set($request, 'status', '');
1331
+		$month_range = ! empty($request['month_range'])
1332
+			? sanitize_text_field($request['month_range'])
1333
+			: '';
1334
+		$retrieve_for_today = $view === 'today';
1335
+		$retrieve_for_this_month = $view === 'month';
1336
+
1337
+		if ($retrieve_for_today) {
1338
+			$now = date('Y-m-d', current_time('timestamp'));
1339
+			$where['REG_date'] = array(
1340
+				'BETWEEN',
1341
+				array(
1342
+					EEM_Registration::instance()->convert_datetime_for_query(
1343
+						'REG_date',
1344
+						$now . ' 00:00:00',
1345
+						'Y-m-d H:i:s'
1346
+					),
1347
+					EEM_Registration::instance()->convert_datetime_for_query(
1348
+						'REG_date',
1349
+						$now . ' 23:59:59',
1350
+						'Y-m-d H:i:s'
1351
+					),
1352
+				),
1353
+			);
1354
+		} elseif ($retrieve_for_this_month) {
1355
+			$current_year_and_month = date('Y-m', current_time('timestamp'));
1356
+			$days_this_month = date('t', current_time('timestamp'));
1357
+			$where['REG_date'] = array(
1358
+				'BETWEEN',
1359
+				array(
1360
+					EEM_Registration::instance()->convert_datetime_for_query(
1361
+						'REG_date',
1362
+						$current_year_and_month . '-01 00:00:00',
1363
+						'Y-m-d H:i:s'
1364
+					),
1365
+					EEM_Registration::instance()->convert_datetime_for_query(
1366
+						'REG_date',
1367
+						$current_year_and_month . '-' . $days_this_month . ' 23:59:59',
1368
+						'Y-m-d H:i:s'
1369
+					),
1370
+				),
1371
+			);
1372
+		} elseif ($month_range) {
1373
+			$pieces = explode(' ', $month_range, 3);
1374
+			$month_requested = ! empty($pieces[0])
1375
+				? date('m', \EEH_DTT_Helper::first_of_month_timestamp($pieces[0]))
1376
+				: '';
1377
+			$year_requested = ! empty($pieces[1])
1378
+				? $pieces[1]
1379
+				: '';
1380
+			// if there is not a month or year then we can't go further
1381
+			if ($month_requested && $year_requested) {
1382
+				$days_in_month = date('t', strtotime($year_requested . '-' . $month_requested . '-' . '01'));
1383
+				$where['REG_date'] = array(
1384
+					'BETWEEN',
1385
+					array(
1386
+						EEM_Registration::instance()->convert_datetime_for_query(
1387
+							'REG_date',
1388
+							$year_requested . '-' . $month_requested . '-01 00:00:00',
1389
+							'Y-m-d H:i:s'
1390
+						),
1391
+						EEM_Registration::instance()->convert_datetime_for_query(
1392
+							'REG_date',
1393
+							$year_requested . '-' . $month_requested . '-' . $days_in_month . ' 23:59:59',
1394
+							'Y-m-d H:i:s'
1395
+						),
1396
+					),
1397
+				);
1398
+			}
1399
+		}
1400
+		return $where;
1401
+	}
1402
+
1403
+
1404
+	/**
1405
+	 * Adds any provided search restraints to the where conditions for the registrations query
1406
+	 *
1407
+	 * @param array $request usually the same as $this->_req_data but not necessarily
1408
+	 * @return array
1409
+	 */
1410
+	protected function _add_search_to_where_conditions(array $request)
1411
+	{
1412
+		$where = array();
1413
+		if (! empty($request['s'])) {
1414
+			$search_string = '%' . sanitize_text_field($request['s']) . '%';
1415
+			$where['OR*search_conditions'] = array(
1416
+				'Event.EVT_name'                          => array('LIKE', $search_string),
1417
+				'Event.EVT_desc'                          => array('LIKE', $search_string),
1418
+				'Event.EVT_short_desc'                    => array('LIKE', $search_string),
1419
+				'Attendee.ATT_full_name'                  => array('LIKE', $search_string),
1420
+				'Attendee.ATT_fname'                      => array('LIKE', $search_string),
1421
+				'Attendee.ATT_lname'                      => array('LIKE', $search_string),
1422
+				'Attendee.ATT_short_bio'                  => array('LIKE', $search_string),
1423
+				'Attendee.ATT_email'                      => array('LIKE', $search_string),
1424
+				'Attendee.ATT_address'                    => array('LIKE', $search_string),
1425
+				'Attendee.ATT_address2'                   => array('LIKE', $search_string),
1426
+				'Attendee.ATT_city'                       => array('LIKE', $search_string),
1427
+				'REG_final_price'                         => array('LIKE', $search_string),
1428
+				'REG_code'                                => array('LIKE', $search_string),
1429
+				'REG_count'                               => array('LIKE', $search_string),
1430
+				'REG_group_size'                          => array('LIKE', $search_string),
1431
+				'Ticket.TKT_name'                         => array('LIKE', $search_string),
1432
+				'Ticket.TKT_description'                  => array('LIKE', $search_string),
1433
+				'Transaction.Payment.PAY_txn_id_chq_nmbr' => array('LIKE', $search_string),
1434
+			);
1435
+		}
1436
+		return $where;
1437
+	}
1438
+
1439
+
1440
+	/**
1441
+	 * Sets up the where conditions for the registrations query.
1442
+	 *
1443
+	 * @param array $request
1444
+	 * @return array
1445
+	 * @throws EE_Error
1446
+	 */
1447
+	protected function _get_where_conditions_for_registrations_query($request)
1448
+	{
1449
+		return apply_filters(
1450
+			'FHEE__Registrations_Admin_Page___get_where_conditions_for_registrations_query',
1451
+			array_merge(
1452
+				$this->addAttendeeIdToWhereConditions($request),
1453
+				$this->_add_event_id_to_where_conditions($request),
1454
+				$this->_add_category_id_to_where_conditions($request),
1455
+				$this->_add_datetime_id_to_where_conditions($request),
1456
+				$this->_add_registration_status_to_where_conditions($request),
1457
+				$this->_add_date_to_where_conditions($request),
1458
+				$this->_add_search_to_where_conditions($request)
1459
+			),
1460
+			$request
1461
+		);
1462
+	}
1463
+
1464
+
1465
+	/**
1466
+	 * Sets up the orderby for the registrations query.
1467
+	 *
1468
+	 * @return array
1469
+	 */
1470
+	protected function _get_orderby_for_registrations_query()
1471
+	{
1472
+		$orderby_field = ! empty($this->_req_data['orderby'])
1473
+			? sanitize_text_field($this->_req_data['orderby'])
1474
+			: '_REG_date';
1475
+		switch ($orderby_field) {
1476
+			case '_REG_ID':
1477
+				$orderby = array('REG_ID');
1478
+				break;
1479
+			case '_Reg_status':
1480
+				$orderby = array('STS_ID');
1481
+				break;
1482
+			case 'ATT_fname':
1483
+				$orderby = array('Attendee.ATT_fname', 'Attendee.ATT_lname');
1484
+				break;
1485
+			case 'ATT_lname':
1486
+				$orderby = array('Attendee.ATT_lname', 'Attendee.ATT_fname');
1487
+				break;
1488
+			case 'event_name':
1489
+				$orderby = array('Event.EVT_name');
1490
+				break;
1491
+			case 'DTT_EVT_start':
1492
+				$orderby = array('Event.Datetime.DTT_EVT_start');
1493
+				break;
1494
+			case '_REG_date':
1495
+				$orderby = array('REG_date');
1496
+				break;
1497
+			default:
1498
+				$orderby = array($orderby_field);
1499
+				break;
1500
+		}
1501
+
1502
+		// order
1503
+		$order = ! empty($this->_req_data['order'])
1504
+			? sanitize_text_field($this->_req_data['order'])
1505
+			: 'DESC';
1506
+		$orderby = array_combine(
1507
+			$orderby,
1508
+			array_fill(0, count($orderby), $order)
1509
+		);
1510
+		// because there are many registrations with the same date, define
1511
+		// a secondary way to order them, otherwise MySQL seems to be a bit random
1512
+		if (empty($orderby['REG_ID'])) {
1513
+			$orderby['REG_ID'] = $order;
1514
+		}
1515
+
1516
+		$orderby = apply_filters(
1517
+			'FHEE__Registrations_Admin_Page___get_orderby_for_registrations_query',
1518
+			$orderby,
1519
+			$this->_req_data
1520
+		);
1521
+
1522
+		return array('order_by' => $orderby);
1523
+	}
1524
+
1525
+
1526
+	/**
1527
+	 * Sets up the limit for the registrations query.
1528
+	 *
1529
+	 * @param $per_page
1530
+	 * @return array
1531
+	 */
1532
+	protected function _get_limit($per_page)
1533
+	{
1534
+		$current_page = ! empty($this->_req_data['paged'])
1535
+			? absint($this->_req_data['paged'])
1536
+			: 1;
1537
+		$per_page = ! empty($this->_req_data['perpage'])
1538
+			? $this->_req_data['perpage']
1539
+			: $per_page;
1540
+
1541
+		// -1 means return all results so get out if that's set.
1542
+		if ((int) $per_page === -1) {
1543
+			return array();
1544
+		}
1545
+		$per_page = absint($per_page);
1546
+		$offset = ($current_page - 1) * $per_page;
1547
+		return array('limit' => array($offset, $per_page));
1548
+	}
1549
+
1550
+
1551
+	public function get_registration_status_array()
1552
+	{
1553
+		return self::$_reg_status;
1554
+	}
1555
+
1556
+
1557
+
1558
+
1559
+	/***************************************        REGISTRATION DETAILS        ***************************************/
1560
+	/**
1561
+	 *        generates HTML for the View Registration Details Admin page
1562
+	 *
1563
+	 * @access protected
1564
+	 * @return void
1565
+	 * @throws DomainException
1566
+	 * @throws EE_Error
1567
+	 * @throws InvalidArgumentException
1568
+	 * @throws InvalidDataTypeException
1569
+	 * @throws InvalidInterfaceException
1570
+	 * @throws EntityNotFoundException
1571
+	 */
1572
+	protected function _registration_details()
1573
+	{
1574
+		$this->_template_args = array();
1575
+		$this->_set_registration_object();
1576
+		if (is_object($this->_registration)) {
1577
+			$transaction = $this->_registration->transaction()
1578
+				? $this->_registration->transaction()
1579
+				: EE_Transaction::new_instance();
1580
+			$this->_session = $transaction->session_data();
1581
+			$event_id = $this->_registration->event_ID();
1582
+			$this->_template_args['reg_nmbr']['value'] = $this->_registration->ID();
1583
+			$this->_template_args['reg_nmbr']['label'] = esc_html__('Registration Number', 'event_espresso');
1584
+			$this->_template_args['reg_datetime']['value'] = $this->_registration->get_i18n_datetime('REG_date');
1585
+			$this->_template_args['reg_datetime']['label'] = esc_html__('Date', 'event_espresso');
1586
+			$this->_template_args['grand_total'] = $transaction->total();
1587
+			$this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
1588
+			// link back to overview
1589
+			$this->_template_args['reg_overview_url'] = REG_ADMIN_URL;
1590
+			$this->_template_args['registration'] = $this->_registration;
1591
+			$this->_template_args['filtered_registrations_link'] = EE_Admin_Page::add_query_args_and_nonce(
1592
+				array(
1593
+					'action'   => 'default',
1594
+					'event_id' => $event_id,
1595
+				),
1596
+				REG_ADMIN_URL
1597
+			);
1598
+			$this->_template_args['filtered_transactions_link'] = EE_Admin_Page::add_query_args_and_nonce(
1599
+				array(
1600
+					'action' => 'default',
1601
+					'EVT_ID' => $event_id,
1602
+					'page'   => 'espresso_transactions',
1603
+				),
1604
+				admin_url('admin.php')
1605
+			);
1606
+			$this->_template_args['event_link'] = EE_Admin_Page::add_query_args_and_nonce(
1607
+				array(
1608
+					'page'   => 'espresso_events',
1609
+					'action' => 'edit',
1610
+					'post'   => $event_id,
1611
+				),
1612
+				admin_url('admin.php')
1613
+			);
1614
+			// next and previous links
1615
+			$next_reg = $this->_registration->next(
1616
+				null,
1617
+				array(),
1618
+				'REG_ID'
1619
+			);
1620
+			$this->_template_args['next_registration'] = $next_reg
1621
+				? $this->_next_link(
1622
+					EE_Admin_Page::add_query_args_and_nonce(
1623
+						array(
1624
+							'action'  => 'view_registration',
1625
+							'_REG_ID' => $next_reg['REG_ID'],
1626
+						),
1627
+						REG_ADMIN_URL
1628
+					),
1629
+					'dashicons dashicons-arrow-right ee-icon-size-22'
1630
+				)
1631
+				: '';
1632
+			$previous_reg = $this->_registration->previous(
1633
+				null,
1634
+				array(),
1635
+				'REG_ID'
1636
+			);
1637
+			$this->_template_args['previous_registration'] = $previous_reg
1638
+				? $this->_previous_link(
1639
+					EE_Admin_Page::add_query_args_and_nonce(
1640
+						array(
1641
+							'action'  => 'view_registration',
1642
+							'_REG_ID' => $previous_reg['REG_ID'],
1643
+						),
1644
+						REG_ADMIN_URL
1645
+					),
1646
+					'dashicons dashicons-arrow-left ee-icon-size-22'
1647
+				)
1648
+				: '';
1649
+			// grab header
1650
+			$template_path = REG_TEMPLATE_PATH . 'reg_admin_details_header.template.php';
1651
+			$this->_template_args['REG_ID'] = $this->_registration->ID();
1652
+			$this->_template_args['admin_page_header'] = EEH_Template::display_template(
1653
+				$template_path,
1654
+				$this->_template_args,
1655
+				true
1656
+			);
1657
+		} else {
1658
+			$this->_template_args['admin_page_header'] = $this->display_espresso_notices();
1659
+		}
1660
+		// the details template wrapper
1661
+		$this->display_admin_page_with_sidebar();
1662
+	}
1663
+
1664
+
1665
+	protected function _registration_details_metaboxes()
1666
+	{
1667
+		do_action('AHEE__Registrations_Admin_Page___registration_details_metabox__start', $this);
1668
+		$this->_set_registration_object();
1669
+		$attendee = $this->_registration instanceof EE_Registration ? $this->_registration->attendee() : null;
1670
+		add_meta_box(
1671
+			'edit-reg-status-mbox',
1672
+			esc_html__('Registration Status', 'event_espresso'),
1673
+			array($this, 'set_reg_status_buttons_metabox'),
1674
+			$this->wp_page_slug,
1675
+			'normal',
1676
+			'high'
1677
+		);
1678
+		add_meta_box(
1679
+			'edit-reg-details-mbox',
1680
+			esc_html__('Registration Details', 'event_espresso'),
1681
+			array($this, '_reg_details_meta_box'),
1682
+			$this->wp_page_slug,
1683
+			'normal',
1684
+			'high'
1685
+		);
1686
+		if ($attendee instanceof EE_Attendee
1687
+			&& EE_Registry::instance()->CAP->current_user_can(
1688
+				'ee_read_registration',
1689
+				'edit-reg-questions-mbox',
1690
+				$this->_registration->ID()
1691
+			)
1692
+		) {
1693
+			add_meta_box(
1694
+				'edit-reg-questions-mbox',
1695
+				esc_html__('Registration Form Answers', 'event_espresso'),
1696
+				array($this, '_reg_questions_meta_box'),
1697
+				$this->wp_page_slug,
1698
+				'normal',
1699
+				'high'
1700
+			);
1701
+		}
1702
+		add_meta_box(
1703
+			'edit-reg-registrant-mbox',
1704
+			esc_html__('Contact Details', 'event_espresso'),
1705
+			array($this, '_reg_registrant_side_meta_box'),
1706
+			$this->wp_page_slug,
1707
+			'side',
1708
+			'high'
1709
+		);
1710
+		if ($this->_registration->group_size() > 1) {
1711
+			add_meta_box(
1712
+				'edit-reg-attendees-mbox',
1713
+				esc_html__('Other Registrations in this Transaction', 'event_espresso'),
1714
+				array($this, '_reg_attendees_meta_box'),
1715
+				$this->wp_page_slug,
1716
+				'normal',
1717
+				'high'
1718
+			);
1719
+		}
1720
+	}
1721
+
1722
+
1723
+	/**
1724
+	 * set_reg_status_buttons_metabox
1725
+	 *
1726
+	 * @access protected
1727
+	 * @return string
1728
+	 * @throws \EE_Error
1729
+	 */
1730
+	public function set_reg_status_buttons_metabox()
1731
+	{
1732
+		$this->_set_registration_object();
1733
+		$change_reg_status_form = $this->_generate_reg_status_change_form();
1734
+		echo $change_reg_status_form->form_open(
1735
+			self::add_query_args_and_nonce(
1736
+				array(
1737
+					'action' => 'change_reg_status',
1738
+				),
1739
+				REG_ADMIN_URL
1740
+			)
1741
+		);
1742
+		echo $change_reg_status_form->get_html();
1743
+		echo $change_reg_status_form->form_close();
1744
+	}
1745
+
1746
+
1747
+	/**
1748
+	 * @return EE_Form_Section_Proper
1749
+	 * @throws EE_Error
1750
+	 * @throws InvalidArgumentException
1751
+	 * @throws InvalidDataTypeException
1752
+	 * @throws InvalidInterfaceException
1753
+	 * @throws \EventEspresso\core\exceptions\EntityNotFoundException
1754
+	 */
1755
+	protected function _generate_reg_status_change_form()
1756
+	{
1757
+		$reg_status_change_form_array = array(
1758
+			'name'            => 'reg_status_change_form',
1759
+			'html_id'         => 'reg-status-change-form',
1760
+			'layout_strategy' => new EE_Admin_Two_Column_Layout(),
1761
+			'subsections'     => array(
1762
+				'return'             => new EE_Hidden_Input(
1763
+					array(
1764
+						'name'    => 'return',
1765
+						'default' => 'view_registration',
1766
+					)
1767
+				),
1768
+				'REG_ID'             => new EE_Hidden_Input(
1769
+					array(
1770
+						'name'    => 'REG_ID',
1771
+						'default' => $this->_registration->ID(),
1772
+					)
1773
+				),
1774
+				'current_status'     => new EE_Form_Section_HTML(
1775
+					EEH_HTML::tr(
1776
+						EEH_HTML::th(
1777
+							EEH_HTML::label(
1778
+								EEH_HTML::strong(
1779
+									esc_html__('Current Registration Status', 'event_espresso')
1780
+								)
1781
+							)
1782
+						)
1783
+						. EEH_HTML::td(
1784
+							EEH_HTML::strong(
1785
+								$this->_registration->pretty_status(),
1786
+								'',
1787
+								'status-' . $this->_registration->status_ID(),
1788
+								'line-height: 1em; font-size: 1.5em; font-weight: bold;'
1789
+							)
1790
+						)
1791
+					)
1792
+				)
1793
+			)
1794
+		);
1795
+		if (EE_Registry::instance()->CAP->current_user_can(
1796
+			'ee_edit_registration',
1797
+			'toggle_registration_status',
1798
+			$this->_registration->ID()
1799
+		)) {
1800
+			$reg_status_change_form_array['subsections']['reg_status'] = new EE_Select_Input(
1801
+				$this->_get_reg_statuses(),
1802
+				array(
1803
+					'html_label_text' => esc_html__('Change Registration Status to', 'event_espresso'),
1804
+					'default'         => $this->_registration->status_ID(),
1805
+				)
1806
+			);
1807
+			$reg_status_change_form_array['subsections']['send_notifications'] = new EE_Yes_No_Input(
1808
+				array(
1809
+					'html_label_text' => esc_html__('Send Related Messages', 'event_espresso'),
1810
+					'default'         => false,
1811
+					'html_help_text'  => esc_html__(
1812
+						'If set to "Yes", then the related messages will be sent to the registrant.',
1813
+						'event_espresso'
1814
+					)
1815
+				)
1816
+			);
1817
+			$reg_status_change_form_array['subsections']['submit'] = new EE_Submit_Input(
1818
+				array(
1819
+					'html_class'      => 'button-primary',
1820
+					'html_label_text' => '&nbsp;',
1821
+					'default'         => esc_html__('Update Registration Status', 'event_espresso'),
1822
+				)
1823
+			);
1824
+		}
1825
+		return new EE_Form_Section_Proper($reg_status_change_form_array);
1826
+	}
1827
+
1828
+
1829
+	/**
1830
+	 * Returns an array of all the buttons for the various statuses and switch status actions
1831
+	 *
1832
+	 * @return array
1833
+	 * @throws EE_Error
1834
+	 * @throws InvalidArgumentException
1835
+	 * @throws InvalidDataTypeException
1836
+	 * @throws InvalidInterfaceException
1837
+	 * @throws EntityNotFoundException
1838
+	 */
1839
+	protected function _get_reg_statuses()
1840
+	{
1841
+		$reg_status_array = EEM_Registration::instance()->reg_status_array();
1842
+		unset($reg_status_array[ EEM_Registration::status_id_incomplete ]);
1843
+		// get current reg status
1844
+		$current_status = $this->_registration->status_ID();
1845
+		// is registration for free event? This will determine whether to display the pending payment option
1846
+		if ($current_status !== EEM_Registration::status_id_pending_payment
1847
+			&& EEH_Money::compare_floats($this->_registration->ticket()->price(), 0.00)
1848
+		) {
1849
+			unset($reg_status_array[ EEM_Registration::status_id_pending_payment ]);
1850
+		}
1851
+		return EEM_Status::instance()->localized_status($reg_status_array, false, 'sentence');
1852
+	}
1853
+
1854
+
1855
+	/**
1856
+	 * This method is used when using _REG_ID from request which may or may not be an array of reg_ids.
1857
+	 *
1858
+	 * @param bool $status REG status given for changing registrations to.
1859
+	 * @param bool $notify Whether to send messages notifications or not.
1860
+	 * @return array (array with reg_id(s) updated and whether update was successful.
1861
+	 * @throws EE_Error
1862
+	 * @throws InvalidArgumentException
1863
+	 * @throws InvalidDataTypeException
1864
+	 * @throws InvalidInterfaceException
1865
+	 * @throws ReflectionException
1866
+	 * @throws RuntimeException
1867
+	 * @throws EntityNotFoundException
1868
+	 */
1869
+	protected function _set_registration_status_from_request($status = false, $notify = false)
1870
+	{
1871
+		if (isset($this->_req_data['reg_status_change_form'])) {
1872
+			$REG_IDs = isset($this->_req_data['reg_status_change_form']['REG_ID'])
1873
+				? (array) $this->_req_data['reg_status_change_form']['REG_ID']
1874
+				: array();
1875
+		} else {
1876
+			$REG_IDs = isset($this->_req_data['_REG_ID'])
1877
+				? (array) $this->_req_data['_REG_ID']
1878
+				: array();
1879
+		}
1880
+		// sanitize $REG_IDs
1881
+		$REG_IDs = array_map('absint', $REG_IDs);
1882
+		// and remove empty entries
1883
+		$REG_IDs = array_filter($REG_IDs);
1884
+
1885
+		$result = $this->_set_registration_status($REG_IDs, $status, $notify);
1886
+
1887
+		/**
1888
+		 * Set and filter $_req_data['_REG_ID'] for any potential future messages notifications.
1889
+		 * Currently this value is used downstream by the _process_resend_registration method.
1890
+		 *
1891
+		 * @param int|array                $registration_ids The registration ids that have had their status changed successfully.
1892
+		 * @param bool                     $status           The status registrations were changed to.
1893
+		 * @param bool                     $success          If the status was changed successfully for all registrations.
1894
+		 * @param Registrations_Admin_Page $admin_page_object
1895
+		 */
1896
+		$this->_req_data['_REG_ID'] = apply_filters(
1897
+			'FHEE__Registrations_Admin_Page___set_registration_status_from_request__REG_IDs',
1898
+			$result['REG_ID'],
1899
+			$status,
1900
+			$result['success'],
1901
+			$this
1902
+		);
1903
+
1904
+		// notify?
1905
+		if ($notify
1906
+			&& $result['success']
1907
+			&& ! empty($this->_req_data['_REG_ID'])
1908
+			&& EE_Registry::instance()->CAP->current_user_can(
1909
+				'ee_send_message',
1910
+				'espresso_registrations_resend_registration'
1911
+			)
1912
+		) {
1913
+			$this->_process_resend_registration();
1914
+		}
1915
+		return $result;
1916
+	}
1917
+
1918
+
1919
+	/**
1920
+	 * Set the registration status for the given reg_id (which may or may not be an array, it gets typecast to an
1921
+	 * array). Note, this method does NOT take care of possible notifications.  That is required by calling code.
1922
+	 *
1923
+	 * @param array  $REG_IDs
1924
+	 * @param string $status
1925
+	 * @param bool   $notify  Used to indicate whether notification was requested or not.  This determines the context
1926
+	 *                        slug sent with setting the registration status.
1927
+	 * @return array (an array with 'success' key representing whether status change was successful, and 'REG_ID' as
1928
+	 * @throws EE_Error
1929
+	 * @throws InvalidArgumentException
1930
+	 * @throws InvalidDataTypeException
1931
+	 * @throws InvalidInterfaceException
1932
+	 * @throws ReflectionException
1933
+	 * @throws RuntimeException
1934
+	 * @throws EntityNotFoundException
1935
+	 */
1936
+	protected function _set_registration_status($REG_IDs = array(), $status = '', $notify = false)
1937
+	{
1938
+		$success = false;
1939
+		// typecast $REG_IDs
1940
+		$REG_IDs = (array) $REG_IDs;
1941
+		if (! empty($REG_IDs)) {
1942
+			$success = true;
1943
+			// set default status if none is passed
1944
+			$status = $status ? $status : EEM_Registration::status_id_pending_payment;
1945
+			$status_context = $notify
1946
+				? Domain::CONTEXT_REGISTRATION_STATUS_CHANGE_REGISTRATION_ADMIN_NOTIFY
1947
+				: Domain::CONTEXT_REGISTRATION_STATUS_CHANGE_REGISTRATION_ADMIN;
1948
+			// loop through REG_ID's and change status
1949
+			foreach ($REG_IDs as $REG_ID) {
1950
+				$registration = EEM_Registration::instance()->get_one_by_ID($REG_ID);
1951
+				if ($registration instanceof EE_Registration) {
1952
+					$registration->set_status(
1953
+						$status,
1954
+						false,
1955
+						new Context(
1956
+							$status_context,
1957
+							esc_html__(
1958
+								'Manually triggered status change on a Registration Admin Page route.',
1959
+								'event_espresso'
1960
+							)
1961
+						)
1962
+					);
1963
+					$result = $registration->save();
1964
+					// verifying explicit fails because update *may* just return 0 for 0 rows affected
1965
+					$success = $result !== false ? $success : false;
1966
+				}
1967
+			}
1968
+		}
1969
+
1970
+		// return $success and processed registrations
1971
+		return array('REG_ID' => $REG_IDs, 'success' => $success);
1972
+	}
1973
+
1974
+
1975
+	/**
1976
+	 * Common logic for setting up success message and redirecting to appropriate route
1977
+	 *
1978
+	 * @param  string $STS_ID status id for the registration changed to
1979
+	 * @param   bool  $notify indicates whether the _set_registration_status_from_request does notifications or not.
1980
+	 * @return void
1981
+	 * @throws EE_Error
1982
+	 */
1983
+	protected function _reg_status_change_return($STS_ID, $notify = false)
1984
+	{
1985
+		$result = ! empty($STS_ID) ? $this->_set_registration_status_from_request($STS_ID, $notify)
1986
+			: array('success' => false);
1987
+		$success = isset($result['success']) && $result['success'];
1988
+		// setup success message
1989
+		if ($success) {
1990
+			if (is_array($result['REG_ID']) && count($result['REG_ID']) === 1) {
1991
+				$msg = sprintf(
1992
+					esc_html__('Registration status has been set to %s', 'event_espresso'),
1993
+					EEH_Template::pretty_status($STS_ID, false, 'lower')
1994
+				);
1995
+			} else {
1996
+				$msg = sprintf(
1997
+					esc_html__('Registrations have been set to %s.', 'event_espresso'),
1998
+					EEH_Template::pretty_status($STS_ID, false, 'lower')
1999
+				);
2000
+			}
2001
+			EE_Error::add_success($msg);
2002
+		} else {
2003
+			EE_Error::add_error(
2004
+				esc_html__(
2005
+					'Something went wrong, and the status was not changed',
2006
+					'event_espresso'
2007
+				),
2008
+				__FILE__,
2009
+				__LINE__,
2010
+				__FUNCTION__
2011
+			);
2012
+		}
2013
+		if (isset($this->_req_data['return']) && $this->_req_data['return'] == 'view_registration') {
2014
+			$route = array('action' => 'view_registration', '_REG_ID' => reset($result['REG_ID']));
2015
+		} else {
2016
+			$route = array('action' => 'default');
2017
+		}
2018
+		$route = $this->mergeExistingRequestParamsWithRedirectArgs($route);
2019
+		$this->_redirect_after_action($success, '', '', $route, true);
2020
+	}
2021
+
2022
+
2023
+	/**
2024
+	 * incoming reg status change from reg details page.
2025
+	 *
2026
+	 * @return void
2027
+	 */
2028
+	protected function _change_reg_status()
2029
+	{
2030
+		$this->_req_data['return'] = 'view_registration';
2031
+		// set notify based on whether the send notifications toggle is set or not
2032
+		$notify = ! empty($this->_req_data['reg_status_change_form']['send_notifications']);
2033
+		// $notify = ! empty( $this->_req_data['txn_reg_status_change']['send_notifications'] );
2034
+		$this->_req_data['reg_status_change_form']['reg_status'] = isset($this->_req_data['reg_status_change_form']['reg_status'])
2035
+			? $this->_req_data['reg_status_change_form']['reg_status'] : '';
2036
+		switch ($this->_req_data['reg_status_change_form']['reg_status']) {
2037
+			case EEM_Registration::status_id_approved:
2038
+			case EEH_Template::pretty_status(EEM_Registration::status_id_approved, false, 'sentence'):
2039
+				$this->approve_registration($notify);
2040
+				break;
2041
+			case EEM_Registration::status_id_pending_payment:
2042
+			case EEH_Template::pretty_status(EEM_Registration::status_id_pending_payment, false, 'sentence'):
2043
+				$this->pending_registration($notify);
2044
+				break;
2045
+			case EEM_Registration::status_id_not_approved:
2046
+			case EEH_Template::pretty_status(EEM_Registration::status_id_not_approved, false, 'sentence'):
2047
+				$this->not_approve_registration($notify);
2048
+				break;
2049
+			case EEM_Registration::status_id_declined:
2050
+			case EEH_Template::pretty_status(EEM_Registration::status_id_declined, false, 'sentence'):
2051
+				$this->decline_registration($notify);
2052
+				break;
2053
+			case EEM_Registration::status_id_cancelled:
2054
+			case EEH_Template::pretty_status(EEM_Registration::status_id_cancelled, false, 'sentence'):
2055
+				$this->cancel_registration($notify);
2056
+				break;
2057
+			case EEM_Registration::status_id_wait_list:
2058
+			case EEH_Template::pretty_status(EEM_Registration::status_id_wait_list, false, 'sentence'):
2059
+				$this->wait_list_registration($notify);
2060
+				break;
2061
+			case EEM_Registration::status_id_incomplete:
2062
+			default:
2063
+				$result['success'] = false;
2064
+				unset($this->_req_data['return']);
2065
+				$this->_reg_status_change_return('', false);
2066
+				break;
2067
+		}
2068
+	}
2069
+
2070
+
2071
+	/**
2072
+	 * Callback for bulk action routes.
2073
+	 * Note: although we could just register the singular route callbacks for each bulk action route as well, this
2074
+	 * method was chosen so there is one central place all the registration status bulk actions are going through.
2075
+	 * Potentially, this provides an easier place to locate logic that is specific to these bulk actions (as opposed to
2076
+	 * when an action is happening on just a single registration).
2077
+	 *
2078
+	 * @param      $action
2079
+	 * @param bool $notify
2080
+	 */
2081
+	protected function bulk_action_on_registrations($action, $notify = false)
2082
+	{
2083
+		do_action(
2084
+			'AHEE__Registrations_Admin_Page__bulk_action_on_registrations__before_execution',
2085
+			$this,
2086
+			$action,
2087
+			$notify
2088
+		);
2089
+		$method = $action . '_registration';
2090
+		if (method_exists($this, $method)) {
2091
+			$this->$method($notify);
2092
+		}
2093
+	}
2094
+
2095
+
2096
+	/**
2097
+	 * approve_registration
2098
+	 *
2099
+	 * @access protected
2100
+	 * @param bool $notify whether or not to notify the registrant about their approval.
2101
+	 * @return void
2102
+	 */
2103
+	protected function approve_registration($notify = false)
2104
+	{
2105
+		$this->_reg_status_change_return(EEM_Registration::status_id_approved, $notify);
2106
+	}
2107
+
2108
+
2109
+	/**
2110
+	 *        decline_registration
2111
+	 *
2112
+	 * @access protected
2113
+	 * @param bool $notify whether or not to notify the registrant about their status change.
2114
+	 * @return void
2115
+	 */
2116
+	protected function decline_registration($notify = false)
2117
+	{
2118
+		$this->_reg_status_change_return(EEM_Registration::status_id_declined, $notify);
2119
+	}
2120
+
2121
+
2122
+	/**
2123
+	 *        cancel_registration
2124
+	 *
2125
+	 * @access protected
2126
+	 * @param bool $notify whether or not to notify the registrant about their status change.
2127
+	 * @return void
2128
+	 */
2129
+	protected function cancel_registration($notify = false)
2130
+	{
2131
+		$this->_reg_status_change_return(EEM_Registration::status_id_cancelled, $notify);
2132
+	}
2133
+
2134
+
2135
+	/**
2136
+	 *        not_approve_registration
2137
+	 *
2138
+	 * @access protected
2139
+	 * @param bool $notify whether or not to notify the registrant about their status change.
2140
+	 * @return void
2141
+	 */
2142
+	protected function not_approve_registration($notify = false)
2143
+	{
2144
+		$this->_reg_status_change_return(EEM_Registration::status_id_not_approved, $notify);
2145
+	}
2146
+
2147
+
2148
+	/**
2149
+	 *        decline_registration
2150
+	 *
2151
+	 * @access protected
2152
+	 * @param bool $notify whether or not to notify the registrant about their status change.
2153
+	 * @return void
2154
+	 */
2155
+	protected function pending_registration($notify = false)
2156
+	{
2157
+		$this->_reg_status_change_return(EEM_Registration::status_id_pending_payment, $notify);
2158
+	}
2159
+
2160
+
2161
+	/**
2162
+	 * waitlist_registration
2163
+	 *
2164
+	 * @access protected
2165
+	 * @param bool $notify whether or not to notify the registrant about their status change.
2166
+	 * @return void
2167
+	 */
2168
+	protected function wait_list_registration($notify = false)
2169
+	{
2170
+		$this->_reg_status_change_return(EEM_Registration::status_id_wait_list, $notify);
2171
+	}
2172
+
2173
+
2174
+	/**
2175
+	 *        generates HTML for the Registration main meta box
2176
+	 *
2177
+	 * @access public
2178
+	 * @return void
2179
+	 * @throws DomainException
2180
+	 * @throws EE_Error
2181
+	 * @throws InvalidArgumentException
2182
+	 * @throws InvalidDataTypeException
2183
+	 * @throws InvalidInterfaceException
2184
+	 * @throws ReflectionException
2185
+	 * @throws EntityNotFoundException
2186
+	 */
2187
+	public function _reg_details_meta_box()
2188
+	{
2189
+		EEH_Autoloader::register_line_item_display_autoloaders();
2190
+		EEH_Autoloader::register_line_item_filter_autoloaders();
2191
+		EE_Registry::instance()->load_helper('Line_Item');
2192
+		$transaction = $this->_registration->transaction() ? $this->_registration->transaction()
2193
+			: EE_Transaction::new_instance();
2194
+		$this->_session = $transaction->session_data();
2195
+		$filters = new EE_Line_Item_Filter_Collection();
2196
+		// $filters->add( new EE_Non_Zero_Line_Item_Filter() );
2197
+		$filters->add(new EE_Single_Registration_Line_Item_Filter($this->_registration));
2198
+		$line_item_filter_processor = new EE_Line_Item_Filter_Processor(
2199
+			$filters,
2200
+			$transaction->total_line_item()
2201
+		);
2202
+		$filtered_line_item_tree = $line_item_filter_processor->process();
2203
+		$line_item_display = new EE_Line_Item_Display(
2204
+			'reg_admin_table',
2205
+			'EE_Admin_Table_Registration_Line_Item_Display_Strategy'
2206
+		);
2207
+		$this->_template_args['line_item_table'] = $line_item_display->display_line_item(
2208
+			$filtered_line_item_tree,
2209
+			array('EE_Registration' => $this->_registration)
2210
+		);
2211
+		$attendee = $this->_registration->attendee();
2212
+		if (EE_Registry::instance()->CAP->current_user_can(
2213
+			'ee_read_transaction',
2214
+			'espresso_transactions_view_transaction'
2215
+		)) {
2216
+			$this->_template_args['view_transaction_button'] = EEH_Template::get_button_or_link(
2217
+				EE_Admin_Page::add_query_args_and_nonce(
2218
+					array(
2219
+						'action' => 'view_transaction',
2220
+						'TXN_ID' => $transaction->ID(),
2221
+					),
2222
+					TXN_ADMIN_URL
2223
+				),
2224
+				esc_html__(' View Transaction', 'event_espresso'),
2225
+				'button secondary-button right',
2226
+				'dashicons dashicons-cart'
2227
+			);
2228
+		} else {
2229
+			$this->_template_args['view_transaction_button'] = '';
2230
+		}
2231
+		if ($attendee instanceof EE_Attendee
2232
+			&& EE_Registry::instance()->CAP->current_user_can(
2233
+				'ee_send_message',
2234
+				'espresso_registrations_resend_registration'
2235
+			)
2236
+		) {
2237
+			$this->_template_args['resend_registration_button'] = EEH_Template::get_button_or_link(
2238
+				EE_Admin_Page::add_query_args_and_nonce(
2239
+					array(
2240
+						'action'      => 'resend_registration',
2241
+						'_REG_ID'     => $this->_registration->ID(),
2242
+						'redirect_to' => 'view_registration',
2243
+					),
2244
+					REG_ADMIN_URL
2245
+				),
2246
+				esc_html__(' Resend Registration', 'event_espresso'),
2247
+				'button secondary-button right',
2248
+				'dashicons dashicons-email-alt'
2249
+			);
2250
+		} else {
2251
+			$this->_template_args['resend_registration_button'] = '';
2252
+		}
2253
+		$this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
2254
+		$payment = $transaction->get_first_related('Payment');
2255
+		$payment = ! $payment instanceof EE_Payment
2256
+			? EE_Payment::new_instance()
2257
+			: $payment;
2258
+		$payment_method = $payment->get_first_related('Payment_Method');
2259
+		$payment_method = ! $payment_method instanceof EE_Payment_Method
2260
+			? EE_Payment_Method::new_instance()
2261
+			: $payment_method;
2262
+		$reg_details = array(
2263
+			'payment_method'       => $payment_method->name(),
2264
+			'response_msg'         => $payment->gateway_response(),
2265
+			'registration_id'      => $this->_registration->get('REG_code'),
2266
+			'registration_session' => $this->_registration->session_ID(),
2267
+			'ip_address'           => isset($this->_session['ip_address']) ? $this->_session['ip_address'] : '',
2268
+			'user_agent'           => isset($this->_session['user_agent']) ? $this->_session['user_agent'] : '',
2269
+		);
2270
+		if (isset($reg_details['registration_id'])) {
2271
+			$this->_template_args['reg_details']['registration_id']['value'] = $reg_details['registration_id'];
2272
+			$this->_template_args['reg_details']['registration_id']['label'] = esc_html__(
2273
+				'Registration ID',
2274
+				'event_espresso'
2275
+			);
2276
+			$this->_template_args['reg_details']['registration_id']['class'] = 'regular-text';
2277
+		}
2278
+		if (isset($reg_details['payment_method'])) {
2279
+			$this->_template_args['reg_details']['payment_method']['value'] = $reg_details['payment_method'];
2280
+			$this->_template_args['reg_details']['payment_method']['label'] = esc_html__(
2281
+				'Most Recent Payment Method',
2282
+				'event_espresso'
2283
+			);
2284
+			$this->_template_args['reg_details']['payment_method']['class'] = 'regular-text';
2285
+			$this->_template_args['reg_details']['response_msg']['value'] = $reg_details['response_msg'];
2286
+			$this->_template_args['reg_details']['response_msg']['label'] = esc_html__(
2287
+				'Payment method response',
2288
+				'event_espresso'
2289
+			);
2290
+			$this->_template_args['reg_details']['response_msg']['class'] = 'regular-text';
2291
+		}
2292
+		$this->_template_args['reg_details']['registration_session']['value'] = $reg_details['registration_session'];
2293
+		$this->_template_args['reg_details']['registration_session']['label'] = esc_html__(
2294
+			'Registration Session',
2295
+			'event_espresso'
2296
+		);
2297
+		$this->_template_args['reg_details']['registration_session']['class'] = 'regular-text';
2298
+		$this->_template_args['reg_details']['ip_address']['value'] = $reg_details['ip_address'];
2299
+		$this->_template_args['reg_details']['ip_address']['label'] = esc_html__(
2300
+			'Registration placed from IP',
2301
+			'event_espresso'
2302
+		);
2303
+		$this->_template_args['reg_details']['ip_address']['class'] = 'regular-text';
2304
+		$this->_template_args['reg_details']['user_agent']['value'] = $reg_details['user_agent'];
2305
+		$this->_template_args['reg_details']['user_agent']['label'] = esc_html__(
2306
+			'Registrant User Agent',
2307
+			'event_espresso'
2308
+		);
2309
+		$this->_template_args['reg_details']['user_agent']['class'] = 'large-text';
2310
+		$this->_template_args['event_link'] = EE_Admin_Page::add_query_args_and_nonce(
2311
+			array(
2312
+				'action'   => 'default',
2313
+				'event_id' => $this->_registration->event_ID(),
2314
+			),
2315
+			REG_ADMIN_URL
2316
+		);
2317
+		$this->_template_args['REG_ID'] = $this->_registration->ID();
2318
+		$this->_template_args['event_id'] = $this->_registration->event_ID();
2319
+		$template_path =
2320
+			REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_reg_details.template.php';
2321
+		echo EEH_Template::display_template($template_path, $this->_template_args, true);
2322
+	}
2323
+
2324
+
2325
+	/**
2326
+	 * generates HTML for the Registration Questions meta box.
2327
+	 * If pre-4.8.32.rc.000 hooks are used, uses old methods (with its filters),
2328
+	 * otherwise uses new forms system
2329
+	 *
2330
+	 * @access public
2331
+	 * @return void
2332
+	 * @throws DomainException
2333
+	 * @throws EE_Error
2334
+	 */
2335
+	public function _reg_questions_meta_box()
2336
+	{
2337
+		// allow someone to override this method entirely
2338
+		if (apply_filters(
2339
+			'FHEE__Registrations_Admin_Page___reg_questions_meta_box__do_default',
2340
+			true,
2341
+			$this,
2342
+			$this->_registration
2343
+		)) {
2344
+			$form = $this->_get_reg_custom_questions_form(
2345
+				$this->_registration->ID()
2346
+			);
2347
+			$this->_template_args['att_questions'] = count($form->subforms()) > 0
2348
+				? $form->get_html_and_js()
2349
+				: '';
2350
+			$this->_template_args['reg_questions_form_action'] = 'edit_registration';
2351
+			$this->_template_args['REG_ID'] = $this->_registration->ID();
2352
+			$template_path =
2353
+				REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_reg_questions.template.php';
2354
+			echo EEH_Template::display_template($template_path, $this->_template_args, true);
2355
+		}
2356
+	}
2357
+
2358
+
2359
+	/**
2360
+	 * form_before_question_group
2361
+	 *
2362
+	 * @deprecated    as of 4.8.32.rc.000
2363
+	 * @access        public
2364
+	 * @param        string $output
2365
+	 * @return        string
2366
+	 */
2367
+	public function form_before_question_group($output)
2368
+	{
2369
+		EE_Error::doing_it_wrong(
2370
+			__CLASS__ . '::' . __FUNCTION__,
2371
+			esc_html__(
2372
+				'This method would have been protected but was used on a filter callback so needed to be public. Please discontinue usage as it will be removed soon.',
2373
+				'event_espresso'
2374
+			),
2375
+			'4.8.32.rc.000'
2376
+		);
2377
+		return '
2378 2378
 	<table class="form-table ee-width-100">
2379 2379
 		<tbody>
2380 2380
 			';
2381
-    }
2382
-
2383
-
2384
-    /**
2385
-     * form_after_question_group
2386
-     *
2387
-     * @deprecated    as of 4.8.32.rc.000
2388
-     * @access        public
2389
-     * @param        string $output
2390
-     * @return        string
2391
-     */
2392
-    public function form_after_question_group($output)
2393
-    {
2394
-        EE_Error::doing_it_wrong(
2395
-            __CLASS__ . '::' . __FUNCTION__,
2396
-            esc_html__(
2397
-                'This method would have been protected but was used on a filter callback so needed to be public. Please discontinue usage as it will be removed soon.',
2398
-                'event_espresso'
2399
-            ),
2400
-            '4.8.32.rc.000'
2401
-        );
2402
-        return '
2381
+	}
2382
+
2383
+
2384
+	/**
2385
+	 * form_after_question_group
2386
+	 *
2387
+	 * @deprecated    as of 4.8.32.rc.000
2388
+	 * @access        public
2389
+	 * @param        string $output
2390
+	 * @return        string
2391
+	 */
2392
+	public function form_after_question_group($output)
2393
+	{
2394
+		EE_Error::doing_it_wrong(
2395
+			__CLASS__ . '::' . __FUNCTION__,
2396
+			esc_html__(
2397
+				'This method would have been protected but was used on a filter callback so needed to be public. Please discontinue usage as it will be removed soon.',
2398
+				'event_espresso'
2399
+			),
2400
+			'4.8.32.rc.000'
2401
+		);
2402
+		return '
2403 2403
 			<tr class="hide-if-no-js">
2404 2404
 				<th> </th>
2405 2405
 				<td class="reg-admin-edit-attendee-question-td">
2406 2406
 					<a class="reg-admin-edit-attendee-question-lnk" href="#" title="'
2407
-               . esc_attr__('click to edit question', 'event_espresso')
2408
-               . '">
2407
+			   . esc_attr__('click to edit question', 'event_espresso')
2408
+			   . '">
2409 2409
 						<span class="reg-admin-edit-question-group-spn lt-grey-txt">'
2410
-               . esc_html__('edit the above question group', 'event_espresso')
2411
-               . '</span>
2410
+			   . esc_html__('edit the above question group', 'event_espresso')
2411
+			   . '</span>
2412 2412
 						<div class="dashicons dashicons-edit"></div>
2413 2413
 					</a>
2414 2414
 				</td>
@@ -2416,609 +2416,609 @@  discard block
 block discarded – undo
2416 2416
 		</tbody>
2417 2417
 	</table>
2418 2418
 ';
2419
-    }
2420
-
2421
-
2422
-    /**
2423
-     * form_form_field_label_wrap
2424
-     *
2425
-     * @deprecated    as of 4.8.32.rc.000
2426
-     * @access        public
2427
-     * @param        string $label
2428
-     * @return        string
2429
-     */
2430
-    public function form_form_field_label_wrap($label)
2431
-    {
2432
-        EE_Error::doing_it_wrong(
2433
-            __CLASS__ . '::' . __FUNCTION__,
2434
-            esc_html__(
2435
-                'This method would have been protected but was used on a filter callback so needed to be public. Please discontinue usage as it will be removed soon.',
2436
-                'event_espresso'
2437
-            ),
2438
-            '4.8.32.rc.000'
2439
-        );
2440
-        return '
2419
+	}
2420
+
2421
+
2422
+	/**
2423
+	 * form_form_field_label_wrap
2424
+	 *
2425
+	 * @deprecated    as of 4.8.32.rc.000
2426
+	 * @access        public
2427
+	 * @param        string $label
2428
+	 * @return        string
2429
+	 */
2430
+	public function form_form_field_label_wrap($label)
2431
+	{
2432
+		EE_Error::doing_it_wrong(
2433
+			__CLASS__ . '::' . __FUNCTION__,
2434
+			esc_html__(
2435
+				'This method would have been protected but was used on a filter callback so needed to be public. Please discontinue usage as it will be removed soon.',
2436
+				'event_espresso'
2437
+			),
2438
+			'4.8.32.rc.000'
2439
+		);
2440
+		return '
2441 2441
 			<tr>
2442 2442
 				<th>
2443 2443
 					' . $label . '
2444 2444
 				</th>';
2445
-    }
2446
-
2447
-
2448
-    /**
2449
-     * form_form_field_input__wrap
2450
-     *
2451
-     * @deprecated    as of 4.8.32.rc.000
2452
-     * @access        public
2453
-     * @param        string $input
2454
-     * @return        string
2455
-     */
2456
-    public function form_form_field_input__wrap($input)
2457
-    {
2458
-        EE_Error::doing_it_wrong(
2459
-            __CLASS__ . '::' . __FUNCTION__,
2460
-            esc_html__(
2461
-                'This method would have been protected but was used on a filter callback so needed to be public. Please discontinue usage as it will be removed soon.',
2462
-                'event_espresso'
2463
-            ),
2464
-            '4.8.32.rc.000'
2465
-        );
2466
-        return '
2445
+	}
2446
+
2447
+
2448
+	/**
2449
+	 * form_form_field_input__wrap
2450
+	 *
2451
+	 * @deprecated    as of 4.8.32.rc.000
2452
+	 * @access        public
2453
+	 * @param        string $input
2454
+	 * @return        string
2455
+	 */
2456
+	public function form_form_field_input__wrap($input)
2457
+	{
2458
+		EE_Error::doing_it_wrong(
2459
+			__CLASS__ . '::' . __FUNCTION__,
2460
+			esc_html__(
2461
+				'This method would have been protected but was used on a filter callback so needed to be public. Please discontinue usage as it will be removed soon.',
2462
+				'event_espresso'
2463
+			),
2464
+			'4.8.32.rc.000'
2465
+		);
2466
+		return '
2467 2467
 				<td class="reg-admin-attendee-questions-input-td disabled-input">
2468 2468
 					' . $input . '
2469 2469
 				</td>
2470 2470
 			</tr>';
2471
-    }
2472
-
2473
-
2474
-    /**
2475
-     * Updates the registration's custom questions according to the form info, if the form is submitted.
2476
-     * If it's not a post, the "view_registrations" route will be called next on the SAME request
2477
-     * to display the page
2478
-     *
2479
-     * @access protected
2480
-     * @return void
2481
-     * @throws EE_Error
2482
-     */
2483
-    protected function _update_attendee_registration_form()
2484
-    {
2485
-        do_action('AHEE__Registrations_Admin_Page___update_attendee_registration_form__start', $this);
2486
-        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
2487
-            $REG_ID = isset($this->_req_data['_REG_ID']) ? absint($this->_req_data['_REG_ID']) : false;
2488
-            $success = $this->_save_reg_custom_questions_form($REG_ID);
2489
-            if ($success) {
2490
-                $what = esc_html__('Registration Form', 'event_espresso');
2491
-                $route = $REG_ID ? array('action' => 'view_registration', '_REG_ID' => $REG_ID)
2492
-                    : array('action' => 'default');
2493
-                $this->_redirect_after_action($success, $what, esc_html__('updated', 'event_espresso'), $route);
2494
-            }
2495
-        }
2496
-    }
2497
-
2498
-
2499
-    /**
2500
-     * Gets the form for saving registrations custom questions (if done
2501
-     * previously retrieves the cached form object, which may have validation errors in it)
2502
-     *
2503
-     * @param int $REG_ID
2504
-     * @return EE_Registration_Custom_Questions_Form
2505
-     * @throws EE_Error
2506
-     * @throws InvalidArgumentException
2507
-     * @throws InvalidDataTypeException
2508
-     * @throws InvalidInterfaceException
2509
-     */
2510
-    protected function _get_reg_custom_questions_form($REG_ID)
2511
-    {
2512
-        if (! $this->_reg_custom_questions_form) {
2513
-            require_once(REG_ADMIN . 'form_sections' . DS . 'EE_Registration_Custom_Questions_Form.form.php');
2514
-            $this->_reg_custom_questions_form = new EE_Registration_Custom_Questions_Form(
2515
-                EEM_Registration::instance()->get_one_by_ID($REG_ID)
2516
-            );
2517
-            $this->_reg_custom_questions_form->_construct_finalize(null, null);
2518
-        }
2519
-        return $this->_reg_custom_questions_form;
2520
-    }
2521
-
2522
-
2523
-    /**
2524
-     * Saves
2525
-     *
2526
-     * @access private
2527
-     * @param bool $REG_ID
2528
-     * @return bool
2529
-     * @throws EE_Error
2530
-     * @throws InvalidArgumentException
2531
-     * @throws InvalidDataTypeException
2532
-     * @throws InvalidInterfaceException
2533
-     */
2534
-    private function _save_reg_custom_questions_form($REG_ID = false)
2535
-    {
2536
-        if (! $REG_ID) {
2537
-            EE_Error::add_error(
2538
-                esc_html__(
2539
-                    'An error occurred. No registration ID was received.',
2540
-                    'event_espresso'
2541
-                ),
2542
-                __FILE__,
2543
-                __FUNCTION__,
2544
-                __LINE__
2545
-            );
2546
-        }
2547
-        $form = $this->_get_reg_custom_questions_form($REG_ID);
2548
-        $form->receive_form_submission($this->_req_data);
2549
-        $success = false;
2550
-        if ($form->is_valid()) {
2551
-            foreach ($form->subforms() as $question_group_id => $question_group_form) {
2552
-                foreach ($question_group_form->inputs() as $question_id => $input) {
2553
-                    $where_conditions = array(
2554
-                        'QST_ID' => $question_id,
2555
-                        'REG_ID' => $REG_ID,
2556
-                    );
2557
-                    $possibly_new_values = array(
2558
-                        'ANS_value' => $input->normalized_value(),
2559
-                    );
2560
-                    $answer = EEM_Answer::instance()->get_one(array($where_conditions));
2561
-                    if ($answer instanceof EE_Answer) {
2562
-                        $success = $answer->save($possibly_new_values);
2563
-                    } else {
2564
-                        // insert it then
2565
-                        $cols_n_vals = array_merge($where_conditions, $possibly_new_values);
2566
-                        $answer = EE_Answer::new_instance($cols_n_vals);
2567
-                        $success = $answer->save();
2568
-                    }
2569
-                }
2570
-            }
2571
-        } else {
2572
-            EE_Error::add_error($form->get_validation_error_string(), __FILE__, __FUNCTION__, __LINE__);
2573
-        }
2574
-        return $success;
2575
-    }
2576
-
2577
-
2578
-    /**
2579
-     *        generates HTML for the Registration main meta box
2580
-     *
2581
-     * @access public
2582
-     * @return void
2583
-     * @throws DomainException
2584
-     * @throws EE_Error
2585
-     * @throws InvalidArgumentException
2586
-     * @throws InvalidDataTypeException
2587
-     * @throws InvalidInterfaceException
2588
-     */
2589
-    public function _reg_attendees_meta_box()
2590
-    {
2591
-        $REG = EEM_Registration::instance();
2592
-        // get all other registrations on this transaction, and cache
2593
-        // the attendees for them so we don't have to run another query using force_join
2594
-        $registrations = $REG->get_all(
2595
-            array(
2596
-                array(
2597
-                    'TXN_ID' => $this->_registration->transaction_ID(),
2598
-                    'REG_ID' => array('!=', $this->_registration->ID()),
2599
-                ),
2600
-                'force_join' => array('Attendee'),
2601
-                'default_where_conditions' => 'other_models_only',
2602
-            )
2603
-        );
2604
-        $this->_template_args['attendees'] = array();
2605
-        $this->_template_args['attendee_notice'] = '';
2606
-        if (empty($registrations)
2607
-            || (is_array($registrations)
2608
-                && ! EEH_Array::get_one_item_from_array($registrations))
2609
-        ) {
2610
-            EE_Error::add_error(
2611
-                esc_html__(
2612
-                    'There are no records attached to this registration. Something may have gone wrong with the registration',
2613
-                    'event_espresso'
2614
-                ),
2615
-                __FILE__,
2616
-                __FUNCTION__,
2617
-                __LINE__
2618
-            );
2619
-            $this->_template_args['attendee_notice'] = EE_Error::get_notices();
2620
-        } else {
2621
-            $att_nmbr = 1;
2622
-            foreach ($registrations as $registration) {
2623
-                /* @var $registration EE_Registration */
2624
-                $attendee = $registration->attendee()
2625
-                    ? $registration->attendee()
2626
-                    : EEM_Attendee::instance()
2627
-                                  ->create_default_object();
2628
-                $this->_template_args['attendees'][ $att_nmbr ]['STS_ID'] = $registration->status_ID();
2629
-                $this->_template_args['attendees'][ $att_nmbr ]['fname'] = $attendee->fname();
2630
-                $this->_template_args['attendees'][ $att_nmbr ]['lname'] = $attendee->lname();
2631
-                $this->_template_args['attendees'][ $att_nmbr ]['email'] = $attendee->email();
2632
-                $this->_template_args['attendees'][ $att_nmbr ]['final_price'] = $registration->final_price();
2633
-                $this->_template_args['attendees'][ $att_nmbr ]['address'] = implode(
2634
-                    ', ',
2635
-                    $attendee->full_address_as_array()
2636
-                );
2637
-                $this->_template_args['attendees'][ $att_nmbr ]['att_link'] = self::add_query_args_and_nonce(
2638
-                    array(
2639
-                        'action' => 'edit_attendee',
2640
-                        'post'   => $attendee->ID(),
2641
-                    ),
2642
-                    REG_ADMIN_URL
2643
-                );
2644
-                $this->_template_args['attendees'][ $att_nmbr ]['event_name'] = $registration->event_obj() instanceof EE_Event
2645
-                    ? $registration->event_obj()->name()
2646
-                    : '';
2647
-                $att_nmbr++;
2648
-            }
2649
-            $this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
2650
-        }
2651
-        $template_path = REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_attendees.template.php';
2652
-        echo EEH_Template::display_template($template_path, $this->_template_args, true);
2653
-    }
2654
-
2655
-
2656
-    /**
2657
-     *        generates HTML for the Edit Registration side meta box
2658
-     *
2659
-     * @access public
2660
-     * @return void
2661
-     * @throws DomainException
2662
-     * @throws EE_Error
2663
-     * @throws InvalidArgumentException
2664
-     * @throws InvalidDataTypeException
2665
-     * @throws InvalidInterfaceException
2666
-     */
2667
-    public function _reg_registrant_side_meta_box()
2668
-    {
2669
-        /*@var $attendee EE_Attendee */
2670
-        $att_check = $this->_registration->attendee();
2671
-        $attendee = $att_check instanceof EE_Attendee ? $att_check : EEM_Attendee::instance()->create_default_object();
2672
-        // now let's determine if this is not the primary registration.  If it isn't then we set the
2673
-        // primary_registration object for reference BUT ONLY if the Attendee object loaded is not the same as the
2674
-        // primary registration object (that way we know if we need to show create button or not)
2675
-        if (! $this->_registration->is_primary_registrant()) {
2676
-            $primary_registration = $this->_registration->get_primary_registration();
2677
-            $primary_attendee = $primary_registration instanceof EE_Registration ? $primary_registration->attendee()
2678
-                : null;
2679
-            if (! $primary_attendee instanceof EE_Attendee || $attendee->ID() !== $primary_attendee->ID()) {
2680
-                // in here?  This means the displayed registration is not the primary registrant but ALREADY HAS its own
2681
-                // custom attendee object so let's not worry about the primary reg.
2682
-                $primary_registration = null;
2683
-            }
2684
-        } else {
2685
-            $primary_registration = null;
2686
-        }
2687
-        $this->_template_args['ATT_ID'] = $attendee->ID();
2688
-        $this->_template_args['fname'] = $attendee->fname();
2689
-        $this->_template_args['lname'] = $attendee->lname();
2690
-        $this->_template_args['email'] = $attendee->email();
2691
-        $this->_template_args['phone'] = $attendee->phone();
2692
-        $this->_template_args['formatted_address'] = EEH_Address::format($attendee);
2693
-        // edit link
2694
-        $this->_template_args['att_edit_link'] = EE_Admin_Page::add_query_args_and_nonce(
2695
-            array(
2696
-                'action' => 'edit_attendee',
2697
-                'post'   => $attendee->ID(),
2698
-            ),
2699
-            REG_ADMIN_URL
2700
-        );
2701
-        $this->_template_args['att_edit_label'] = esc_html__('View/Edit Contact', 'event_espresso');
2702
-        // create link
2703
-        $this->_template_args['create_link'] = $primary_registration instanceof EE_Registration
2704
-            ? EE_Admin_Page::add_query_args_and_nonce(
2705
-                array(
2706
-                    'action'  => 'duplicate_attendee',
2707
-                    '_REG_ID' => $this->_registration->ID(),
2708
-                ),
2709
-                REG_ADMIN_URL
2710
-            ) : '';
2711
-        $this->_template_args['create_label'] = esc_html__('Create Contact', 'event_espresso');
2712
-        $this->_template_args['att_check'] = $att_check;
2713
-        $template_path = REG_TEMPLATE_PATH . 'reg_admin_details_side_meta_box_registrant.template.php';
2714
-        echo EEH_Template::display_template($template_path, $this->_template_args, true);
2715
-    }
2716
-
2717
-
2718
-    /**
2719
-     * trash or restore registrations
2720
-     *
2721
-     * @param  boolean $trash whether to archive or restore
2722
-     * @return void
2723
-     * @throws EE_Error
2724
-     * @throws InvalidArgumentException
2725
-     * @throws InvalidDataTypeException
2726
-     * @throws InvalidInterfaceException
2727
-     * @throws RuntimeException
2728
-     * @access protected
2729
-     */
2730
-    protected function _trash_or_restore_registrations($trash = true)
2731
-    {
2732
-        // if empty _REG_ID then get out because there's nothing to do
2733
-        if (empty($this->_req_data['_REG_ID'])) {
2734
-            EE_Error::add_error(
2735
-                sprintf(
2736
-                    esc_html__(
2737
-                        'In order to %1$s registrations you must select which ones you wish to %1$s by clicking the checkboxes.',
2738
-                        'event_espresso'
2739
-                    ),
2740
-                    $trash ? 'trash' : 'restore'
2741
-                ),
2742
-                __FILE__,
2743
-                __LINE__,
2744
-                __FUNCTION__
2745
-            );
2746
-            $this->_redirect_after_action(false, '', '', array(), true);
2747
-        }
2748
-        $success = 0;
2749
-        $overwrite_msgs = false;
2750
-        // Checkboxes
2751
-        if (! is_array($this->_req_data['_REG_ID'])) {
2752
-            $this->_req_data['_REG_ID'] = array($this->_req_data['_REG_ID']);
2753
-        }
2754
-        $reg_count = count($this->_req_data['_REG_ID']);
2755
-        // cycle thru checkboxes
2756
-        foreach ($this->_req_data['_REG_ID'] as $REG_ID) {
2757
-            /** @var EE_Registration $REG */
2758
-            $REG = EEM_Registration::instance()->get_one_by_ID($REG_ID);
2759
-            $payments = $REG->registration_payments();
2760
-            if (! empty($payments)) {
2761
-                $name = $REG->attendee() instanceof EE_Attendee
2762
-                    ? $REG->attendee()->full_name()
2763
-                    : esc_html__('Unknown Attendee', 'event_espresso');
2764
-                $overwrite_msgs = true;
2765
-                EE_Error::add_error(
2766
-                    sprintf(
2767
-                        esc_html__(
2768
-                            'The registration for %s could not be trashed because it has payments attached to the related transaction.  If you wish to trash this registration you must first delete the payments on the related transaction.',
2769
-                            'event_espresso'
2770
-                        ),
2771
-                        $name
2772
-                    ),
2773
-                    __FILE__,
2774
-                    __FUNCTION__,
2775
-                    __LINE__
2776
-                );
2777
-                // can't trash this registration because it has payments.
2778
-                continue;
2779
-            }
2780
-            $updated = $trash ? $REG->delete() : $REG->restore();
2781
-            if ($updated) {
2782
-                $success++;
2783
-            }
2784
-        }
2785
-        $this->_redirect_after_action(
2786
-            $success === $reg_count, // were ALL registrations affected?
2787
-            $success > 1
2788
-                ? esc_html__('Registrations', 'event_espresso')
2789
-                : esc_html__('Registration', 'event_espresso'),
2790
-            $trash
2791
-                ? esc_html__('moved to the trash', 'event_espresso')
2792
-                : esc_html__('restored', 'event_espresso'),
2793
-            $this->mergeExistingRequestParamsWithRedirectArgs(array('action' => 'default')),
2794
-            $overwrite_msgs
2795
-        );
2796
-    }
2797
-
2798
-
2799
-    /**
2800
-     * This is used to permanently delete registrations.  Note, this will handle not only deleting permanently the
2801
-     * registration but also.
2802
-     * 1. Removing relations to EE_Attendee
2803
-     * 2. Deleting permanently the related transaction, but ONLY if all related registrations to the transaction are
2804
-     * ALSO trashed.
2805
-     * 3. Deleting permanently any related Line items but only if the above conditions are met.
2806
-     * 4. Removing relationships between all tickets and the related registrations
2807
-     * 5. Deleting permanently any related Answers (and the answers for other related registrations that were deleted.)
2808
-     * 6. Deleting permanently any related Checkins.
2809
-     *
2810
-     * @return void
2811
-     * @throws EE_Error
2812
-     * @throws InvalidArgumentException
2813
-     * @throws InvalidDataTypeException
2814
-     * @throws InvalidInterfaceException
2815
-     */
2816
-    protected function _delete_registrations()
2817
-    {
2818
-        $REG_MDL = EEM_Registration::instance();
2819
-        $success = 1;
2820
-        // Checkboxes
2821
-        if (! empty($this->_req_data['_REG_ID']) && is_array($this->_req_data['_REG_ID'])) {
2822
-            // if array has more than one element than success message should be plural
2823
-            $success = count($this->_req_data['_REG_ID']) > 1 ? 2 : 1;
2824
-            // cycle thru checkboxes
2825
-            while (list($ind, $REG_ID) = each($this->_req_data['_REG_ID'])) {
2826
-                $REG = $REG_MDL->get_one_by_ID($REG_ID);
2827
-                if (! $REG instanceof EE_Registration) {
2828
-                    continue;
2829
-                }
2830
-                $deleted = $this->_delete_registration($REG);
2831
-                if (! $deleted) {
2832
-                    $success = 0;
2833
-                }
2834
-            }
2835
-        } else {
2836
-            // grab single id and delete
2837
-            $REG_ID = $this->_req_data['_REG_ID'];
2838
-            $REG = $REG_MDL->get_one_by_ID($REG_ID);
2839
-            $deleted = $this->_delete_registration($REG);
2840
-            if (! $deleted) {
2841
-                $success = 0;
2842
-            }
2843
-        }
2844
-        $what = $success > 1
2845
-            ? esc_html__('Registrations', 'event_espresso')
2846
-            : esc_html__('Registration', 'event_espresso');
2847
-        $action_desc = esc_html__('permanently deleted.', 'event_espresso');
2848
-        $this->_redirect_after_action(
2849
-            $success,
2850
-            $what,
2851
-            $action_desc,
2852
-            $this->mergeExistingRequestParamsWithRedirectArgs(['action' => 'default']),
2853
-            true
2854
-        );
2855
-    }
2856
-
2857
-
2858
-    /**
2859
-     * handles the permanent deletion of a registration.  See comments with _delete_registrations() for details on what
2860
-     * models get affected.
2861
-     *
2862
-     * @param  EE_Registration $REG registration to be deleted permenantly
2863
-     * @return bool true = successful deletion, false = fail.
2864
-     * @throws EE_Error
2865
-     */
2866
-    protected function _delete_registration(EE_Registration $REG)
2867
-    {
2868
-        // first we start with the transaction... ultimately, we WILL not delete permanently if there are any related
2869
-        // registrations on the transaction that are NOT trashed.
2870
-        $TXN = $REG->get_first_related('Transaction');
2871
-        $REGS = $TXN->get_many_related('Registration');
2872
-        $all_trashed = true;
2873
-        foreach ($REGS as $registration) {
2874
-            if (! $registration->get('REG_deleted')) {
2875
-                $all_trashed = false;
2876
-            }
2877
-        }
2878
-        if (! $all_trashed) {
2879
-            EE_Error::add_error(
2880
-                esc_html__(
2881
-                    'Unable to permanently delete this registration. Before this registration can be permanently deleted, all registrations made in the same transaction must be trashed as well.  These registrations will be permanently deleted in the same action.',
2882
-                    'event_espresso'
2883
-                ),
2884
-                __FILE__,
2885
-                __FUNCTION__,
2886
-                __LINE__
2887
-            );
2888
-            return false;
2889
-        }
2890
-        // k made it here so that means we can delete all the related transactions and their answers (but let's do them
2891
-        // separately from THIS one).
2892
-        foreach ($REGS as $registration) {
2893
-            // delete related answers
2894
-            $registration->delete_related_permanently('Answer');
2895
-            // remove relationship to EE_Attendee (but we ALWAYS leave the contact record intact)
2896
-            $attendee = $registration->get_first_related('Attendee');
2897
-            if ($attendee instanceof EE_Attendee) {
2898
-                $registration->_remove_relation_to($attendee, 'Attendee');
2899
-            }
2900
-            // now remove relationships to tickets on this registration.
2901
-            $registration->_remove_relations('Ticket');
2902
-            // now delete permanently the checkins related to this registration.
2903
-            $registration->delete_related_permanently('Checkin');
2904
-            if ($registration->ID() === $REG->ID()) {
2905
-                continue;
2906
-            } //we don't want to delete permanently the existing registration just yet.
2907
-            // remove relation to transaction for these registrations if NOT the existing registrations
2908
-            $registration->_remove_relations('Transaction');
2909
-            // delete permanently any related messages.
2910
-            $registration->delete_related_permanently('Message');
2911
-            // now delete this registration permanently
2912
-            $registration->delete_permanently();
2913
-        }
2914
-        // now all related registrations on the transaction are handled.  So let's just handle this registration itself
2915
-        // (the transaction and line items should be all that's left).
2916
-        // delete the line items related to the transaction for this registration.
2917
-        $TXN->delete_related_permanently('Line_Item');
2918
-        // we need to remove all the relationships on the transaction
2919
-        $TXN->delete_related_permanently('Payment');
2920
-        $TXN->delete_related_permanently('Extra_Meta');
2921
-        $TXN->delete_related_permanently('Message');
2922
-        // now we can delete this REG permanently (and the transaction of course)
2923
-        $REG->delete_related_permanently('Transaction');
2924
-        return $REG->delete_permanently();
2925
-    }
2926
-
2927
-
2928
-    /**
2929
-     *    generates HTML for the Register New Attendee Admin page
2930
-     *
2931
-     * @access private
2932
-     * @throws DomainException
2933
-     * @throws EE_Error
2934
-     */
2935
-    public function new_registration()
2936
-    {
2937
-        if (! $this->_set_reg_event()) {
2938
-            throw new EE_Error(
2939
-                esc_html__(
2940
-                    'Unable to continue with registering because there is no Event ID in the request',
2941
-                    'event_espresso'
2942
-                )
2943
-            );
2944
-        }
2945
-        EE_Registry::instance()->REQ->set_espresso_page(true);
2946
-        // gotta start with a clean slate if we're not coming here via ajax
2947
-        if (! defined('DOING_AJAX')
2948
-            && (! isset($this->_req_data['processing_registration']) || isset($this->_req_data['step_error']))
2949
-        ) {
2950
-            EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
2951
-        }
2952
-        $this->_template_args['event_name'] = '';
2953
-        // event name
2954
-        if ($this->_reg_event) {
2955
-            $this->_template_args['event_name'] = $this->_reg_event->name();
2956
-            $edit_event_url = self::add_query_args_and_nonce(
2957
-                array(
2958
-                    'action' => 'edit',
2959
-                    'post'   => $this->_reg_event->ID(),
2960
-                ),
2961
-                EVENTS_ADMIN_URL
2962
-            );
2963
-            $edit_event_lnk = '<a href="'
2964
-                              . $edit_event_url
2965
-                              . '" title="'
2966
-                              . esc_attr__('Edit ', 'event_espresso')
2967
-                              . $this->_reg_event->name()
2968
-                              . '">'
2969
-                              . esc_html__('Edit Event', 'event_espresso')
2970
-                              . '</a>';
2971
-            $this->_template_args['event_name'] .= ' <span class="admin-page-header-edit-lnk not-bold">'
2972
-                                                   . $edit_event_lnk
2973
-                                                   . '</span>';
2974
-        }
2975
-        $this->_template_args['step_content'] = $this->_get_registration_step_content();
2976
-        if (defined('DOING_AJAX')) {
2977
-            $this->_return_json();
2978
-        }
2979
-        // grab header
2980
-        $template_path =
2981
-            REG_TEMPLATE_PATH . 'reg_admin_register_new_attendee.template.php';
2982
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
2983
-            $template_path,
2984
-            $this->_template_args,
2985
-            true
2986
-        );
2987
-        // $this->_set_publish_post_box_vars( NULL, FALSE, FALSE, NULL, FALSE );
2988
-        // the details template wrapper
2989
-        $this->display_admin_page_with_sidebar();
2990
-    }
2991
-
2992
-
2993
-    /**
2994
-     * This returns the content for a registration step
2995
-     *
2996
-     * @access protected
2997
-     * @return string html
2998
-     * @throws DomainException
2999
-     * @throws EE_Error
3000
-     * @throws InvalidArgumentException
3001
-     * @throws InvalidDataTypeException
3002
-     * @throws InvalidInterfaceException
3003
-     */
3004
-    protected function _get_registration_step_content()
3005
-    {
3006
-        if (isset($_COOKIE['ee_registration_added']) && $_COOKIE['ee_registration_added']) {
3007
-            $warning_msg = sprintf(
3008
-                esc_html__(
3009
-                    '%2$sWARNING!!!%3$s%1$sPlease do not use the back button to return to this page for the purpose of adding another registration.%1$sThis can result in lost and/or corrupted data.%1$sIf you wish to add another registration, then please click the%1$s%7$s"Add Another New Registration to Event"%8$s button%1$son the Transaction details page, after you are redirected.%1$s%1$s%4$s redirecting in %5$s seconds %6$s',
3010
-                    'event_espresso'
3011
-                ),
3012
-                '<br />',
3013
-                '<h3 class="important-notice">',
3014
-                '</h3>',
3015
-                '<div class="float-right">',
3016
-                '<span id="redirect_timer" class="important-notice">30</span>',
3017
-                '</div>',
3018
-                '<b>',
3019
-                '</b>'
3020
-            );
3021
-            return '
2471
+	}
2472
+
2473
+
2474
+	/**
2475
+	 * Updates the registration's custom questions according to the form info, if the form is submitted.
2476
+	 * If it's not a post, the "view_registrations" route will be called next on the SAME request
2477
+	 * to display the page
2478
+	 *
2479
+	 * @access protected
2480
+	 * @return void
2481
+	 * @throws EE_Error
2482
+	 */
2483
+	protected function _update_attendee_registration_form()
2484
+	{
2485
+		do_action('AHEE__Registrations_Admin_Page___update_attendee_registration_form__start', $this);
2486
+		if ($_SERVER['REQUEST_METHOD'] == 'POST') {
2487
+			$REG_ID = isset($this->_req_data['_REG_ID']) ? absint($this->_req_data['_REG_ID']) : false;
2488
+			$success = $this->_save_reg_custom_questions_form($REG_ID);
2489
+			if ($success) {
2490
+				$what = esc_html__('Registration Form', 'event_espresso');
2491
+				$route = $REG_ID ? array('action' => 'view_registration', '_REG_ID' => $REG_ID)
2492
+					: array('action' => 'default');
2493
+				$this->_redirect_after_action($success, $what, esc_html__('updated', 'event_espresso'), $route);
2494
+			}
2495
+		}
2496
+	}
2497
+
2498
+
2499
+	/**
2500
+	 * Gets the form for saving registrations custom questions (if done
2501
+	 * previously retrieves the cached form object, which may have validation errors in it)
2502
+	 *
2503
+	 * @param int $REG_ID
2504
+	 * @return EE_Registration_Custom_Questions_Form
2505
+	 * @throws EE_Error
2506
+	 * @throws InvalidArgumentException
2507
+	 * @throws InvalidDataTypeException
2508
+	 * @throws InvalidInterfaceException
2509
+	 */
2510
+	protected function _get_reg_custom_questions_form($REG_ID)
2511
+	{
2512
+		if (! $this->_reg_custom_questions_form) {
2513
+			require_once(REG_ADMIN . 'form_sections' . DS . 'EE_Registration_Custom_Questions_Form.form.php');
2514
+			$this->_reg_custom_questions_form = new EE_Registration_Custom_Questions_Form(
2515
+				EEM_Registration::instance()->get_one_by_ID($REG_ID)
2516
+			);
2517
+			$this->_reg_custom_questions_form->_construct_finalize(null, null);
2518
+		}
2519
+		return $this->_reg_custom_questions_form;
2520
+	}
2521
+
2522
+
2523
+	/**
2524
+	 * Saves
2525
+	 *
2526
+	 * @access private
2527
+	 * @param bool $REG_ID
2528
+	 * @return bool
2529
+	 * @throws EE_Error
2530
+	 * @throws InvalidArgumentException
2531
+	 * @throws InvalidDataTypeException
2532
+	 * @throws InvalidInterfaceException
2533
+	 */
2534
+	private function _save_reg_custom_questions_form($REG_ID = false)
2535
+	{
2536
+		if (! $REG_ID) {
2537
+			EE_Error::add_error(
2538
+				esc_html__(
2539
+					'An error occurred. No registration ID was received.',
2540
+					'event_espresso'
2541
+				),
2542
+				__FILE__,
2543
+				__FUNCTION__,
2544
+				__LINE__
2545
+			);
2546
+		}
2547
+		$form = $this->_get_reg_custom_questions_form($REG_ID);
2548
+		$form->receive_form_submission($this->_req_data);
2549
+		$success = false;
2550
+		if ($form->is_valid()) {
2551
+			foreach ($form->subforms() as $question_group_id => $question_group_form) {
2552
+				foreach ($question_group_form->inputs() as $question_id => $input) {
2553
+					$where_conditions = array(
2554
+						'QST_ID' => $question_id,
2555
+						'REG_ID' => $REG_ID,
2556
+					);
2557
+					$possibly_new_values = array(
2558
+						'ANS_value' => $input->normalized_value(),
2559
+					);
2560
+					$answer = EEM_Answer::instance()->get_one(array($where_conditions));
2561
+					if ($answer instanceof EE_Answer) {
2562
+						$success = $answer->save($possibly_new_values);
2563
+					} else {
2564
+						// insert it then
2565
+						$cols_n_vals = array_merge($where_conditions, $possibly_new_values);
2566
+						$answer = EE_Answer::new_instance($cols_n_vals);
2567
+						$success = $answer->save();
2568
+					}
2569
+				}
2570
+			}
2571
+		} else {
2572
+			EE_Error::add_error($form->get_validation_error_string(), __FILE__, __FUNCTION__, __LINE__);
2573
+		}
2574
+		return $success;
2575
+	}
2576
+
2577
+
2578
+	/**
2579
+	 *        generates HTML for the Registration main meta box
2580
+	 *
2581
+	 * @access public
2582
+	 * @return void
2583
+	 * @throws DomainException
2584
+	 * @throws EE_Error
2585
+	 * @throws InvalidArgumentException
2586
+	 * @throws InvalidDataTypeException
2587
+	 * @throws InvalidInterfaceException
2588
+	 */
2589
+	public function _reg_attendees_meta_box()
2590
+	{
2591
+		$REG = EEM_Registration::instance();
2592
+		// get all other registrations on this transaction, and cache
2593
+		// the attendees for them so we don't have to run another query using force_join
2594
+		$registrations = $REG->get_all(
2595
+			array(
2596
+				array(
2597
+					'TXN_ID' => $this->_registration->transaction_ID(),
2598
+					'REG_ID' => array('!=', $this->_registration->ID()),
2599
+				),
2600
+				'force_join' => array('Attendee'),
2601
+				'default_where_conditions' => 'other_models_only',
2602
+			)
2603
+		);
2604
+		$this->_template_args['attendees'] = array();
2605
+		$this->_template_args['attendee_notice'] = '';
2606
+		if (empty($registrations)
2607
+			|| (is_array($registrations)
2608
+				&& ! EEH_Array::get_one_item_from_array($registrations))
2609
+		) {
2610
+			EE_Error::add_error(
2611
+				esc_html__(
2612
+					'There are no records attached to this registration. Something may have gone wrong with the registration',
2613
+					'event_espresso'
2614
+				),
2615
+				__FILE__,
2616
+				__FUNCTION__,
2617
+				__LINE__
2618
+			);
2619
+			$this->_template_args['attendee_notice'] = EE_Error::get_notices();
2620
+		} else {
2621
+			$att_nmbr = 1;
2622
+			foreach ($registrations as $registration) {
2623
+				/* @var $registration EE_Registration */
2624
+				$attendee = $registration->attendee()
2625
+					? $registration->attendee()
2626
+					: EEM_Attendee::instance()
2627
+								  ->create_default_object();
2628
+				$this->_template_args['attendees'][ $att_nmbr ]['STS_ID'] = $registration->status_ID();
2629
+				$this->_template_args['attendees'][ $att_nmbr ]['fname'] = $attendee->fname();
2630
+				$this->_template_args['attendees'][ $att_nmbr ]['lname'] = $attendee->lname();
2631
+				$this->_template_args['attendees'][ $att_nmbr ]['email'] = $attendee->email();
2632
+				$this->_template_args['attendees'][ $att_nmbr ]['final_price'] = $registration->final_price();
2633
+				$this->_template_args['attendees'][ $att_nmbr ]['address'] = implode(
2634
+					', ',
2635
+					$attendee->full_address_as_array()
2636
+				);
2637
+				$this->_template_args['attendees'][ $att_nmbr ]['att_link'] = self::add_query_args_and_nonce(
2638
+					array(
2639
+						'action' => 'edit_attendee',
2640
+						'post'   => $attendee->ID(),
2641
+					),
2642
+					REG_ADMIN_URL
2643
+				);
2644
+				$this->_template_args['attendees'][ $att_nmbr ]['event_name'] = $registration->event_obj() instanceof EE_Event
2645
+					? $registration->event_obj()->name()
2646
+					: '';
2647
+				$att_nmbr++;
2648
+			}
2649
+			$this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
2650
+		}
2651
+		$template_path = REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_attendees.template.php';
2652
+		echo EEH_Template::display_template($template_path, $this->_template_args, true);
2653
+	}
2654
+
2655
+
2656
+	/**
2657
+	 *        generates HTML for the Edit Registration side meta box
2658
+	 *
2659
+	 * @access public
2660
+	 * @return void
2661
+	 * @throws DomainException
2662
+	 * @throws EE_Error
2663
+	 * @throws InvalidArgumentException
2664
+	 * @throws InvalidDataTypeException
2665
+	 * @throws InvalidInterfaceException
2666
+	 */
2667
+	public function _reg_registrant_side_meta_box()
2668
+	{
2669
+		/*@var $attendee EE_Attendee */
2670
+		$att_check = $this->_registration->attendee();
2671
+		$attendee = $att_check instanceof EE_Attendee ? $att_check : EEM_Attendee::instance()->create_default_object();
2672
+		// now let's determine if this is not the primary registration.  If it isn't then we set the
2673
+		// primary_registration object for reference BUT ONLY if the Attendee object loaded is not the same as the
2674
+		// primary registration object (that way we know if we need to show create button or not)
2675
+		if (! $this->_registration->is_primary_registrant()) {
2676
+			$primary_registration = $this->_registration->get_primary_registration();
2677
+			$primary_attendee = $primary_registration instanceof EE_Registration ? $primary_registration->attendee()
2678
+				: null;
2679
+			if (! $primary_attendee instanceof EE_Attendee || $attendee->ID() !== $primary_attendee->ID()) {
2680
+				// in here?  This means the displayed registration is not the primary registrant but ALREADY HAS its own
2681
+				// custom attendee object so let's not worry about the primary reg.
2682
+				$primary_registration = null;
2683
+			}
2684
+		} else {
2685
+			$primary_registration = null;
2686
+		}
2687
+		$this->_template_args['ATT_ID'] = $attendee->ID();
2688
+		$this->_template_args['fname'] = $attendee->fname();
2689
+		$this->_template_args['lname'] = $attendee->lname();
2690
+		$this->_template_args['email'] = $attendee->email();
2691
+		$this->_template_args['phone'] = $attendee->phone();
2692
+		$this->_template_args['formatted_address'] = EEH_Address::format($attendee);
2693
+		// edit link
2694
+		$this->_template_args['att_edit_link'] = EE_Admin_Page::add_query_args_and_nonce(
2695
+			array(
2696
+				'action' => 'edit_attendee',
2697
+				'post'   => $attendee->ID(),
2698
+			),
2699
+			REG_ADMIN_URL
2700
+		);
2701
+		$this->_template_args['att_edit_label'] = esc_html__('View/Edit Contact', 'event_espresso');
2702
+		// create link
2703
+		$this->_template_args['create_link'] = $primary_registration instanceof EE_Registration
2704
+			? EE_Admin_Page::add_query_args_and_nonce(
2705
+				array(
2706
+					'action'  => 'duplicate_attendee',
2707
+					'_REG_ID' => $this->_registration->ID(),
2708
+				),
2709
+				REG_ADMIN_URL
2710
+			) : '';
2711
+		$this->_template_args['create_label'] = esc_html__('Create Contact', 'event_espresso');
2712
+		$this->_template_args['att_check'] = $att_check;
2713
+		$template_path = REG_TEMPLATE_PATH . 'reg_admin_details_side_meta_box_registrant.template.php';
2714
+		echo EEH_Template::display_template($template_path, $this->_template_args, true);
2715
+	}
2716
+
2717
+
2718
+	/**
2719
+	 * trash or restore registrations
2720
+	 *
2721
+	 * @param  boolean $trash whether to archive or restore
2722
+	 * @return void
2723
+	 * @throws EE_Error
2724
+	 * @throws InvalidArgumentException
2725
+	 * @throws InvalidDataTypeException
2726
+	 * @throws InvalidInterfaceException
2727
+	 * @throws RuntimeException
2728
+	 * @access protected
2729
+	 */
2730
+	protected function _trash_or_restore_registrations($trash = true)
2731
+	{
2732
+		// if empty _REG_ID then get out because there's nothing to do
2733
+		if (empty($this->_req_data['_REG_ID'])) {
2734
+			EE_Error::add_error(
2735
+				sprintf(
2736
+					esc_html__(
2737
+						'In order to %1$s registrations you must select which ones you wish to %1$s by clicking the checkboxes.',
2738
+						'event_espresso'
2739
+					),
2740
+					$trash ? 'trash' : 'restore'
2741
+				),
2742
+				__FILE__,
2743
+				__LINE__,
2744
+				__FUNCTION__
2745
+			);
2746
+			$this->_redirect_after_action(false, '', '', array(), true);
2747
+		}
2748
+		$success = 0;
2749
+		$overwrite_msgs = false;
2750
+		// Checkboxes
2751
+		if (! is_array($this->_req_data['_REG_ID'])) {
2752
+			$this->_req_data['_REG_ID'] = array($this->_req_data['_REG_ID']);
2753
+		}
2754
+		$reg_count = count($this->_req_data['_REG_ID']);
2755
+		// cycle thru checkboxes
2756
+		foreach ($this->_req_data['_REG_ID'] as $REG_ID) {
2757
+			/** @var EE_Registration $REG */
2758
+			$REG = EEM_Registration::instance()->get_one_by_ID($REG_ID);
2759
+			$payments = $REG->registration_payments();
2760
+			if (! empty($payments)) {
2761
+				$name = $REG->attendee() instanceof EE_Attendee
2762
+					? $REG->attendee()->full_name()
2763
+					: esc_html__('Unknown Attendee', 'event_espresso');
2764
+				$overwrite_msgs = true;
2765
+				EE_Error::add_error(
2766
+					sprintf(
2767
+						esc_html__(
2768
+							'The registration for %s could not be trashed because it has payments attached to the related transaction.  If you wish to trash this registration you must first delete the payments on the related transaction.',
2769
+							'event_espresso'
2770
+						),
2771
+						$name
2772
+					),
2773
+					__FILE__,
2774
+					__FUNCTION__,
2775
+					__LINE__
2776
+				);
2777
+				// can't trash this registration because it has payments.
2778
+				continue;
2779
+			}
2780
+			$updated = $trash ? $REG->delete() : $REG->restore();
2781
+			if ($updated) {
2782
+				$success++;
2783
+			}
2784
+		}
2785
+		$this->_redirect_after_action(
2786
+			$success === $reg_count, // were ALL registrations affected?
2787
+			$success > 1
2788
+				? esc_html__('Registrations', 'event_espresso')
2789
+				: esc_html__('Registration', 'event_espresso'),
2790
+			$trash
2791
+				? esc_html__('moved to the trash', 'event_espresso')
2792
+				: esc_html__('restored', 'event_espresso'),
2793
+			$this->mergeExistingRequestParamsWithRedirectArgs(array('action' => 'default')),
2794
+			$overwrite_msgs
2795
+		);
2796
+	}
2797
+
2798
+
2799
+	/**
2800
+	 * This is used to permanently delete registrations.  Note, this will handle not only deleting permanently the
2801
+	 * registration but also.
2802
+	 * 1. Removing relations to EE_Attendee
2803
+	 * 2. Deleting permanently the related transaction, but ONLY if all related registrations to the transaction are
2804
+	 * ALSO trashed.
2805
+	 * 3. Deleting permanently any related Line items but only if the above conditions are met.
2806
+	 * 4. Removing relationships between all tickets and the related registrations
2807
+	 * 5. Deleting permanently any related Answers (and the answers for other related registrations that were deleted.)
2808
+	 * 6. Deleting permanently any related Checkins.
2809
+	 *
2810
+	 * @return void
2811
+	 * @throws EE_Error
2812
+	 * @throws InvalidArgumentException
2813
+	 * @throws InvalidDataTypeException
2814
+	 * @throws InvalidInterfaceException
2815
+	 */
2816
+	protected function _delete_registrations()
2817
+	{
2818
+		$REG_MDL = EEM_Registration::instance();
2819
+		$success = 1;
2820
+		// Checkboxes
2821
+		if (! empty($this->_req_data['_REG_ID']) && is_array($this->_req_data['_REG_ID'])) {
2822
+			// if array has more than one element than success message should be plural
2823
+			$success = count($this->_req_data['_REG_ID']) > 1 ? 2 : 1;
2824
+			// cycle thru checkboxes
2825
+			while (list($ind, $REG_ID) = each($this->_req_data['_REG_ID'])) {
2826
+				$REG = $REG_MDL->get_one_by_ID($REG_ID);
2827
+				if (! $REG instanceof EE_Registration) {
2828
+					continue;
2829
+				}
2830
+				$deleted = $this->_delete_registration($REG);
2831
+				if (! $deleted) {
2832
+					$success = 0;
2833
+				}
2834
+			}
2835
+		} else {
2836
+			// grab single id and delete
2837
+			$REG_ID = $this->_req_data['_REG_ID'];
2838
+			$REG = $REG_MDL->get_one_by_ID($REG_ID);
2839
+			$deleted = $this->_delete_registration($REG);
2840
+			if (! $deleted) {
2841
+				$success = 0;
2842
+			}
2843
+		}
2844
+		$what = $success > 1
2845
+			? esc_html__('Registrations', 'event_espresso')
2846
+			: esc_html__('Registration', 'event_espresso');
2847
+		$action_desc = esc_html__('permanently deleted.', 'event_espresso');
2848
+		$this->_redirect_after_action(
2849
+			$success,
2850
+			$what,
2851
+			$action_desc,
2852
+			$this->mergeExistingRequestParamsWithRedirectArgs(['action' => 'default']),
2853
+			true
2854
+		);
2855
+	}
2856
+
2857
+
2858
+	/**
2859
+	 * handles the permanent deletion of a registration.  See comments with _delete_registrations() for details on what
2860
+	 * models get affected.
2861
+	 *
2862
+	 * @param  EE_Registration $REG registration to be deleted permenantly
2863
+	 * @return bool true = successful deletion, false = fail.
2864
+	 * @throws EE_Error
2865
+	 */
2866
+	protected function _delete_registration(EE_Registration $REG)
2867
+	{
2868
+		// first we start with the transaction... ultimately, we WILL not delete permanently if there are any related
2869
+		// registrations on the transaction that are NOT trashed.
2870
+		$TXN = $REG->get_first_related('Transaction');
2871
+		$REGS = $TXN->get_many_related('Registration');
2872
+		$all_trashed = true;
2873
+		foreach ($REGS as $registration) {
2874
+			if (! $registration->get('REG_deleted')) {
2875
+				$all_trashed = false;
2876
+			}
2877
+		}
2878
+		if (! $all_trashed) {
2879
+			EE_Error::add_error(
2880
+				esc_html__(
2881
+					'Unable to permanently delete this registration. Before this registration can be permanently deleted, all registrations made in the same transaction must be trashed as well.  These registrations will be permanently deleted in the same action.',
2882
+					'event_espresso'
2883
+				),
2884
+				__FILE__,
2885
+				__FUNCTION__,
2886
+				__LINE__
2887
+			);
2888
+			return false;
2889
+		}
2890
+		// k made it here so that means we can delete all the related transactions and their answers (but let's do them
2891
+		// separately from THIS one).
2892
+		foreach ($REGS as $registration) {
2893
+			// delete related answers
2894
+			$registration->delete_related_permanently('Answer');
2895
+			// remove relationship to EE_Attendee (but we ALWAYS leave the contact record intact)
2896
+			$attendee = $registration->get_first_related('Attendee');
2897
+			if ($attendee instanceof EE_Attendee) {
2898
+				$registration->_remove_relation_to($attendee, 'Attendee');
2899
+			}
2900
+			// now remove relationships to tickets on this registration.
2901
+			$registration->_remove_relations('Ticket');
2902
+			// now delete permanently the checkins related to this registration.
2903
+			$registration->delete_related_permanently('Checkin');
2904
+			if ($registration->ID() === $REG->ID()) {
2905
+				continue;
2906
+			} //we don't want to delete permanently the existing registration just yet.
2907
+			// remove relation to transaction for these registrations if NOT the existing registrations
2908
+			$registration->_remove_relations('Transaction');
2909
+			// delete permanently any related messages.
2910
+			$registration->delete_related_permanently('Message');
2911
+			// now delete this registration permanently
2912
+			$registration->delete_permanently();
2913
+		}
2914
+		// now all related registrations on the transaction are handled.  So let's just handle this registration itself
2915
+		// (the transaction and line items should be all that's left).
2916
+		// delete the line items related to the transaction for this registration.
2917
+		$TXN->delete_related_permanently('Line_Item');
2918
+		// we need to remove all the relationships on the transaction
2919
+		$TXN->delete_related_permanently('Payment');
2920
+		$TXN->delete_related_permanently('Extra_Meta');
2921
+		$TXN->delete_related_permanently('Message');
2922
+		// now we can delete this REG permanently (and the transaction of course)
2923
+		$REG->delete_related_permanently('Transaction');
2924
+		return $REG->delete_permanently();
2925
+	}
2926
+
2927
+
2928
+	/**
2929
+	 *    generates HTML for the Register New Attendee Admin page
2930
+	 *
2931
+	 * @access private
2932
+	 * @throws DomainException
2933
+	 * @throws EE_Error
2934
+	 */
2935
+	public function new_registration()
2936
+	{
2937
+		if (! $this->_set_reg_event()) {
2938
+			throw new EE_Error(
2939
+				esc_html__(
2940
+					'Unable to continue with registering because there is no Event ID in the request',
2941
+					'event_espresso'
2942
+				)
2943
+			);
2944
+		}
2945
+		EE_Registry::instance()->REQ->set_espresso_page(true);
2946
+		// gotta start with a clean slate if we're not coming here via ajax
2947
+		if (! defined('DOING_AJAX')
2948
+			&& (! isset($this->_req_data['processing_registration']) || isset($this->_req_data['step_error']))
2949
+		) {
2950
+			EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
2951
+		}
2952
+		$this->_template_args['event_name'] = '';
2953
+		// event name
2954
+		if ($this->_reg_event) {
2955
+			$this->_template_args['event_name'] = $this->_reg_event->name();
2956
+			$edit_event_url = self::add_query_args_and_nonce(
2957
+				array(
2958
+					'action' => 'edit',
2959
+					'post'   => $this->_reg_event->ID(),
2960
+				),
2961
+				EVENTS_ADMIN_URL
2962
+			);
2963
+			$edit_event_lnk = '<a href="'
2964
+							  . $edit_event_url
2965
+							  . '" title="'
2966
+							  . esc_attr__('Edit ', 'event_espresso')
2967
+							  . $this->_reg_event->name()
2968
+							  . '">'
2969
+							  . esc_html__('Edit Event', 'event_espresso')
2970
+							  . '</a>';
2971
+			$this->_template_args['event_name'] .= ' <span class="admin-page-header-edit-lnk not-bold">'
2972
+												   . $edit_event_lnk
2973
+												   . '</span>';
2974
+		}
2975
+		$this->_template_args['step_content'] = $this->_get_registration_step_content();
2976
+		if (defined('DOING_AJAX')) {
2977
+			$this->_return_json();
2978
+		}
2979
+		// grab header
2980
+		$template_path =
2981
+			REG_TEMPLATE_PATH . 'reg_admin_register_new_attendee.template.php';
2982
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
2983
+			$template_path,
2984
+			$this->_template_args,
2985
+			true
2986
+		);
2987
+		// $this->_set_publish_post_box_vars( NULL, FALSE, FALSE, NULL, FALSE );
2988
+		// the details template wrapper
2989
+		$this->display_admin_page_with_sidebar();
2990
+	}
2991
+
2992
+
2993
+	/**
2994
+	 * This returns the content for a registration step
2995
+	 *
2996
+	 * @access protected
2997
+	 * @return string html
2998
+	 * @throws DomainException
2999
+	 * @throws EE_Error
3000
+	 * @throws InvalidArgumentException
3001
+	 * @throws InvalidDataTypeException
3002
+	 * @throws InvalidInterfaceException
3003
+	 */
3004
+	protected function _get_registration_step_content()
3005
+	{
3006
+		if (isset($_COOKIE['ee_registration_added']) && $_COOKIE['ee_registration_added']) {
3007
+			$warning_msg = sprintf(
3008
+				esc_html__(
3009
+					'%2$sWARNING!!!%3$s%1$sPlease do not use the back button to return to this page for the purpose of adding another registration.%1$sThis can result in lost and/or corrupted data.%1$sIf you wish to add another registration, then please click the%1$s%7$s"Add Another New Registration to Event"%8$s button%1$son the Transaction details page, after you are redirected.%1$s%1$s%4$s redirecting in %5$s seconds %6$s',
3010
+					'event_espresso'
3011
+				),
3012
+				'<br />',
3013
+				'<h3 class="important-notice">',
3014
+				'</h3>',
3015
+				'<div class="float-right">',
3016
+				'<span id="redirect_timer" class="important-notice">30</span>',
3017
+				'</div>',
3018
+				'<b>',
3019
+				'</b>'
3020
+			);
3021
+			return '
3022 3022
 	<div id="ee-add-reg-back-button-dv"><p>' . $warning_msg . '</p></div>
3023 3023
 	<script >
3024 3024
 		// WHOAH !!! it appears that someone is using the back button from the Transaction admin page
@@ -3031,855 +3031,855 @@  discard block
 block discarded – undo
3031 3031
 	        }
3032 3032
 	    }, 800 );
3033 3033
 	</script >';
3034
-        }
3035
-        $template_args = array(
3036
-            'title'                    => '',
3037
-            'content'                  => '',
3038
-            'step_button_text'         => '',
3039
-            'show_notification_toggle' => false,
3040
-        );
3041
-        // to indicate we're processing a new registration
3042
-        $hidden_fields = array(
3043
-            'processing_registration' => array(
3044
-                'type'  => 'hidden',
3045
-                'value' => 0,
3046
-            ),
3047
-            'event_id'                => array(
3048
-                'type'  => 'hidden',
3049
-                'value' => $this->_reg_event->ID(),
3050
-            ),
3051
-        );
3052
-        // if the cart is empty then we know we're at step one so we'll display ticket selector
3053
-        $cart = EE_Registry::instance()->SSN->cart();
3054
-        $step = ! $cart instanceof EE_Cart ? 'ticket' : 'questions';
3055
-        switch ($step) {
3056
-            case 'ticket':
3057
-                $hidden_fields['processing_registration']['value'] = 1;
3058
-                $template_args['title'] = esc_html__(
3059
-                    'Step One: Select the Ticket for this registration',
3060
-                    'event_espresso'
3061
-                );
3062
-                $template_args['content'] =
3063
-                    EED_Ticket_Selector::instance()->display_ticket_selector($this->_reg_event);
3064
-                $template_args['step_button_text'] = esc_html__(
3065
-                    'Add Tickets and Continue to Registrant Details',
3066
-                    'event_espresso'
3067
-                );
3068
-                $template_args['show_notification_toggle'] = false;
3069
-                break;
3070
-            case 'questions':
3071
-                $hidden_fields['processing_registration']['value'] = 2;
3072
-                $template_args['title'] = esc_html__(
3073
-                    'Step Two: Add Registrant Details for this Registration',
3074
-                    'event_espresso'
3075
-                );
3076
-                // in theory we should be able to run EED_SPCO at this point because the cart should have been setup
3077
-                // properly by the first process_reg_step run.
3078
-                $template_args['content'] =
3079
-                    EED_Single_Page_Checkout::registration_checkout_for_admin();
3080
-                $template_args['step_button_text'] = esc_html__(
3081
-                    'Save Registration and Continue to Details',
3082
-                    'event_espresso'
3083
-                );
3084
-                $template_args['show_notification_toggle'] = true;
3085
-                break;
3086
-        }
3087
-        // we come back to the process_registration_step route.
3088
-        $this->_set_add_edit_form_tags('process_reg_step', $hidden_fields);
3089
-        return EEH_Template::display_template(
3090
-            REG_TEMPLATE_PATH . 'reg_admin_register_new_attendee_step_content.template.php',
3091
-            $template_args,
3092
-            true
3093
-        );
3094
-    }
3095
-
3096
-
3097
-    /**
3098
-     *        set_reg_event
3099
-     *
3100
-     * @access private
3101
-     * @return bool
3102
-     * @throws EE_Error
3103
-     * @throws InvalidArgumentException
3104
-     * @throws InvalidDataTypeException
3105
-     * @throws InvalidInterfaceException
3106
-     */
3107
-    private function _set_reg_event()
3108
-    {
3109
-        if (is_object($this->_reg_event)) {
3110
-            return true;
3111
-        }
3112
-        $EVT_ID = (! empty($this->_req_data['event_id'])) ? absint($this->_req_data['event_id']) : false;
3113
-        if (! $EVT_ID) {
3114
-            return false;
3115
-        }
3116
-        $this->_reg_event = EEM_Event::instance()->get_one_by_ID($EVT_ID);
3117
-        return true;
3118
-    }
3119
-
3120
-
3121
-    /**
3122
-     * process_reg_step
3123
-     *
3124
-     * @access        public
3125
-     * @return string
3126
-     * @throws DomainException
3127
-     * @throws EE_Error
3128
-     * @throws InvalidArgumentException
3129
-     * @throws InvalidDataTypeException
3130
-     * @throws InvalidInterfaceException
3131
-     * @throws ReflectionException
3132
-     * @throws RuntimeException
3133
-     */
3134
-    public function process_reg_step()
3135
-    {
3136
-        EE_System::do_not_cache();
3137
-        $this->_set_reg_event();
3138
-        EE_Registry::instance()->REQ->set_espresso_page(true);
3139
-        EE_Registry::instance()->REQ->set('uts', time());
3140
-        // what step are we on?
3141
-        $cart = EE_Registry::instance()->SSN->cart();
3142
-        $step = ! $cart instanceof EE_Cart ? 'ticket' : 'questions';
3143
-        // if doing ajax then we need to verify the nonce
3144
-        if (defined('DOING_AJAX')) {
3145
-            $nonce = isset($this->_req_data[ $this->_req_nonce ])
3146
-                ? sanitize_text_field($this->_req_data[ $this->_req_nonce ]) : '';
3147
-            $this->_verify_nonce($nonce, $this->_req_nonce);
3148
-        }
3149
-        switch ($step) {
3150
-            case 'ticket':
3151
-                // process ticket selection
3152
-                $success = EED_Ticket_Selector::instance()->process_ticket_selections();
3153
-                if ($success) {
3154
-                    EE_Error::add_success(
3155
-                        esc_html__(
3156
-                            'Tickets Selected. Now complete the registration.',
3157
-                            'event_espresso'
3158
-                        )
3159
-                    );
3160
-                } else {
3161
-                    $query_args['step_error'] = $this->_req_data['step_error'] = true;
3162
-                }
3163
-                if (defined('DOING_AJAX')) {
3164
-                    $this->new_registration(); // display next step
3165
-                } else {
3166
-                    $query_args = array(
3167
-                        'action'                  => 'new_registration',
3168
-                        'processing_registration' => 1,
3169
-                        'event_id'                => $this->_reg_event->ID(),
3170
-                        'uts'                     => time(),
3171
-                    );
3172
-                    $this->_redirect_after_action(
3173
-                        false,
3174
-                        '',
3175
-                        '',
3176
-                        $query_args,
3177
-                        true
3178
-                    );
3179
-                }
3180
-                break;
3181
-            case 'questions':
3182
-                if (! isset(
3183
-                    $this->_req_data['txn_reg_status_change'],
3184
-                    $this->_req_data['txn_reg_status_change']['send_notifications']
3185
-                )
3186
-                ) {
3187
-                    add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_false', 15);
3188
-                }
3189
-                // process registration
3190
-                $transaction = EED_Single_Page_Checkout::instance()->process_registration_from_admin();
3191
-                if ($cart instanceof EE_Cart) {
3192
-                    $grand_total = $cart->get_cart_grand_total();
3193
-                    if ($grand_total instanceof EE_Line_Item) {
3194
-                        $grand_total->save_this_and_descendants_to_txn();
3195
-                    }
3196
-                }
3197
-                if (! $transaction instanceof EE_Transaction) {
3198
-                    $query_args = array(
3199
-                        'action'                  => 'new_registration',
3200
-                        'processing_registration' => 2,
3201
-                        'event_id'                => $this->_reg_event->ID(),
3202
-                        'uts'                     => time(),
3203
-                    );
3204
-                    if (defined('DOING_AJAX')) {
3205
-                        // display registration form again because there are errors (maybe validation?)
3206
-                        $this->new_registration();
3207
-                        return;
3208
-                    } else {
3209
-                        $this->_redirect_after_action(
3210
-                            false,
3211
-                            '',
3212
-                            '',
3213
-                            $query_args,
3214
-                            true
3215
-                        );
3216
-                        return;
3217
-                    }
3218
-                }
3219
-                // maybe update status, and make sure to save transaction if not done already
3220
-                if (! $transaction->update_status_based_on_total_paid()) {
3221
-                    $transaction->save();
3222
-                }
3223
-                EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
3224
-                $this->_req_data = array();
3225
-                $query_args = array(
3226
-                    'action'        => 'redirect_to_txn',
3227
-                    'TXN_ID'        => $transaction->ID(),
3228
-                    'EVT_ID'        => $this->_reg_event->ID(),
3229
-                    'event_name'    => urlencode($this->_reg_event->name()),
3230
-                    'redirect_from' => 'new_registration',
3231
-                );
3232
-                $this->_redirect_after_action(false, '', '', $query_args, true);
3233
-                break;
3234
-        }
3235
-        // what are you looking here for?  Should be nothing to do at this point.
3236
-    }
3237
-
3238
-
3239
-    /**
3240
-     * redirect_to_txn
3241
-     *
3242
-     * @access public
3243
-     * @return void
3244
-     * @throws EE_Error
3245
-     * @throws InvalidArgumentException
3246
-     * @throws InvalidDataTypeException
3247
-     * @throws InvalidInterfaceException
3248
-     */
3249
-    public function redirect_to_txn()
3250
-    {
3251
-        EE_System::do_not_cache();
3252
-        EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
3253
-        $query_args = array(
3254
-            'action' => 'view_transaction',
3255
-            'TXN_ID' => isset($this->_req_data['TXN_ID']) ? absint($this->_req_data['TXN_ID']) : 0,
3256
-            'page'   => 'espresso_transactions',
3257
-        );
3258
-        if (isset($this->_req_data['EVT_ID'], $this->_req_data['redirect_from'])) {
3259
-            $query_args['EVT_ID'] = $this->_req_data['EVT_ID'];
3260
-            $query_args['event_name'] = urlencode($this->_req_data['event_name']);
3261
-            $query_args['redirect_from'] = $this->_req_data['redirect_from'];
3262
-        }
3263
-        EE_Error::add_success(
3264
-            esc_html__(
3265
-                'Registration Created.  Please review the transaction and add any payments as necessary',
3266
-                'event_espresso'
3267
-            )
3268
-        );
3269
-        $this->_redirect_after_action(false, '', '', $query_args, true);
3270
-    }
3271
-
3272
-
3273
-    /**
3274
-     *        generates HTML for the Attendee Contact List
3275
-     *
3276
-     * @access protected
3277
-     * @return void
3278
-     */
3279
-    protected function _attendee_contact_list_table()
3280
-    {
3281
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3282
-        $this->_search_btn_label = esc_html__('Contacts', 'event_espresso');
3283
-        $this->display_admin_list_table_page_with_no_sidebar();
3284
-    }
3285
-
3286
-
3287
-    /**
3288
-     *        get_attendees
3289
-     *
3290
-     * @param      $per_page
3291
-     * @param bool $count whether to return count or data.
3292
-     * @param bool $trash
3293
-     * @return array
3294
-     * @throws EE_Error
3295
-     * @throws InvalidArgumentException
3296
-     * @throws InvalidDataTypeException
3297
-     * @throws InvalidInterfaceException
3298
-     * @access public
3299
-     */
3300
-    public function get_attendees($per_page, $count = false, $trash = false)
3301
-    {
3302
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3303
-        require_once(REG_ADMIN . 'EE_Attendee_Contact_List_Table.class.php');
3304
-        $ATT_MDL = EEM_Attendee::instance();
3305
-        $this->_req_data['orderby'] = ! empty($this->_req_data['orderby']) ? $this->_req_data['orderby'] : '';
3306
-        switch ($this->_req_data['orderby']) {
3307
-            case 'ATT_ID':
3308
-                $orderby = 'ATT_ID';
3309
-                break;
3310
-            case 'ATT_fname':
3311
-                $orderby = 'ATT_fname';
3312
-                break;
3313
-            case 'ATT_email':
3314
-                $orderby = 'ATT_email';
3315
-                break;
3316
-            case 'ATT_city':
3317
-                $orderby = 'ATT_city';
3318
-                break;
3319
-            case 'STA_ID':
3320
-                $orderby = 'STA_ID';
3321
-                break;
3322
-            case 'CNT_ID':
3323
-                $orderby = 'CNT_ID';
3324
-                break;
3325
-            case 'Registration_Count':
3326
-                $orderby = 'Registration_Count';
3327
-                break;
3328
-            default:
3329
-                $orderby = 'ATT_lname';
3330
-        }
3331
-        $sort = (isset($this->_req_data['order']) && ! empty($this->_req_data['order']))
3332
-            ? $this->_req_data['order']
3333
-            : 'ASC';
3334
-        $current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
3335
-            ? $this->_req_data['paged']
3336
-            : 1;
3337
-        $per_page = isset($per_page) && ! empty($per_page) ? $per_page : 10;
3338
-        $per_page = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
3339
-            ? $this->_req_data['perpage']
3340
-            : $per_page;
3341
-        $_where = array();
3342
-        if (! empty($this->_req_data['s'])) {
3343
-            $sstr = '%' . $this->_req_data['s'] . '%';
3344
-            $_where['OR'] = array(
3345
-                'Registration.Event.EVT_name'       => array('LIKE', $sstr),
3346
-                'Registration.Event.EVT_desc'       => array('LIKE', $sstr),
3347
-                'Registration.Event.EVT_short_desc' => array('LIKE', $sstr),
3348
-                'ATT_fname'                         => array('LIKE', $sstr),
3349
-                'ATT_lname'                         => array('LIKE', $sstr),
3350
-                'ATT_short_bio'                     => array('LIKE', $sstr),
3351
-                'ATT_email'                         => array('LIKE', $sstr),
3352
-                'ATT_address'                       => array('LIKE', $sstr),
3353
-                'ATT_address2'                      => array('LIKE', $sstr),
3354
-                'ATT_city'                          => array('LIKE', $sstr),
3355
-                'Country.CNT_name'                  => array('LIKE', $sstr),
3356
-                'State.STA_name'                    => array('LIKE', $sstr),
3357
-                'ATT_phone'                         => array('LIKE', $sstr),
3358
-                'Registration.REG_final_price'      => array('LIKE', $sstr),
3359
-                'Registration.REG_code'             => array('LIKE', $sstr),
3360
-                'Registration.REG_group_size'       => array('LIKE', $sstr),
3361
-            );
3362
-        }
3363
-        $offset = ($current_page - 1) * $per_page;
3364
-        $limit = $count ? null : array($offset, $per_page);
3365
-        $query_args = array(
3366
-            $_where,
3367
-            'extra_selects' => array('Registration_Count' => array('Registration.REG_ID', 'count', '%d')),
3368
-            'limit'         => $limit,
3369
-        );
3370
-        if (! $count) {
3371
-            $query_args['order_by'] = array($orderby => $sort);
3372
-        }
3373
-        if ($trash) {
3374
-            $query_args[0]['status'] = array('!=', 'publish');
3375
-            $all_attendees = $count
3376
-                ? $ATT_MDL->count($query_args, 'ATT_ID', true)
3377
-                : $ATT_MDL->get_all($query_args);
3378
-        } else {
3379
-            $query_args[0]['status'] = array('IN', array('publish'));
3380
-            $all_attendees = $count
3381
-                ? $ATT_MDL->count($query_args, 'ATT_ID', true)
3382
-                : $ATT_MDL->get_all($query_args);
3383
-        }
3384
-        return $all_attendees;
3385
-    }
3386
-
3387
-
3388
-    /**
3389
-     * This is just taking care of resending the registration confirmation
3390
-     *
3391
-     * @access protected
3392
-     * @return void
3393
-     */
3394
-    protected function _resend_registration()
3395
-    {
3396
-        $this->_process_resend_registration();
3397
-        $query_args = isset($this->_req_data['redirect_to'])
3398
-            ? array('action' => $this->_req_data['redirect_to'], '_REG_ID' => $this->_req_data['_REG_ID'])
3399
-            : array('action' => 'default');
3400
-        $this->_redirect_after_action(false, '', '', $query_args, true);
3401
-    }
3402
-
3403
-    /**
3404
-     * Creates a registration report, but accepts the name of a method to use for preparing the query parameters
3405
-     * to use when selecting registrations
3406
-     *
3407
-     * @param string $method_name_for_getting_query_params the name of the method (on this class) to use for preparing
3408
-     *                                                     the query parameters from the request
3409
-     * @return void ends the request with a redirect or download
3410
-     */
3411
-    public function _registrations_report_base($method_name_for_getting_query_params)
3412
-    {
3413
-        if (! defined('EE_USE_OLD_CSV_REPORT_CLASS')) {
3414
-            wp_redirect(
3415
-                EE_Admin_Page::add_query_args_and_nonce(
3416
-                    array(
3417
-                        'page'        => 'espresso_batch',
3418
-                        'batch'       => 'file',
3419
-                        'EVT_ID'      => isset($this->_req_data['EVT_ID']) ? $this->_req_data['EVT_ID'] : null,
3420
-                        'filters'     => urlencode(
3421
-                            serialize(
3422
-                                call_user_func(
3423
-                                    array($this, $method_name_for_getting_query_params),
3424
-                                    EEH_Array::is_set(
3425
-                                        $this->_req_data,
3426
-                                        'filters',
3427
-                                        array()
3428
-                                    )
3429
-                                )
3430
-                            )
3431
-                        ),
3432
-                        'use_filters' => EEH_Array::is_set($this->_req_data, 'use_filters', false),
3433
-                        'job_handler' => urlencode('EventEspressoBatchRequest\JobHandlers\RegistrationsReport'),
3434
-                        'return_url'  => urlencode($this->_req_data['return_url']),
3435
-                    )
3436
-                )
3437
-            );
3438
-        } else {
3439
-            $new_request_args = array(
3440
-                'export' => 'report',
3441
-                'action' => 'registrations_report_for_event',
3442
-                'EVT_ID' => isset($this->_req_data['EVT_ID']) ? $this->_req_data['EVT_ID'] : null,
3443
-            );
3444
-            $this->_req_data = array_merge($this->_req_data, $new_request_args);
3445
-            if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
3446
-                require_once(EE_CLASSES . 'EE_Export.class.php');
3447
-                $EE_Export = EE_Export::instance($this->_req_data);
3448
-                $EE_Export->export();
3449
-            }
3450
-        }
3451
-    }
3452
-
3453
-
3454
-    /**
3455
-     * Creates a registration report using only query parameters in the request
3456
-     *
3457
-     * @return void
3458
-     */
3459
-    public function _registrations_report()
3460
-    {
3461
-        $this->_registrations_report_base('_get_registration_query_parameters');
3462
-    }
3463
-
3464
-
3465
-    public function _contact_list_export()
3466
-    {
3467
-        if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
3468
-            require_once(EE_CLASSES . 'EE_Export.class.php');
3469
-            $EE_Export = EE_Export::instance($this->_req_data);
3470
-            $EE_Export->export_attendees();
3471
-        }
3472
-    }
3473
-
3474
-
3475
-    public function _contact_list_report()
3476
-    {
3477
-        if (! defined('EE_USE_OLD_CSV_REPORT_CLASS')) {
3478
-            wp_redirect(
3479
-                EE_Admin_Page::add_query_args_and_nonce(
3480
-                    array(
3481
-                        'page'        => 'espresso_batch',
3482
-                        'batch'       => 'file',
3483
-                        'job_handler' => urlencode('EventEspressoBatchRequest\JobHandlers\AttendeesReport'),
3484
-                        'return_url'  => urlencode($this->_req_data['return_url']),
3485
-                    )
3486
-                )
3487
-            );
3488
-        } else {
3489
-            if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
3490
-                require_once(EE_CLASSES . 'EE_Export.class.php');
3491
-                $EE_Export = EE_Export::instance($this->_req_data);
3492
-                $EE_Export->report_attendees();
3493
-            }
3494
-        }
3495
-    }
3496
-
3497
-
3498
-
3499
-
3500
-
3501
-    /***************************************        ATTENDEE DETAILS        ***************************************/
3502
-    /**
3503
-     * This duplicates the attendee object for the given incoming registration id and attendee_id.
3504
-     *
3505
-     * @return void
3506
-     * @throws EE_Error
3507
-     * @throws InvalidArgumentException
3508
-     * @throws InvalidDataTypeException
3509
-     * @throws InvalidInterfaceException
3510
-     */
3511
-    protected function _duplicate_attendee()
3512
-    {
3513
-        $action = ! empty($this->_req_data['return']) ? $this->_req_data['return'] : 'default';
3514
-        // verify we have necessary info
3515
-        if (empty($this->_req_data['_REG_ID'])) {
3516
-            EE_Error::add_error(
3517
-                esc_html__(
3518
-                    'Unable to create the contact for the registration because the required parameters are not present (_REG_ID )',
3519
-                    'event_espresso'
3520
-                ),
3521
-                __FILE__,
3522
-                __LINE__,
3523
-                __FUNCTION__
3524
-            );
3525
-            $query_args = array('action' => $action);
3526
-            $this->_redirect_after_action('', '', '', $query_args, true);
3527
-        }
3528
-        // okay necessary deets present... let's dupe the incoming attendee and attach to incoming registration.
3529
-        $registration = EEM_Registration::instance()->get_one_by_ID($this->_req_data['_REG_ID']);
3530
-        $attendee = $registration->attendee();
3531
-        // remove relation of existing attendee on registration
3532
-        $registration->_remove_relation_to($attendee, 'Attendee');
3533
-        // new attendee
3534
-        $new_attendee = clone $attendee;
3535
-        $new_attendee->set('ATT_ID', 0);
3536
-        $new_attendee->save();
3537
-        // add new attendee to reg
3538
-        $registration->_add_relation_to($new_attendee, 'Attendee');
3539
-        EE_Error::add_success(
3540
-            esc_html__(
3541
-                'New Contact record created.  Now make any edits you wish to make for this contact.',
3542
-                'event_espresso'
3543
-            )
3544
-        );
3545
-        // redirect to edit page for attendee
3546
-        $query_args = array('post' => $new_attendee->ID(), 'action' => 'edit_attendee');
3547
-        $this->_redirect_after_action('', '', '', $query_args, true);
3548
-    }
3549
-
3550
-
3551
-    /**
3552
-     * Callback invoked by parent EE_Admin_CPT class hooked in on `save_post` wp hook.
3553
-     *
3554
-     * @param int     $post_id
3555
-     * @param WP_POST $post
3556
-     * @throws DomainException
3557
-     * @throws EE_Error
3558
-     * @throws InvalidArgumentException
3559
-     * @throws InvalidDataTypeException
3560
-     * @throws InvalidInterfaceException
3561
-     * @throws LogicException
3562
-     * @throws InvalidFormSubmissionException
3563
-     */
3564
-    protected function _insert_update_cpt_item($post_id, $post)
3565
-    {
3566
-        $success = true;
3567
-        $attendee = $post instanceof WP_Post && $post->post_type === 'espresso_attendees'
3568
-            ? EEM_Attendee::instance()->get_one_by_ID($post_id)
3569
-            : null;
3570
-        // for attendee updates
3571
-        if ($attendee instanceof EE_Attendee) {
3572
-            // note we should only be UPDATING attendees at this point.
3573
-            $updated_fields = array(
3574
-                'ATT_fname'     => $this->_req_data['ATT_fname'],
3575
-                'ATT_lname'     => $this->_req_data['ATT_lname'],
3576
-                'ATT_full_name' => $this->_req_data['ATT_fname'] . ' ' . $this->_req_data['ATT_lname'],
3577
-                'ATT_address'   => isset($this->_req_data['ATT_address']) ? $this->_req_data['ATT_address'] : '',
3578
-                'ATT_address2'  => isset($this->_req_data['ATT_address2']) ? $this->_req_data['ATT_address2'] : '',
3579
-                'ATT_city'      => isset($this->_req_data['ATT_city']) ? $this->_req_data['ATT_city'] : '',
3580
-                'STA_ID'        => isset($this->_req_data['STA_ID']) ? $this->_req_data['STA_ID'] : '',
3581
-                'CNT_ISO'       => isset($this->_req_data['CNT_ISO']) ? $this->_req_data['CNT_ISO'] : '',
3582
-                'ATT_zip'       => isset($this->_req_data['ATT_zip']) ? $this->_req_data['ATT_zip'] : '',
3583
-            );
3584
-            foreach ($updated_fields as $field => $value) {
3585
-                $attendee->set($field, $value);
3586
-            }
3587
-
3588
-            // process contact details metabox form handler (which will also save the attendee)
3589
-            $contact_details_form = $this->getAttendeeContactDetailsMetaboxFormHandler($attendee);
3590
-            $success = $contact_details_form->process($this->_req_data);
3591
-
3592
-            $attendee_update_callbacks = apply_filters(
3593
-                'FHEE__Registrations_Admin_Page__insert_update_cpt_item__attendee_update',
3594
-                array()
3595
-            );
3596
-            foreach ($attendee_update_callbacks as $a_callback) {
3597
-                if (false === call_user_func_array($a_callback, array($attendee, $this->_req_data))) {
3598
-                    throw new EE_Error(
3599
-                        sprintf(
3600
-                            esc_html__(
3601
-                                'The %s callback given for the "FHEE__Registrations_Admin_Page__insert_update_cpt_item__attendee_update" filter is not a valid callback.  Please check the spelling.',
3602
-                                'event_espresso'
3603
-                            ),
3604
-                            $a_callback
3605
-                        )
3606
-                    );
3607
-                }
3608
-            }
3609
-        }
3610
-
3611
-        if ($success === false) {
3612
-            EE_Error::add_error(
3613
-                esc_html__(
3614
-                    'Something went wrong with updating the meta table data for the registration.',
3615
-                    'event_espresso'
3616
-                ),
3617
-                __FILE__,
3618
-                __FUNCTION__,
3619
-                __LINE__
3620
-            );
3621
-        }
3622
-    }
3623
-
3624
-
3625
-    public function trash_cpt_item($post_id)
3626
-    {
3627
-    }
3628
-
3629
-
3630
-    public function delete_cpt_item($post_id)
3631
-    {
3632
-    }
3633
-
3634
-
3635
-    public function restore_cpt_item($post_id)
3636
-    {
3637
-    }
3638
-
3639
-
3640
-    protected function _restore_cpt_item($post_id, $revision_id)
3641
-    {
3642
-    }
3643
-
3644
-
3645
-    public function attendee_editor_metaboxes()
3646
-    {
3647
-        $this->verify_cpt_object();
3648
-        remove_meta_box(
3649
-            'postexcerpt',
3650
-            esc_html__('Excerpt', 'event_espresso'),
3651
-            'post_excerpt_meta_box',
3652
-            $this->_cpt_routes[ $this->_req_action ],
3653
-            'normal',
3654
-            'core'
3655
-        );
3656
-        remove_meta_box('commentstatusdiv', $this->_cpt_routes[ $this->_req_action ], 'normal', 'core');
3657
-        if (post_type_supports('espresso_attendees', 'excerpt')) {
3658
-            add_meta_box(
3659
-                'postexcerpt',
3660
-                esc_html__('Short Biography', 'event_espresso'),
3661
-                'post_excerpt_meta_box',
3662
-                $this->_cpt_routes[ $this->_req_action ],
3663
-                'normal'
3664
-            );
3665
-        }
3666
-        if (post_type_supports('espresso_attendees', 'comments')) {
3667
-            add_meta_box(
3668
-                'commentsdiv',
3669
-                esc_html__('Notes on the Contact', 'event_espresso'),
3670
-                'post_comment_meta_box',
3671
-                $this->_cpt_routes[ $this->_req_action ],
3672
-                'normal',
3673
-                'core'
3674
-            );
3675
-        }
3676
-        add_meta_box(
3677
-            'attendee_contact_info',
3678
-            esc_html__('Contact Info', 'event_espresso'),
3679
-            array($this, 'attendee_contact_info'),
3680
-            $this->_cpt_routes[ $this->_req_action ],
3681
-            'side',
3682
-            'core'
3683
-        );
3684
-        add_meta_box(
3685
-            'attendee_details_address',
3686
-            esc_html__('Address Details', 'event_espresso'),
3687
-            array($this, 'attendee_address_details'),
3688
-            $this->_cpt_routes[ $this->_req_action ],
3689
-            'normal',
3690
-            'core'
3691
-        );
3692
-        add_meta_box(
3693
-            'attendee_registrations',
3694
-            esc_html__('Registrations for this Contact', 'event_espresso'),
3695
-            array($this, 'attendee_registrations_meta_box'),
3696
-            $this->_cpt_routes[ $this->_req_action ],
3697
-            'normal',
3698
-            'high'
3699
-        );
3700
-    }
3701
-
3702
-
3703
-    /**
3704
-     * Metabox for attendee contact info
3705
-     *
3706
-     * @param  WP_Post $post wp post object
3707
-     * @return string attendee contact info ( and form )
3708
-     * @throws EE_Error
3709
-     * @throws InvalidArgumentException
3710
-     * @throws InvalidDataTypeException
3711
-     * @throws InvalidInterfaceException
3712
-     * @throws LogicException
3713
-     * @throws DomainException
3714
-     */
3715
-    public function attendee_contact_info($post)
3716
-    {
3717
-        // get attendee object ( should already have it )
3718
-        $form = $this->getAttendeeContactDetailsMetaboxFormHandler($this->_cpt_model_obj);
3719
-        $form->enqueueStylesAndScripts();
3720
-        echo $form->display();
3721
-    }
3722
-
3723
-
3724
-    /**
3725
-     * Return form handler for the contact details metabox
3726
-     *
3727
-     * @param EE_Attendee $attendee
3728
-     * @return AttendeeContactDetailsMetaboxFormHandler
3729
-     * @throws DomainException
3730
-     * @throws InvalidArgumentException
3731
-     * @throws InvalidDataTypeException
3732
-     * @throws InvalidInterfaceException
3733
-     */
3734
-    protected function getAttendeeContactDetailsMetaboxFormHandler(EE_Attendee $attendee)
3735
-    {
3736
-        return new AttendeeContactDetailsMetaboxFormHandler($attendee, EE_Registry::instance());
3737
-    }
3738
-
3739
-
3740
-    /**
3741
-     * Metabox for attendee details
3742
-     *
3743
-     * @param  WP_Post $post wp post object
3744
-     * @throws DomainException
3745
-     */
3746
-    public function attendee_address_details($post)
3747
-    {
3748
-        // get attendee object (should already have it)
3749
-        $this->_template_args['attendee'] = $this->_cpt_model_obj;
3750
-        $this->_template_args['state_html'] = EEH_Form_Fields::generate_form_input(
3751
-            new EE_Question_Form_Input(
3752
-                EE_Question::new_instance(
3753
-                    array(
3754
-                        'QST_ID'           => 0,
3755
-                        'QST_display_text' => esc_html__('State/Province', 'event_espresso'),
3756
-                        'QST_system'       => 'admin-state',
3757
-                    )
3758
-                ),
3759
-                EE_Answer::new_instance(
3760
-                    array(
3761
-                        'ANS_ID'    => 0,
3762
-                        'ANS_value' => $this->_cpt_model_obj->state_ID(),
3763
-                    )
3764
-                ),
3765
-                array(
3766
-                    'input_id'       => 'STA_ID',
3767
-                    'input_name'     => 'STA_ID',
3768
-                    'input_prefix'   => '',
3769
-                    'append_qstn_id' => false,
3770
-                )
3771
-            )
3772
-        );
3773
-        $this->_template_args['country_html'] = EEH_Form_Fields::generate_form_input(
3774
-            new EE_Question_Form_Input(
3775
-                EE_Question::new_instance(
3776
-                    array(
3777
-                        'QST_ID'           => 0,
3778
-                        'QST_display_text' => esc_html__('Country', 'event_espresso'),
3779
-                        'QST_system'       => 'admin-country',
3780
-                    )
3781
-                ),
3782
-                EE_Answer::new_instance(
3783
-                    array(
3784
-                        'ANS_ID'    => 0,
3785
-                        'ANS_value' => $this->_cpt_model_obj->country_ID(),
3786
-                    )
3787
-                ),
3788
-                array(
3789
-                    'input_id'       => 'CNT_ISO',
3790
-                    'input_name'     => 'CNT_ISO',
3791
-                    'input_prefix'   => '',
3792
-                    'append_qstn_id' => false,
3793
-                )
3794
-            )
3795
-        );
3796
-        $template =
3797
-            REG_TEMPLATE_PATH . 'attendee_address_details_metabox_content.template.php';
3798
-        EEH_Template::display_template($template, $this->_template_args);
3799
-    }
3800
-
3801
-
3802
-    /**
3803
-     *        _attendee_details
3804
-     *
3805
-     * @access protected
3806
-     * @param $post
3807
-     * @return void
3808
-     * @throws DomainException
3809
-     * @throws EE_Error
3810
-     */
3811
-    public function attendee_registrations_meta_box($post)
3812
-    {
3813
-        $this->_template_args['attendee'] = $this->_cpt_model_obj;
3814
-        $this->_template_args['registrations'] = $this->_cpt_model_obj->get_many_related('Registration');
3815
-        $template =
3816
-            REG_TEMPLATE_PATH . 'attendee_registrations_main_meta_box.template.php';
3817
-        EEH_Template::display_template($template, $this->_template_args);
3818
-    }
3819
-
3820
-
3821
-    /**
3822
-     * add in the form fields for the attendee edit
3823
-     *
3824
-     * @param  WP_Post $post wp post object
3825
-     * @return string html for new form.
3826
-     * @throws DomainException
3827
-     */
3828
-    public function after_title_form_fields($post)
3829
-    {
3830
-        if ($post->post_type == 'espresso_attendees') {
3831
-            $template = REG_TEMPLATE_PATH . 'attendee_details_after_title_form_fields.template.php';
3832
-            $template_args['attendee'] = $this->_cpt_model_obj;
3833
-            EEH_Template::display_template($template, $template_args);
3834
-        }
3835
-    }
3836
-
3837
-
3838
-    /**
3839
-     *        _trash_or_restore_attendee
3840
-     *
3841
-     * @param boolean $trash - whether to move item to trash (TRUE) or restore it (FALSE)
3842
-     * @return void
3843
-     * @throws EE_Error
3844
-     * @throws InvalidArgumentException
3845
-     * @throws InvalidDataTypeException
3846
-     * @throws InvalidInterfaceException
3847
-     * @access protected
3848
-     */
3849
-    protected function _trash_or_restore_attendees($trash = true)
3850
-    {
3851
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3852
-        $ATT_MDL = EEM_Attendee::instance();
3853
-        $success = 1;
3854
-        // Checkboxes
3855
-        if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3856
-            // if array has more than one element than success message should be plural
3857
-            $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
3858
-            // cycle thru checkboxes
3859
-            while (list($ATT_ID, $value) = each($this->_req_data['checkbox'])) {
3860
-                $updated = $trash ? $ATT_MDL->update_by_ID(array('status' => 'trash'), $ATT_ID)
3861
-                    : $ATT_MDL->update_by_ID(array('status' => 'publish'), $ATT_ID);
3862
-                if (! $updated) {
3863
-                    $success = 0;
3864
-                }
3865
-            }
3866
-        } else {
3867
-            // grab single id and delete
3868
-            $ATT_ID = absint($this->_req_data['ATT_ID']);
3869
-            // get attendee
3870
-            $att = $ATT_MDL->get_one_by_ID($ATT_ID);
3871
-            $updated = $trash ? $att->set_status('trash') : $att->set_status('publish');
3872
-            $updated = $att->save();
3873
-            if (! $updated) {
3874
-                $success = 0;
3875
-            }
3876
-        }
3877
-        $what = $success > 1
3878
-            ? esc_html__('Contacts', 'event_espresso')
3879
-            : esc_html__('Contact', 'event_espresso');
3880
-        $action_desc = $trash
3881
-            ? esc_html__('moved to the trash', 'event_espresso')
3882
-            : esc_html__('restored', 'event_espresso');
3883
-        $this->_redirect_after_action($success, $what, $action_desc, array('action' => 'contact_list'));
3884
-    }
3034
+		}
3035
+		$template_args = array(
3036
+			'title'                    => '',
3037
+			'content'                  => '',
3038
+			'step_button_text'         => '',
3039
+			'show_notification_toggle' => false,
3040
+		);
3041
+		// to indicate we're processing a new registration
3042
+		$hidden_fields = array(
3043
+			'processing_registration' => array(
3044
+				'type'  => 'hidden',
3045
+				'value' => 0,
3046
+			),
3047
+			'event_id'                => array(
3048
+				'type'  => 'hidden',
3049
+				'value' => $this->_reg_event->ID(),
3050
+			),
3051
+		);
3052
+		// if the cart is empty then we know we're at step one so we'll display ticket selector
3053
+		$cart = EE_Registry::instance()->SSN->cart();
3054
+		$step = ! $cart instanceof EE_Cart ? 'ticket' : 'questions';
3055
+		switch ($step) {
3056
+			case 'ticket':
3057
+				$hidden_fields['processing_registration']['value'] = 1;
3058
+				$template_args['title'] = esc_html__(
3059
+					'Step One: Select the Ticket for this registration',
3060
+					'event_espresso'
3061
+				);
3062
+				$template_args['content'] =
3063
+					EED_Ticket_Selector::instance()->display_ticket_selector($this->_reg_event);
3064
+				$template_args['step_button_text'] = esc_html__(
3065
+					'Add Tickets and Continue to Registrant Details',
3066
+					'event_espresso'
3067
+				);
3068
+				$template_args['show_notification_toggle'] = false;
3069
+				break;
3070
+			case 'questions':
3071
+				$hidden_fields['processing_registration']['value'] = 2;
3072
+				$template_args['title'] = esc_html__(
3073
+					'Step Two: Add Registrant Details for this Registration',
3074
+					'event_espresso'
3075
+				);
3076
+				// in theory we should be able to run EED_SPCO at this point because the cart should have been setup
3077
+				// properly by the first process_reg_step run.
3078
+				$template_args['content'] =
3079
+					EED_Single_Page_Checkout::registration_checkout_for_admin();
3080
+				$template_args['step_button_text'] = esc_html__(
3081
+					'Save Registration and Continue to Details',
3082
+					'event_espresso'
3083
+				);
3084
+				$template_args['show_notification_toggle'] = true;
3085
+				break;
3086
+		}
3087
+		// we come back to the process_registration_step route.
3088
+		$this->_set_add_edit_form_tags('process_reg_step', $hidden_fields);
3089
+		return EEH_Template::display_template(
3090
+			REG_TEMPLATE_PATH . 'reg_admin_register_new_attendee_step_content.template.php',
3091
+			$template_args,
3092
+			true
3093
+		);
3094
+	}
3095
+
3096
+
3097
+	/**
3098
+	 *        set_reg_event
3099
+	 *
3100
+	 * @access private
3101
+	 * @return bool
3102
+	 * @throws EE_Error
3103
+	 * @throws InvalidArgumentException
3104
+	 * @throws InvalidDataTypeException
3105
+	 * @throws InvalidInterfaceException
3106
+	 */
3107
+	private function _set_reg_event()
3108
+	{
3109
+		if (is_object($this->_reg_event)) {
3110
+			return true;
3111
+		}
3112
+		$EVT_ID = (! empty($this->_req_data['event_id'])) ? absint($this->_req_data['event_id']) : false;
3113
+		if (! $EVT_ID) {
3114
+			return false;
3115
+		}
3116
+		$this->_reg_event = EEM_Event::instance()->get_one_by_ID($EVT_ID);
3117
+		return true;
3118
+	}
3119
+
3120
+
3121
+	/**
3122
+	 * process_reg_step
3123
+	 *
3124
+	 * @access        public
3125
+	 * @return string
3126
+	 * @throws DomainException
3127
+	 * @throws EE_Error
3128
+	 * @throws InvalidArgumentException
3129
+	 * @throws InvalidDataTypeException
3130
+	 * @throws InvalidInterfaceException
3131
+	 * @throws ReflectionException
3132
+	 * @throws RuntimeException
3133
+	 */
3134
+	public function process_reg_step()
3135
+	{
3136
+		EE_System::do_not_cache();
3137
+		$this->_set_reg_event();
3138
+		EE_Registry::instance()->REQ->set_espresso_page(true);
3139
+		EE_Registry::instance()->REQ->set('uts', time());
3140
+		// what step are we on?
3141
+		$cart = EE_Registry::instance()->SSN->cart();
3142
+		$step = ! $cart instanceof EE_Cart ? 'ticket' : 'questions';
3143
+		// if doing ajax then we need to verify the nonce
3144
+		if (defined('DOING_AJAX')) {
3145
+			$nonce = isset($this->_req_data[ $this->_req_nonce ])
3146
+				? sanitize_text_field($this->_req_data[ $this->_req_nonce ]) : '';
3147
+			$this->_verify_nonce($nonce, $this->_req_nonce);
3148
+		}
3149
+		switch ($step) {
3150
+			case 'ticket':
3151
+				// process ticket selection
3152
+				$success = EED_Ticket_Selector::instance()->process_ticket_selections();
3153
+				if ($success) {
3154
+					EE_Error::add_success(
3155
+						esc_html__(
3156
+							'Tickets Selected. Now complete the registration.',
3157
+							'event_espresso'
3158
+						)
3159
+					);
3160
+				} else {
3161
+					$query_args['step_error'] = $this->_req_data['step_error'] = true;
3162
+				}
3163
+				if (defined('DOING_AJAX')) {
3164
+					$this->new_registration(); // display next step
3165
+				} else {
3166
+					$query_args = array(
3167
+						'action'                  => 'new_registration',
3168
+						'processing_registration' => 1,
3169
+						'event_id'                => $this->_reg_event->ID(),
3170
+						'uts'                     => time(),
3171
+					);
3172
+					$this->_redirect_after_action(
3173
+						false,
3174
+						'',
3175
+						'',
3176
+						$query_args,
3177
+						true
3178
+					);
3179
+				}
3180
+				break;
3181
+			case 'questions':
3182
+				if (! isset(
3183
+					$this->_req_data['txn_reg_status_change'],
3184
+					$this->_req_data['txn_reg_status_change']['send_notifications']
3185
+				)
3186
+				) {
3187
+					add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_false', 15);
3188
+				}
3189
+				// process registration
3190
+				$transaction = EED_Single_Page_Checkout::instance()->process_registration_from_admin();
3191
+				if ($cart instanceof EE_Cart) {
3192
+					$grand_total = $cart->get_cart_grand_total();
3193
+					if ($grand_total instanceof EE_Line_Item) {
3194
+						$grand_total->save_this_and_descendants_to_txn();
3195
+					}
3196
+				}
3197
+				if (! $transaction instanceof EE_Transaction) {
3198
+					$query_args = array(
3199
+						'action'                  => 'new_registration',
3200
+						'processing_registration' => 2,
3201
+						'event_id'                => $this->_reg_event->ID(),
3202
+						'uts'                     => time(),
3203
+					);
3204
+					if (defined('DOING_AJAX')) {
3205
+						// display registration form again because there are errors (maybe validation?)
3206
+						$this->new_registration();
3207
+						return;
3208
+					} else {
3209
+						$this->_redirect_after_action(
3210
+							false,
3211
+							'',
3212
+							'',
3213
+							$query_args,
3214
+							true
3215
+						);
3216
+						return;
3217
+					}
3218
+				}
3219
+				// maybe update status, and make sure to save transaction if not done already
3220
+				if (! $transaction->update_status_based_on_total_paid()) {
3221
+					$transaction->save();
3222
+				}
3223
+				EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
3224
+				$this->_req_data = array();
3225
+				$query_args = array(
3226
+					'action'        => 'redirect_to_txn',
3227
+					'TXN_ID'        => $transaction->ID(),
3228
+					'EVT_ID'        => $this->_reg_event->ID(),
3229
+					'event_name'    => urlencode($this->_reg_event->name()),
3230
+					'redirect_from' => 'new_registration',
3231
+				);
3232
+				$this->_redirect_after_action(false, '', '', $query_args, true);
3233
+				break;
3234
+		}
3235
+		// what are you looking here for?  Should be nothing to do at this point.
3236
+	}
3237
+
3238
+
3239
+	/**
3240
+	 * redirect_to_txn
3241
+	 *
3242
+	 * @access public
3243
+	 * @return void
3244
+	 * @throws EE_Error
3245
+	 * @throws InvalidArgumentException
3246
+	 * @throws InvalidDataTypeException
3247
+	 * @throws InvalidInterfaceException
3248
+	 */
3249
+	public function redirect_to_txn()
3250
+	{
3251
+		EE_System::do_not_cache();
3252
+		EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
3253
+		$query_args = array(
3254
+			'action' => 'view_transaction',
3255
+			'TXN_ID' => isset($this->_req_data['TXN_ID']) ? absint($this->_req_data['TXN_ID']) : 0,
3256
+			'page'   => 'espresso_transactions',
3257
+		);
3258
+		if (isset($this->_req_data['EVT_ID'], $this->_req_data['redirect_from'])) {
3259
+			$query_args['EVT_ID'] = $this->_req_data['EVT_ID'];
3260
+			$query_args['event_name'] = urlencode($this->_req_data['event_name']);
3261
+			$query_args['redirect_from'] = $this->_req_data['redirect_from'];
3262
+		}
3263
+		EE_Error::add_success(
3264
+			esc_html__(
3265
+				'Registration Created.  Please review the transaction and add any payments as necessary',
3266
+				'event_espresso'
3267
+			)
3268
+		);
3269
+		$this->_redirect_after_action(false, '', '', $query_args, true);
3270
+	}
3271
+
3272
+
3273
+	/**
3274
+	 *        generates HTML for the Attendee Contact List
3275
+	 *
3276
+	 * @access protected
3277
+	 * @return void
3278
+	 */
3279
+	protected function _attendee_contact_list_table()
3280
+	{
3281
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3282
+		$this->_search_btn_label = esc_html__('Contacts', 'event_espresso');
3283
+		$this->display_admin_list_table_page_with_no_sidebar();
3284
+	}
3285
+
3286
+
3287
+	/**
3288
+	 *        get_attendees
3289
+	 *
3290
+	 * @param      $per_page
3291
+	 * @param bool $count whether to return count or data.
3292
+	 * @param bool $trash
3293
+	 * @return array
3294
+	 * @throws EE_Error
3295
+	 * @throws InvalidArgumentException
3296
+	 * @throws InvalidDataTypeException
3297
+	 * @throws InvalidInterfaceException
3298
+	 * @access public
3299
+	 */
3300
+	public function get_attendees($per_page, $count = false, $trash = false)
3301
+	{
3302
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3303
+		require_once(REG_ADMIN . 'EE_Attendee_Contact_List_Table.class.php');
3304
+		$ATT_MDL = EEM_Attendee::instance();
3305
+		$this->_req_data['orderby'] = ! empty($this->_req_data['orderby']) ? $this->_req_data['orderby'] : '';
3306
+		switch ($this->_req_data['orderby']) {
3307
+			case 'ATT_ID':
3308
+				$orderby = 'ATT_ID';
3309
+				break;
3310
+			case 'ATT_fname':
3311
+				$orderby = 'ATT_fname';
3312
+				break;
3313
+			case 'ATT_email':
3314
+				$orderby = 'ATT_email';
3315
+				break;
3316
+			case 'ATT_city':
3317
+				$orderby = 'ATT_city';
3318
+				break;
3319
+			case 'STA_ID':
3320
+				$orderby = 'STA_ID';
3321
+				break;
3322
+			case 'CNT_ID':
3323
+				$orderby = 'CNT_ID';
3324
+				break;
3325
+			case 'Registration_Count':
3326
+				$orderby = 'Registration_Count';
3327
+				break;
3328
+			default:
3329
+				$orderby = 'ATT_lname';
3330
+		}
3331
+		$sort = (isset($this->_req_data['order']) && ! empty($this->_req_data['order']))
3332
+			? $this->_req_data['order']
3333
+			: 'ASC';
3334
+		$current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
3335
+			? $this->_req_data['paged']
3336
+			: 1;
3337
+		$per_page = isset($per_page) && ! empty($per_page) ? $per_page : 10;
3338
+		$per_page = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
3339
+			? $this->_req_data['perpage']
3340
+			: $per_page;
3341
+		$_where = array();
3342
+		if (! empty($this->_req_data['s'])) {
3343
+			$sstr = '%' . $this->_req_data['s'] . '%';
3344
+			$_where['OR'] = array(
3345
+				'Registration.Event.EVT_name'       => array('LIKE', $sstr),
3346
+				'Registration.Event.EVT_desc'       => array('LIKE', $sstr),
3347
+				'Registration.Event.EVT_short_desc' => array('LIKE', $sstr),
3348
+				'ATT_fname'                         => array('LIKE', $sstr),
3349
+				'ATT_lname'                         => array('LIKE', $sstr),
3350
+				'ATT_short_bio'                     => array('LIKE', $sstr),
3351
+				'ATT_email'                         => array('LIKE', $sstr),
3352
+				'ATT_address'                       => array('LIKE', $sstr),
3353
+				'ATT_address2'                      => array('LIKE', $sstr),
3354
+				'ATT_city'                          => array('LIKE', $sstr),
3355
+				'Country.CNT_name'                  => array('LIKE', $sstr),
3356
+				'State.STA_name'                    => array('LIKE', $sstr),
3357
+				'ATT_phone'                         => array('LIKE', $sstr),
3358
+				'Registration.REG_final_price'      => array('LIKE', $sstr),
3359
+				'Registration.REG_code'             => array('LIKE', $sstr),
3360
+				'Registration.REG_group_size'       => array('LIKE', $sstr),
3361
+			);
3362
+		}
3363
+		$offset = ($current_page - 1) * $per_page;
3364
+		$limit = $count ? null : array($offset, $per_page);
3365
+		$query_args = array(
3366
+			$_where,
3367
+			'extra_selects' => array('Registration_Count' => array('Registration.REG_ID', 'count', '%d')),
3368
+			'limit'         => $limit,
3369
+		);
3370
+		if (! $count) {
3371
+			$query_args['order_by'] = array($orderby => $sort);
3372
+		}
3373
+		if ($trash) {
3374
+			$query_args[0]['status'] = array('!=', 'publish');
3375
+			$all_attendees = $count
3376
+				? $ATT_MDL->count($query_args, 'ATT_ID', true)
3377
+				: $ATT_MDL->get_all($query_args);
3378
+		} else {
3379
+			$query_args[0]['status'] = array('IN', array('publish'));
3380
+			$all_attendees = $count
3381
+				? $ATT_MDL->count($query_args, 'ATT_ID', true)
3382
+				: $ATT_MDL->get_all($query_args);
3383
+		}
3384
+		return $all_attendees;
3385
+	}
3386
+
3387
+
3388
+	/**
3389
+	 * This is just taking care of resending the registration confirmation
3390
+	 *
3391
+	 * @access protected
3392
+	 * @return void
3393
+	 */
3394
+	protected function _resend_registration()
3395
+	{
3396
+		$this->_process_resend_registration();
3397
+		$query_args = isset($this->_req_data['redirect_to'])
3398
+			? array('action' => $this->_req_data['redirect_to'], '_REG_ID' => $this->_req_data['_REG_ID'])
3399
+			: array('action' => 'default');
3400
+		$this->_redirect_after_action(false, '', '', $query_args, true);
3401
+	}
3402
+
3403
+	/**
3404
+	 * Creates a registration report, but accepts the name of a method to use for preparing the query parameters
3405
+	 * to use when selecting registrations
3406
+	 *
3407
+	 * @param string $method_name_for_getting_query_params the name of the method (on this class) to use for preparing
3408
+	 *                                                     the query parameters from the request
3409
+	 * @return void ends the request with a redirect or download
3410
+	 */
3411
+	public function _registrations_report_base($method_name_for_getting_query_params)
3412
+	{
3413
+		if (! defined('EE_USE_OLD_CSV_REPORT_CLASS')) {
3414
+			wp_redirect(
3415
+				EE_Admin_Page::add_query_args_and_nonce(
3416
+					array(
3417
+						'page'        => 'espresso_batch',
3418
+						'batch'       => 'file',
3419
+						'EVT_ID'      => isset($this->_req_data['EVT_ID']) ? $this->_req_data['EVT_ID'] : null,
3420
+						'filters'     => urlencode(
3421
+							serialize(
3422
+								call_user_func(
3423
+									array($this, $method_name_for_getting_query_params),
3424
+									EEH_Array::is_set(
3425
+										$this->_req_data,
3426
+										'filters',
3427
+										array()
3428
+									)
3429
+								)
3430
+							)
3431
+						),
3432
+						'use_filters' => EEH_Array::is_set($this->_req_data, 'use_filters', false),
3433
+						'job_handler' => urlencode('EventEspressoBatchRequest\JobHandlers\RegistrationsReport'),
3434
+						'return_url'  => urlencode($this->_req_data['return_url']),
3435
+					)
3436
+				)
3437
+			);
3438
+		} else {
3439
+			$new_request_args = array(
3440
+				'export' => 'report',
3441
+				'action' => 'registrations_report_for_event',
3442
+				'EVT_ID' => isset($this->_req_data['EVT_ID']) ? $this->_req_data['EVT_ID'] : null,
3443
+			);
3444
+			$this->_req_data = array_merge($this->_req_data, $new_request_args);
3445
+			if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
3446
+				require_once(EE_CLASSES . 'EE_Export.class.php');
3447
+				$EE_Export = EE_Export::instance($this->_req_data);
3448
+				$EE_Export->export();
3449
+			}
3450
+		}
3451
+	}
3452
+
3453
+
3454
+	/**
3455
+	 * Creates a registration report using only query parameters in the request
3456
+	 *
3457
+	 * @return void
3458
+	 */
3459
+	public function _registrations_report()
3460
+	{
3461
+		$this->_registrations_report_base('_get_registration_query_parameters');
3462
+	}
3463
+
3464
+
3465
+	public function _contact_list_export()
3466
+	{
3467
+		if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
3468
+			require_once(EE_CLASSES . 'EE_Export.class.php');
3469
+			$EE_Export = EE_Export::instance($this->_req_data);
3470
+			$EE_Export->export_attendees();
3471
+		}
3472
+	}
3473
+
3474
+
3475
+	public function _contact_list_report()
3476
+	{
3477
+		if (! defined('EE_USE_OLD_CSV_REPORT_CLASS')) {
3478
+			wp_redirect(
3479
+				EE_Admin_Page::add_query_args_and_nonce(
3480
+					array(
3481
+						'page'        => 'espresso_batch',
3482
+						'batch'       => 'file',
3483
+						'job_handler' => urlencode('EventEspressoBatchRequest\JobHandlers\AttendeesReport'),
3484
+						'return_url'  => urlencode($this->_req_data['return_url']),
3485
+					)
3486
+				)
3487
+			);
3488
+		} else {
3489
+			if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
3490
+				require_once(EE_CLASSES . 'EE_Export.class.php');
3491
+				$EE_Export = EE_Export::instance($this->_req_data);
3492
+				$EE_Export->report_attendees();
3493
+			}
3494
+		}
3495
+	}
3496
+
3497
+
3498
+
3499
+
3500
+
3501
+	/***************************************        ATTENDEE DETAILS        ***************************************/
3502
+	/**
3503
+	 * This duplicates the attendee object for the given incoming registration id and attendee_id.
3504
+	 *
3505
+	 * @return void
3506
+	 * @throws EE_Error
3507
+	 * @throws InvalidArgumentException
3508
+	 * @throws InvalidDataTypeException
3509
+	 * @throws InvalidInterfaceException
3510
+	 */
3511
+	protected function _duplicate_attendee()
3512
+	{
3513
+		$action = ! empty($this->_req_data['return']) ? $this->_req_data['return'] : 'default';
3514
+		// verify we have necessary info
3515
+		if (empty($this->_req_data['_REG_ID'])) {
3516
+			EE_Error::add_error(
3517
+				esc_html__(
3518
+					'Unable to create the contact for the registration because the required parameters are not present (_REG_ID )',
3519
+					'event_espresso'
3520
+				),
3521
+				__FILE__,
3522
+				__LINE__,
3523
+				__FUNCTION__
3524
+			);
3525
+			$query_args = array('action' => $action);
3526
+			$this->_redirect_after_action('', '', '', $query_args, true);
3527
+		}
3528
+		// okay necessary deets present... let's dupe the incoming attendee and attach to incoming registration.
3529
+		$registration = EEM_Registration::instance()->get_one_by_ID($this->_req_data['_REG_ID']);
3530
+		$attendee = $registration->attendee();
3531
+		// remove relation of existing attendee on registration
3532
+		$registration->_remove_relation_to($attendee, 'Attendee');
3533
+		// new attendee
3534
+		$new_attendee = clone $attendee;
3535
+		$new_attendee->set('ATT_ID', 0);
3536
+		$new_attendee->save();
3537
+		// add new attendee to reg
3538
+		$registration->_add_relation_to($new_attendee, 'Attendee');
3539
+		EE_Error::add_success(
3540
+			esc_html__(
3541
+				'New Contact record created.  Now make any edits you wish to make for this contact.',
3542
+				'event_espresso'
3543
+			)
3544
+		);
3545
+		// redirect to edit page for attendee
3546
+		$query_args = array('post' => $new_attendee->ID(), 'action' => 'edit_attendee');
3547
+		$this->_redirect_after_action('', '', '', $query_args, true);
3548
+	}
3549
+
3550
+
3551
+	/**
3552
+	 * Callback invoked by parent EE_Admin_CPT class hooked in on `save_post` wp hook.
3553
+	 *
3554
+	 * @param int     $post_id
3555
+	 * @param WP_POST $post
3556
+	 * @throws DomainException
3557
+	 * @throws EE_Error
3558
+	 * @throws InvalidArgumentException
3559
+	 * @throws InvalidDataTypeException
3560
+	 * @throws InvalidInterfaceException
3561
+	 * @throws LogicException
3562
+	 * @throws InvalidFormSubmissionException
3563
+	 */
3564
+	protected function _insert_update_cpt_item($post_id, $post)
3565
+	{
3566
+		$success = true;
3567
+		$attendee = $post instanceof WP_Post && $post->post_type === 'espresso_attendees'
3568
+			? EEM_Attendee::instance()->get_one_by_ID($post_id)
3569
+			: null;
3570
+		// for attendee updates
3571
+		if ($attendee instanceof EE_Attendee) {
3572
+			// note we should only be UPDATING attendees at this point.
3573
+			$updated_fields = array(
3574
+				'ATT_fname'     => $this->_req_data['ATT_fname'],
3575
+				'ATT_lname'     => $this->_req_data['ATT_lname'],
3576
+				'ATT_full_name' => $this->_req_data['ATT_fname'] . ' ' . $this->_req_data['ATT_lname'],
3577
+				'ATT_address'   => isset($this->_req_data['ATT_address']) ? $this->_req_data['ATT_address'] : '',
3578
+				'ATT_address2'  => isset($this->_req_data['ATT_address2']) ? $this->_req_data['ATT_address2'] : '',
3579
+				'ATT_city'      => isset($this->_req_data['ATT_city']) ? $this->_req_data['ATT_city'] : '',
3580
+				'STA_ID'        => isset($this->_req_data['STA_ID']) ? $this->_req_data['STA_ID'] : '',
3581
+				'CNT_ISO'       => isset($this->_req_data['CNT_ISO']) ? $this->_req_data['CNT_ISO'] : '',
3582
+				'ATT_zip'       => isset($this->_req_data['ATT_zip']) ? $this->_req_data['ATT_zip'] : '',
3583
+			);
3584
+			foreach ($updated_fields as $field => $value) {
3585
+				$attendee->set($field, $value);
3586
+			}
3587
+
3588
+			// process contact details metabox form handler (which will also save the attendee)
3589
+			$contact_details_form = $this->getAttendeeContactDetailsMetaboxFormHandler($attendee);
3590
+			$success = $contact_details_form->process($this->_req_data);
3591
+
3592
+			$attendee_update_callbacks = apply_filters(
3593
+				'FHEE__Registrations_Admin_Page__insert_update_cpt_item__attendee_update',
3594
+				array()
3595
+			);
3596
+			foreach ($attendee_update_callbacks as $a_callback) {
3597
+				if (false === call_user_func_array($a_callback, array($attendee, $this->_req_data))) {
3598
+					throw new EE_Error(
3599
+						sprintf(
3600
+							esc_html__(
3601
+								'The %s callback given for the "FHEE__Registrations_Admin_Page__insert_update_cpt_item__attendee_update" filter is not a valid callback.  Please check the spelling.',
3602
+								'event_espresso'
3603
+							),
3604
+							$a_callback
3605
+						)
3606
+					);
3607
+				}
3608
+			}
3609
+		}
3610
+
3611
+		if ($success === false) {
3612
+			EE_Error::add_error(
3613
+				esc_html__(
3614
+					'Something went wrong with updating the meta table data for the registration.',
3615
+					'event_espresso'
3616
+				),
3617
+				__FILE__,
3618
+				__FUNCTION__,
3619
+				__LINE__
3620
+			);
3621
+		}
3622
+	}
3623
+
3624
+
3625
+	public function trash_cpt_item($post_id)
3626
+	{
3627
+	}
3628
+
3629
+
3630
+	public function delete_cpt_item($post_id)
3631
+	{
3632
+	}
3633
+
3634
+
3635
+	public function restore_cpt_item($post_id)
3636
+	{
3637
+	}
3638
+
3639
+
3640
+	protected function _restore_cpt_item($post_id, $revision_id)
3641
+	{
3642
+	}
3643
+
3644
+
3645
+	public function attendee_editor_metaboxes()
3646
+	{
3647
+		$this->verify_cpt_object();
3648
+		remove_meta_box(
3649
+			'postexcerpt',
3650
+			esc_html__('Excerpt', 'event_espresso'),
3651
+			'post_excerpt_meta_box',
3652
+			$this->_cpt_routes[ $this->_req_action ],
3653
+			'normal',
3654
+			'core'
3655
+		);
3656
+		remove_meta_box('commentstatusdiv', $this->_cpt_routes[ $this->_req_action ], 'normal', 'core');
3657
+		if (post_type_supports('espresso_attendees', 'excerpt')) {
3658
+			add_meta_box(
3659
+				'postexcerpt',
3660
+				esc_html__('Short Biography', 'event_espresso'),
3661
+				'post_excerpt_meta_box',
3662
+				$this->_cpt_routes[ $this->_req_action ],
3663
+				'normal'
3664
+			);
3665
+		}
3666
+		if (post_type_supports('espresso_attendees', 'comments')) {
3667
+			add_meta_box(
3668
+				'commentsdiv',
3669
+				esc_html__('Notes on the Contact', 'event_espresso'),
3670
+				'post_comment_meta_box',
3671
+				$this->_cpt_routes[ $this->_req_action ],
3672
+				'normal',
3673
+				'core'
3674
+			);
3675
+		}
3676
+		add_meta_box(
3677
+			'attendee_contact_info',
3678
+			esc_html__('Contact Info', 'event_espresso'),
3679
+			array($this, 'attendee_contact_info'),
3680
+			$this->_cpt_routes[ $this->_req_action ],
3681
+			'side',
3682
+			'core'
3683
+		);
3684
+		add_meta_box(
3685
+			'attendee_details_address',
3686
+			esc_html__('Address Details', 'event_espresso'),
3687
+			array($this, 'attendee_address_details'),
3688
+			$this->_cpt_routes[ $this->_req_action ],
3689
+			'normal',
3690
+			'core'
3691
+		);
3692
+		add_meta_box(
3693
+			'attendee_registrations',
3694
+			esc_html__('Registrations for this Contact', 'event_espresso'),
3695
+			array($this, 'attendee_registrations_meta_box'),
3696
+			$this->_cpt_routes[ $this->_req_action ],
3697
+			'normal',
3698
+			'high'
3699
+		);
3700
+	}
3701
+
3702
+
3703
+	/**
3704
+	 * Metabox for attendee contact info
3705
+	 *
3706
+	 * @param  WP_Post $post wp post object
3707
+	 * @return string attendee contact info ( and form )
3708
+	 * @throws EE_Error
3709
+	 * @throws InvalidArgumentException
3710
+	 * @throws InvalidDataTypeException
3711
+	 * @throws InvalidInterfaceException
3712
+	 * @throws LogicException
3713
+	 * @throws DomainException
3714
+	 */
3715
+	public function attendee_contact_info($post)
3716
+	{
3717
+		// get attendee object ( should already have it )
3718
+		$form = $this->getAttendeeContactDetailsMetaboxFormHandler($this->_cpt_model_obj);
3719
+		$form->enqueueStylesAndScripts();
3720
+		echo $form->display();
3721
+	}
3722
+
3723
+
3724
+	/**
3725
+	 * Return form handler for the contact details metabox
3726
+	 *
3727
+	 * @param EE_Attendee $attendee
3728
+	 * @return AttendeeContactDetailsMetaboxFormHandler
3729
+	 * @throws DomainException
3730
+	 * @throws InvalidArgumentException
3731
+	 * @throws InvalidDataTypeException
3732
+	 * @throws InvalidInterfaceException
3733
+	 */
3734
+	protected function getAttendeeContactDetailsMetaboxFormHandler(EE_Attendee $attendee)
3735
+	{
3736
+		return new AttendeeContactDetailsMetaboxFormHandler($attendee, EE_Registry::instance());
3737
+	}
3738
+
3739
+
3740
+	/**
3741
+	 * Metabox for attendee details
3742
+	 *
3743
+	 * @param  WP_Post $post wp post object
3744
+	 * @throws DomainException
3745
+	 */
3746
+	public function attendee_address_details($post)
3747
+	{
3748
+		// get attendee object (should already have it)
3749
+		$this->_template_args['attendee'] = $this->_cpt_model_obj;
3750
+		$this->_template_args['state_html'] = EEH_Form_Fields::generate_form_input(
3751
+			new EE_Question_Form_Input(
3752
+				EE_Question::new_instance(
3753
+					array(
3754
+						'QST_ID'           => 0,
3755
+						'QST_display_text' => esc_html__('State/Province', 'event_espresso'),
3756
+						'QST_system'       => 'admin-state',
3757
+					)
3758
+				),
3759
+				EE_Answer::new_instance(
3760
+					array(
3761
+						'ANS_ID'    => 0,
3762
+						'ANS_value' => $this->_cpt_model_obj->state_ID(),
3763
+					)
3764
+				),
3765
+				array(
3766
+					'input_id'       => 'STA_ID',
3767
+					'input_name'     => 'STA_ID',
3768
+					'input_prefix'   => '',
3769
+					'append_qstn_id' => false,
3770
+				)
3771
+			)
3772
+		);
3773
+		$this->_template_args['country_html'] = EEH_Form_Fields::generate_form_input(
3774
+			new EE_Question_Form_Input(
3775
+				EE_Question::new_instance(
3776
+					array(
3777
+						'QST_ID'           => 0,
3778
+						'QST_display_text' => esc_html__('Country', 'event_espresso'),
3779
+						'QST_system'       => 'admin-country',
3780
+					)
3781
+				),
3782
+				EE_Answer::new_instance(
3783
+					array(
3784
+						'ANS_ID'    => 0,
3785
+						'ANS_value' => $this->_cpt_model_obj->country_ID(),
3786
+					)
3787
+				),
3788
+				array(
3789
+					'input_id'       => 'CNT_ISO',
3790
+					'input_name'     => 'CNT_ISO',
3791
+					'input_prefix'   => '',
3792
+					'append_qstn_id' => false,
3793
+				)
3794
+			)
3795
+		);
3796
+		$template =
3797
+			REG_TEMPLATE_PATH . 'attendee_address_details_metabox_content.template.php';
3798
+		EEH_Template::display_template($template, $this->_template_args);
3799
+	}
3800
+
3801
+
3802
+	/**
3803
+	 *        _attendee_details
3804
+	 *
3805
+	 * @access protected
3806
+	 * @param $post
3807
+	 * @return void
3808
+	 * @throws DomainException
3809
+	 * @throws EE_Error
3810
+	 */
3811
+	public function attendee_registrations_meta_box($post)
3812
+	{
3813
+		$this->_template_args['attendee'] = $this->_cpt_model_obj;
3814
+		$this->_template_args['registrations'] = $this->_cpt_model_obj->get_many_related('Registration');
3815
+		$template =
3816
+			REG_TEMPLATE_PATH . 'attendee_registrations_main_meta_box.template.php';
3817
+		EEH_Template::display_template($template, $this->_template_args);
3818
+	}
3819
+
3820
+
3821
+	/**
3822
+	 * add in the form fields for the attendee edit
3823
+	 *
3824
+	 * @param  WP_Post $post wp post object
3825
+	 * @return string html for new form.
3826
+	 * @throws DomainException
3827
+	 */
3828
+	public function after_title_form_fields($post)
3829
+	{
3830
+		if ($post->post_type == 'espresso_attendees') {
3831
+			$template = REG_TEMPLATE_PATH . 'attendee_details_after_title_form_fields.template.php';
3832
+			$template_args['attendee'] = $this->_cpt_model_obj;
3833
+			EEH_Template::display_template($template, $template_args);
3834
+		}
3835
+	}
3836
+
3837
+
3838
+	/**
3839
+	 *        _trash_or_restore_attendee
3840
+	 *
3841
+	 * @param boolean $trash - whether to move item to trash (TRUE) or restore it (FALSE)
3842
+	 * @return void
3843
+	 * @throws EE_Error
3844
+	 * @throws InvalidArgumentException
3845
+	 * @throws InvalidDataTypeException
3846
+	 * @throws InvalidInterfaceException
3847
+	 * @access protected
3848
+	 */
3849
+	protected function _trash_or_restore_attendees($trash = true)
3850
+	{
3851
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3852
+		$ATT_MDL = EEM_Attendee::instance();
3853
+		$success = 1;
3854
+		// Checkboxes
3855
+		if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3856
+			// if array has more than one element than success message should be plural
3857
+			$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
3858
+			// cycle thru checkboxes
3859
+			while (list($ATT_ID, $value) = each($this->_req_data['checkbox'])) {
3860
+				$updated = $trash ? $ATT_MDL->update_by_ID(array('status' => 'trash'), $ATT_ID)
3861
+					: $ATT_MDL->update_by_ID(array('status' => 'publish'), $ATT_ID);
3862
+				if (! $updated) {
3863
+					$success = 0;
3864
+				}
3865
+			}
3866
+		} else {
3867
+			// grab single id and delete
3868
+			$ATT_ID = absint($this->_req_data['ATT_ID']);
3869
+			// get attendee
3870
+			$att = $ATT_MDL->get_one_by_ID($ATT_ID);
3871
+			$updated = $trash ? $att->set_status('trash') : $att->set_status('publish');
3872
+			$updated = $att->save();
3873
+			if (! $updated) {
3874
+				$success = 0;
3875
+			}
3876
+		}
3877
+		$what = $success > 1
3878
+			? esc_html__('Contacts', 'event_espresso')
3879
+			: esc_html__('Contact', 'event_espresso');
3880
+		$action_desc = $trash
3881
+			? esc_html__('moved to the trash', 'event_espresso')
3882
+			: esc_html__('restored', 'event_espresso');
3883
+		$this->_redirect_after_action($success, $what, $action_desc, array('action' => 'contact_list'));
3884
+	}
3885 3885
 }
Please login to merge, or discard this patch.
core/libraries/form_sections/inputs/EE_File_Input.input.php 1 patch
Indentation   +75 added lines, -75 removed lines patch added patch discarded remove patch
@@ -19,86 +19,86 @@
 block discarded – undo
19 19
  */
20 20
 class EE_File_Input extends EE_Form_Input_Base
21 21
 {
22
-    /**
23
-     * @var array
24
-     */
25
-    protected $allowed_file_extensions;
22
+	/**
23
+	 * @var array
24
+	 */
25
+	protected $allowed_file_extensions;
26 26
 
27
-    /**
28
-     * @var array
29
-     */
30
-    protected $allowed_mime_types;
27
+	/**
28
+	 * @var array
29
+	 */
30
+	protected $allowed_mime_types;
31 31
 
32
-    /**
33
-     * @param array $options
34
-     * @throws InvalidArgumentException
35
-     */
36
-    public function __construct($options = array())
37
-    {
38
-        if (isset($options['allowed_file_extensions'])) {
39
-            $this->allowed_file_extensions = (array) $options['allowed_file_extensions'];
40
-        } else {
41
-            $this->allowed_file_extensions = ['csv'];
42
-        }
43
-        if (isset($options['allowed_mime_types'])) {
44
-            $this->allowed_mime_types = (array) $options['allowed_file_extensions'];
45
-        } else {
46
-            $this->allowed_mime_types = ['text/csv'];
47
-        }
32
+	/**
33
+	 * @param array $options
34
+	 * @throws InvalidArgumentException
35
+	 */
36
+	public function __construct($options = array())
37
+	{
38
+		if (isset($options['allowed_file_extensions'])) {
39
+			$this->allowed_file_extensions = (array) $options['allowed_file_extensions'];
40
+		} else {
41
+			$this->allowed_file_extensions = ['csv'];
42
+		}
43
+		if (isset($options['allowed_mime_types'])) {
44
+			$this->allowed_mime_types = (array) $options['allowed_file_extensions'];
45
+		} else {
46
+			$this->allowed_mime_types = ['text/csv'];
47
+		}
48 48
 
49
-        $this->_set_display_strategy(new EE_File_Input_Display_Strategy());
50
-        $this->_set_normalization_strategy(new EE_File_Normalization());
51
-        $this->add_validation_strategy(
52
-            new EE_Text_Validation_Strategy(
53
-                sprintf(
54
-                    // translators: %1$s is a list of allowed file extensions.
55
-                    esc_html__('Please provide a file of the requested filetype: %1$s', 'event_espresso'),
56
-                    implode(', ', $this->allowed_file_extensions)
57
-                ),
58
-                '~.*\.(' . implode('|', $this->allowed_file_extensions) . ')$~'
59
-            )
60
-        );
61
-        parent::__construct($options);
49
+		$this->_set_display_strategy(new EE_File_Input_Display_Strategy());
50
+		$this->_set_normalization_strategy(new EE_File_Normalization());
51
+		$this->add_validation_strategy(
52
+			new EE_Text_Validation_Strategy(
53
+				sprintf(
54
+					// translators: %1$s is a list of allowed file extensions.
55
+					esc_html__('Please provide a file of the requested filetype: %1$s', 'event_espresso'),
56
+					implode(', ', $this->allowed_file_extensions)
57
+				),
58
+				'~.*\.(' . implode('|', $this->allowed_file_extensions) . ')$~'
59
+			)
60
+		);
61
+		parent::__construct($options);
62 62
 
63 63
 //        It would be great to add this HTML attribute, but jQuery validate chokes on it.
64
-        $this->set_other_html_attributes(
65
-            $this->other_html_attributes()
66
-            . ' extension="'
67
-            . implode(
68
-                ',',
69
-                $this->allowed_file_extensions
70
-            )
71
-            . '"'
72
-        );
73
-    }
64
+		$this->set_other_html_attributes(
65
+			$this->other_html_attributes()
66
+			. ' extension="'
67
+			. implode(
68
+				',',
69
+				$this->allowed_file_extensions
70
+			)
71
+			. '"'
72
+		);
73
+	}
74 74
 
75
-    /**
76
-     * $_FILES has a really weird structure. So we let `FilesDataHandler` take care of finding the file info for
77
-     * this input.
78
-     * @since 4.9.80.p
79
-     * @param array $req_data
80
-     * @return FileSubmissionInterface
81
-     * @throws InvalidArgumentException
82
-     * @throws InvalidDataTypeException
83
-     * @throws InvalidInterfaceException
84
-     */
85
-    public function find_form_data_for_this_section($req_data)
86
-    {
87
-        // ignore $req_data. Files are in the files data handler.
88
-        $fileDataHandler = LoaderFactory::getLoader()->getShared(
89
-            'EventEspresso\core\services\request\files\FilesDataHandler'
90
-        );
91
-        return $fileDataHandler->getFileObject($this->html_name());
92
-    }
75
+	/**
76
+	 * $_FILES has a really weird structure. So we let `FilesDataHandler` take care of finding the file info for
77
+	 * this input.
78
+	 * @since 4.9.80.p
79
+	 * @param array $req_data
80
+	 * @return FileSubmissionInterface
81
+	 * @throws InvalidArgumentException
82
+	 * @throws InvalidDataTypeException
83
+	 * @throws InvalidInterfaceException
84
+	 */
85
+	public function find_form_data_for_this_section($req_data)
86
+	{
87
+		// ignore $req_data. Files are in the files data handler.
88
+		$fileDataHandler = LoaderFactory::getLoader()->getShared(
89
+			'EventEspresso\core\services\request\files\FilesDataHandler'
90
+		);
91
+		return $fileDataHandler->getFileObject($this->html_name());
92
+	}
93 93
 
94
-    /**
95
-     * Don't transform the file submission object into a string, thanks.
96
-     *
97
-     * @param string $value
98
-     * @return null|string
99
-     */
100
-    protected function _sanitize($value)
101
-    {
102
-        return $value;
103
-    }
94
+	/**
95
+	 * Don't transform the file submission object into a string, thanks.
96
+	 *
97
+	 * @param string $value
98
+	 * @return null|string
99
+	 */
100
+	protected function _sanitize($value)
101
+	{
102
+		return $value;
103
+	}
104 104
 }
Please login to merge, or discard this patch.
core/libraries/form_sections/form_handlers/FormHandler.php 1 patch
Indentation   +635 added lines, -635 removed lines patch added patch discarded remove patch
@@ -29,639 +29,639 @@
 block discarded – undo
29 29
 abstract class FormHandler implements FormHandlerInterface
30 30
 {
31 31
 
32
-    /**
33
-     * will add opening and closing HTML form tags as well as a submit button
34
-     */
35
-    const ADD_FORM_TAGS_AND_SUBMIT = 'add_form_tags_and_submit';
36
-
37
-    /**
38
-     * will add opening and closing HTML form tags but NOT a submit button
39
-     */
40
-    const ADD_FORM_TAGS_ONLY = 'add_form_tags_only';
41
-
42
-    /**
43
-     * will NOT add opening and closing HTML form tags but will add a submit button
44
-     */
45
-    const ADD_FORM_SUBMIT_ONLY = 'add_form_submit_only';
46
-
47
-    /**
48
-     * will NOT add opening and closing HTML form tags NOR a submit button
49
-     */
50
-    const DO_NOT_SETUP_FORM = 'do_not_setup_form';
51
-
52
-    /**
53
-     * if set to false, then this form has no displayable content,
54
-     * and will only be used for processing data sent passed via GET or POST
55
-     * defaults to true ( ie: form has displayable content )
56
-     *
57
-     * @var boolean $displayable
58
-     */
59
-    private $displayable = true;
60
-
61
-    /**
62
-     * @var string $form_name
63
-     */
64
-    private $form_name;
65
-
66
-    /**
67
-     * @var string $admin_name
68
-     */
69
-    private $admin_name;
70
-
71
-    /**
72
-     * @var string $slug
73
-     */
74
-    private $slug;
75
-
76
-    /**
77
-     * @var string $submit_btn_text
78
-     */
79
-    private $submit_btn_text;
80
-
81
-    /**
82
-     * @var string $form_action
83
-     */
84
-    private $form_action;
85
-
86
-    /**
87
-     * form params in key value pairs
88
-     * can be added to form action URL or as hidden inputs
89
-     *
90
-     * @var array $form_args
91
-     */
92
-    private $form_args = array();
93
-
94
-    /**
95
-     * value of one of the string constant above
96
-     *
97
-     * @var string $form_config
98
-     */
99
-    private $form_config;
100
-
101
-    /**
102
-     * whether or not the form was determined to be invalid
103
-     *
104
-     * @var boolean $form_has_errors
105
-     */
106
-    private $form_has_errors;
107
-
108
-    /**
109
-     * the absolute top level form section being used on the page
110
-     *
111
-     * @var EE_Form_Section_Proper $form
112
-     */
113
-    private $form;
114
-
115
-    /**
116
-     * @var EE_Registry $registry
117
-     */
118
-    protected $registry;
119
-
120
-    // phpcs:disable PEAR.Functions.ValidDefaultValue.NotAtEnd
121
-    /**
122
-     * Form constructor.
123
-     *
124
-     * @param string      $form_name
125
-     * @param string      $admin_name
126
-     * @param string      $slug
127
-     * @param string      $form_action
128
-     * @param string      $form_config
129
-     * @param EE_Registry $registry
130
-     * @throws InvalidDataTypeException
131
-     * @throws DomainException
132
-     * @throws InvalidArgumentException
133
-     */
134
-    public function __construct(
135
-        $form_name,
136
-        $admin_name,
137
-        $slug,
138
-        $form_action = '',
139
-        $form_config = FormHandler::ADD_FORM_TAGS_AND_SUBMIT,
140
-        EE_Registry $registry
141
-    ) {
142
-        $this->setFormName($form_name);
143
-        $this->setAdminName($admin_name);
144
-        $this->setSlug($slug);
145
-        $this->setFormAction($form_action);
146
-        $this->setFormConfig($form_config);
147
-        $this->setSubmitBtnText(esc_html__('Submit', 'event_espresso'));
148
-        $this->registry = $registry;
149
-    }
150
-
151
-
152
-    /**
153
-     * @return array
154
-     */
155
-    public static function getFormConfigConstants()
156
-    {
157
-        return array(
158
-            FormHandler::ADD_FORM_TAGS_AND_SUBMIT,
159
-            FormHandler::ADD_FORM_TAGS_ONLY,
160
-            FormHandler::ADD_FORM_SUBMIT_ONLY,
161
-            FormHandler::DO_NOT_SETUP_FORM,
162
-        );
163
-    }
164
-
165
-
166
-    /**
167
-     * @param bool $for_display
168
-     * @return EE_Form_Section_Proper
169
-     * @throws EE_Error
170
-     * @throws LogicException
171
-     */
172
-    public function form($for_display = false)
173
-    {
174
-        if (! $this->formIsValid()) {
175
-            return null;
176
-        }
177
-        if ($for_display) {
178
-            $form_config = $this->formConfig();
179
-            if ($form_config === FormHandler::ADD_FORM_TAGS_AND_SUBMIT
180
-                || $form_config === FormHandler::ADD_FORM_SUBMIT_ONLY
181
-            ) {
182
-                $this->appendSubmitButton();
183
-                $this->clearFormButtonFloats();
184
-            }
185
-        }
186
-        return $this->form;
187
-    }
188
-
189
-
190
-    /**
191
-     * @return boolean
192
-     * @throws LogicException
193
-     */
194
-    public function formIsValid()
195
-    {
196
-        if ($this->form instanceof EE_Form_Section_Proper) {
197
-            return true;
198
-        }
199
-        $form = apply_filters(
200
-            'FHEE__EventEspresso_core_libraries_form_sections_form_handlers_FormHandler__formIsValid__generated_form_object',
201
-            $this->generate(),
202
-            $this
203
-        );
204
-        if ($this->verifyForm($form)) {
205
-            $this->setForm($form);
206
-        }
207
-        return true;
208
-    }
209
-
210
-
211
-    /**
212
-     * @param EE_Form_Section_Proper|null $form
213
-     * @return bool
214
-     * @throws LogicException
215
-     */
216
-    public function verifyForm(EE_Form_Section_Proper $form = null)
217
-    {
218
-        $form = $form !== null ? $form : $this->form;
219
-        if ($form instanceof EE_Form_Section_Proper) {
220
-            return true;
221
-        }
222
-        throw new LogicException(
223
-            sprintf(
224
-                esc_html__('The "%1$s" form is invalid or missing. %2$s', 'event_espresso'),
225
-                $this->form_name,
226
-                var_export($form, true)
227
-            )
228
-        );
229
-    }
230
-
231
-
232
-    /**
233
-     * @param EE_Form_Section_Proper $form
234
-     */
235
-    public function setForm(EE_Form_Section_Proper $form)
236
-    {
237
-        $this->form = $form;
238
-    }
239
-
240
-
241
-    /**
242
-     * @return boolean
243
-     */
244
-    public function displayable()
245
-    {
246
-        return $this->displayable;
247
-    }
248
-
249
-
250
-    /**
251
-     * @param boolean $displayable
252
-     */
253
-    public function setDisplayable($displayable = false)
254
-    {
255
-        $this->displayable = filter_var($displayable, FILTER_VALIDATE_BOOLEAN);
256
-    }
257
-
258
-
259
-    /**
260
-     * a public name for the form that can be displayed on the frontend of a site
261
-     *
262
-     * @return string
263
-     */
264
-    public function formName()
265
-    {
266
-        return $this->form_name;
267
-    }
268
-
269
-
270
-    /**
271
-     * @param string $form_name
272
-     * @throws InvalidDataTypeException
273
-     */
274
-    public function setFormName($form_name)
275
-    {
276
-        if (! is_string($form_name)) {
277
-            throw new InvalidDataTypeException('$form_name', $form_name, 'string');
278
-        }
279
-        $this->form_name = $form_name;
280
-    }
281
-
282
-
283
-    /**
284
-     * a public name for the form that can be displayed, but only in the admin
285
-     *
286
-     * @return string
287
-     */
288
-    public function adminName()
289
-    {
290
-        return $this->admin_name;
291
-    }
292
-
293
-
294
-    /**
295
-     * @param string $admin_name
296
-     * @throws InvalidDataTypeException
297
-     */
298
-    public function setAdminName($admin_name)
299
-    {
300
-        if (! is_string($admin_name)) {
301
-            throw new InvalidDataTypeException('$admin_name', $admin_name, 'string');
302
-        }
303
-        $this->admin_name = $admin_name;
304
-    }
305
-
306
-
307
-    /**
308
-     * a URL friendly string that can be used for identifying the form
309
-     *
310
-     * @return string
311
-     */
312
-    public function slug()
313
-    {
314
-        return $this->slug;
315
-    }
316
-
317
-
318
-    /**
319
-     * @param string $slug
320
-     * @throws InvalidDataTypeException
321
-     */
322
-    public function setSlug($slug)
323
-    {
324
-        if (! is_string($slug)) {
325
-            throw new InvalidDataTypeException('$slug', $slug, 'string');
326
-        }
327
-        $this->slug = $slug;
328
-    }
329
-
330
-
331
-    /**
332
-     * @return string
333
-     */
334
-    public function submitBtnText()
335
-    {
336
-        return $this->submit_btn_text;
337
-    }
338
-
339
-
340
-    /**
341
-     * @param string $submit_btn_text
342
-     * @throws InvalidDataTypeException
343
-     * @throws InvalidArgumentException
344
-     */
345
-    public function setSubmitBtnText($submit_btn_text)
346
-    {
347
-        if (! is_string($submit_btn_text)) {
348
-            throw new InvalidDataTypeException('$submit_btn_text', $submit_btn_text, 'string');
349
-        }
350
-        if (empty($submit_btn_text)) {
351
-            throw new InvalidArgumentException(
352
-                esc_html__('Can not set Submit button text because an empty string was provided.', 'event_espresso')
353
-            );
354
-        }
355
-        $this->submit_btn_text = $submit_btn_text;
356
-    }
357
-
358
-
359
-    /**
360
-     * @return string
361
-     */
362
-    public function formAction()
363
-    {
364
-        return ! empty($this->form_args)
365
-            ? add_query_arg($this->form_args, $this->form_action)
366
-            : $this->form_action;
367
-    }
368
-
369
-
370
-    /**
371
-     * @param string $form_action
372
-     * @throws InvalidDataTypeException
373
-     */
374
-    public function setFormAction($form_action)
375
-    {
376
-        if (! is_string($form_action)) {
377
-            throw new InvalidDataTypeException('$form_action', $form_action, 'string');
378
-        }
379
-        $this->form_action = $form_action;
380
-    }
381
-
382
-
383
-    /**
384
-     * @param array $form_args
385
-     * @throws InvalidDataTypeException
386
-     * @throws InvalidArgumentException
387
-     */
388
-    public function addFormActionArgs($form_args = array())
389
-    {
390
-        if (is_object($form_args)) {
391
-            throw new InvalidDataTypeException(
392
-                '$form_args',
393
-                $form_args,
394
-                'anything other than an object was expected.'
395
-            );
396
-        }
397
-        if (empty($form_args)) {
398
-            throw new InvalidArgumentException(
399
-                esc_html__('The redirect arguments can not be an empty array.', 'event_espresso')
400
-            );
401
-        }
402
-        $this->form_args = array_merge($this->form_args, $form_args);
403
-    }
404
-
405
-
406
-    /**
407
-     * @return string
408
-     */
409
-    public function formConfig()
410
-    {
411
-        return $this->form_config;
412
-    }
413
-
414
-
415
-    /**
416
-     * @param string $form_config
417
-     * @throws DomainException
418
-     */
419
-    public function setFormConfig($form_config)
420
-    {
421
-        if (! in_array(
422
-            $form_config,
423
-            array(
424
-                FormHandler::ADD_FORM_TAGS_AND_SUBMIT,
425
-                FormHandler::ADD_FORM_TAGS_ONLY,
426
-                FormHandler::ADD_FORM_SUBMIT_ONLY,
427
-                FormHandler::DO_NOT_SETUP_FORM,
428
-            ),
429
-            true
430
-        )
431
-        ) {
432
-            throw new DomainException(
433
-                sprintf(
434
-                    esc_html__(
435
-                        '"%1$s" is not a valid value for the form config. Please use one of the class constants on \EventEspresso\core\libraries\form_sections\form_handlers\Form',
436
-                        'event_espresso'
437
-                    ),
438
-                    $form_config
439
-                )
440
-            );
441
-        }
442
-        $this->form_config = $form_config;
443
-    }
444
-
445
-
446
-    /**
447
-     * called after the form is instantiated
448
-     * and used for performing any logic that needs to occur early
449
-     * before any of the other methods are called.
450
-     * returns true if everything is ok to proceed,
451
-     * and false if no further form logic should be implemented
452
-     *
453
-     * @return boolean
454
-     */
455
-    public function initialize()
456
-    {
457
-        $this->form_has_errors = EE_Error::has_error(true);
458
-        return true;
459
-    }
460
-
461
-
462
-    /**
463
-     * used for setting up css and js
464
-     *
465
-     * @return void
466
-     * @throws LogicException
467
-     * @throws EE_Error
468
-     */
469
-    public function enqueueStylesAndScripts()
470
-    {
471
-        $this->form()->enqueue_js();
472
-    }
473
-
474
-
475
-    /**
476
-     * creates and returns the actual form
477
-     *
478
-     * @return EE_Form_Section_Proper
479
-     */
480
-    abstract public function generate();
481
-
482
-
483
-    /**
484
-     * creates and returns an EE_Submit_Input labeled "Submit"
485
-     *
486
-     * @param string $text
487
-     * @return EE_Submit_Input
488
-     */
489
-    public function generateSubmitButton($text = '')
490
-    {
491
-        $text = ! empty($text) ? $text : $this->submitBtnText();
492
-        return new EE_Submit_Input(
493
-            array(
494
-                'html_name'             => 'ee-form-submit-' . $this->slug(),
495
-                'html_id'               => 'ee-form-submit-' . $this->slug(),
496
-                'html_class'            => 'ee-form-submit',
497
-                'html_label'            => '&nbsp;',
498
-                'other_html_attributes' => ' rel="' . $this->slug() . '"',
499
-                'default'               => $text,
500
-            )
501
-        );
502
-    }
503
-
504
-
505
-    /**
506
-     * calls generateSubmitButton() and appends it onto the form along with a float clearing div
507
-     *
508
-     * @param string $text
509
-     * @return void
510
-     * @throws EE_Error
511
-     */
512
-    public function appendSubmitButton($text = '')
513
-    {
514
-        if ($this->form->subsection_exists($this->slug() . '-submit-btn')) {
515
-            return;
516
-        }
517
-        $this->form->add_subsections(
518
-            array($this->slug() . '-submit-btn' => $this->generateSubmitButton($text)),
519
-            null,
520
-            false
521
-        );
522
-    }
523
-
524
-
525
-    /**
526
-     * creates and returns an EE_Submit_Input labeled "Cancel"
527
-     *
528
-     * @param string $text
529
-     * @return EE_Submit_Input
530
-     */
531
-    public function generateCancelButton($text = '')
532
-    {
533
-        $cancel_button = new EE_Submit_Input(
534
-            array(
535
-                'html_name'             => 'ee-form-submit-' . $this->slug(), // YES! Same name as submit !!!
536
-                'html_id'               => 'ee-cancel-form-' . $this->slug(),
537
-                'html_class'            => 'ee-cancel-form',
538
-                'html_label'            => '&nbsp;',
539
-                'other_html_attributes' => ' rel="' . $this->slug() . '"',
540
-                'default'               => ! empty($text) ? $text : esc_html__('Cancel', 'event_espresso'),
541
-            )
542
-        );
543
-        $cancel_button->set_button_css_attributes(false);
544
-        return $cancel_button;
545
-    }
546
-
547
-
548
-    /**
549
-     * appends a float clearing div onto end of form
550
-     *
551
-     * @return void
552
-     * @throws EE_Error
553
-     */
554
-    public function clearFormButtonFloats()
555
-    {
556
-        $this->form->add_subsections(
557
-            array(
558
-                'clear-submit-btn-float' => new EE_Form_Section_HTML(
559
-                    EEH_HTML::div('', '', 'clear-float') . EEH_HTML::divx()
560
-                ),
561
-            ),
562
-            null,
563
-            false
564
-        );
565
-    }
566
-
567
-
568
-    /**
569
-     * takes the generated form and displays it along with ony other non-form HTML that may be required
570
-     * returns a string of HTML that can be directly echoed in a template
571
-     *
572
-     * @return string
573
-     * @throws \InvalidArgumentException
574
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
575
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
576
-     * @throws LogicException
577
-     * @throws EE_Error
578
-     */
579
-    public function display()
580
-    {
581
-        $form_html = apply_filters(
582
-            'FHEE__EventEspresso_core_libraries_form_sections_form_handlers_FormHandler__display__before_form',
583
-            ''
584
-        );
585
-        $form_config = $this->formConfig();
586
-        if ($form_config === FormHandler::ADD_FORM_TAGS_AND_SUBMIT
587
-            || $form_config === FormHandler::ADD_FORM_TAGS_ONLY
588
-        ) {
589
-            $additional_props = $this->requiresMultipartEnctype()
590
-                ? 'enctype="multipart/form-data"'
591
-                : '';
592
-            $form_html .= $this->form()->form_open(
593
-                $this->formAction(),
594
-                'POST',
595
-                $additional_props
596
-            );
597
-        }
598
-        $form_html .= $this->form(true)->get_html();
599
-        if ($form_config === FormHandler::ADD_FORM_TAGS_AND_SUBMIT
600
-            || $form_config === FormHandler::ADD_FORM_TAGS_ONLY
601
-        ) {
602
-            $form_html .= $this->form()->form_close();
603
-        }
604
-        $form_html .= apply_filters(
605
-            'FHEE__EventEspresso_core_libraries_form_sections_form_handlers_FormHandler__display__after_form',
606
-            ''
607
-        );
608
-        return $form_html;
609
-    }
610
-
611
-    /**
612
-     * Determines if this form needs "enctype='multipart/form-data'" or not.
613
-     * @since 4.9.80.p
614
-     * @return bool
615
-     * @throws EE_Error
616
-     */
617
-    public function requiresMultipartEnctype()
618
-    {
619
-        foreach ($this->form()->inputs_in_subsections() as $input) {
620
-            if ($input instanceof EE_File_Input) {
621
-                return true;
622
-            }
623
-        }
624
-        return false;
625
-    }
626
-
627
-
628
-    /**
629
-     * handles processing the form submission
630
-     * returns true or false depending on whether the form was processed successfully or not
631
-     *
632
-     * @param array $submitted_form_data
633
-     * @return array
634
-     * @throws \InvalidArgumentException
635
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
636
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
637
-     * @throws EE_Error
638
-     * @throws LogicException
639
-     * @throws InvalidFormSubmissionException
640
-     */
641
-    public function process($submitted_form_data = array())
642
-    {
643
-        if (! $this->form()->was_submitted($submitted_form_data)) {
644
-            throw new InvalidFormSubmissionException($this->form_name);
645
-        }
646
-        $this->form(true)->receive_form_submission($submitted_form_data);
647
-        if (! $this->form()->is_valid()) {
648
-            throw new InvalidFormSubmissionException(
649
-                $this->form_name,
650
-                sprintf(
651
-                    esc_html__(
652
-                        'The "%1$s" form is invalid. Please correct the following errors and resubmit: %2$s %3$s',
653
-                        'event_espresso'
654
-                    ),
655
-                    $this->form_name,
656
-                    '<br />',
657
-                    implode('<br />', $this->form()->get_validation_errors_accumulated())
658
-                )
659
-            );
660
-        }
661
-        return apply_filters(
662
-            'FHEE__EventEspresso_core_libraries_form_sections_form_handlers_FormHandler__process__valid_data',
663
-            $this->form()->valid_data(),
664
-            $this
665
-        );
666
-    }
32
+	/**
33
+	 * will add opening and closing HTML form tags as well as a submit button
34
+	 */
35
+	const ADD_FORM_TAGS_AND_SUBMIT = 'add_form_tags_and_submit';
36
+
37
+	/**
38
+	 * will add opening and closing HTML form tags but NOT a submit button
39
+	 */
40
+	const ADD_FORM_TAGS_ONLY = 'add_form_tags_only';
41
+
42
+	/**
43
+	 * will NOT add opening and closing HTML form tags but will add a submit button
44
+	 */
45
+	const ADD_FORM_SUBMIT_ONLY = 'add_form_submit_only';
46
+
47
+	/**
48
+	 * will NOT add opening and closing HTML form tags NOR a submit button
49
+	 */
50
+	const DO_NOT_SETUP_FORM = 'do_not_setup_form';
51
+
52
+	/**
53
+	 * if set to false, then this form has no displayable content,
54
+	 * and will only be used for processing data sent passed via GET or POST
55
+	 * defaults to true ( ie: form has displayable content )
56
+	 *
57
+	 * @var boolean $displayable
58
+	 */
59
+	private $displayable = true;
60
+
61
+	/**
62
+	 * @var string $form_name
63
+	 */
64
+	private $form_name;
65
+
66
+	/**
67
+	 * @var string $admin_name
68
+	 */
69
+	private $admin_name;
70
+
71
+	/**
72
+	 * @var string $slug
73
+	 */
74
+	private $slug;
75
+
76
+	/**
77
+	 * @var string $submit_btn_text
78
+	 */
79
+	private $submit_btn_text;
80
+
81
+	/**
82
+	 * @var string $form_action
83
+	 */
84
+	private $form_action;
85
+
86
+	/**
87
+	 * form params in key value pairs
88
+	 * can be added to form action URL or as hidden inputs
89
+	 *
90
+	 * @var array $form_args
91
+	 */
92
+	private $form_args = array();
93
+
94
+	/**
95
+	 * value of one of the string constant above
96
+	 *
97
+	 * @var string $form_config
98
+	 */
99
+	private $form_config;
100
+
101
+	/**
102
+	 * whether or not the form was determined to be invalid
103
+	 *
104
+	 * @var boolean $form_has_errors
105
+	 */
106
+	private $form_has_errors;
107
+
108
+	/**
109
+	 * the absolute top level form section being used on the page
110
+	 *
111
+	 * @var EE_Form_Section_Proper $form
112
+	 */
113
+	private $form;
114
+
115
+	/**
116
+	 * @var EE_Registry $registry
117
+	 */
118
+	protected $registry;
119
+
120
+	// phpcs:disable PEAR.Functions.ValidDefaultValue.NotAtEnd
121
+	/**
122
+	 * Form constructor.
123
+	 *
124
+	 * @param string      $form_name
125
+	 * @param string      $admin_name
126
+	 * @param string      $slug
127
+	 * @param string      $form_action
128
+	 * @param string      $form_config
129
+	 * @param EE_Registry $registry
130
+	 * @throws InvalidDataTypeException
131
+	 * @throws DomainException
132
+	 * @throws InvalidArgumentException
133
+	 */
134
+	public function __construct(
135
+		$form_name,
136
+		$admin_name,
137
+		$slug,
138
+		$form_action = '',
139
+		$form_config = FormHandler::ADD_FORM_TAGS_AND_SUBMIT,
140
+		EE_Registry $registry
141
+	) {
142
+		$this->setFormName($form_name);
143
+		$this->setAdminName($admin_name);
144
+		$this->setSlug($slug);
145
+		$this->setFormAction($form_action);
146
+		$this->setFormConfig($form_config);
147
+		$this->setSubmitBtnText(esc_html__('Submit', 'event_espresso'));
148
+		$this->registry = $registry;
149
+	}
150
+
151
+
152
+	/**
153
+	 * @return array
154
+	 */
155
+	public static function getFormConfigConstants()
156
+	{
157
+		return array(
158
+			FormHandler::ADD_FORM_TAGS_AND_SUBMIT,
159
+			FormHandler::ADD_FORM_TAGS_ONLY,
160
+			FormHandler::ADD_FORM_SUBMIT_ONLY,
161
+			FormHandler::DO_NOT_SETUP_FORM,
162
+		);
163
+	}
164
+
165
+
166
+	/**
167
+	 * @param bool $for_display
168
+	 * @return EE_Form_Section_Proper
169
+	 * @throws EE_Error
170
+	 * @throws LogicException
171
+	 */
172
+	public function form($for_display = false)
173
+	{
174
+		if (! $this->formIsValid()) {
175
+			return null;
176
+		}
177
+		if ($for_display) {
178
+			$form_config = $this->formConfig();
179
+			if ($form_config === FormHandler::ADD_FORM_TAGS_AND_SUBMIT
180
+				|| $form_config === FormHandler::ADD_FORM_SUBMIT_ONLY
181
+			) {
182
+				$this->appendSubmitButton();
183
+				$this->clearFormButtonFloats();
184
+			}
185
+		}
186
+		return $this->form;
187
+	}
188
+
189
+
190
+	/**
191
+	 * @return boolean
192
+	 * @throws LogicException
193
+	 */
194
+	public function formIsValid()
195
+	{
196
+		if ($this->form instanceof EE_Form_Section_Proper) {
197
+			return true;
198
+		}
199
+		$form = apply_filters(
200
+			'FHEE__EventEspresso_core_libraries_form_sections_form_handlers_FormHandler__formIsValid__generated_form_object',
201
+			$this->generate(),
202
+			$this
203
+		);
204
+		if ($this->verifyForm($form)) {
205
+			$this->setForm($form);
206
+		}
207
+		return true;
208
+	}
209
+
210
+
211
+	/**
212
+	 * @param EE_Form_Section_Proper|null $form
213
+	 * @return bool
214
+	 * @throws LogicException
215
+	 */
216
+	public function verifyForm(EE_Form_Section_Proper $form = null)
217
+	{
218
+		$form = $form !== null ? $form : $this->form;
219
+		if ($form instanceof EE_Form_Section_Proper) {
220
+			return true;
221
+		}
222
+		throw new LogicException(
223
+			sprintf(
224
+				esc_html__('The "%1$s" form is invalid or missing. %2$s', 'event_espresso'),
225
+				$this->form_name,
226
+				var_export($form, true)
227
+			)
228
+		);
229
+	}
230
+
231
+
232
+	/**
233
+	 * @param EE_Form_Section_Proper $form
234
+	 */
235
+	public function setForm(EE_Form_Section_Proper $form)
236
+	{
237
+		$this->form = $form;
238
+	}
239
+
240
+
241
+	/**
242
+	 * @return boolean
243
+	 */
244
+	public function displayable()
245
+	{
246
+		return $this->displayable;
247
+	}
248
+
249
+
250
+	/**
251
+	 * @param boolean $displayable
252
+	 */
253
+	public function setDisplayable($displayable = false)
254
+	{
255
+		$this->displayable = filter_var($displayable, FILTER_VALIDATE_BOOLEAN);
256
+	}
257
+
258
+
259
+	/**
260
+	 * a public name for the form that can be displayed on the frontend of a site
261
+	 *
262
+	 * @return string
263
+	 */
264
+	public function formName()
265
+	{
266
+		return $this->form_name;
267
+	}
268
+
269
+
270
+	/**
271
+	 * @param string $form_name
272
+	 * @throws InvalidDataTypeException
273
+	 */
274
+	public function setFormName($form_name)
275
+	{
276
+		if (! is_string($form_name)) {
277
+			throw new InvalidDataTypeException('$form_name', $form_name, 'string');
278
+		}
279
+		$this->form_name = $form_name;
280
+	}
281
+
282
+
283
+	/**
284
+	 * a public name for the form that can be displayed, but only in the admin
285
+	 *
286
+	 * @return string
287
+	 */
288
+	public function adminName()
289
+	{
290
+		return $this->admin_name;
291
+	}
292
+
293
+
294
+	/**
295
+	 * @param string $admin_name
296
+	 * @throws InvalidDataTypeException
297
+	 */
298
+	public function setAdminName($admin_name)
299
+	{
300
+		if (! is_string($admin_name)) {
301
+			throw new InvalidDataTypeException('$admin_name', $admin_name, 'string');
302
+		}
303
+		$this->admin_name = $admin_name;
304
+	}
305
+
306
+
307
+	/**
308
+	 * a URL friendly string that can be used for identifying the form
309
+	 *
310
+	 * @return string
311
+	 */
312
+	public function slug()
313
+	{
314
+		return $this->slug;
315
+	}
316
+
317
+
318
+	/**
319
+	 * @param string $slug
320
+	 * @throws InvalidDataTypeException
321
+	 */
322
+	public function setSlug($slug)
323
+	{
324
+		if (! is_string($slug)) {
325
+			throw new InvalidDataTypeException('$slug', $slug, 'string');
326
+		}
327
+		$this->slug = $slug;
328
+	}
329
+
330
+
331
+	/**
332
+	 * @return string
333
+	 */
334
+	public function submitBtnText()
335
+	{
336
+		return $this->submit_btn_text;
337
+	}
338
+
339
+
340
+	/**
341
+	 * @param string $submit_btn_text
342
+	 * @throws InvalidDataTypeException
343
+	 * @throws InvalidArgumentException
344
+	 */
345
+	public function setSubmitBtnText($submit_btn_text)
346
+	{
347
+		if (! is_string($submit_btn_text)) {
348
+			throw new InvalidDataTypeException('$submit_btn_text', $submit_btn_text, 'string');
349
+		}
350
+		if (empty($submit_btn_text)) {
351
+			throw new InvalidArgumentException(
352
+				esc_html__('Can not set Submit button text because an empty string was provided.', 'event_espresso')
353
+			);
354
+		}
355
+		$this->submit_btn_text = $submit_btn_text;
356
+	}
357
+
358
+
359
+	/**
360
+	 * @return string
361
+	 */
362
+	public function formAction()
363
+	{
364
+		return ! empty($this->form_args)
365
+			? add_query_arg($this->form_args, $this->form_action)
366
+			: $this->form_action;
367
+	}
368
+
369
+
370
+	/**
371
+	 * @param string $form_action
372
+	 * @throws InvalidDataTypeException
373
+	 */
374
+	public function setFormAction($form_action)
375
+	{
376
+		if (! is_string($form_action)) {
377
+			throw new InvalidDataTypeException('$form_action', $form_action, 'string');
378
+		}
379
+		$this->form_action = $form_action;
380
+	}
381
+
382
+
383
+	/**
384
+	 * @param array $form_args
385
+	 * @throws InvalidDataTypeException
386
+	 * @throws InvalidArgumentException
387
+	 */
388
+	public function addFormActionArgs($form_args = array())
389
+	{
390
+		if (is_object($form_args)) {
391
+			throw new InvalidDataTypeException(
392
+				'$form_args',
393
+				$form_args,
394
+				'anything other than an object was expected.'
395
+			);
396
+		}
397
+		if (empty($form_args)) {
398
+			throw new InvalidArgumentException(
399
+				esc_html__('The redirect arguments can not be an empty array.', 'event_espresso')
400
+			);
401
+		}
402
+		$this->form_args = array_merge($this->form_args, $form_args);
403
+	}
404
+
405
+
406
+	/**
407
+	 * @return string
408
+	 */
409
+	public function formConfig()
410
+	{
411
+		return $this->form_config;
412
+	}
413
+
414
+
415
+	/**
416
+	 * @param string $form_config
417
+	 * @throws DomainException
418
+	 */
419
+	public function setFormConfig($form_config)
420
+	{
421
+		if (! in_array(
422
+			$form_config,
423
+			array(
424
+				FormHandler::ADD_FORM_TAGS_AND_SUBMIT,
425
+				FormHandler::ADD_FORM_TAGS_ONLY,
426
+				FormHandler::ADD_FORM_SUBMIT_ONLY,
427
+				FormHandler::DO_NOT_SETUP_FORM,
428
+			),
429
+			true
430
+		)
431
+		) {
432
+			throw new DomainException(
433
+				sprintf(
434
+					esc_html__(
435
+						'"%1$s" is not a valid value for the form config. Please use one of the class constants on \EventEspresso\core\libraries\form_sections\form_handlers\Form',
436
+						'event_espresso'
437
+					),
438
+					$form_config
439
+				)
440
+			);
441
+		}
442
+		$this->form_config = $form_config;
443
+	}
444
+
445
+
446
+	/**
447
+	 * called after the form is instantiated
448
+	 * and used for performing any logic that needs to occur early
449
+	 * before any of the other methods are called.
450
+	 * returns true if everything is ok to proceed,
451
+	 * and false if no further form logic should be implemented
452
+	 *
453
+	 * @return boolean
454
+	 */
455
+	public function initialize()
456
+	{
457
+		$this->form_has_errors = EE_Error::has_error(true);
458
+		return true;
459
+	}
460
+
461
+
462
+	/**
463
+	 * used for setting up css and js
464
+	 *
465
+	 * @return void
466
+	 * @throws LogicException
467
+	 * @throws EE_Error
468
+	 */
469
+	public function enqueueStylesAndScripts()
470
+	{
471
+		$this->form()->enqueue_js();
472
+	}
473
+
474
+
475
+	/**
476
+	 * creates and returns the actual form
477
+	 *
478
+	 * @return EE_Form_Section_Proper
479
+	 */
480
+	abstract public function generate();
481
+
482
+
483
+	/**
484
+	 * creates and returns an EE_Submit_Input labeled "Submit"
485
+	 *
486
+	 * @param string $text
487
+	 * @return EE_Submit_Input
488
+	 */
489
+	public function generateSubmitButton($text = '')
490
+	{
491
+		$text = ! empty($text) ? $text : $this->submitBtnText();
492
+		return new EE_Submit_Input(
493
+			array(
494
+				'html_name'             => 'ee-form-submit-' . $this->slug(),
495
+				'html_id'               => 'ee-form-submit-' . $this->slug(),
496
+				'html_class'            => 'ee-form-submit',
497
+				'html_label'            => '&nbsp;',
498
+				'other_html_attributes' => ' rel="' . $this->slug() . '"',
499
+				'default'               => $text,
500
+			)
501
+		);
502
+	}
503
+
504
+
505
+	/**
506
+	 * calls generateSubmitButton() and appends it onto the form along with a float clearing div
507
+	 *
508
+	 * @param string $text
509
+	 * @return void
510
+	 * @throws EE_Error
511
+	 */
512
+	public function appendSubmitButton($text = '')
513
+	{
514
+		if ($this->form->subsection_exists($this->slug() . '-submit-btn')) {
515
+			return;
516
+		}
517
+		$this->form->add_subsections(
518
+			array($this->slug() . '-submit-btn' => $this->generateSubmitButton($text)),
519
+			null,
520
+			false
521
+		);
522
+	}
523
+
524
+
525
+	/**
526
+	 * creates and returns an EE_Submit_Input labeled "Cancel"
527
+	 *
528
+	 * @param string $text
529
+	 * @return EE_Submit_Input
530
+	 */
531
+	public function generateCancelButton($text = '')
532
+	{
533
+		$cancel_button = new EE_Submit_Input(
534
+			array(
535
+				'html_name'             => 'ee-form-submit-' . $this->slug(), // YES! Same name as submit !!!
536
+				'html_id'               => 'ee-cancel-form-' . $this->slug(),
537
+				'html_class'            => 'ee-cancel-form',
538
+				'html_label'            => '&nbsp;',
539
+				'other_html_attributes' => ' rel="' . $this->slug() . '"',
540
+				'default'               => ! empty($text) ? $text : esc_html__('Cancel', 'event_espresso'),
541
+			)
542
+		);
543
+		$cancel_button->set_button_css_attributes(false);
544
+		return $cancel_button;
545
+	}
546
+
547
+
548
+	/**
549
+	 * appends a float clearing div onto end of form
550
+	 *
551
+	 * @return void
552
+	 * @throws EE_Error
553
+	 */
554
+	public function clearFormButtonFloats()
555
+	{
556
+		$this->form->add_subsections(
557
+			array(
558
+				'clear-submit-btn-float' => new EE_Form_Section_HTML(
559
+					EEH_HTML::div('', '', 'clear-float') . EEH_HTML::divx()
560
+				),
561
+			),
562
+			null,
563
+			false
564
+		);
565
+	}
566
+
567
+
568
+	/**
569
+	 * takes the generated form and displays it along with ony other non-form HTML that may be required
570
+	 * returns a string of HTML that can be directly echoed in a template
571
+	 *
572
+	 * @return string
573
+	 * @throws \InvalidArgumentException
574
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
575
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
576
+	 * @throws LogicException
577
+	 * @throws EE_Error
578
+	 */
579
+	public function display()
580
+	{
581
+		$form_html = apply_filters(
582
+			'FHEE__EventEspresso_core_libraries_form_sections_form_handlers_FormHandler__display__before_form',
583
+			''
584
+		);
585
+		$form_config = $this->formConfig();
586
+		if ($form_config === FormHandler::ADD_FORM_TAGS_AND_SUBMIT
587
+			|| $form_config === FormHandler::ADD_FORM_TAGS_ONLY
588
+		) {
589
+			$additional_props = $this->requiresMultipartEnctype()
590
+				? 'enctype="multipart/form-data"'
591
+				: '';
592
+			$form_html .= $this->form()->form_open(
593
+				$this->formAction(),
594
+				'POST',
595
+				$additional_props
596
+			);
597
+		}
598
+		$form_html .= $this->form(true)->get_html();
599
+		if ($form_config === FormHandler::ADD_FORM_TAGS_AND_SUBMIT
600
+			|| $form_config === FormHandler::ADD_FORM_TAGS_ONLY
601
+		) {
602
+			$form_html .= $this->form()->form_close();
603
+		}
604
+		$form_html .= apply_filters(
605
+			'FHEE__EventEspresso_core_libraries_form_sections_form_handlers_FormHandler__display__after_form',
606
+			''
607
+		);
608
+		return $form_html;
609
+	}
610
+
611
+	/**
612
+	 * Determines if this form needs "enctype='multipart/form-data'" or not.
613
+	 * @since 4.9.80.p
614
+	 * @return bool
615
+	 * @throws EE_Error
616
+	 */
617
+	public function requiresMultipartEnctype()
618
+	{
619
+		foreach ($this->form()->inputs_in_subsections() as $input) {
620
+			if ($input instanceof EE_File_Input) {
621
+				return true;
622
+			}
623
+		}
624
+		return false;
625
+	}
626
+
627
+
628
+	/**
629
+	 * handles processing the form submission
630
+	 * returns true or false depending on whether the form was processed successfully or not
631
+	 *
632
+	 * @param array $submitted_form_data
633
+	 * @return array
634
+	 * @throws \InvalidArgumentException
635
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
636
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
637
+	 * @throws EE_Error
638
+	 * @throws LogicException
639
+	 * @throws InvalidFormSubmissionException
640
+	 */
641
+	public function process($submitted_form_data = array())
642
+	{
643
+		if (! $this->form()->was_submitted($submitted_form_data)) {
644
+			throw new InvalidFormSubmissionException($this->form_name);
645
+		}
646
+		$this->form(true)->receive_form_submission($submitted_form_data);
647
+		if (! $this->form()->is_valid()) {
648
+			throw new InvalidFormSubmissionException(
649
+				$this->form_name,
650
+				sprintf(
651
+					esc_html__(
652
+						'The "%1$s" form is invalid. Please correct the following errors and resubmit: %2$s %3$s',
653
+						'event_espresso'
654
+					),
655
+					$this->form_name,
656
+					'<br />',
657
+					implode('<br />', $this->form()->get_validation_errors_accumulated())
658
+				)
659
+			);
660
+		}
661
+		return apply_filters(
662
+			'FHEE__EventEspresso_core_libraries_form_sections_form_handlers_FormHandler__process__valid_data',
663
+			$this->form()->valid_data(),
664
+			$this
665
+		);
666
+	}
667 667
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Base_Class.class.php 1 patch
Indentation   +3330 added lines, -3330 removed lines patch added patch discarded remove patch
@@ -13,3345 +13,3345 @@
 block discarded – undo
13 13
 abstract class EE_Base_Class
14 14
 {
15 15
 
16
-    /**
17
-     * This is an array of the original properties and values provided during construction
18
-     * of this model object. (keys are model field names, values are their values).
19
-     * This list is important to remember so that when we are merging data from the db, we know
20
-     * which values to override and which to not override.
21
-     *
22
-     * @var array
23
-     */
24
-    protected $_props_n_values_provided_in_constructor;
25
-
26
-    /**
27
-     * Timezone
28
-     * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
29
-     * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
30
-     * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
31
-     * access to it.
32
-     *
33
-     * @var string
34
-     */
35
-    protected $_timezone;
36
-
37
-    /**
38
-     * date format
39
-     * pattern or format for displaying dates
40
-     *
41
-     * @var string $_dt_frmt
42
-     */
43
-    protected $_dt_frmt;
44
-
45
-    /**
46
-     * time format
47
-     * pattern or format for displaying time
48
-     *
49
-     * @var string $_tm_frmt
50
-     */
51
-    protected $_tm_frmt;
52
-
53
-    /**
54
-     * This property is for holding a cached array of object properties indexed by property name as the key.
55
-     * The purpose of this is for setting a cache on properties that may have calculated values after a
56
-     * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
57
-     * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
58
-     *
59
-     * @var array
60
-     */
61
-    protected $_cached_properties = array();
62
-
63
-    /**
64
-     * An array containing keys of the related model, and values are either an array of related mode objects or a
65
-     * single
66
-     * related model object. see the model's _model_relations. The keys should match those specified. And if the
67
-     * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
68
-     * all others have an array)
69
-     *
70
-     * @var array
71
-     */
72
-    protected $_model_relations = array();
73
-
74
-    /**
75
-     * Array where keys are field names (see the model's _fields property) and values are their values. To see what
76
-     * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
77
-     *
78
-     * @var array
79
-     */
80
-    protected $_fields = array();
81
-
82
-    /**
83
-     * @var boolean indicating whether or not this model object is intended to ever be saved
84
-     * For example, we might create model objects intended to only be used for the duration
85
-     * of this request and to be thrown away, and if they were accidentally saved
86
-     * it would be a bug.
87
-     */
88
-    protected $_allow_persist = true;
89
-
90
-    /**
91
-     * @var boolean indicating whether or not this model object's properties have changed since construction
92
-     */
93
-    protected $_has_changes = false;
94
-
95
-    /**
96
-     * @var EEM_Base
97
-     */
98
-    protected $_model;
99
-
100
-    /**
101
-     * This is a cache of results from custom selections done on a query that constructs this entity. The only purpose
102
-     * for these values is for retrieval of the results, they are not further queryable and they are not persisted to
103
-     * the db.  They also do not automatically update if there are any changes to the data that produced their results.
104
-     * The format is a simple array of field_alias => field_value.  So for instance if a custom select was something
105
-     * like,  "Select COUNT(Registration.REG_ID) as Registration_Count ...", then the resulting value will be in this
106
-     * array as:
107
-     * array(
108
-     *  'Registration_Count' => 24
109
-     * );
110
-     * Note: if the custom select configuration for the query included a data type, the value will be in the data type
111
-     * provided for the query (@see EventEspresso\core\domain\values\model\CustomSelects::__construct phpdocs for more
112
-     * info)
113
-     *
114
-     * @var array
115
-     */
116
-    protected $custom_selection_results = array();
117
-
118
-
119
-    /**
120
-     * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
121
-     * play nice
122
-     *
123
-     * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
124
-     *                                                         layer of the model's _fields array, (eg, EVT_ID,
125
-     *                                                         TXN_amount, QST_name, etc) and values are their values
126
-     * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
127
-     *                                                         corresponding db model or not.
128
-     * @param string  $timezone                                indicate what timezone you want any datetime fields to
129
-     *                                                         be in when instantiating a EE_Base_Class object.
130
-     * @param array   $date_formats                            An array of date formats to set on construct where first
131
-     *                                                         value is the date_format and second value is the time
132
-     *                                                         format.
133
-     * @throws InvalidArgumentException
134
-     * @throws InvalidInterfaceException
135
-     * @throws InvalidDataTypeException
136
-     * @throws EE_Error
137
-     * @throws ReflectionException
138
-     */
139
-    protected function __construct($fieldValues = array(), $bydb = false, $timezone = '', $date_formats = array())
140
-    {
141
-        $className = get_class($this);
142
-        do_action("AHEE__{$className}__construct", $this, $fieldValues);
143
-        $model = $this->get_model();
144
-        $model_fields = $model->field_settings(false);
145
-        // ensure $fieldValues is an array
146
-        $fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
147
-        // verify client code has not passed any invalid field names
148
-        foreach ($fieldValues as $field_name => $field_value) {
149
-            if (! isset($model_fields[ $field_name ])) {
150
-                throw new EE_Error(
151
-                    sprintf(
152
-                        esc_html__(
153
-                            'Invalid field (%s) passed to constructor of %s. Allowed fields are :%s',
154
-                            'event_espresso'
155
-                        ),
156
-                        $field_name,
157
-                        get_class($this),
158
-                        implode(', ', array_keys($model_fields))
159
-                    )
160
-                );
161
-            }
162
-        }
163
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
164
-        if (! empty($date_formats) && is_array($date_formats)) {
165
-            list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
166
-        } else {
167
-            // set default formats for date and time
168
-            $this->_dt_frmt = (string) get_option('date_format', 'Y-m-d');
169
-            $this->_tm_frmt = (string) get_option('time_format', 'g:i a');
170
-        }
171
-        // if db model is instantiating
172
-        if ($bydb) {
173
-            // client code has indicated these field values are from the database
174
-            foreach ($model_fields as $fieldName => $field) {
175
-                $this->set_from_db(
176
-                    $fieldName,
177
-                    isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null
178
-                );
179
-            }
180
-        } else {
181
-            // we're constructing a brand
182
-            // new instance of the model object. Generally, this means we'll need to do more field validation
183
-            foreach ($model_fields as $fieldName => $field) {
184
-                $this->set(
185
-                    $fieldName,
186
-                    isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null,
187
-                    true
188
-                );
189
-            }
190
-        }
191
-        // remember what values were passed to this constructor
192
-        $this->_props_n_values_provided_in_constructor = $fieldValues;
193
-        // remember in entity mapper
194
-        if (! $bydb && $model->has_primary_key_field() && $this->ID()) {
195
-            $model->add_to_entity_map($this);
196
-        }
197
-        // setup all the relations
198
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
199
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
200
-                $this->_model_relations[ $relation_name ] = null;
201
-            } else {
202
-                $this->_model_relations[ $relation_name ] = array();
203
-            }
204
-        }
205
-        /**
206
-         * Action done at the end of each model object construction
207
-         *
208
-         * @param EE_Base_Class $this the model object just created
209
-         */
210
-        do_action('AHEE__EE_Base_Class__construct__finished', $this);
211
-    }
212
-
213
-
214
-    /**
215
-     * Gets whether or not this model object is allowed to persist/be saved to the database.
216
-     *
217
-     * @return boolean
218
-     */
219
-    public function allow_persist()
220
-    {
221
-        return $this->_allow_persist;
222
-    }
223
-
224
-
225
-    /**
226
-     * Sets whether or not this model object should be allowed to be saved to the DB.
227
-     * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
228
-     * you got new information that somehow made you change your mind.
229
-     *
230
-     * @param boolean $allow_persist
231
-     * @return boolean
232
-     */
233
-    public function set_allow_persist($allow_persist)
234
-    {
235
-        return $this->_allow_persist = $allow_persist;
236
-    }
237
-
238
-
239
-    /**
240
-     * Gets the field's original value when this object was constructed during this request.
241
-     * This can be helpful when determining if a model object has changed or not
242
-     *
243
-     * @param string $field_name
244
-     * @return mixed|null
245
-     * @throws ReflectionException
246
-     * @throws InvalidArgumentException
247
-     * @throws InvalidInterfaceException
248
-     * @throws InvalidDataTypeException
249
-     * @throws EE_Error
250
-     */
251
-    public function get_original($field_name)
252
-    {
253
-        if (isset($this->_props_n_values_provided_in_constructor[ $field_name ])
254
-            && $field_settings = $this->get_model()->field_settings_for($field_name)
255
-        ) {
256
-            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
257
-        }
258
-        return null;
259
-    }
260
-
261
-
262
-    /**
263
-     * @param EE_Base_Class $obj
264
-     * @return string
265
-     */
266
-    public function get_class($obj)
267
-    {
268
-        return get_class($obj);
269
-    }
270
-
271
-
272
-    /**
273
-     * Overrides parent because parent expects old models.
274
-     * This also doesn't do any validation, and won't work for serialized arrays
275
-     *
276
-     * @param    string $field_name
277
-     * @param    mixed  $field_value
278
-     * @param bool      $use_default
279
-     * @throws InvalidArgumentException
280
-     * @throws InvalidInterfaceException
281
-     * @throws InvalidDataTypeException
282
-     * @throws EE_Error
283
-     * @throws ReflectionException
284
-     * @throws ReflectionException
285
-     * @throws ReflectionException
286
-     */
287
-    public function set($field_name, $field_value, $use_default = false)
288
-    {
289
-        // if not using default and nothing has changed, and object has already been setup (has ID),
290
-        // then don't do anything
291
-        if (! $use_default
292
-            && $this->_fields[ $field_name ] === $field_value
293
-            && $this->ID()
294
-        ) {
295
-            return;
296
-        }
297
-        $model = $this->get_model();
298
-        $this->_has_changes = true;
299
-        $field_obj = $model->field_settings_for($field_name);
300
-        if ($field_obj instanceof EE_Model_Field_Base) {
301
-            // if ( method_exists( $field_obj, 'set_timezone' )) {
302
-            if ($field_obj instanceof EE_Datetime_Field) {
303
-                $field_obj->set_timezone($this->_timezone);
304
-                $field_obj->set_date_format($this->_dt_frmt);
305
-                $field_obj->set_time_format($this->_tm_frmt);
306
-            }
307
-            $holder_of_value = $field_obj->prepare_for_set($field_value);
308
-            // should the value be null?
309
-            if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
310
-                $this->_fields[ $field_name ] = $field_obj->get_default_value();
311
-                /**
312
-                 * To save having to refactor all the models, if a default value is used for a
313
-                 * EE_Datetime_Field, and that value is not null nor is it a DateTime
314
-                 * object.  Then let's do a set again to ensure that it becomes a DateTime
315
-                 * object.
316
-                 *
317
-                 * @since 4.6.10+
318
-                 */
319
-                if ($field_obj instanceof EE_Datetime_Field
320
-                    && $this->_fields[ $field_name ] !== null
321
-                    && ! $this->_fields[ $field_name ] instanceof DateTime
322
-                ) {
323
-                    empty($this->_fields[ $field_name ])
324
-                        ? $this->set($field_name, time())
325
-                        : $this->set($field_name, $this->_fields[ $field_name ]);
326
-                }
327
-            } else {
328
-                $this->_fields[ $field_name ] = $holder_of_value;
329
-            }
330
-            // if we're not in the constructor...
331
-            // now check if what we set was a primary key
332
-            if (// note: props_n_values_provided_in_constructor is only set at the END of the constructor
333
-                $this->_props_n_values_provided_in_constructor
334
-                && $field_value
335
-                && $field_name === $model->primary_key_name()
336
-            ) {
337
-                // if so, we want all this object's fields to be filled either with
338
-                // what we've explicitly set on this model
339
-                // or what we have in the db
340
-                // echo "setting primary key!";
341
-                $fields_on_model = self::_get_model(get_class($this))->field_settings();
342
-                $obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
343
-                foreach ($fields_on_model as $field_obj) {
344
-                    if (! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
345
-                        && $field_obj->get_name() !== $field_name
346
-                    ) {
347
-                        $this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
348
-                    }
349
-                }
350
-                // oh this model object has an ID? well make sure its in the entity mapper
351
-                $model->add_to_entity_map($this);
352
-            }
353
-            // let's unset any cache for this field_name from the $_cached_properties property.
354
-            $this->_clear_cached_property($field_name);
355
-        } else {
356
-            throw new EE_Error(
357
-                sprintf(
358
-                    esc_html__(
359
-                        'A valid EE_Model_Field_Base could not be found for the given field name: %s',
360
-                        'event_espresso'
361
-                    ),
362
-                    $field_name
363
-                )
364
-            );
365
-        }
366
-    }
367
-
368
-
369
-    /**
370
-     * Set custom select values for model.
371
-     *
372
-     * @param array $custom_select_values
373
-     */
374
-    public function setCustomSelectsValues(array $custom_select_values)
375
-    {
376
-        $this->custom_selection_results = $custom_select_values;
377
-    }
378
-
379
-
380
-    /**
381
-     * Returns the custom select value for the provided alias if its set.
382
-     * If not set, returns null.
383
-     *
384
-     * @param string $alias
385
-     * @return string|int|float|null
386
-     */
387
-    public function getCustomSelect($alias)
388
-    {
389
-        return isset($this->custom_selection_results[ $alias ])
390
-            ? $this->custom_selection_results[ $alias ]
391
-            : null;
392
-    }
393
-
394
-
395
-    /**
396
-     * This sets the field value on the db column if it exists for the given $column_name or
397
-     * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
398
-     *
399
-     * @see EE_message::get_column_value for related documentation on the necessity of this method.
400
-     * @param string $field_name  Must be the exact column name.
401
-     * @param mixed  $field_value The value to set.
402
-     * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
403
-     * @throws InvalidArgumentException
404
-     * @throws InvalidInterfaceException
405
-     * @throws InvalidDataTypeException
406
-     * @throws EE_Error
407
-     * @throws ReflectionException
408
-     */
409
-    public function set_field_or_extra_meta($field_name, $field_value)
410
-    {
411
-        if ($this->get_model()->has_field($field_name)) {
412
-            $this->set($field_name, $field_value);
413
-            return true;
414
-        }
415
-        // ensure this object is saved first so that extra meta can be properly related.
416
-        $this->save();
417
-        return $this->update_extra_meta($field_name, $field_value);
418
-    }
419
-
420
-
421
-    /**
422
-     * This retrieves the value of the db column set on this class or if that's not present
423
-     * it will attempt to retrieve from extra_meta if found.
424
-     * Example Usage:
425
-     * Via EE_Message child class:
426
-     * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
427
-     * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
428
-     * also have additional main fields specific to the messenger.  The system accommodates those extra
429
-     * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
430
-     * value for those extra fields dynamically via the EE_message object.
431
-     *
432
-     * @param  string $field_name expecting the fully qualified field name.
433
-     * @return mixed|null  value for the field if found.  null if not found.
434
-     * @throws ReflectionException
435
-     * @throws InvalidArgumentException
436
-     * @throws InvalidInterfaceException
437
-     * @throws InvalidDataTypeException
438
-     * @throws EE_Error
439
-     */
440
-    public function get_field_or_extra_meta($field_name)
441
-    {
442
-        if ($this->get_model()->has_field($field_name)) {
443
-            $column_value = $this->get($field_name);
444
-        } else {
445
-            // This isn't a column in the main table, let's see if it is in the extra meta.
446
-            $column_value = $this->get_extra_meta($field_name, true, null);
447
-        }
448
-        return $column_value;
449
-    }
450
-
451
-
452
-    /**
453
-     * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
454
-     * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
455
-     * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
456
-     * available to all child classes that may be using the EE_Datetime_Field for a field data type.
457
-     *
458
-     * @access public
459
-     * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
460
-     * @return void
461
-     * @throws InvalidArgumentException
462
-     * @throws InvalidInterfaceException
463
-     * @throws InvalidDataTypeException
464
-     * @throws EE_Error
465
-     * @throws ReflectionException
466
-     */
467
-    public function set_timezone($timezone = '')
468
-    {
469
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
470
-        // make sure we clear all cached properties because they won't be relevant now
471
-        $this->_clear_cached_properties();
472
-        // make sure we update field settings and the date for all EE_Datetime_Fields
473
-        $model_fields = $this->get_model()->field_settings(false);
474
-        foreach ($model_fields as $field_name => $field_obj) {
475
-            if ($field_obj instanceof EE_Datetime_Field) {
476
-                $field_obj->set_timezone($this->_timezone);
477
-                if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
478
-                    EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone));
479
-                }
480
-            }
481
-        }
482
-    }
483
-
484
-
485
-    /**
486
-     * This just returns whatever is set for the current timezone.
487
-     *
488
-     * @access public
489
-     * @return string timezone string
490
-     */
491
-    public function get_timezone()
492
-    {
493
-        return $this->_timezone;
494
-    }
495
-
496
-
497
-    /**
498
-     * This sets the internal date format to what is sent in to be used as the new default for the class
499
-     * internally instead of wp set date format options
500
-     *
501
-     * @since 4.6
502
-     * @param string $format should be a format recognizable by PHP date() functions.
503
-     */
504
-    public function set_date_format($format)
505
-    {
506
-        $this->_dt_frmt = $format;
507
-        // clear cached_properties because they won't be relevant now.
508
-        $this->_clear_cached_properties();
509
-    }
510
-
511
-
512
-    /**
513
-     * This sets the internal time format string to what is sent in to be used as the new default for the
514
-     * class internally instead of wp set time format options.
515
-     *
516
-     * @since 4.6
517
-     * @param string $format should be a format recognizable by PHP date() functions.
518
-     */
519
-    public function set_time_format($format)
520
-    {
521
-        $this->_tm_frmt = $format;
522
-        // clear cached_properties because they won't be relevant now.
523
-        $this->_clear_cached_properties();
524
-    }
525
-
526
-
527
-    /**
528
-     * This returns the current internal set format for the date and time formats.
529
-     *
530
-     * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
531
-     *                             where the first value is the date format and the second value is the time format.
532
-     * @return mixed string|array
533
-     */
534
-    public function get_format($full = true)
535
-    {
536
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
537
-    }
538
-
539
-
540
-    /**
541
-     * cache
542
-     * stores the passed model object on the current model object.
543
-     * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
544
-     *
545
-     * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
546
-     *                                       'Registration' associated with this model object
547
-     * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
548
-     *                                       that could be a payment or a registration)
549
-     * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
550
-     *                                       items which will be stored in an array on this object
551
-     * @throws ReflectionException
552
-     * @throws InvalidArgumentException
553
-     * @throws InvalidInterfaceException
554
-     * @throws InvalidDataTypeException
555
-     * @throws EE_Error
556
-     * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
557
-     *                                       related thing, no array)
558
-     */
559
-    public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
560
-    {
561
-        // its entirely possible that there IS no related object yet in which case there is nothing to cache.
562
-        if (! $object_to_cache instanceof EE_Base_Class) {
563
-            return false;
564
-        }
565
-        // also get "how" the object is related, or throw an error
566
-        if (! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
567
-            throw new EE_Error(
568
-                sprintf(
569
-                    esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
570
-                    $relationName,
571
-                    get_class($this)
572
-                )
573
-            );
574
-        }
575
-        // how many things are related ?
576
-        if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
577
-            // if it's a "belongs to" relationship, then there's only one related model object
578
-            // eg, if this is a registration, there's only 1 attendee for it
579
-            // so for these model objects just set it to be cached
580
-            $this->_model_relations[ $relationName ] = $object_to_cache;
581
-            $return = true;
582
-        } else {
583
-            // otherwise, this is the "many" side of a one to many relationship,
584
-            // so we'll add the object to the array of related objects for that type.
585
-            // eg: if this is an event, there are many registrations for that event,
586
-            // so we cache the registrations in an array
587
-            if (! is_array($this->_model_relations[ $relationName ])) {
588
-                // if for some reason, the cached item is a model object,
589
-                // then stick that in the array, otherwise start with an empty array
590
-                $this->_model_relations[ $relationName ] = $this->_model_relations[ $relationName ]
591
-                                                           instanceof
592
-                                                           EE_Base_Class
593
-                    ? array($this->_model_relations[ $relationName ]) : array();
594
-            }
595
-            // first check for a cache_id which is normally empty
596
-            if (! empty($cache_id)) {
597
-                // if the cache_id exists, then it means we are purposely trying to cache this
598
-                // with a known key that can then be used to retrieve the object later on
599
-                $this->_model_relations[ $relationName ][ $cache_id ] = $object_to_cache;
600
-                $return = $cache_id;
601
-            } elseif ($object_to_cache->ID()) {
602
-                // OR the cached object originally came from the db, so let's just use it's PK for an ID
603
-                $this->_model_relations[ $relationName ][ $object_to_cache->ID() ] = $object_to_cache;
604
-                $return = $object_to_cache->ID();
605
-            } else {
606
-                // OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
607
-                $this->_model_relations[ $relationName ][] = $object_to_cache;
608
-                // move the internal pointer to the end of the array
609
-                end($this->_model_relations[ $relationName ]);
610
-                // and grab the key so that we can return it
611
-                $return = key($this->_model_relations[ $relationName ]);
612
-            }
613
-        }
614
-        return $return;
615
-    }
616
-
617
-
618
-    /**
619
-     * For adding an item to the cached_properties property.
620
-     *
621
-     * @access protected
622
-     * @param string      $fieldname the property item the corresponding value is for.
623
-     * @param mixed       $value     The value we are caching.
624
-     * @param string|null $cache_type
625
-     * @return void
626
-     * @throws ReflectionException
627
-     * @throws InvalidArgumentException
628
-     * @throws InvalidInterfaceException
629
-     * @throws InvalidDataTypeException
630
-     * @throws EE_Error
631
-     */
632
-    protected function _set_cached_property($fieldname, $value, $cache_type = null)
633
-    {
634
-        // first make sure this property exists
635
-        $this->get_model()->field_settings_for($fieldname);
636
-        $cache_type = empty($cache_type) ? 'standard' : $cache_type;
637
-        $this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
638
-    }
639
-
640
-
641
-    /**
642
-     * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
643
-     * This also SETS the cache if we return the actual property!
644
-     *
645
-     * @param string $fieldname        the name of the property we're trying to retrieve
646
-     * @param bool   $pretty
647
-     * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
648
-     *                                 (in cases where the same property may be used for different outputs
649
-     *                                 - i.e. datetime, money etc.)
650
-     *                                 It can also accept certain pre-defined "schema" strings
651
-     *                                 to define how to output the property.
652
-     *                                 see the field's prepare_for_pretty_echoing for what strings can be used
653
-     * @return mixed                   whatever the value for the property is we're retrieving
654
-     * @throws ReflectionException
655
-     * @throws InvalidArgumentException
656
-     * @throws InvalidInterfaceException
657
-     * @throws InvalidDataTypeException
658
-     * @throws EE_Error
659
-     */
660
-    protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
661
-    {
662
-        // verify the field exists
663
-        $model = $this->get_model();
664
-        $model->field_settings_for($fieldname);
665
-        $cache_type = $pretty ? 'pretty' : 'standard';
666
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
667
-        if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
668
-            return $this->_cached_properties[ $fieldname ][ $cache_type ];
669
-        }
670
-        $value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
671
-        $this->_set_cached_property($fieldname, $value, $cache_type);
672
-        return $value;
673
-    }
674
-
675
-
676
-    /**
677
-     * If the cache didn't fetch the needed item, this fetches it.
678
-     *
679
-     * @param string $fieldname
680
-     * @param bool   $pretty
681
-     * @param string $extra_cache_ref
682
-     * @return mixed
683
-     * @throws InvalidArgumentException
684
-     * @throws InvalidInterfaceException
685
-     * @throws InvalidDataTypeException
686
-     * @throws EE_Error
687
-     * @throws ReflectionException
688
-     */
689
-    protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
690
-    {
691
-        $field_obj = $this->get_model()->field_settings_for($fieldname);
692
-        // If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
693
-        if ($field_obj instanceof EE_Datetime_Field) {
694
-            $this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
695
-        }
696
-        if (! isset($this->_fields[ $fieldname ])) {
697
-            $this->_fields[ $fieldname ] = null;
698
-        }
699
-        $value = $pretty
700
-            ? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
701
-            : $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
702
-        return $value;
703
-    }
704
-
705
-
706
-    /**
707
-     * set timezone, formats, and output for EE_Datetime_Field objects
708
-     *
709
-     * @param \EE_Datetime_Field $datetime_field
710
-     * @param bool               $pretty
711
-     * @param null               $date_or_time
712
-     * @return void
713
-     * @throws InvalidArgumentException
714
-     * @throws InvalidInterfaceException
715
-     * @throws InvalidDataTypeException
716
-     * @throws EE_Error
717
-     */
718
-    protected function _prepare_datetime_field(
719
-        EE_Datetime_Field $datetime_field,
720
-        $pretty = false,
721
-        $date_or_time = null
722
-    ) {
723
-        $datetime_field->set_timezone($this->_timezone);
724
-        $datetime_field->set_date_format($this->_dt_frmt, $pretty);
725
-        $datetime_field->set_time_format($this->_tm_frmt, $pretty);
726
-        // set the output returned
727
-        switch ($date_or_time) {
728
-            case 'D':
729
-                $datetime_field->set_date_time_output('date');
730
-                break;
731
-            case 'T':
732
-                $datetime_field->set_date_time_output('time');
733
-                break;
734
-            default:
735
-                $datetime_field->set_date_time_output();
736
-        }
737
-    }
738
-
739
-
740
-    /**
741
-     * This just takes care of clearing out the cached_properties
742
-     *
743
-     * @return void
744
-     */
745
-    protected function _clear_cached_properties()
746
-    {
747
-        $this->_cached_properties = array();
748
-    }
749
-
750
-
751
-    /**
752
-     * This just clears out ONE property if it exists in the cache
753
-     *
754
-     * @param  string $property_name the property to remove if it exists (from the _cached_properties array)
755
-     * @return void
756
-     */
757
-    protected function _clear_cached_property($property_name)
758
-    {
759
-        if (isset($this->_cached_properties[ $property_name ])) {
760
-            unset($this->_cached_properties[ $property_name ]);
761
-        }
762
-    }
763
-
764
-
765
-    /**
766
-     * Ensures that this related thing is a model object.
767
-     *
768
-     * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
769
-     * @param string $model_name   name of the related thing, eg 'Attendee',
770
-     * @return EE_Base_Class
771
-     * @throws ReflectionException
772
-     * @throws InvalidArgumentException
773
-     * @throws InvalidInterfaceException
774
-     * @throws InvalidDataTypeException
775
-     * @throws EE_Error
776
-     */
777
-    protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
778
-    {
779
-        $other_model_instance = self::_get_model_instance_with_name(
780
-            self::_get_model_classname($model_name),
781
-            $this->_timezone
782
-        );
783
-        return $other_model_instance->ensure_is_obj($object_or_id);
784
-    }
785
-
786
-
787
-    /**
788
-     * Forgets the cached model of the given relation Name. So the next time we request it,
789
-     * we will fetch it again from the database. (Handy if you know it's changed somehow).
790
-     * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
791
-     * then only remove that one object from our cached array. Otherwise, clear the entire list
792
-     *
793
-     * @param string $relationName                         one of the keys in the _model_relations array on the model.
794
-     *                                                     Eg 'Registration'
795
-     * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
796
-     *                                                     if you intend to use $clear_all = TRUE, or the relation only
797
-     *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
798
-     * @param bool   $clear_all                            This flags clearing the entire cache relation property if
799
-     *                                                     this is HasMany or HABTM.
800
-     * @throws ReflectionException
801
-     * @throws InvalidArgumentException
802
-     * @throws InvalidInterfaceException
803
-     * @throws InvalidDataTypeException
804
-     * @throws EE_Error
805
-     * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
806
-     *                                                     relation from all
807
-     */
808
-    public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
809
-    {
810
-        $relationship_to_model = $this->get_model()->related_settings_for($relationName);
811
-        $index_in_cache = '';
812
-        if (! $relationship_to_model) {
813
-            throw new EE_Error(
814
-                sprintf(
815
-                    esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
816
-                    $relationName,
817
-                    get_class($this)
818
-                )
819
-            );
820
-        }
821
-        if ($clear_all) {
822
-            $obj_removed = true;
823
-            $this->_model_relations[ $relationName ] = null;
824
-        } elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
825
-            $obj_removed = $this->_model_relations[ $relationName ];
826
-            $this->_model_relations[ $relationName ] = null;
827
-        } else {
828
-            if ($object_to_remove_or_index_into_array instanceof EE_Base_Class
829
-                && $object_to_remove_or_index_into_array->ID()
830
-            ) {
831
-                $index_in_cache = $object_to_remove_or_index_into_array->ID();
832
-                if (is_array($this->_model_relations[ $relationName ])
833
-                    && ! isset($this->_model_relations[ $relationName ][ $index_in_cache ])
834
-                ) {
835
-                    $index_found_at = null;
836
-                    // find this object in the array even though it has a different key
837
-                    foreach ($this->_model_relations[ $relationName ] as $index => $obj) {
838
-                        /** @noinspection TypeUnsafeComparisonInspection */
839
-                        if ($obj instanceof EE_Base_Class
840
-                            && (
841
-                                $obj == $object_to_remove_or_index_into_array
842
-                                || $obj->ID() === $object_to_remove_or_index_into_array->ID()
843
-                            )
844
-                        ) {
845
-                            $index_found_at = $index;
846
-                            break;
847
-                        }
848
-                    }
849
-                    if ($index_found_at) {
850
-                        $index_in_cache = $index_found_at;
851
-                    } else {
852
-                        // it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
853
-                        // if it wasn't in it to begin with. So we're done
854
-                        return $object_to_remove_or_index_into_array;
855
-                    }
856
-                }
857
-            } elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
858
-                // so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
859
-                foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
860
-                    /** @noinspection TypeUnsafeComparisonInspection */
861
-                    if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
862
-                        $index_in_cache = $index;
863
-                    }
864
-                }
865
-            } else {
866
-                $index_in_cache = $object_to_remove_or_index_into_array;
867
-            }
868
-            // supposedly we've found it. But it could just be that the client code
869
-            // provided a bad index/object
870
-            if (isset($this->_model_relations[ $relationName ][ $index_in_cache ])) {
871
-                $obj_removed = $this->_model_relations[ $relationName ][ $index_in_cache ];
872
-                unset($this->_model_relations[ $relationName ][ $index_in_cache ]);
873
-            } else {
874
-                // that thing was never cached anyways.
875
-                $obj_removed = null;
876
-            }
877
-        }
878
-        return $obj_removed;
879
-    }
880
-
881
-
882
-    /**
883
-     * update_cache_after_object_save
884
-     * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
885
-     * obtained after being saved to the db
886
-     *
887
-     * @param string        $relationName       - the type of object that is cached
888
-     * @param EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
889
-     * @param string        $current_cache_id   - the ID that was used when originally caching the object
890
-     * @return boolean TRUE on success, FALSE on fail
891
-     * @throws ReflectionException
892
-     * @throws InvalidArgumentException
893
-     * @throws InvalidInterfaceException
894
-     * @throws InvalidDataTypeException
895
-     * @throws EE_Error
896
-     */
897
-    public function update_cache_after_object_save(
898
-        $relationName,
899
-        EE_Base_Class $newly_saved_object,
900
-        $current_cache_id = ''
901
-    ) {
902
-        // verify that incoming object is of the correct type
903
-        $obj_class = 'EE_' . $relationName;
904
-        if ($newly_saved_object instanceof $obj_class) {
905
-            /* @type EE_Base_Class $newly_saved_object */
906
-            // now get the type of relation
907
-            $relationship_to_model = $this->get_model()->related_settings_for($relationName);
908
-            // if this is a 1:1 relationship
909
-            if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
910
-                // then just replace the cached object with the newly saved object
911
-                $this->_model_relations[ $relationName ] = $newly_saved_object;
912
-                return true;
913
-                // or if it's some kind of sordid feral polyamorous relationship...
914
-            }
915
-            if (is_array($this->_model_relations[ $relationName ])
916
-                && isset($this->_model_relations[ $relationName ][ $current_cache_id ])
917
-            ) {
918
-                // then remove the current cached item
919
-                unset($this->_model_relations[ $relationName ][ $current_cache_id ]);
920
-                // and cache the newly saved object using it's new ID
921
-                $this->_model_relations[ $relationName ][ $newly_saved_object->ID() ] = $newly_saved_object;
922
-                return true;
923
-            }
924
-        }
925
-        return false;
926
-    }
927
-
928
-
929
-    /**
930
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
931
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
932
-     *
933
-     * @param string $relationName
934
-     * @return EE_Base_Class
935
-     */
936
-    public function get_one_from_cache($relationName)
937
-    {
938
-        $cached_array_or_object = isset($this->_model_relations[ $relationName ])
939
-            ? $this->_model_relations[ $relationName ]
940
-            : null;
941
-        if (is_array($cached_array_or_object)) {
942
-            return array_shift($cached_array_or_object);
943
-        }
944
-        return $cached_array_or_object;
945
-    }
946
-
947
-
948
-    /**
949
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
950
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
951
-     *
952
-     * @param string $relationName
953
-     * @throws ReflectionException
954
-     * @throws InvalidArgumentException
955
-     * @throws InvalidInterfaceException
956
-     * @throws InvalidDataTypeException
957
-     * @throws EE_Error
958
-     * @return EE_Base_Class[] NOT necessarily indexed by primary keys
959
-     */
960
-    public function get_all_from_cache($relationName)
961
-    {
962
-        $objects = isset($this->_model_relations[ $relationName ]) ? $this->_model_relations[ $relationName ] : array();
963
-        // if the result is not an array, but exists, make it an array
964
-        $objects = is_array($objects) ? $objects : array($objects);
965
-        // bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
966
-        // basically, if this model object was stored in the session, and these cached model objects
967
-        // already have IDs, let's make sure they're in their model's entity mapper
968
-        // otherwise we will have duplicates next time we call
969
-        // EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
970
-        $model = EE_Registry::instance()->load_model($relationName);
971
-        foreach ($objects as $model_object) {
972
-            if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
973
-                // ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
974
-                if ($model_object->ID()) {
975
-                    $model->add_to_entity_map($model_object);
976
-                }
977
-            } else {
978
-                throw new EE_Error(
979
-                    sprintf(
980
-                        esc_html__(
981
-                            'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
982
-                            'event_espresso'
983
-                        ),
984
-                        $relationName,
985
-                        gettype($model_object)
986
-                    )
987
-                );
988
-            }
989
-        }
990
-        return $objects;
991
-    }
992
-
993
-
994
-    /**
995
-     * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
996
-     * matching the given query conditions.
997
-     *
998
-     * @param null  $field_to_order_by  What field is being used as the reference point.
999
-     * @param int   $limit              How many objects to return.
1000
-     * @param array $query_params       Any additional conditions on the query.
1001
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1002
-     *                                  you can indicate just the columns you want returned
1003
-     * @return array|EE_Base_Class[]
1004
-     * @throws ReflectionException
1005
-     * @throws InvalidArgumentException
1006
-     * @throws InvalidInterfaceException
1007
-     * @throws InvalidDataTypeException
1008
-     * @throws EE_Error
1009
-     */
1010
-    public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
1011
-    {
1012
-        $model = $this->get_model();
1013
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1014
-            ? $model->get_primary_key_field()->get_name()
1015
-            : $field_to_order_by;
1016
-        $current_value = ! empty($field) ? $this->get($field) : null;
1017
-        if (empty($field) || empty($current_value)) {
1018
-            return array();
1019
-        }
1020
-        return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
1021
-    }
1022
-
1023
-
1024
-    /**
1025
-     * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
1026
-     * matching the given query conditions.
1027
-     *
1028
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1029
-     * @param int   $limit              How many objects to return.
1030
-     * @param array $query_params       Any additional conditions on the query.
1031
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1032
-     *                                  you can indicate just the columns you want returned
1033
-     * @return array|EE_Base_Class[]
1034
-     * @throws ReflectionException
1035
-     * @throws InvalidArgumentException
1036
-     * @throws InvalidInterfaceException
1037
-     * @throws InvalidDataTypeException
1038
-     * @throws EE_Error
1039
-     */
1040
-    public function previous_x(
1041
-        $field_to_order_by = null,
1042
-        $limit = 1,
1043
-        $query_params = array(),
1044
-        $columns_to_select = null
1045
-    ) {
1046
-        $model = $this->get_model();
1047
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1048
-            ? $model->get_primary_key_field()->get_name()
1049
-            : $field_to_order_by;
1050
-        $current_value = ! empty($field) ? $this->get($field) : null;
1051
-        if (empty($field) || empty($current_value)) {
1052
-            return array();
1053
-        }
1054
-        return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
1055
-    }
1056
-
1057
-
1058
-    /**
1059
-     * Returns the next EE_Base_Class object in sequence from this object as found in the database
1060
-     * matching the given query conditions.
1061
-     *
1062
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1063
-     * @param array $query_params       Any additional conditions on the query.
1064
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1065
-     *                                  you can indicate just the columns you want returned
1066
-     * @return array|EE_Base_Class
1067
-     * @throws ReflectionException
1068
-     * @throws InvalidArgumentException
1069
-     * @throws InvalidInterfaceException
1070
-     * @throws InvalidDataTypeException
1071
-     * @throws EE_Error
1072
-     */
1073
-    public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1074
-    {
1075
-        $model = $this->get_model();
1076
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1077
-            ? $model->get_primary_key_field()->get_name()
1078
-            : $field_to_order_by;
1079
-        $current_value = ! empty($field) ? $this->get($field) : null;
1080
-        if (empty($field) || empty($current_value)) {
1081
-            return array();
1082
-        }
1083
-        return $model->next($current_value, $field, $query_params, $columns_to_select);
1084
-    }
1085
-
1086
-
1087
-    /**
1088
-     * Returns the previous EE_Base_Class object in sequence from this object as found in the database
1089
-     * matching the given query conditions.
1090
-     *
1091
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1092
-     * @param array $query_params       Any additional conditions on the query.
1093
-     * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1094
-     *                                  you can indicate just the column you want returned
1095
-     * @return array|EE_Base_Class
1096
-     * @throws ReflectionException
1097
-     * @throws InvalidArgumentException
1098
-     * @throws InvalidInterfaceException
1099
-     * @throws InvalidDataTypeException
1100
-     * @throws EE_Error
1101
-     */
1102
-    public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1103
-    {
1104
-        $model = $this->get_model();
1105
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1106
-            ? $model->get_primary_key_field()->get_name()
1107
-            : $field_to_order_by;
1108
-        $current_value = ! empty($field) ? $this->get($field) : null;
1109
-        if (empty($field) || empty($current_value)) {
1110
-            return array();
1111
-        }
1112
-        return $model->previous($current_value, $field, $query_params, $columns_to_select);
1113
-    }
1114
-
1115
-
1116
-    /**
1117
-     * Overrides parent because parent expects old models.
1118
-     * This also doesn't do any validation, and won't work for serialized arrays
1119
-     *
1120
-     * @param string $field_name
1121
-     * @param mixed  $field_value_from_db
1122
-     * @throws ReflectionException
1123
-     * @throws InvalidArgumentException
1124
-     * @throws InvalidInterfaceException
1125
-     * @throws InvalidDataTypeException
1126
-     * @throws EE_Error
1127
-     */
1128
-    public function set_from_db($field_name, $field_value_from_db)
1129
-    {
1130
-        $field_obj = $this->get_model()->field_settings_for($field_name);
1131
-        if ($field_obj instanceof EE_Model_Field_Base) {
1132
-            // you would think the DB has no NULLs for non-null label fields right? wrong!
1133
-            // eg, a CPT model object could have an entry in the posts table, but no
1134
-            // entry in the meta table. Meaning that all its columns in the meta table
1135
-            // are null! yikes! so when we find one like that, use defaults for its meta columns
1136
-            if ($field_value_from_db === null) {
1137
-                if ($field_obj->is_nullable()) {
1138
-                    // if the field allows nulls, then let it be null
1139
-                    $field_value = null;
1140
-                } else {
1141
-                    $field_value = $field_obj->get_default_value();
1142
-                }
1143
-            } else {
1144
-                $field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1145
-            }
1146
-            $this->_fields[ $field_name ] = $field_value;
1147
-            $this->_clear_cached_property($field_name);
1148
-        }
1149
-    }
1150
-
1151
-
1152
-    /**
1153
-     * verifies that the specified field is of the correct type
1154
-     *
1155
-     * @param string $field_name
1156
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1157
-     *                                (in cases where the same property may be used for different outputs
1158
-     *                                - i.e. datetime, money etc.)
1159
-     * @return mixed
1160
-     * @throws ReflectionException
1161
-     * @throws InvalidArgumentException
1162
-     * @throws InvalidInterfaceException
1163
-     * @throws InvalidDataTypeException
1164
-     * @throws EE_Error
1165
-     */
1166
-    public function get($field_name, $extra_cache_ref = null)
1167
-    {
1168
-        return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1169
-    }
1170
-
1171
-
1172
-    /**
1173
-     * This method simply returns the RAW unprocessed value for the given property in this class
1174
-     *
1175
-     * @param  string $field_name A valid fieldname
1176
-     * @return mixed              Whatever the raw value stored on the property is.
1177
-     * @throws ReflectionException
1178
-     * @throws InvalidArgumentException
1179
-     * @throws InvalidInterfaceException
1180
-     * @throws InvalidDataTypeException
1181
-     * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1182
-     */
1183
-    public function get_raw($field_name)
1184
-    {
1185
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1186
-        return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1187
-            ? $this->_fields[ $field_name ]->format('U')
1188
-            : $this->_fields[ $field_name ];
1189
-    }
1190
-
1191
-
1192
-    /**
1193
-     * This is used to return the internal DateTime object used for a field that is a
1194
-     * EE_Datetime_Field.
1195
-     *
1196
-     * @param string $field_name               The field name retrieving the DateTime object.
1197
-     * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1198
-     * @throws EE_Error an error is set and false returned.  If the field IS an
1199
-     *                                         EE_Datetime_Field and but the field value is null, then
1200
-     *                                         just null is returned (because that indicates that likely
1201
-     *                                         this field is nullable).
1202
-     * @throws InvalidArgumentException
1203
-     * @throws InvalidDataTypeException
1204
-     * @throws InvalidInterfaceException
1205
-     * @throws ReflectionException
1206
-     */
1207
-    public function get_DateTime_object($field_name)
1208
-    {
1209
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1210
-        if (! $field_settings instanceof EE_Datetime_Field) {
1211
-            EE_Error::add_error(
1212
-                sprintf(
1213
-                    esc_html__(
1214
-                        'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1215
-                        'event_espresso'
1216
-                    ),
1217
-                    $field_name
1218
-                ),
1219
-                __FILE__,
1220
-                __FUNCTION__,
1221
-                __LINE__
1222
-            );
1223
-            return false;
1224
-        }
1225
-        return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1226
-            ? clone $this->_fields[ $field_name ]
1227
-            : null;
1228
-    }
1229
-
1230
-
1231
-    /**
1232
-     * To be used in template to immediately echo out the value, and format it for output.
1233
-     * Eg, should call stripslashes and whatnot before echoing
1234
-     *
1235
-     * @param string $field_name      the name of the field as it appears in the DB
1236
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1237
-     *                                (in cases where the same property may be used for different outputs
1238
-     *                                - i.e. datetime, money etc.)
1239
-     * @return void
1240
-     * @throws ReflectionException
1241
-     * @throws InvalidArgumentException
1242
-     * @throws InvalidInterfaceException
1243
-     * @throws InvalidDataTypeException
1244
-     * @throws EE_Error
1245
-     */
1246
-    public function e($field_name, $extra_cache_ref = null)
1247
-    {
1248
-        echo $this->get_pretty($field_name, $extra_cache_ref);
1249
-    }
1250
-
1251
-
1252
-    /**
1253
-     * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1254
-     * can be easily used as the value of form input.
1255
-     *
1256
-     * @param string $field_name
1257
-     * @return void
1258
-     * @throws ReflectionException
1259
-     * @throws InvalidArgumentException
1260
-     * @throws InvalidInterfaceException
1261
-     * @throws InvalidDataTypeException
1262
-     * @throws EE_Error
1263
-     */
1264
-    public function f($field_name)
1265
-    {
1266
-        $this->e($field_name, 'form_input');
1267
-    }
1268
-
1269
-
1270
-    /**
1271
-     * Same as `f()` but just returns the value instead of echoing it
1272
-     *
1273
-     * @param string $field_name
1274
-     * @return string
1275
-     * @throws ReflectionException
1276
-     * @throws InvalidArgumentException
1277
-     * @throws InvalidInterfaceException
1278
-     * @throws InvalidDataTypeException
1279
-     * @throws EE_Error
1280
-     */
1281
-    public function get_f($field_name)
1282
-    {
1283
-        return (string) $this->get_pretty($field_name, 'form_input');
1284
-    }
1285
-
1286
-
1287
-    /**
1288
-     * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1289
-     * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1290
-     * to see what options are available.
1291
-     *
1292
-     * @param string $field_name
1293
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1294
-     *                                (in cases where the same property may be used for different outputs
1295
-     *                                - i.e. datetime, money etc.)
1296
-     * @return mixed
1297
-     * @throws ReflectionException
1298
-     * @throws InvalidArgumentException
1299
-     * @throws InvalidInterfaceException
1300
-     * @throws InvalidDataTypeException
1301
-     * @throws EE_Error
1302
-     */
1303
-    public function get_pretty($field_name, $extra_cache_ref = null)
1304
-    {
1305
-        return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1306
-    }
1307
-
1308
-
1309
-    /**
1310
-     * This simply returns the datetime for the given field name
1311
-     * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1312
-     * (and the equivalent e_date, e_time, e_datetime).
1313
-     *
1314
-     * @access   protected
1315
-     * @param string   $field_name   Field on the instantiated EE_Base_Class child object
1316
-     * @param string   $dt_frmt      valid datetime format used for date
1317
-     *                               (if '' then we just use the default on the field,
1318
-     *                               if NULL we use the last-used format)
1319
-     * @param string   $tm_frmt      Same as above except this is for time format
1320
-     * @param string   $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1321
-     * @param  boolean $echo         Whether the dtt is echoing using pretty echoing or just returned using vanilla get
1322
-     * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1323
-     *                               if field is not a valid dtt field, or void if echoing
1324
-     * @throws ReflectionException
1325
-     * @throws InvalidArgumentException
1326
-     * @throws InvalidInterfaceException
1327
-     * @throws InvalidDataTypeException
1328
-     * @throws EE_Error
1329
-     */
1330
-    protected function _get_datetime($field_name, $dt_frmt = '', $tm_frmt = '', $date_or_time = '', $echo = false)
1331
-    {
1332
-        // clear cached property
1333
-        $this->_clear_cached_property($field_name);
1334
-        // reset format properties because they are used in get()
1335
-        $this->_dt_frmt = $dt_frmt !== '' ? $dt_frmt : $this->_dt_frmt;
1336
-        $this->_tm_frmt = $tm_frmt !== '' ? $tm_frmt : $this->_tm_frmt;
1337
-        if ($echo) {
1338
-            $this->e($field_name, $date_or_time);
1339
-            return '';
1340
-        }
1341
-        return $this->get($field_name, $date_or_time);
1342
-    }
1343
-
1344
-
1345
-    /**
1346
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1347
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1348
-     * other echoes the pretty value for dtt)
1349
-     *
1350
-     * @param  string $field_name name of model object datetime field holding the value
1351
-     * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1352
-     * @return string            datetime value formatted
1353
-     * @throws ReflectionException
1354
-     * @throws InvalidArgumentException
1355
-     * @throws InvalidInterfaceException
1356
-     * @throws InvalidDataTypeException
1357
-     * @throws EE_Error
1358
-     */
1359
-    public function get_date($field_name, $format = '')
1360
-    {
1361
-        return $this->_get_datetime($field_name, $format, null, 'D');
1362
-    }
1363
-
1364
-
1365
-    /**
1366
-     * @param        $field_name
1367
-     * @param string $format
1368
-     * @throws ReflectionException
1369
-     * @throws InvalidArgumentException
1370
-     * @throws InvalidInterfaceException
1371
-     * @throws InvalidDataTypeException
1372
-     * @throws EE_Error
1373
-     */
1374
-    public function e_date($field_name, $format = '')
1375
-    {
1376
-        $this->_get_datetime($field_name, $format, null, 'D', true);
1377
-    }
1378
-
1379
-
1380
-    /**
1381
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1382
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1383
-     * other echoes the pretty value for dtt)
1384
-     *
1385
-     * @param  string $field_name name of model object datetime field holding the value
1386
-     * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1387
-     * @return string             datetime value formatted
1388
-     * @throws ReflectionException
1389
-     * @throws InvalidArgumentException
1390
-     * @throws InvalidInterfaceException
1391
-     * @throws InvalidDataTypeException
1392
-     * @throws EE_Error
1393
-     */
1394
-    public function get_time($field_name, $format = '')
1395
-    {
1396
-        return $this->_get_datetime($field_name, null, $format, 'T');
1397
-    }
1398
-
1399
-
1400
-    /**
1401
-     * @param        $field_name
1402
-     * @param string $format
1403
-     * @throws ReflectionException
1404
-     * @throws InvalidArgumentException
1405
-     * @throws InvalidInterfaceException
1406
-     * @throws InvalidDataTypeException
1407
-     * @throws EE_Error
1408
-     */
1409
-    public function e_time($field_name, $format = '')
1410
-    {
1411
-        $this->_get_datetime($field_name, null, $format, 'T', true);
1412
-    }
1413
-
1414
-
1415
-    /**
1416
-     * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1417
-     * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1418
-     * other echoes the pretty value for dtt)
1419
-     *
1420
-     * @param  string $field_name name of model object datetime field holding the value
1421
-     * @param  string $dt_frmt    format for the date returned (if NULL we use default in dt_frmt property)
1422
-     * @param  string $tm_frmt    format for the time returned (if NULL we use default in tm_frmt property)
1423
-     * @return string             datetime value formatted
1424
-     * @throws ReflectionException
1425
-     * @throws InvalidArgumentException
1426
-     * @throws InvalidInterfaceException
1427
-     * @throws InvalidDataTypeException
1428
-     * @throws EE_Error
1429
-     */
1430
-    public function get_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1431
-    {
1432
-        return $this->_get_datetime($field_name, $dt_frmt, $tm_frmt);
1433
-    }
1434
-
1435
-
1436
-    /**
1437
-     * @param string $field_name
1438
-     * @param string $dt_frmt
1439
-     * @param string $tm_frmt
1440
-     * @throws ReflectionException
1441
-     * @throws InvalidArgumentException
1442
-     * @throws InvalidInterfaceException
1443
-     * @throws InvalidDataTypeException
1444
-     * @throws EE_Error
1445
-     */
1446
-    public function e_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1447
-    {
1448
-        $this->_get_datetime($field_name, $dt_frmt, $tm_frmt, null, true);
1449
-    }
1450
-
1451
-
1452
-    /**
1453
-     * Get the i8ln value for a date using the WordPress @see date_i18n function.
1454
-     *
1455
-     * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1456
-     * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1457
-     *                           on the object will be used.
1458
-     * @return string Date and time string in set locale or false if no field exists for the given
1459
-     * @throws ReflectionException
1460
-     * @throws InvalidArgumentException
1461
-     * @throws InvalidInterfaceException
1462
-     * @throws InvalidDataTypeException
1463
-     * @throws EE_Error
1464
-     *                           field name.
1465
-     */
1466
-    public function get_i18n_datetime($field_name, $format = '')
1467
-    {
1468
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1469
-        return date_i18n(
1470
-            $format,
1471
-            EEH_DTT_Helper::get_timestamp_with_offset(
1472
-                $this->get_raw($field_name),
1473
-                $this->_timezone
1474
-            )
1475
-        );
1476
-    }
1477
-
1478
-
1479
-    /**
1480
-     * This method validates whether the given field name is a valid field on the model object as well as it is of a
1481
-     * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1482
-     * thrown.
1483
-     *
1484
-     * @param  string $field_name The field name being checked
1485
-     * @throws ReflectionException
1486
-     * @throws InvalidArgumentException
1487
-     * @throws InvalidInterfaceException
1488
-     * @throws InvalidDataTypeException
1489
-     * @throws EE_Error
1490
-     * @return EE_Datetime_Field
1491
-     */
1492
-    protected function _get_dtt_field_settings($field_name)
1493
-    {
1494
-        $field = $this->get_model()->field_settings_for($field_name);
1495
-        // check if field is dtt
1496
-        if ($field instanceof EE_Datetime_Field) {
1497
-            return $field;
1498
-        }
1499
-        throw new EE_Error(
1500
-            sprintf(
1501
-                esc_html__(
1502
-                    'The field name "%s" has been requested for the EE_Base_Class datetime functions and it is not a valid EE_Datetime_Field.  Please check the spelling of the field and make sure it has been setup as a EE_Datetime_Field in the %s model constructor',
1503
-                    'event_espresso'
1504
-                ),
1505
-                $field_name,
1506
-                self::_get_model_classname(get_class($this))
1507
-            )
1508
-        );
1509
-    }
1510
-
1511
-
1512
-
1513
-
1514
-    /**
1515
-     * NOTE ABOUT BELOW:
1516
-     * These convenience date and time setters are for setting date and time independently.  In other words you might
1517
-     * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1518
-     * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1519
-     * method and make sure you send the entire datetime value for setting.
1520
-     */
1521
-    /**
1522
-     * sets the time on a datetime property
1523
-     *
1524
-     * @access protected
1525
-     * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1526
-     * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1527
-     * @throws ReflectionException
1528
-     * @throws InvalidArgumentException
1529
-     * @throws InvalidInterfaceException
1530
-     * @throws InvalidDataTypeException
1531
-     * @throws EE_Error
1532
-     */
1533
-    protected function _set_time_for($time, $fieldname)
1534
-    {
1535
-        $this->_set_date_time('T', $time, $fieldname);
1536
-    }
1537
-
1538
-
1539
-    /**
1540
-     * sets the date on a datetime property
1541
-     *
1542
-     * @access protected
1543
-     * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1544
-     * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1545
-     * @throws ReflectionException
1546
-     * @throws InvalidArgumentException
1547
-     * @throws InvalidInterfaceException
1548
-     * @throws InvalidDataTypeException
1549
-     * @throws EE_Error
1550
-     */
1551
-    protected function _set_date_for($date, $fieldname)
1552
-    {
1553
-        $this->_set_date_time('D', $date, $fieldname);
1554
-    }
1555
-
1556
-
1557
-    /**
1558
-     * This takes care of setting a date or time independently on a given model object property. This method also
1559
-     * verifies that the given fieldname matches a model object property and is for a EE_Datetime_Field field
1560
-     *
1561
-     * @access protected
1562
-     * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1563
-     * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1564
-     * @param string          $fieldname      the name of the field the date OR time is being set on (must match a
1565
-     *                                        EE_Datetime_Field property)
1566
-     * @throws ReflectionException
1567
-     * @throws InvalidArgumentException
1568
-     * @throws InvalidInterfaceException
1569
-     * @throws InvalidDataTypeException
1570
-     * @throws EE_Error
1571
-     */
1572
-    protected function _set_date_time($what = 'T', $datetime_value, $fieldname)
1573
-    {
1574
-        $field = $this->_get_dtt_field_settings($fieldname);
1575
-        $field->set_timezone($this->_timezone);
1576
-        $field->set_date_format($this->_dt_frmt);
1577
-        $field->set_time_format($this->_tm_frmt);
1578
-        switch ($what) {
1579
-            case 'T':
1580
-                $this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_time(
1581
-                    $datetime_value,
1582
-                    $this->_fields[ $fieldname ]
1583
-                );
1584
-                break;
1585
-            case 'D':
1586
-                $this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_date(
1587
-                    $datetime_value,
1588
-                    $this->_fields[ $fieldname ]
1589
-                );
1590
-                break;
1591
-            case 'B':
1592
-                $this->_fields[ $fieldname ] = $field->prepare_for_set($datetime_value);
1593
-                break;
1594
-        }
1595
-        $this->_clear_cached_property($fieldname);
1596
-    }
1597
-
1598
-
1599
-    /**
1600
-     * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1601
-     * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1602
-     * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1603
-     * that could lead to some unexpected results!
1604
-     *
1605
-     * @access public
1606
-     * @param string $field_name               This is the name of the field on the object that contains the date/time
1607
-     *                                         value being returned.
1608
-     * @param string $callback                 must match a valid method in this class (defaults to get_datetime)
1609
-     * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1610
-     * @param string $prepend                  You can include something to prepend on the timestamp
1611
-     * @param string $append                   You can include something to append on the timestamp
1612
-     * @throws ReflectionException
1613
-     * @throws InvalidArgumentException
1614
-     * @throws InvalidInterfaceException
1615
-     * @throws InvalidDataTypeException
1616
-     * @throws EE_Error
1617
-     * @return string timestamp
1618
-     */
1619
-    public function display_in_my_timezone(
1620
-        $field_name,
1621
-        $callback = 'get_datetime',
1622
-        $args = null,
1623
-        $prepend = '',
1624
-        $append = ''
1625
-    ) {
1626
-        $timezone = EEH_DTT_Helper::get_timezone();
1627
-        if ($timezone === $this->_timezone) {
1628
-            return '';
1629
-        }
1630
-        $original_timezone = $this->_timezone;
1631
-        $this->set_timezone($timezone);
1632
-        $fn = (array) $field_name;
1633
-        $args = array_merge($fn, (array) $args);
1634
-        if (! method_exists($this, $callback)) {
1635
-            throw new EE_Error(
1636
-                sprintf(
1637
-                    esc_html__(
1638
-                        'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1639
-                        'event_espresso'
1640
-                    ),
1641
-                    $callback
1642
-                )
1643
-            );
1644
-        }
1645
-        $args = (array) $args;
1646
-        $return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1647
-        $this->set_timezone($original_timezone);
1648
-        return $return;
1649
-    }
1650
-
1651
-
1652
-    /**
1653
-     * Deletes this model object.
1654
-     * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1655
-     * override
1656
-     * `EE_Base_Class::_delete` NOT this class.
1657
-     *
1658
-     * @return boolean | int
1659
-     * @throws ReflectionException
1660
-     * @throws InvalidArgumentException
1661
-     * @throws InvalidInterfaceException
1662
-     * @throws InvalidDataTypeException
1663
-     * @throws EE_Error
1664
-     */
1665
-    public function delete()
1666
-    {
1667
-        /**
1668
-         * Called just before the `EE_Base_Class::_delete` method call.
1669
-         * Note:
1670
-         * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1671
-         * should be aware that `_delete` may not always result in a permanent delete.
1672
-         * For example, `EE_Soft_Delete_Base_Class::_delete`
1673
-         * soft deletes (trash) the object and does not permanently delete it.
1674
-         *
1675
-         * @param EE_Base_Class $model_object about to be 'deleted'
1676
-         */
1677
-        do_action('AHEE__EE_Base_Class__delete__before', $this);
1678
-        $result = $this->_delete();
1679
-        /**
1680
-         * Called just after the `EE_Base_Class::_delete` method call.
1681
-         * Note:
1682
-         * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1683
-         * should be aware that `_delete` may not always result in a permanent delete.
1684
-         * For example `EE_Soft_Base_Class::_delete`
1685
-         * soft deletes (trash) the object and does not permanently delete it.
1686
-         *
1687
-         * @param EE_Base_Class $model_object that was just 'deleted'
1688
-         * @param boolean       $result
1689
-         */
1690
-        do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1691
-        return $result;
1692
-    }
1693
-
1694
-
1695
-    /**
1696
-     * Calls the specific delete method for the instantiated class.
1697
-     * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1698
-     * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1699
-     * `EE_Base_Class::delete`
1700
-     *
1701
-     * @return bool|int
1702
-     * @throws ReflectionException
1703
-     * @throws InvalidArgumentException
1704
-     * @throws InvalidInterfaceException
1705
-     * @throws InvalidDataTypeException
1706
-     * @throws EE_Error
1707
-     */
1708
-    protected function _delete()
1709
-    {
1710
-        return $this->delete_permanently();
1711
-    }
1712
-
1713
-
1714
-    /**
1715
-     * Deletes this model object permanently from db
1716
-     * (but keep in mind related models may block the delete and return an error)
1717
-     *
1718
-     * @return bool | int
1719
-     * @throws ReflectionException
1720
-     * @throws InvalidArgumentException
1721
-     * @throws InvalidInterfaceException
1722
-     * @throws InvalidDataTypeException
1723
-     * @throws EE_Error
1724
-     */
1725
-    public function delete_permanently()
1726
-    {
1727
-        /**
1728
-         * Called just before HARD deleting a model object
1729
-         *
1730
-         * @param EE_Base_Class $model_object about to be 'deleted'
1731
-         */
1732
-        do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1733
-        $model = $this->get_model();
1734
-        $result = $model->delete_permanently_by_ID($this->ID());
1735
-        $this->refresh_cache_of_related_objects();
1736
-        /**
1737
-         * Called just after HARD deleting a model object
1738
-         *
1739
-         * @param EE_Base_Class $model_object that was just 'deleted'
1740
-         * @param boolean       $result
1741
-         */
1742
-        do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1743
-        return $result;
1744
-    }
1745
-
1746
-
1747
-    /**
1748
-     * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1749
-     * related model objects
1750
-     *
1751
-     * @throws ReflectionException
1752
-     * @throws InvalidArgumentException
1753
-     * @throws InvalidInterfaceException
1754
-     * @throws InvalidDataTypeException
1755
-     * @throws EE_Error
1756
-     */
1757
-    public function refresh_cache_of_related_objects()
1758
-    {
1759
-        $model = $this->get_model();
1760
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1761
-            if (! empty($this->_model_relations[ $relation_name ])) {
1762
-                $related_objects = $this->_model_relations[ $relation_name ];
1763
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
1764
-                    // this relation only stores a single model object, not an array
1765
-                    // but let's make it consistent
1766
-                    $related_objects = array($related_objects);
1767
-                }
1768
-                foreach ($related_objects as $related_object) {
1769
-                    // only refresh their cache if they're in memory
1770
-                    if ($related_object instanceof EE_Base_Class) {
1771
-                        $related_object->clear_cache(
1772
-                            $model->get_this_model_name(),
1773
-                            $this
1774
-                        );
1775
-                    }
1776
-                }
1777
-            }
1778
-        }
1779
-    }
1780
-
1781
-
1782
-    /**
1783
-     *        Saves this object to the database. An array may be supplied to set some values on this
1784
-     * object just before saving.
1785
-     *
1786
-     * @access public
1787
-     * @param array $set_cols_n_values keys are field names, values are their new values,
1788
-     *                                 if provided during the save() method (often client code will change the fields'
1789
-     *                                 values before calling save)
1790
-     * @throws InvalidArgumentException
1791
-     * @throws InvalidInterfaceException
1792
-     * @throws InvalidDataTypeException
1793
-     * @throws EE_Error
1794
-     * @return int , 1 on a successful update, the ID of the new entry on insert; 0 on failure or if the model object
1795
-     *                                 isn't allowed to persist (as determined by EE_Base_Class::allow_persist())
1796
-     * @throws ReflectionException
1797
-     * @throws ReflectionException
1798
-     * @throws ReflectionException
1799
-     */
1800
-    public function save($set_cols_n_values = array())
1801
-    {
1802
-        $model = $this->get_model();
1803
-        /**
1804
-         * Filters the fields we're about to save on the model object
1805
-         *
1806
-         * @param array         $set_cols_n_values
1807
-         * @param EE_Base_Class $model_object
1808
-         */
1809
-        $set_cols_n_values = (array) apply_filters(
1810
-            'FHEE__EE_Base_Class__save__set_cols_n_values',
1811
-            $set_cols_n_values,
1812
-            $this
1813
-        );
1814
-        // set attributes as provided in $set_cols_n_values
1815
-        foreach ($set_cols_n_values as $column => $value) {
1816
-            $this->set($column, $value);
1817
-        }
1818
-        // no changes ? then don't do anything
1819
-        if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1820
-            return 0;
1821
-        }
1822
-        /**
1823
-         * Saving a model object.
1824
-         * Before we perform a save, this action is fired.
1825
-         *
1826
-         * @param EE_Base_Class $model_object the model object about to be saved.
1827
-         */
1828
-        do_action('AHEE__EE_Base_Class__save__begin', $this);
1829
-        if (! $this->allow_persist()) {
1830
-            return 0;
1831
-        }
1832
-        // now get current attribute values
1833
-        $save_cols_n_values = $this->_fields;
1834
-        // if the object already has an ID, update it. Otherwise, insert it
1835
-        // also: change the assumption about values passed to the model NOT being prepare dby the model object.
1836
-        // They have been
1837
-        $old_assumption_concerning_value_preparation = $model
1838
-            ->get_assumption_concerning_values_already_prepared_by_model_object();
1839
-        $model->assume_values_already_prepared_by_model_object(true);
1840
-        // does this model have an autoincrement PK?
1841
-        if ($model->has_primary_key_field()) {
1842
-            if ($model->get_primary_key_field()->is_auto_increment()) {
1843
-                // ok check if it's set, if so: update; if not, insert
1844
-                if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1845
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1846
-                } else {
1847
-                    unset($save_cols_n_values[ $model->primary_key_name() ]);
1848
-                    $results = $model->insert($save_cols_n_values);
1849
-                    if ($results) {
1850
-                        // if successful, set the primary key
1851
-                        // but don't use the normal SET method, because it will check if
1852
-                        // an item with the same ID exists in the mapper & db, then
1853
-                        // will find it in the db (because we just added it) and THAT object
1854
-                        // will get added to the mapper before we can add this one!
1855
-                        // but if we just avoid using the SET method, all that headache can be avoided
1856
-                        $pk_field_name = $model->primary_key_name();
1857
-                        $this->_fields[ $pk_field_name ] = $results;
1858
-                        $this->_clear_cached_property($pk_field_name);
1859
-                        $model->add_to_entity_map($this);
1860
-                        $this->_update_cached_related_model_objs_fks();
1861
-                    }
1862
-                }
1863
-            } else {// PK is NOT auto-increment
1864
-                // so check if one like it already exists in the db
1865
-                if ($model->exists_by_ID($this->ID())) {
1866
-                    if (WP_DEBUG && ! $this->in_entity_map()) {
1867
-                        throw new EE_Error(
1868
-                            sprintf(
1869
-                                esc_html__(
1870
-                                    'Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1871
-                                    'event_espresso'
1872
-                                ),
1873
-                                get_class($this),
1874
-                                get_class($model) . '::instance()->add_to_entity_map()',
1875
-                                get_class($model) . '::instance()->get_one_by_ID()',
1876
-                                '<br />'
1877
-                            )
1878
-                        );
1879
-                    }
1880
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1881
-                } else {
1882
-                    $results = $model->insert($save_cols_n_values);
1883
-                    $this->_update_cached_related_model_objs_fks();
1884
-                }
1885
-            }
1886
-        } else {// there is NO primary key
1887
-            $already_in_db = false;
1888
-            foreach ($model->unique_indexes() as $index) {
1889
-                $uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1890
-                if ($model->exists(array($uniqueness_where_params))) {
1891
-                    $already_in_db = true;
1892
-                }
1893
-            }
1894
-            if ($already_in_db) {
1895
-                $combined_pk_fields_n_values = array_intersect_key(
1896
-                    $save_cols_n_values,
1897
-                    $model->get_combined_primary_key_fields()
1898
-                );
1899
-                $results = $model->update(
1900
-                    $save_cols_n_values,
1901
-                    $combined_pk_fields_n_values
1902
-                );
1903
-            } else {
1904
-                $results = $model->insert($save_cols_n_values);
1905
-            }
1906
-        }
1907
-        // restore the old assumption about values being prepared by the model object
1908
-        $model->assume_values_already_prepared_by_model_object(
1909
-            $old_assumption_concerning_value_preparation
1910
-        );
1911
-        /**
1912
-         * After saving the model object this action is called
1913
-         *
1914
-         * @param EE_Base_Class $model_object which was just saved
1915
-         * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1916
-         *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1917
-         */
1918
-        do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1919
-        $this->_has_changes = false;
1920
-        return $results;
1921
-    }
1922
-
1923
-
1924
-    /**
1925
-     * Updates the foreign key on related models objects pointing to this to have this model object's ID
1926
-     * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1927
-     * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1928
-     * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1929
-     * saved it to the db. We also create a registration and don't save it to the DB, but we DO cache it on the
1930
-     * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1931
-     * or not they exist in the DB (if they do, their DB records will be automatically updated)
1932
-     *
1933
-     * @return void
1934
-     * @throws ReflectionException
1935
-     * @throws InvalidArgumentException
1936
-     * @throws InvalidInterfaceException
1937
-     * @throws InvalidDataTypeException
1938
-     * @throws EE_Error
1939
-     */
1940
-    protected function _update_cached_related_model_objs_fks()
1941
-    {
1942
-        $model = $this->get_model();
1943
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1944
-            if ($relation_obj instanceof EE_Has_Many_Relation) {
1945
-                foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1946
-                    $fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1947
-                        $model->get_this_model_name()
1948
-                    );
1949
-                    $related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1950
-                    if ($related_model_obj_in_cache->ID()) {
1951
-                        $related_model_obj_in_cache->save();
1952
-                    }
1953
-                }
1954
-            }
1955
-        }
1956
-    }
1957
-
1958
-
1959
-    /**
1960
-     * Saves this model object and its NEW cached relations to the database.
1961
-     * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1962
-     * In order for that to work, we would need to mark model objects as dirty/clean...
1963
-     * because otherwise, there's a potential for infinite looping of saving
1964
-     * Saves the cached related model objects, and ensures the relation between them
1965
-     * and this object and properly setup
1966
-     *
1967
-     * @return int ID of new model object on save; 0 on failure+
1968
-     * @throws ReflectionException
1969
-     * @throws InvalidArgumentException
1970
-     * @throws InvalidInterfaceException
1971
-     * @throws InvalidDataTypeException
1972
-     * @throws EE_Error
1973
-     */
1974
-    public function save_new_cached_related_model_objs()
1975
-    {
1976
-        // make sure this has been saved
1977
-        if (! $this->ID()) {
1978
-            $id = $this->save();
1979
-        } else {
1980
-            $id = $this->ID();
1981
-        }
1982
-        // now save all the NEW cached model objects  (ie they don't exist in the DB)
1983
-        foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1984
-            if ($this->_model_relations[ $relationName ]) {
1985
-                // is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
1986
-                // or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
1987
-                /* @var $related_model_obj EE_Base_Class */
1988
-                if ($relationObj instanceof EE_Belongs_To_Relation) {
1989
-                    // add a relation to that relation type (which saves the appropriate thing in the process)
1990
-                    // but ONLY if it DOES NOT exist in the DB
1991
-                    $related_model_obj = $this->_model_relations[ $relationName ];
1992
-                    // if( ! $related_model_obj->ID()){
1993
-                    $this->_add_relation_to($related_model_obj, $relationName);
1994
-                    $related_model_obj->save_new_cached_related_model_objs();
1995
-                    // }
1996
-                } else {
1997
-                    foreach ($this->_model_relations[ $relationName ] as $related_model_obj) {
1998
-                        // add a relation to that relation type (which saves the appropriate thing in the process)
1999
-                        // but ONLY if it DOES NOT exist in the DB
2000
-                        // if( ! $related_model_obj->ID()){
2001
-                        $this->_add_relation_to($related_model_obj, $relationName);
2002
-                        $related_model_obj->save_new_cached_related_model_objs();
2003
-                        // }
2004
-                    }
2005
-                }
2006
-            }
2007
-        }
2008
-        return $id;
2009
-    }
2010
-
2011
-
2012
-    /**
2013
-     * for getting a model while instantiated.
2014
-     *
2015
-     * @return EEM_Base | EEM_CPT_Base
2016
-     * @throws ReflectionException
2017
-     * @throws InvalidArgumentException
2018
-     * @throws InvalidInterfaceException
2019
-     * @throws InvalidDataTypeException
2020
-     * @throws EE_Error
2021
-     */
2022
-    public function get_model()
2023
-    {
2024
-        if (! $this->_model) {
2025
-            $modelName = self::_get_model_classname(get_class($this));
2026
-            $this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2027
-        } else {
2028
-            $this->_model->set_timezone($this->_timezone);
2029
-        }
2030
-        return $this->_model;
2031
-    }
2032
-
2033
-
2034
-    /**
2035
-     * @param $props_n_values
2036
-     * @param $classname
2037
-     * @return mixed bool|EE_Base_Class|EEM_CPT_Base
2038
-     * @throws ReflectionException
2039
-     * @throws InvalidArgumentException
2040
-     * @throws InvalidInterfaceException
2041
-     * @throws InvalidDataTypeException
2042
-     * @throws EE_Error
2043
-     */
2044
-    protected static function _get_object_from_entity_mapper($props_n_values, $classname)
2045
-    {
2046
-        // TODO: will not work for Term_Relationships because they have no PK!
2047
-        $primary_id_ref = self::_get_primary_key_name($classname);
2048
-        if (array_key_exists($primary_id_ref, $props_n_values)
2049
-            && ! empty($props_n_values[ $primary_id_ref ])
2050
-        ) {
2051
-            $id = $props_n_values[ $primary_id_ref ];
2052
-            return self::_get_model($classname)->get_from_entity_map($id);
2053
-        }
2054
-        return false;
2055
-    }
2056
-
2057
-
2058
-    /**
2059
-     * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
2060
-     * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
2061
-     * primary key for the model AND it is not null, then we check the db. If there's a an object we return it.  If not
2062
-     * we return false.
2063
-     *
2064
-     * @param  array  $props_n_values   incoming array of properties and their values
2065
-     * @param  string $classname        the classname of the child class
2066
-     * @param null    $timezone
2067
-     * @param array   $date_formats     incoming date_formats in an array where the first value is the
2068
-     *                                  date_format and the second value is the time format
2069
-     * @return mixed (EE_Base_Class|bool)
2070
-     * @throws InvalidArgumentException
2071
-     * @throws InvalidInterfaceException
2072
-     * @throws InvalidDataTypeException
2073
-     * @throws EE_Error
2074
-     * @throws ReflectionException
2075
-     * @throws ReflectionException
2076
-     * @throws ReflectionException
2077
-     */
2078
-    protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
2079
-    {
2080
-        $existing = null;
2081
-        $model = self::_get_model($classname, $timezone);
2082
-        if ($model->has_primary_key_field()) {
2083
-            $primary_id_ref = self::_get_primary_key_name($classname);
2084
-            if (array_key_exists($primary_id_ref, $props_n_values)
2085
-                && ! empty($props_n_values[ $primary_id_ref ])
2086
-            ) {
2087
-                $existing = $model->get_one_by_ID(
2088
-                    $props_n_values[ $primary_id_ref ]
2089
-                );
2090
-            }
2091
-        } elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
2092
-            // no primary key on this model, but there's still a matching item in the DB
2093
-            $existing = self::_get_model($classname, $timezone)->get_one_by_ID(
2094
-                self::_get_model($classname, $timezone)
2095
-                    ->get_index_primary_key_string($props_n_values)
2096
-            );
2097
-        }
2098
-        if ($existing) {
2099
-            // set date formats if present before setting values
2100
-            if (! empty($date_formats) && is_array($date_formats)) {
2101
-                $existing->set_date_format($date_formats[0]);
2102
-                $existing->set_time_format($date_formats[1]);
2103
-            } else {
2104
-                // set default formats for date and time
2105
-                $existing->set_date_format(get_option('date_format'));
2106
-                $existing->set_time_format(get_option('time_format'));
2107
-            }
2108
-            foreach ($props_n_values as $property => $field_value) {
2109
-                $existing->set($property, $field_value);
2110
-            }
2111
-            return $existing;
2112
-        }
2113
-        return false;
2114
-    }
2115
-
2116
-
2117
-    /**
2118
-     * Gets the EEM_*_Model for this class
2119
-     *
2120
-     * @access public now, as this is more convenient
2121
-     * @param      $classname
2122
-     * @param null $timezone
2123
-     * @throws ReflectionException
2124
-     * @throws InvalidArgumentException
2125
-     * @throws InvalidInterfaceException
2126
-     * @throws InvalidDataTypeException
2127
-     * @throws EE_Error
2128
-     * @return EEM_Base
2129
-     */
2130
-    protected static function _get_model($classname, $timezone = null)
2131
-    {
2132
-        // find model for this class
2133
-        if (! $classname) {
2134
-            throw new EE_Error(
2135
-                sprintf(
2136
-                    esc_html__(
2137
-                        'What were you thinking calling _get_model(%s)?? You need to specify the class name',
2138
-                        'event_espresso'
2139
-                    ),
2140
-                    $classname
2141
-                )
2142
-            );
2143
-        }
2144
-        $modelName = self::_get_model_classname($classname);
2145
-        return self::_get_model_instance_with_name($modelName, $timezone);
2146
-    }
2147
-
2148
-
2149
-    /**
2150
-     * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
2151
-     *
2152
-     * @param string $model_classname
2153
-     * @param null   $timezone
2154
-     * @return EEM_Base
2155
-     * @throws ReflectionException
2156
-     * @throws InvalidArgumentException
2157
-     * @throws InvalidInterfaceException
2158
-     * @throws InvalidDataTypeException
2159
-     * @throws EE_Error
2160
-     */
2161
-    protected static function _get_model_instance_with_name($model_classname, $timezone = null)
2162
-    {
2163
-        $model_classname = str_replace('EEM_', '', $model_classname);
2164
-        $model = EE_Registry::instance()->load_model($model_classname);
2165
-        $model->set_timezone($timezone);
2166
-        return $model;
2167
-    }
2168
-
2169
-
2170
-    /**
2171
-     * If a model name is provided (eg Registration), gets the model classname for that model.
2172
-     * Also works if a model class's classname is provided (eg EE_Registration).
2173
-     *
2174
-     * @param null $model_name
2175
-     * @return string like EEM_Attendee
2176
-     */
2177
-    private static function _get_model_classname($model_name = null)
2178
-    {
2179
-        if (strpos($model_name, 'EE_') === 0) {
2180
-            $model_classname = str_replace('EE_', 'EEM_', $model_name);
2181
-        } else {
2182
-            $model_classname = 'EEM_' . $model_name;
2183
-        }
2184
-        return $model_classname;
2185
-    }
2186
-
2187
-
2188
-    /**
2189
-     * returns the name of the primary key attribute
2190
-     *
2191
-     * @param null $classname
2192
-     * @throws ReflectionException
2193
-     * @throws InvalidArgumentException
2194
-     * @throws InvalidInterfaceException
2195
-     * @throws InvalidDataTypeException
2196
-     * @throws EE_Error
2197
-     * @return string
2198
-     */
2199
-    protected static function _get_primary_key_name($classname = null)
2200
-    {
2201
-        if (! $classname) {
2202
-            throw new EE_Error(
2203
-                sprintf(
2204
-                    esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
2205
-                    $classname
2206
-                )
2207
-            );
2208
-        }
2209
-        return self::_get_model($classname)->get_primary_key_field()->get_name();
2210
-    }
2211
-
2212
-
2213
-    /**
2214
-     * Gets the value of the primary key.
2215
-     * If the object hasn't yet been saved, it should be whatever the model field's default was
2216
-     * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
2217
-     * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
2218
-     *
2219
-     * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
2220
-     * @throws ReflectionException
2221
-     * @throws InvalidArgumentException
2222
-     * @throws InvalidInterfaceException
2223
-     * @throws InvalidDataTypeException
2224
-     * @throws EE_Error
2225
-     */
2226
-    public function ID()
2227
-    {
2228
-        $model = $this->get_model();
2229
-        // now that we know the name of the variable, use a variable variable to get its value and return its
2230
-        if ($model->has_primary_key_field()) {
2231
-            return $this->_fields[ $model->primary_key_name() ];
2232
-        }
2233
-        return $model->get_index_primary_key_string($this->_fields);
2234
-    }
2235
-
2236
-
2237
-    /**
2238
-     * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2239
-     * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
2240
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2241
-     *
2242
-     * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2243
-     * @param string $relationName                     eg 'Events','Question',etc.
2244
-     *                                                 an attendee to a group, you also want to specify which role they
2245
-     *                                                 will have in that group. So you would use this parameter to
2246
-     *                                                 specify array('role-column-name'=>'role-id')
2247
-     * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2248
-     *                                                 allow you to further constrict the relation to being added.
2249
-     *                                                 However, keep in mind that the columns (keys) given must match a
2250
-     *                                                 column on the JOIN table and currently only the HABTM models
2251
-     *                                                 accept these additional conditions.  Also remember that if an
2252
-     *                                                 exact match isn't found for these extra cols/val pairs, then a
2253
-     *                                                 NEW row is created in the join table.
2254
-     * @param null   $cache_id
2255
-     * @throws ReflectionException
2256
-     * @throws InvalidArgumentException
2257
-     * @throws InvalidInterfaceException
2258
-     * @throws InvalidDataTypeException
2259
-     * @throws EE_Error
2260
-     * @return EE_Base_Class the object the relation was added to
2261
-     */
2262
-    public function _add_relation_to(
2263
-        $otherObjectModelObjectOrID,
2264
-        $relationName,
2265
-        $extra_join_model_fields_n_values = array(),
2266
-        $cache_id = null
2267
-    ) {
2268
-        $model = $this->get_model();
2269
-        // if this thing exists in the DB, save the relation to the DB
2270
-        if ($this->ID()) {
2271
-            $otherObject = $model->add_relationship_to(
2272
-                $this,
2273
-                $otherObjectModelObjectOrID,
2274
-                $relationName,
2275
-                $extra_join_model_fields_n_values
2276
-            );
2277
-            // clear cache so future get_many_related and get_first_related() return new results.
2278
-            $this->clear_cache($relationName, $otherObject, true);
2279
-            if ($otherObject instanceof EE_Base_Class) {
2280
-                $otherObject->clear_cache($model->get_this_model_name(), $this);
2281
-            }
2282
-        } else {
2283
-            // this thing doesn't exist in the DB,  so just cache it
2284
-            if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2285
-                throw new EE_Error(
2286
-                    sprintf(
2287
-                        esc_html__(
2288
-                            'Before a model object is saved to the database, calls to _add_relation_to must be passed an actual object, not just an ID. You provided %s as the model object to a %s',
2289
-                            'event_espresso'
2290
-                        ),
2291
-                        $otherObjectModelObjectOrID,
2292
-                        get_class($this)
2293
-                    )
2294
-                );
2295
-            }
2296
-            $otherObject = $otherObjectModelObjectOrID;
2297
-            $this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
2298
-        }
2299
-        if ($otherObject instanceof EE_Base_Class) {
2300
-            // fix the reciprocal relation too
2301
-            if ($otherObject->ID()) {
2302
-                // its saved so assumed relations exist in the DB, so we can just
2303
-                // clear the cache so future queries use the updated info in the DB
2304
-                $otherObject->clear_cache(
2305
-                    $model->get_this_model_name(),
2306
-                    null,
2307
-                    true
2308
-                );
2309
-            } else {
2310
-                // it's not saved, so it caches relations like this
2311
-                $otherObject->cache($model->get_this_model_name(), $this);
2312
-            }
2313
-        }
2314
-        return $otherObject;
2315
-    }
2316
-
2317
-
2318
-    /**
2319
-     * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2320
-     * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
2321
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2322
-     * from the cache
2323
-     *
2324
-     * @param mixed  $otherObjectModelObjectOrID
2325
-     *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2326
-     *                to the DB yet
2327
-     * @param string $relationName
2328
-     * @param array  $where_query
2329
-     *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2330
-     *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2331
-     *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2332
-     *                remember that if an exact match isn't found for these extra cols/val pairs, then no row is
2333
-     *                deleted.
2334
-     * @return EE_Base_Class the relation was removed from
2335
-     * @throws ReflectionException
2336
-     * @throws InvalidArgumentException
2337
-     * @throws InvalidInterfaceException
2338
-     * @throws InvalidDataTypeException
2339
-     * @throws EE_Error
2340
-     */
2341
-    public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2342
-    {
2343
-        if ($this->ID()) {
2344
-            // if this exists in the DB, save the relation change to the DB too
2345
-            $otherObject = $this->get_model()->remove_relationship_to(
2346
-                $this,
2347
-                $otherObjectModelObjectOrID,
2348
-                $relationName,
2349
-                $where_query
2350
-            );
2351
-            $this->clear_cache(
2352
-                $relationName,
2353
-                $otherObject
2354
-            );
2355
-        } else {
2356
-            // this doesn't exist in the DB, just remove it from the cache
2357
-            $otherObject = $this->clear_cache(
2358
-                $relationName,
2359
-                $otherObjectModelObjectOrID
2360
-            );
2361
-        }
2362
-        if ($otherObject instanceof EE_Base_Class) {
2363
-            $otherObject->clear_cache(
2364
-                $this->get_model()->get_this_model_name(),
2365
-                $this
2366
-            );
2367
-        }
2368
-        return $otherObject;
2369
-    }
2370
-
2371
-
2372
-    /**
2373
-     * Removes ALL the related things for the $relationName.
2374
-     *
2375
-     * @param string $relationName
2376
-     * @param array  $where_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2377
-     * @return EE_Base_Class
2378
-     * @throws ReflectionException
2379
-     * @throws InvalidArgumentException
2380
-     * @throws InvalidInterfaceException
2381
-     * @throws InvalidDataTypeException
2382
-     * @throws EE_Error
2383
-     */
2384
-    public function _remove_relations($relationName, $where_query_params = array())
2385
-    {
2386
-        if ($this->ID()) {
2387
-            // if this exists in the DB, save the relation change to the DB too
2388
-            $otherObjects = $this->get_model()->remove_relations(
2389
-                $this,
2390
-                $relationName,
2391
-                $where_query_params
2392
-            );
2393
-            $this->clear_cache(
2394
-                $relationName,
2395
-                null,
2396
-                true
2397
-            );
2398
-        } else {
2399
-            // this doesn't exist in the DB, just remove it from the cache
2400
-            $otherObjects = $this->clear_cache(
2401
-                $relationName,
2402
-                null,
2403
-                true
2404
-            );
2405
-        }
2406
-        if (is_array($otherObjects)) {
2407
-            foreach ($otherObjects as $otherObject) {
2408
-                $otherObject->clear_cache(
2409
-                    $this->get_model()->get_this_model_name(),
2410
-                    $this
2411
-                );
2412
-            }
2413
-        }
2414
-        return $otherObjects;
2415
-    }
2416
-
2417
-
2418
-    /**
2419
-     * Gets all the related model objects of the specified type. Eg, if the current class if
2420
-     * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2421
-     * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2422
-     * because we want to get even deleted items etc.
2423
-     *
2424
-     * @param string $relationName key in the model's _model_relations array
2425
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2426
-     * @return EE_Base_Class[]     Results not necessarily indexed by IDs, because some results might not have primary
2427
-     *                             keys or might not be saved yet. Consider using EEM_Base::get_IDs() on these
2428
-     *                             results if you want IDs
2429
-     * @throws ReflectionException
2430
-     * @throws InvalidArgumentException
2431
-     * @throws InvalidInterfaceException
2432
-     * @throws InvalidDataTypeException
2433
-     * @throws EE_Error
2434
-     */
2435
-    public function get_many_related($relationName, $query_params = array())
2436
-    {
2437
-        if ($this->ID()) {
2438
-            // this exists in the DB, so get the related things from either the cache or the DB
2439
-            // if there are query parameters, forget about caching the related model objects.
2440
-            if ($query_params) {
2441
-                $related_model_objects = $this->get_model()->get_all_related(
2442
-                    $this,
2443
-                    $relationName,
2444
-                    $query_params
2445
-                );
2446
-            } else {
2447
-                // did we already cache the result of this query?
2448
-                $cached_results = $this->get_all_from_cache($relationName);
2449
-                if (! $cached_results) {
2450
-                    $related_model_objects = $this->get_model()->get_all_related(
2451
-                        $this,
2452
-                        $relationName,
2453
-                        $query_params
2454
-                    );
2455
-                    // if no query parameters were passed, then we got all the related model objects
2456
-                    // for that relation. We can cache them then.
2457
-                    foreach ($related_model_objects as $related_model_object) {
2458
-                        $this->cache($relationName, $related_model_object);
2459
-                    }
2460
-                } else {
2461
-                    $related_model_objects = $cached_results;
2462
-                }
2463
-            }
2464
-        } else {
2465
-            // this doesn't exist in the DB, so just get the related things from the cache
2466
-            $related_model_objects = $this->get_all_from_cache($relationName);
2467
-        }
2468
-        return $related_model_objects;
2469
-    }
2470
-
2471
-
2472
-    /**
2473
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2474
-     * unless otherwise specified in the $query_params
2475
-     *
2476
-     * @param string $relation_name  model_name like 'Event', or 'Registration'
2477
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2478
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2479
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2480
-     *                               that by the setting $distinct to TRUE;
2481
-     * @return int
2482
-     * @throws ReflectionException
2483
-     * @throws InvalidArgumentException
2484
-     * @throws InvalidInterfaceException
2485
-     * @throws InvalidDataTypeException
2486
-     * @throws EE_Error
2487
-     */
2488
-    public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2489
-    {
2490
-        return $this->get_model()->count_related(
2491
-            $this,
2492
-            $relation_name,
2493
-            $query_params,
2494
-            $field_to_count,
2495
-            $distinct
2496
-        );
2497
-    }
2498
-
2499
-
2500
-    /**
2501
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2502
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2503
-     *
2504
-     * @param string $relation_name model_name like 'Event', or 'Registration'
2505
-     * @param array  $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2506
-     * @param string $field_to_sum  name of field to count by.
2507
-     *                              By default, uses primary key
2508
-     *                              (which doesn't make much sense, so you should probably change it)
2509
-     * @return int
2510
-     * @throws ReflectionException
2511
-     * @throws InvalidArgumentException
2512
-     * @throws InvalidInterfaceException
2513
-     * @throws InvalidDataTypeException
2514
-     * @throws EE_Error
2515
-     */
2516
-    public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2517
-    {
2518
-        return $this->get_model()->sum_related(
2519
-            $this,
2520
-            $relation_name,
2521
-            $query_params,
2522
-            $field_to_sum
2523
-        );
2524
-    }
2525
-
2526
-
2527
-    /**
2528
-     * Gets the first (ie, one) related model object of the specified type.
2529
-     *
2530
-     * @param string $relationName key in the model's _model_relations array
2531
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2532
-     * @return EE_Base_Class (not an array, a single object)
2533
-     * @throws ReflectionException
2534
-     * @throws InvalidArgumentException
2535
-     * @throws InvalidInterfaceException
2536
-     * @throws InvalidDataTypeException
2537
-     * @throws EE_Error
2538
-     */
2539
-    public function get_first_related($relationName, $query_params = array())
2540
-    {
2541
-        $model = $this->get_model();
2542
-        if ($this->ID()) {// this exists in the DB, get from the cache OR the DB
2543
-            // if they've provided some query parameters, don't bother trying to cache the result
2544
-            // also make sure we're not caching the result of get_first_related
2545
-            // on a relation which should have an array of objects (because the cache might have an array of objects)
2546
-            if ($query_params
2547
-                || ! $model->related_settings_for($relationName)
2548
-                     instanceof
2549
-                     EE_Belongs_To_Relation
2550
-            ) {
2551
-                $related_model_object = $model->get_first_related(
2552
-                    $this,
2553
-                    $relationName,
2554
-                    $query_params
2555
-                );
2556
-            } else {
2557
-                // first, check if we've already cached the result of this query
2558
-                $cached_result = $this->get_one_from_cache($relationName);
2559
-                if (! $cached_result) {
2560
-                    $related_model_object = $model->get_first_related(
2561
-                        $this,
2562
-                        $relationName,
2563
-                        $query_params
2564
-                    );
2565
-                    $this->cache($relationName, $related_model_object);
2566
-                } else {
2567
-                    $related_model_object = $cached_result;
2568
-                }
2569
-            }
2570
-        } else {
2571
-            $related_model_object = null;
2572
-            // this doesn't exist in the Db,
2573
-            // but maybe the relation is of type belongs to, and so the related thing might
2574
-            if ($model->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2575
-                $related_model_object = $model->get_first_related(
2576
-                    $this,
2577
-                    $relationName,
2578
-                    $query_params
2579
-                );
2580
-            }
2581
-            // this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2582
-            // just get what's cached on this object
2583
-            if (! $related_model_object) {
2584
-                $related_model_object = $this->get_one_from_cache($relationName);
2585
-            }
2586
-        }
2587
-        return $related_model_object;
2588
-    }
2589
-
2590
-
2591
-    /**
2592
-     * Does a delete on all related objects of type $relationName and removes
2593
-     * the current model object's relation to them. If they can't be deleted (because
2594
-     * of blocking related model objects) does nothing. If the related model objects are
2595
-     * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2596
-     * If this model object doesn't exist yet in the DB, just removes its related things
2597
-     *
2598
-     * @param string $relationName
2599
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2600
-     * @return int how many deleted
2601
-     * @throws ReflectionException
2602
-     * @throws InvalidArgumentException
2603
-     * @throws InvalidInterfaceException
2604
-     * @throws InvalidDataTypeException
2605
-     * @throws EE_Error
2606
-     */
2607
-    public function delete_related($relationName, $query_params = array())
2608
-    {
2609
-        if ($this->ID()) {
2610
-            $count = $this->get_model()->delete_related(
2611
-                $this,
2612
-                $relationName,
2613
-                $query_params
2614
-            );
2615
-        } else {
2616
-            $count = count($this->get_all_from_cache($relationName));
2617
-            $this->clear_cache($relationName, null, true);
2618
-        }
2619
-        return $count;
2620
-    }
2621
-
2622
-
2623
-    /**
2624
-     * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2625
-     * the current model object's relation to them. If they can't be deleted (because
2626
-     * of blocking related model objects) just does a soft delete on it instead, if possible.
2627
-     * If the related thing isn't a soft-deletable model object, this function is identical
2628
-     * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2629
-     *
2630
-     * @param string $relationName
2631
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2632
-     * @return int how many deleted (including those soft deleted)
2633
-     * @throws ReflectionException
2634
-     * @throws InvalidArgumentException
2635
-     * @throws InvalidInterfaceException
2636
-     * @throws InvalidDataTypeException
2637
-     * @throws EE_Error
2638
-     */
2639
-    public function delete_related_permanently($relationName, $query_params = array())
2640
-    {
2641
-        if ($this->ID()) {
2642
-            $count = $this->get_model()->delete_related_permanently(
2643
-                $this,
2644
-                $relationName,
2645
-                $query_params
2646
-            );
2647
-        } else {
2648
-            $count = count($this->get_all_from_cache($relationName));
2649
-        }
2650
-        $this->clear_cache($relationName, null, true);
2651
-        return $count;
2652
-    }
2653
-
2654
-
2655
-    /**
2656
-     * is_set
2657
-     * Just a simple utility function children can use for checking if property exists
2658
-     *
2659
-     * @access  public
2660
-     * @param  string $field_name property to check
2661
-     * @return bool                              TRUE if existing,FALSE if not.
2662
-     */
2663
-    public function is_set($field_name)
2664
-    {
2665
-        return isset($this->_fields[ $field_name ]);
2666
-    }
2667
-
2668
-
2669
-    /**
2670
-     * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2671
-     * EE_Error exception if they don't
2672
-     *
2673
-     * @param  mixed (string|array) $properties properties to check
2674
-     * @throws EE_Error
2675
-     * @return bool                              TRUE if existing, throw EE_Error if not.
2676
-     */
2677
-    protected function _property_exists($properties)
2678
-    {
2679
-        foreach ((array) $properties as $property_name) {
2680
-            // first make sure this property exists
2681
-            if (! $this->_fields[ $property_name ]) {
2682
-                throw new EE_Error(
2683
-                    sprintf(
2684
-                        esc_html__(
2685
-                            'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2686
-                            'event_espresso'
2687
-                        ),
2688
-                        $property_name
2689
-                    )
2690
-                );
2691
-            }
2692
-        }
2693
-        return true;
2694
-    }
2695
-
2696
-
2697
-    /**
2698
-     * This simply returns an array of model fields for this object
2699
-     *
2700
-     * @return array
2701
-     * @throws ReflectionException
2702
-     * @throws InvalidArgumentException
2703
-     * @throws InvalidInterfaceException
2704
-     * @throws InvalidDataTypeException
2705
-     * @throws EE_Error
2706
-     */
2707
-    public function model_field_array()
2708
-    {
2709
-        $fields = $this->get_model()->field_settings(false);
2710
-        $properties = array();
2711
-        // remove prepended underscore
2712
-        foreach ($fields as $field_name => $settings) {
2713
-            $properties[ $field_name ] = $this->get($field_name);
2714
-        }
2715
-        return $properties;
2716
-    }
2717
-
2718
-
2719
-    /**
2720
-     * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2721
-     * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2722
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments.
2723
-     * Instead of requiring a plugin to extend the EE_Base_Class
2724
-     * (which works fine is there's only 1 plugin, but when will that happen?)
2725
-     * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}'
2726
-     * (eg, filters_hook_espresso__EE_Answer__my_great_function)
2727
-     * and accepts 2 arguments: the object on which the function was called,
2728
-     * and an array of the original arguments passed to the function.
2729
-     * Whatever their callback function returns will be returned by this function.
2730
-     * Example: in functions.php (or in a plugin):
2731
-     *      add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3);
2732
-     *      function my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2733
-     *          $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2734
-     *          return $previousReturnValue.$returnString;
2735
-     *      }
2736
-     * require('EE_Answer.class.php');
2737
-     * $answer= EE_Answer::new_instance(array('REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'));
2738
-     * echo $answer->my_callback('monkeys',100);
2739
-     * //will output "you called my_callback! and passed args:monkeys,100"
2740
-     *
2741
-     * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2742
-     * @param array  $args       array of original arguments passed to the function
2743
-     * @throws EE_Error
2744
-     * @return mixed whatever the plugin which calls add_filter decides
2745
-     */
2746
-    public function __call($methodName, $args)
2747
-    {
2748
-        $className = get_class($this);
2749
-        $tagName = "FHEE__{$className}__{$methodName}";
2750
-        if (! has_filter($tagName)) {
2751
-            throw new EE_Error(
2752
-                sprintf(
2753
-                    esc_html__(
2754
-                        "Method %s on class %s does not exist! You can create one with the following code in functions.php or in a plugin: add_filter('%s','my_callback',10,3);function my_callback(\$previousReturnValue,EE_Base_Class \$object, \$argsArray){/*function body*/return \$whatever;}",
2755
-                        'event_espresso'
2756
-                    ),
2757
-                    $methodName,
2758
-                    $className,
2759
-                    $tagName
2760
-                )
2761
-            );
2762
-        }
2763
-        return apply_filters($tagName, null, $this, $args);
2764
-    }
2765
-
2766
-
2767
-    /**
2768
-     * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2769
-     * A $previous_value can be specified in case there are many meta rows with the same key
2770
-     *
2771
-     * @param string $meta_key
2772
-     * @param mixed  $meta_value
2773
-     * @param mixed  $previous_value
2774
-     * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2775
-     *                  NOTE: if the values haven't changed, returns 0
2776
-     * @throws InvalidArgumentException
2777
-     * @throws InvalidInterfaceException
2778
-     * @throws InvalidDataTypeException
2779
-     * @throws EE_Error
2780
-     * @throws ReflectionException
2781
-     */
2782
-    public function update_extra_meta($meta_key, $meta_value, $previous_value = null)
2783
-    {
2784
-        $query_params = array(
2785
-            array(
2786
-                'EXM_key'  => $meta_key,
2787
-                'OBJ_ID'   => $this->ID(),
2788
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2789
-            ),
2790
-        );
2791
-        if ($previous_value !== null) {
2792
-            $query_params[0]['EXM_value'] = $meta_value;
2793
-        }
2794
-        $existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2795
-        if (! $existing_rows_like_that) {
2796
-            return $this->add_extra_meta($meta_key, $meta_value);
2797
-        }
2798
-        foreach ($existing_rows_like_that as $existing_row) {
2799
-            $existing_row->save(array('EXM_value' => $meta_value));
2800
-        }
2801
-        return count($existing_rows_like_that);
2802
-    }
2803
-
2804
-
2805
-    /**
2806
-     * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2807
-     * no other extra meta for this model object have the same key. Returns TRUE if the
2808
-     * extra meta row was entered, false if not
2809
-     *
2810
-     * @param string  $meta_key
2811
-     * @param mixed   $meta_value
2812
-     * @param boolean $unique
2813
-     * @return boolean
2814
-     * @throws InvalidArgumentException
2815
-     * @throws InvalidInterfaceException
2816
-     * @throws InvalidDataTypeException
2817
-     * @throws EE_Error
2818
-     * @throws ReflectionException
2819
-     * @throws ReflectionException
2820
-     */
2821
-    public function add_extra_meta($meta_key, $meta_value, $unique = false)
2822
-    {
2823
-        if ($unique) {
2824
-            $existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2825
-                array(
2826
-                    array(
2827
-                        'EXM_key'  => $meta_key,
2828
-                        'OBJ_ID'   => $this->ID(),
2829
-                        'EXM_type' => $this->get_model()->get_this_model_name(),
2830
-                    ),
2831
-                )
2832
-            );
2833
-            if ($existing_extra_meta) {
2834
-                return false;
2835
-            }
2836
-        }
2837
-        $new_extra_meta = EE_Extra_Meta::new_instance(
2838
-            array(
2839
-                'EXM_key'   => $meta_key,
2840
-                'EXM_value' => $meta_value,
2841
-                'OBJ_ID'    => $this->ID(),
2842
-                'EXM_type'  => $this->get_model()->get_this_model_name(),
2843
-            )
2844
-        );
2845
-        $new_extra_meta->save();
2846
-        return true;
2847
-    }
2848
-
2849
-
2850
-    /**
2851
-     * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2852
-     * is specified, only deletes extra meta records with that value.
2853
-     *
2854
-     * @param string $meta_key
2855
-     * @param mixed  $meta_value
2856
-     * @return int number of extra meta rows deleted
2857
-     * @throws InvalidArgumentException
2858
-     * @throws InvalidInterfaceException
2859
-     * @throws InvalidDataTypeException
2860
-     * @throws EE_Error
2861
-     * @throws ReflectionException
2862
-     */
2863
-    public function delete_extra_meta($meta_key, $meta_value = null)
2864
-    {
2865
-        $query_params = array(
2866
-            array(
2867
-                'EXM_key'  => $meta_key,
2868
-                'OBJ_ID'   => $this->ID(),
2869
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2870
-            ),
2871
-        );
2872
-        if ($meta_value !== null) {
2873
-            $query_params[0]['EXM_value'] = $meta_value;
2874
-        }
2875
-        return EEM_Extra_Meta::instance()->delete($query_params);
2876
-    }
2877
-
2878
-
2879
-    /**
2880
-     * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2881
-     * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2882
-     * You can specify $default is case you haven't found the extra meta
2883
-     *
2884
-     * @param string  $meta_key
2885
-     * @param boolean $single
2886
-     * @param mixed   $default if we don't find anything, what should we return?
2887
-     * @return mixed single value if $single; array if ! $single
2888
-     * @throws ReflectionException
2889
-     * @throws InvalidArgumentException
2890
-     * @throws InvalidInterfaceException
2891
-     * @throws InvalidDataTypeException
2892
-     * @throws EE_Error
2893
-     */
2894
-    public function get_extra_meta($meta_key, $single = false, $default = null)
2895
-    {
2896
-        if ($single) {
2897
-            $result = $this->get_first_related(
2898
-                'Extra_Meta',
2899
-                array(array('EXM_key' => $meta_key))
2900
-            );
2901
-            if ($result instanceof EE_Extra_Meta) {
2902
-                return $result->value();
2903
-            }
2904
-        } else {
2905
-            $results = $this->get_many_related(
2906
-                'Extra_Meta',
2907
-                array(array('EXM_key' => $meta_key))
2908
-            );
2909
-            if ($results) {
2910
-                $values = array();
2911
-                foreach ($results as $result) {
2912
-                    if ($result instanceof EE_Extra_Meta) {
2913
-                        $values[ $result->ID() ] = $result->value();
2914
-                    }
2915
-                }
2916
-                return $values;
2917
-            }
2918
-        }
2919
-        // if nothing discovered yet return default.
2920
-        return apply_filters(
2921
-            'FHEE__EE_Base_Class__get_extra_meta__default_value',
2922
-            $default,
2923
-            $meta_key,
2924
-            $single,
2925
-            $this
2926
-        );
2927
-    }
2928
-
2929
-
2930
-    /**
2931
-     * Returns a simple array of all the extra meta associated with this model object.
2932
-     * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2933
-     * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2934
-     * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2935
-     * If $one_of_each_key is false, it will return an array with the top-level keys being
2936
-     * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2937
-     * finally the extra meta's value as each sub-value. (eg
2938
-     * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2939
-     *
2940
-     * @param boolean $one_of_each_key
2941
-     * @return array
2942
-     * @throws ReflectionException
2943
-     * @throws InvalidArgumentException
2944
-     * @throws InvalidInterfaceException
2945
-     * @throws InvalidDataTypeException
2946
-     * @throws EE_Error
2947
-     */
2948
-    public function all_extra_meta_array($one_of_each_key = true)
2949
-    {
2950
-        $return_array = array();
2951
-        if ($one_of_each_key) {
2952
-            $extra_meta_objs = $this->get_many_related(
2953
-                'Extra_Meta',
2954
-                array('group_by' => 'EXM_key')
2955
-            );
2956
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2957
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2958
-                    $return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2959
-                }
2960
-            }
2961
-        } else {
2962
-            $extra_meta_objs = $this->get_many_related('Extra_Meta');
2963
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2964
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2965
-                    if (! isset($return_array[ $extra_meta_obj->key() ])) {
2966
-                        $return_array[ $extra_meta_obj->key() ] = array();
2967
-                    }
2968
-                    $return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2969
-                }
2970
-            }
2971
-        }
2972
-        return $return_array;
2973
-    }
2974
-
2975
-
2976
-    /**
2977
-     * Gets a pretty nice displayable nice for this model object. Often overridden
2978
-     *
2979
-     * @return string
2980
-     * @throws ReflectionException
2981
-     * @throws InvalidArgumentException
2982
-     * @throws InvalidInterfaceException
2983
-     * @throws InvalidDataTypeException
2984
-     * @throws EE_Error
2985
-     */
2986
-    public function name()
2987
-    {
2988
-        // find a field that's not a text field
2989
-        $field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
2990
-        if ($field_we_can_use) {
2991
-            return $this->get($field_we_can_use->get_name());
2992
-        }
2993
-        $first_few_properties = $this->model_field_array();
2994
-        $first_few_properties = array_slice($first_few_properties, 0, 3);
2995
-        $name_parts = array();
2996
-        foreach ($first_few_properties as $name => $value) {
2997
-            $name_parts[] = "$name:$value";
2998
-        }
2999
-        return implode(',', $name_parts);
3000
-    }
3001
-
3002
-
3003
-    /**
3004
-     * in_entity_map
3005
-     * Checks if this model object has been proven to already be in the entity map
3006
-     *
3007
-     * @return boolean
3008
-     * @throws ReflectionException
3009
-     * @throws InvalidArgumentException
3010
-     * @throws InvalidInterfaceException
3011
-     * @throws InvalidDataTypeException
3012
-     * @throws EE_Error
3013
-     */
3014
-    public function in_entity_map()
3015
-    {
3016
-        // well, if we looked, did we find it in the entity map?
3017
-        return $this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this;
3018
-    }
3019
-
3020
-
3021
-    /**
3022
-     * refresh_from_db
3023
-     * Makes sure the fields and values on this model object are in-sync with what's in the database.
3024
-     *
3025
-     * @throws ReflectionException
3026
-     * @throws InvalidArgumentException
3027
-     * @throws InvalidInterfaceException
3028
-     * @throws InvalidDataTypeException
3029
-     * @throws EE_Error if this model object isn't in the entity mapper (because then you should
3030
-     * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
3031
-     */
3032
-    public function refresh_from_db()
3033
-    {
3034
-        if ($this->ID() && $this->in_entity_map()) {
3035
-            $this->get_model()->refresh_entity_map_from_db($this->ID());
3036
-        } else {
3037
-            // if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
3038
-            // if it has an ID but it's not in the map, and you're asking me to refresh it
3039
-            // that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
3040
-            // absolutely nothing in it for this ID
3041
-            if (WP_DEBUG) {
3042
-                throw new EE_Error(
3043
-                    sprintf(
3044
-                        esc_html__(
3045
-                            'Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
3046
-                            'event_espresso'
3047
-                        ),
3048
-                        $this->ID(),
3049
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3050
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3051
-                    )
3052
-                );
3053
-            }
3054
-        }
3055
-    }
3056
-
3057
-
3058
-    /**
3059
-     * Change $fields' values to $new_value_sql (which is a string of raw SQL)
3060
-     *
3061
-     * @since 4.9.80.p
3062
-     * @param EE_Model_Field_Base[] $fields
3063
-     * @param string $new_value_sql
3064
-     *      example: 'column_name=123',
3065
-     *      or 'column_name=column_name+1',
3066
-     *      or 'column_name= CASE
3067
-     *          WHEN (`column_name` + `other_column` + 5) <= `yet_another_column`
3068
-     *          THEN `column_name` + 5
3069
-     *          ELSE `column_name`
3070
-     *      END'
3071
-     *      Also updates $field on this model object with the latest value from the database.
3072
-     * @return bool
3073
-     * @throws EE_Error
3074
-     * @throws InvalidArgumentException
3075
-     * @throws InvalidDataTypeException
3076
-     * @throws InvalidInterfaceException
3077
-     * @throws ReflectionException
3078
-     */
3079
-    protected function updateFieldsInDB($fields, $new_value_sql)
3080
-    {
3081
-        // First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3082
-        // if it wasn't even there to start off.
3083
-        if (! $this->ID()) {
3084
-            $this->save();
3085
-        }
3086
-        global $wpdb;
3087
-        if (empty($fields)) {
3088
-            throw new InvalidArgumentException(
3089
-                esc_html__(
3090
-                    'EE_Base_Class::updateFieldsInDB was passed an empty array of fields.',
3091
-                    'event_espresso'
3092
-                )
3093
-            );
3094
-        }
3095
-        $first_field = reset($fields);
3096
-        $table_alias = $first_field->get_table_alias();
3097
-        foreach ($fields as $field) {
3098
-            if ($table_alias !== $field->get_table_alias()) {
3099
-                throw new InvalidArgumentException(
3100
-                    sprintf(
3101
-                        esc_html__(
3102
-                            // @codingStandardsIgnoreStart
3103
-                            'EE_Base_Class::updateFieldsInDB was passed fields for different tables ("%1$s" and "%2$s"), which is not supported. Instead, please call the method multiple times.',
3104
-                            // @codingStandardsIgnoreEnd
3105
-                            'event_espresso'
3106
-                        ),
3107
-                        $table_alias,
3108
-                        $field->get_table_alias()
3109
-                    )
3110
-                );
3111
-            }
3112
-        }
3113
-        // Ok the fields are now known to all be for the same table. Proceed with creating the SQL to update it.
3114
-        $table_obj = $this->get_model()->get_table_obj_by_alias($table_alias);
3115
-        $table_pk_value = $this->ID();
3116
-        $table_name = $table_obj->get_table_name();
3117
-        if ($table_obj instanceof EE_Secondary_Table) {
3118
-            $table_pk_field_name = $table_obj->get_fk_on_table();
3119
-        } else {
3120
-            $table_pk_field_name = $table_obj->get_pk_column();
3121
-        }
3122
-
3123
-        $query =
3124
-            "UPDATE `{$table_name}`
16
+	/**
17
+	 * This is an array of the original properties and values provided during construction
18
+	 * of this model object. (keys are model field names, values are their values).
19
+	 * This list is important to remember so that when we are merging data from the db, we know
20
+	 * which values to override and which to not override.
21
+	 *
22
+	 * @var array
23
+	 */
24
+	protected $_props_n_values_provided_in_constructor;
25
+
26
+	/**
27
+	 * Timezone
28
+	 * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
29
+	 * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
30
+	 * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
31
+	 * access to it.
32
+	 *
33
+	 * @var string
34
+	 */
35
+	protected $_timezone;
36
+
37
+	/**
38
+	 * date format
39
+	 * pattern or format for displaying dates
40
+	 *
41
+	 * @var string $_dt_frmt
42
+	 */
43
+	protected $_dt_frmt;
44
+
45
+	/**
46
+	 * time format
47
+	 * pattern or format for displaying time
48
+	 *
49
+	 * @var string $_tm_frmt
50
+	 */
51
+	protected $_tm_frmt;
52
+
53
+	/**
54
+	 * This property is for holding a cached array of object properties indexed by property name as the key.
55
+	 * The purpose of this is for setting a cache on properties that may have calculated values after a
56
+	 * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
57
+	 * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
58
+	 *
59
+	 * @var array
60
+	 */
61
+	protected $_cached_properties = array();
62
+
63
+	/**
64
+	 * An array containing keys of the related model, and values are either an array of related mode objects or a
65
+	 * single
66
+	 * related model object. see the model's _model_relations. The keys should match those specified. And if the
67
+	 * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
68
+	 * all others have an array)
69
+	 *
70
+	 * @var array
71
+	 */
72
+	protected $_model_relations = array();
73
+
74
+	/**
75
+	 * Array where keys are field names (see the model's _fields property) and values are their values. To see what
76
+	 * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
77
+	 *
78
+	 * @var array
79
+	 */
80
+	protected $_fields = array();
81
+
82
+	/**
83
+	 * @var boolean indicating whether or not this model object is intended to ever be saved
84
+	 * For example, we might create model objects intended to only be used for the duration
85
+	 * of this request and to be thrown away, and if they were accidentally saved
86
+	 * it would be a bug.
87
+	 */
88
+	protected $_allow_persist = true;
89
+
90
+	/**
91
+	 * @var boolean indicating whether or not this model object's properties have changed since construction
92
+	 */
93
+	protected $_has_changes = false;
94
+
95
+	/**
96
+	 * @var EEM_Base
97
+	 */
98
+	protected $_model;
99
+
100
+	/**
101
+	 * This is a cache of results from custom selections done on a query that constructs this entity. The only purpose
102
+	 * for these values is for retrieval of the results, they are not further queryable and they are not persisted to
103
+	 * the db.  They also do not automatically update if there are any changes to the data that produced their results.
104
+	 * The format is a simple array of field_alias => field_value.  So for instance if a custom select was something
105
+	 * like,  "Select COUNT(Registration.REG_ID) as Registration_Count ...", then the resulting value will be in this
106
+	 * array as:
107
+	 * array(
108
+	 *  'Registration_Count' => 24
109
+	 * );
110
+	 * Note: if the custom select configuration for the query included a data type, the value will be in the data type
111
+	 * provided for the query (@see EventEspresso\core\domain\values\model\CustomSelects::__construct phpdocs for more
112
+	 * info)
113
+	 *
114
+	 * @var array
115
+	 */
116
+	protected $custom_selection_results = array();
117
+
118
+
119
+	/**
120
+	 * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
121
+	 * play nice
122
+	 *
123
+	 * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
124
+	 *                                                         layer of the model's _fields array, (eg, EVT_ID,
125
+	 *                                                         TXN_amount, QST_name, etc) and values are their values
126
+	 * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
127
+	 *                                                         corresponding db model or not.
128
+	 * @param string  $timezone                                indicate what timezone you want any datetime fields to
129
+	 *                                                         be in when instantiating a EE_Base_Class object.
130
+	 * @param array   $date_formats                            An array of date formats to set on construct where first
131
+	 *                                                         value is the date_format and second value is the time
132
+	 *                                                         format.
133
+	 * @throws InvalidArgumentException
134
+	 * @throws InvalidInterfaceException
135
+	 * @throws InvalidDataTypeException
136
+	 * @throws EE_Error
137
+	 * @throws ReflectionException
138
+	 */
139
+	protected function __construct($fieldValues = array(), $bydb = false, $timezone = '', $date_formats = array())
140
+	{
141
+		$className = get_class($this);
142
+		do_action("AHEE__{$className}__construct", $this, $fieldValues);
143
+		$model = $this->get_model();
144
+		$model_fields = $model->field_settings(false);
145
+		// ensure $fieldValues is an array
146
+		$fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
147
+		// verify client code has not passed any invalid field names
148
+		foreach ($fieldValues as $field_name => $field_value) {
149
+			if (! isset($model_fields[ $field_name ])) {
150
+				throw new EE_Error(
151
+					sprintf(
152
+						esc_html__(
153
+							'Invalid field (%s) passed to constructor of %s. Allowed fields are :%s',
154
+							'event_espresso'
155
+						),
156
+						$field_name,
157
+						get_class($this),
158
+						implode(', ', array_keys($model_fields))
159
+					)
160
+				);
161
+			}
162
+		}
163
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
164
+		if (! empty($date_formats) && is_array($date_formats)) {
165
+			list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
166
+		} else {
167
+			// set default formats for date and time
168
+			$this->_dt_frmt = (string) get_option('date_format', 'Y-m-d');
169
+			$this->_tm_frmt = (string) get_option('time_format', 'g:i a');
170
+		}
171
+		// if db model is instantiating
172
+		if ($bydb) {
173
+			// client code has indicated these field values are from the database
174
+			foreach ($model_fields as $fieldName => $field) {
175
+				$this->set_from_db(
176
+					$fieldName,
177
+					isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null
178
+				);
179
+			}
180
+		} else {
181
+			// we're constructing a brand
182
+			// new instance of the model object. Generally, this means we'll need to do more field validation
183
+			foreach ($model_fields as $fieldName => $field) {
184
+				$this->set(
185
+					$fieldName,
186
+					isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null,
187
+					true
188
+				);
189
+			}
190
+		}
191
+		// remember what values were passed to this constructor
192
+		$this->_props_n_values_provided_in_constructor = $fieldValues;
193
+		// remember in entity mapper
194
+		if (! $bydb && $model->has_primary_key_field() && $this->ID()) {
195
+			$model->add_to_entity_map($this);
196
+		}
197
+		// setup all the relations
198
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
199
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
200
+				$this->_model_relations[ $relation_name ] = null;
201
+			} else {
202
+				$this->_model_relations[ $relation_name ] = array();
203
+			}
204
+		}
205
+		/**
206
+		 * Action done at the end of each model object construction
207
+		 *
208
+		 * @param EE_Base_Class $this the model object just created
209
+		 */
210
+		do_action('AHEE__EE_Base_Class__construct__finished', $this);
211
+	}
212
+
213
+
214
+	/**
215
+	 * Gets whether or not this model object is allowed to persist/be saved to the database.
216
+	 *
217
+	 * @return boolean
218
+	 */
219
+	public function allow_persist()
220
+	{
221
+		return $this->_allow_persist;
222
+	}
223
+
224
+
225
+	/**
226
+	 * Sets whether or not this model object should be allowed to be saved to the DB.
227
+	 * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
228
+	 * you got new information that somehow made you change your mind.
229
+	 *
230
+	 * @param boolean $allow_persist
231
+	 * @return boolean
232
+	 */
233
+	public function set_allow_persist($allow_persist)
234
+	{
235
+		return $this->_allow_persist = $allow_persist;
236
+	}
237
+
238
+
239
+	/**
240
+	 * Gets the field's original value when this object was constructed during this request.
241
+	 * This can be helpful when determining if a model object has changed or not
242
+	 *
243
+	 * @param string $field_name
244
+	 * @return mixed|null
245
+	 * @throws ReflectionException
246
+	 * @throws InvalidArgumentException
247
+	 * @throws InvalidInterfaceException
248
+	 * @throws InvalidDataTypeException
249
+	 * @throws EE_Error
250
+	 */
251
+	public function get_original($field_name)
252
+	{
253
+		if (isset($this->_props_n_values_provided_in_constructor[ $field_name ])
254
+			&& $field_settings = $this->get_model()->field_settings_for($field_name)
255
+		) {
256
+			return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
257
+		}
258
+		return null;
259
+	}
260
+
261
+
262
+	/**
263
+	 * @param EE_Base_Class $obj
264
+	 * @return string
265
+	 */
266
+	public function get_class($obj)
267
+	{
268
+		return get_class($obj);
269
+	}
270
+
271
+
272
+	/**
273
+	 * Overrides parent because parent expects old models.
274
+	 * This also doesn't do any validation, and won't work for serialized arrays
275
+	 *
276
+	 * @param    string $field_name
277
+	 * @param    mixed  $field_value
278
+	 * @param bool      $use_default
279
+	 * @throws InvalidArgumentException
280
+	 * @throws InvalidInterfaceException
281
+	 * @throws InvalidDataTypeException
282
+	 * @throws EE_Error
283
+	 * @throws ReflectionException
284
+	 * @throws ReflectionException
285
+	 * @throws ReflectionException
286
+	 */
287
+	public function set($field_name, $field_value, $use_default = false)
288
+	{
289
+		// if not using default and nothing has changed, and object has already been setup (has ID),
290
+		// then don't do anything
291
+		if (! $use_default
292
+			&& $this->_fields[ $field_name ] === $field_value
293
+			&& $this->ID()
294
+		) {
295
+			return;
296
+		}
297
+		$model = $this->get_model();
298
+		$this->_has_changes = true;
299
+		$field_obj = $model->field_settings_for($field_name);
300
+		if ($field_obj instanceof EE_Model_Field_Base) {
301
+			// if ( method_exists( $field_obj, 'set_timezone' )) {
302
+			if ($field_obj instanceof EE_Datetime_Field) {
303
+				$field_obj->set_timezone($this->_timezone);
304
+				$field_obj->set_date_format($this->_dt_frmt);
305
+				$field_obj->set_time_format($this->_tm_frmt);
306
+			}
307
+			$holder_of_value = $field_obj->prepare_for_set($field_value);
308
+			// should the value be null?
309
+			if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
310
+				$this->_fields[ $field_name ] = $field_obj->get_default_value();
311
+				/**
312
+				 * To save having to refactor all the models, if a default value is used for a
313
+				 * EE_Datetime_Field, and that value is not null nor is it a DateTime
314
+				 * object.  Then let's do a set again to ensure that it becomes a DateTime
315
+				 * object.
316
+				 *
317
+				 * @since 4.6.10+
318
+				 */
319
+				if ($field_obj instanceof EE_Datetime_Field
320
+					&& $this->_fields[ $field_name ] !== null
321
+					&& ! $this->_fields[ $field_name ] instanceof DateTime
322
+				) {
323
+					empty($this->_fields[ $field_name ])
324
+						? $this->set($field_name, time())
325
+						: $this->set($field_name, $this->_fields[ $field_name ]);
326
+				}
327
+			} else {
328
+				$this->_fields[ $field_name ] = $holder_of_value;
329
+			}
330
+			// if we're not in the constructor...
331
+			// now check if what we set was a primary key
332
+			if (// note: props_n_values_provided_in_constructor is only set at the END of the constructor
333
+				$this->_props_n_values_provided_in_constructor
334
+				&& $field_value
335
+				&& $field_name === $model->primary_key_name()
336
+			) {
337
+				// if so, we want all this object's fields to be filled either with
338
+				// what we've explicitly set on this model
339
+				// or what we have in the db
340
+				// echo "setting primary key!";
341
+				$fields_on_model = self::_get_model(get_class($this))->field_settings();
342
+				$obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
343
+				foreach ($fields_on_model as $field_obj) {
344
+					if (! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
345
+						&& $field_obj->get_name() !== $field_name
346
+					) {
347
+						$this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
348
+					}
349
+				}
350
+				// oh this model object has an ID? well make sure its in the entity mapper
351
+				$model->add_to_entity_map($this);
352
+			}
353
+			// let's unset any cache for this field_name from the $_cached_properties property.
354
+			$this->_clear_cached_property($field_name);
355
+		} else {
356
+			throw new EE_Error(
357
+				sprintf(
358
+					esc_html__(
359
+						'A valid EE_Model_Field_Base could not be found for the given field name: %s',
360
+						'event_espresso'
361
+					),
362
+					$field_name
363
+				)
364
+			);
365
+		}
366
+	}
367
+
368
+
369
+	/**
370
+	 * Set custom select values for model.
371
+	 *
372
+	 * @param array $custom_select_values
373
+	 */
374
+	public function setCustomSelectsValues(array $custom_select_values)
375
+	{
376
+		$this->custom_selection_results = $custom_select_values;
377
+	}
378
+
379
+
380
+	/**
381
+	 * Returns the custom select value for the provided alias if its set.
382
+	 * If not set, returns null.
383
+	 *
384
+	 * @param string $alias
385
+	 * @return string|int|float|null
386
+	 */
387
+	public function getCustomSelect($alias)
388
+	{
389
+		return isset($this->custom_selection_results[ $alias ])
390
+			? $this->custom_selection_results[ $alias ]
391
+			: null;
392
+	}
393
+
394
+
395
+	/**
396
+	 * This sets the field value on the db column if it exists for the given $column_name or
397
+	 * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
398
+	 *
399
+	 * @see EE_message::get_column_value for related documentation on the necessity of this method.
400
+	 * @param string $field_name  Must be the exact column name.
401
+	 * @param mixed  $field_value The value to set.
402
+	 * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
403
+	 * @throws InvalidArgumentException
404
+	 * @throws InvalidInterfaceException
405
+	 * @throws InvalidDataTypeException
406
+	 * @throws EE_Error
407
+	 * @throws ReflectionException
408
+	 */
409
+	public function set_field_or_extra_meta($field_name, $field_value)
410
+	{
411
+		if ($this->get_model()->has_field($field_name)) {
412
+			$this->set($field_name, $field_value);
413
+			return true;
414
+		}
415
+		// ensure this object is saved first so that extra meta can be properly related.
416
+		$this->save();
417
+		return $this->update_extra_meta($field_name, $field_value);
418
+	}
419
+
420
+
421
+	/**
422
+	 * This retrieves the value of the db column set on this class or if that's not present
423
+	 * it will attempt to retrieve from extra_meta if found.
424
+	 * Example Usage:
425
+	 * Via EE_Message child class:
426
+	 * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
427
+	 * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
428
+	 * also have additional main fields specific to the messenger.  The system accommodates those extra
429
+	 * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
430
+	 * value for those extra fields dynamically via the EE_message object.
431
+	 *
432
+	 * @param  string $field_name expecting the fully qualified field name.
433
+	 * @return mixed|null  value for the field if found.  null if not found.
434
+	 * @throws ReflectionException
435
+	 * @throws InvalidArgumentException
436
+	 * @throws InvalidInterfaceException
437
+	 * @throws InvalidDataTypeException
438
+	 * @throws EE_Error
439
+	 */
440
+	public function get_field_or_extra_meta($field_name)
441
+	{
442
+		if ($this->get_model()->has_field($field_name)) {
443
+			$column_value = $this->get($field_name);
444
+		} else {
445
+			// This isn't a column in the main table, let's see if it is in the extra meta.
446
+			$column_value = $this->get_extra_meta($field_name, true, null);
447
+		}
448
+		return $column_value;
449
+	}
450
+
451
+
452
+	/**
453
+	 * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
454
+	 * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
455
+	 * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
456
+	 * available to all child classes that may be using the EE_Datetime_Field for a field data type.
457
+	 *
458
+	 * @access public
459
+	 * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
460
+	 * @return void
461
+	 * @throws InvalidArgumentException
462
+	 * @throws InvalidInterfaceException
463
+	 * @throws InvalidDataTypeException
464
+	 * @throws EE_Error
465
+	 * @throws ReflectionException
466
+	 */
467
+	public function set_timezone($timezone = '')
468
+	{
469
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
470
+		// make sure we clear all cached properties because they won't be relevant now
471
+		$this->_clear_cached_properties();
472
+		// make sure we update field settings and the date for all EE_Datetime_Fields
473
+		$model_fields = $this->get_model()->field_settings(false);
474
+		foreach ($model_fields as $field_name => $field_obj) {
475
+			if ($field_obj instanceof EE_Datetime_Field) {
476
+				$field_obj->set_timezone($this->_timezone);
477
+				if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
478
+					EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone));
479
+				}
480
+			}
481
+		}
482
+	}
483
+
484
+
485
+	/**
486
+	 * This just returns whatever is set for the current timezone.
487
+	 *
488
+	 * @access public
489
+	 * @return string timezone string
490
+	 */
491
+	public function get_timezone()
492
+	{
493
+		return $this->_timezone;
494
+	}
495
+
496
+
497
+	/**
498
+	 * This sets the internal date format to what is sent in to be used as the new default for the class
499
+	 * internally instead of wp set date format options
500
+	 *
501
+	 * @since 4.6
502
+	 * @param string $format should be a format recognizable by PHP date() functions.
503
+	 */
504
+	public function set_date_format($format)
505
+	{
506
+		$this->_dt_frmt = $format;
507
+		// clear cached_properties because they won't be relevant now.
508
+		$this->_clear_cached_properties();
509
+	}
510
+
511
+
512
+	/**
513
+	 * This sets the internal time format string to what is sent in to be used as the new default for the
514
+	 * class internally instead of wp set time format options.
515
+	 *
516
+	 * @since 4.6
517
+	 * @param string $format should be a format recognizable by PHP date() functions.
518
+	 */
519
+	public function set_time_format($format)
520
+	{
521
+		$this->_tm_frmt = $format;
522
+		// clear cached_properties because they won't be relevant now.
523
+		$this->_clear_cached_properties();
524
+	}
525
+
526
+
527
+	/**
528
+	 * This returns the current internal set format for the date and time formats.
529
+	 *
530
+	 * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
531
+	 *                             where the first value is the date format and the second value is the time format.
532
+	 * @return mixed string|array
533
+	 */
534
+	public function get_format($full = true)
535
+	{
536
+		return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
537
+	}
538
+
539
+
540
+	/**
541
+	 * cache
542
+	 * stores the passed model object on the current model object.
543
+	 * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
544
+	 *
545
+	 * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
546
+	 *                                       'Registration' associated with this model object
547
+	 * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
548
+	 *                                       that could be a payment or a registration)
549
+	 * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
550
+	 *                                       items which will be stored in an array on this object
551
+	 * @throws ReflectionException
552
+	 * @throws InvalidArgumentException
553
+	 * @throws InvalidInterfaceException
554
+	 * @throws InvalidDataTypeException
555
+	 * @throws EE_Error
556
+	 * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
557
+	 *                                       related thing, no array)
558
+	 */
559
+	public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
560
+	{
561
+		// its entirely possible that there IS no related object yet in which case there is nothing to cache.
562
+		if (! $object_to_cache instanceof EE_Base_Class) {
563
+			return false;
564
+		}
565
+		// also get "how" the object is related, or throw an error
566
+		if (! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
567
+			throw new EE_Error(
568
+				sprintf(
569
+					esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
570
+					$relationName,
571
+					get_class($this)
572
+				)
573
+			);
574
+		}
575
+		// how many things are related ?
576
+		if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
577
+			// if it's a "belongs to" relationship, then there's only one related model object
578
+			// eg, if this is a registration, there's only 1 attendee for it
579
+			// so for these model objects just set it to be cached
580
+			$this->_model_relations[ $relationName ] = $object_to_cache;
581
+			$return = true;
582
+		} else {
583
+			// otherwise, this is the "many" side of a one to many relationship,
584
+			// so we'll add the object to the array of related objects for that type.
585
+			// eg: if this is an event, there are many registrations for that event,
586
+			// so we cache the registrations in an array
587
+			if (! is_array($this->_model_relations[ $relationName ])) {
588
+				// if for some reason, the cached item is a model object,
589
+				// then stick that in the array, otherwise start with an empty array
590
+				$this->_model_relations[ $relationName ] = $this->_model_relations[ $relationName ]
591
+														   instanceof
592
+														   EE_Base_Class
593
+					? array($this->_model_relations[ $relationName ]) : array();
594
+			}
595
+			// first check for a cache_id which is normally empty
596
+			if (! empty($cache_id)) {
597
+				// if the cache_id exists, then it means we are purposely trying to cache this
598
+				// with a known key that can then be used to retrieve the object later on
599
+				$this->_model_relations[ $relationName ][ $cache_id ] = $object_to_cache;
600
+				$return = $cache_id;
601
+			} elseif ($object_to_cache->ID()) {
602
+				// OR the cached object originally came from the db, so let's just use it's PK for an ID
603
+				$this->_model_relations[ $relationName ][ $object_to_cache->ID() ] = $object_to_cache;
604
+				$return = $object_to_cache->ID();
605
+			} else {
606
+				// OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
607
+				$this->_model_relations[ $relationName ][] = $object_to_cache;
608
+				// move the internal pointer to the end of the array
609
+				end($this->_model_relations[ $relationName ]);
610
+				// and grab the key so that we can return it
611
+				$return = key($this->_model_relations[ $relationName ]);
612
+			}
613
+		}
614
+		return $return;
615
+	}
616
+
617
+
618
+	/**
619
+	 * For adding an item to the cached_properties property.
620
+	 *
621
+	 * @access protected
622
+	 * @param string      $fieldname the property item the corresponding value is for.
623
+	 * @param mixed       $value     The value we are caching.
624
+	 * @param string|null $cache_type
625
+	 * @return void
626
+	 * @throws ReflectionException
627
+	 * @throws InvalidArgumentException
628
+	 * @throws InvalidInterfaceException
629
+	 * @throws InvalidDataTypeException
630
+	 * @throws EE_Error
631
+	 */
632
+	protected function _set_cached_property($fieldname, $value, $cache_type = null)
633
+	{
634
+		// first make sure this property exists
635
+		$this->get_model()->field_settings_for($fieldname);
636
+		$cache_type = empty($cache_type) ? 'standard' : $cache_type;
637
+		$this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
638
+	}
639
+
640
+
641
+	/**
642
+	 * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
643
+	 * This also SETS the cache if we return the actual property!
644
+	 *
645
+	 * @param string $fieldname        the name of the property we're trying to retrieve
646
+	 * @param bool   $pretty
647
+	 * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
648
+	 *                                 (in cases where the same property may be used for different outputs
649
+	 *                                 - i.e. datetime, money etc.)
650
+	 *                                 It can also accept certain pre-defined "schema" strings
651
+	 *                                 to define how to output the property.
652
+	 *                                 see the field's prepare_for_pretty_echoing for what strings can be used
653
+	 * @return mixed                   whatever the value for the property is we're retrieving
654
+	 * @throws ReflectionException
655
+	 * @throws InvalidArgumentException
656
+	 * @throws InvalidInterfaceException
657
+	 * @throws InvalidDataTypeException
658
+	 * @throws EE_Error
659
+	 */
660
+	protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
661
+	{
662
+		// verify the field exists
663
+		$model = $this->get_model();
664
+		$model->field_settings_for($fieldname);
665
+		$cache_type = $pretty ? 'pretty' : 'standard';
666
+		$cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
667
+		if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
668
+			return $this->_cached_properties[ $fieldname ][ $cache_type ];
669
+		}
670
+		$value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
671
+		$this->_set_cached_property($fieldname, $value, $cache_type);
672
+		return $value;
673
+	}
674
+
675
+
676
+	/**
677
+	 * If the cache didn't fetch the needed item, this fetches it.
678
+	 *
679
+	 * @param string $fieldname
680
+	 * @param bool   $pretty
681
+	 * @param string $extra_cache_ref
682
+	 * @return mixed
683
+	 * @throws InvalidArgumentException
684
+	 * @throws InvalidInterfaceException
685
+	 * @throws InvalidDataTypeException
686
+	 * @throws EE_Error
687
+	 * @throws ReflectionException
688
+	 */
689
+	protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
690
+	{
691
+		$field_obj = $this->get_model()->field_settings_for($fieldname);
692
+		// If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
693
+		if ($field_obj instanceof EE_Datetime_Field) {
694
+			$this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
695
+		}
696
+		if (! isset($this->_fields[ $fieldname ])) {
697
+			$this->_fields[ $fieldname ] = null;
698
+		}
699
+		$value = $pretty
700
+			? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
701
+			: $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
702
+		return $value;
703
+	}
704
+
705
+
706
+	/**
707
+	 * set timezone, formats, and output for EE_Datetime_Field objects
708
+	 *
709
+	 * @param \EE_Datetime_Field $datetime_field
710
+	 * @param bool               $pretty
711
+	 * @param null               $date_or_time
712
+	 * @return void
713
+	 * @throws InvalidArgumentException
714
+	 * @throws InvalidInterfaceException
715
+	 * @throws InvalidDataTypeException
716
+	 * @throws EE_Error
717
+	 */
718
+	protected function _prepare_datetime_field(
719
+		EE_Datetime_Field $datetime_field,
720
+		$pretty = false,
721
+		$date_or_time = null
722
+	) {
723
+		$datetime_field->set_timezone($this->_timezone);
724
+		$datetime_field->set_date_format($this->_dt_frmt, $pretty);
725
+		$datetime_field->set_time_format($this->_tm_frmt, $pretty);
726
+		// set the output returned
727
+		switch ($date_or_time) {
728
+			case 'D':
729
+				$datetime_field->set_date_time_output('date');
730
+				break;
731
+			case 'T':
732
+				$datetime_field->set_date_time_output('time');
733
+				break;
734
+			default:
735
+				$datetime_field->set_date_time_output();
736
+		}
737
+	}
738
+
739
+
740
+	/**
741
+	 * This just takes care of clearing out the cached_properties
742
+	 *
743
+	 * @return void
744
+	 */
745
+	protected function _clear_cached_properties()
746
+	{
747
+		$this->_cached_properties = array();
748
+	}
749
+
750
+
751
+	/**
752
+	 * This just clears out ONE property if it exists in the cache
753
+	 *
754
+	 * @param  string $property_name the property to remove if it exists (from the _cached_properties array)
755
+	 * @return void
756
+	 */
757
+	protected function _clear_cached_property($property_name)
758
+	{
759
+		if (isset($this->_cached_properties[ $property_name ])) {
760
+			unset($this->_cached_properties[ $property_name ]);
761
+		}
762
+	}
763
+
764
+
765
+	/**
766
+	 * Ensures that this related thing is a model object.
767
+	 *
768
+	 * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
769
+	 * @param string $model_name   name of the related thing, eg 'Attendee',
770
+	 * @return EE_Base_Class
771
+	 * @throws ReflectionException
772
+	 * @throws InvalidArgumentException
773
+	 * @throws InvalidInterfaceException
774
+	 * @throws InvalidDataTypeException
775
+	 * @throws EE_Error
776
+	 */
777
+	protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
778
+	{
779
+		$other_model_instance = self::_get_model_instance_with_name(
780
+			self::_get_model_classname($model_name),
781
+			$this->_timezone
782
+		);
783
+		return $other_model_instance->ensure_is_obj($object_or_id);
784
+	}
785
+
786
+
787
+	/**
788
+	 * Forgets the cached model of the given relation Name. So the next time we request it,
789
+	 * we will fetch it again from the database. (Handy if you know it's changed somehow).
790
+	 * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
791
+	 * then only remove that one object from our cached array. Otherwise, clear the entire list
792
+	 *
793
+	 * @param string $relationName                         one of the keys in the _model_relations array on the model.
794
+	 *                                                     Eg 'Registration'
795
+	 * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
796
+	 *                                                     if you intend to use $clear_all = TRUE, or the relation only
797
+	 *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
798
+	 * @param bool   $clear_all                            This flags clearing the entire cache relation property if
799
+	 *                                                     this is HasMany or HABTM.
800
+	 * @throws ReflectionException
801
+	 * @throws InvalidArgumentException
802
+	 * @throws InvalidInterfaceException
803
+	 * @throws InvalidDataTypeException
804
+	 * @throws EE_Error
805
+	 * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
806
+	 *                                                     relation from all
807
+	 */
808
+	public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
809
+	{
810
+		$relationship_to_model = $this->get_model()->related_settings_for($relationName);
811
+		$index_in_cache = '';
812
+		if (! $relationship_to_model) {
813
+			throw new EE_Error(
814
+				sprintf(
815
+					esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
816
+					$relationName,
817
+					get_class($this)
818
+				)
819
+			);
820
+		}
821
+		if ($clear_all) {
822
+			$obj_removed = true;
823
+			$this->_model_relations[ $relationName ] = null;
824
+		} elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
825
+			$obj_removed = $this->_model_relations[ $relationName ];
826
+			$this->_model_relations[ $relationName ] = null;
827
+		} else {
828
+			if ($object_to_remove_or_index_into_array instanceof EE_Base_Class
829
+				&& $object_to_remove_or_index_into_array->ID()
830
+			) {
831
+				$index_in_cache = $object_to_remove_or_index_into_array->ID();
832
+				if (is_array($this->_model_relations[ $relationName ])
833
+					&& ! isset($this->_model_relations[ $relationName ][ $index_in_cache ])
834
+				) {
835
+					$index_found_at = null;
836
+					// find this object in the array even though it has a different key
837
+					foreach ($this->_model_relations[ $relationName ] as $index => $obj) {
838
+						/** @noinspection TypeUnsafeComparisonInspection */
839
+						if ($obj instanceof EE_Base_Class
840
+							&& (
841
+								$obj == $object_to_remove_or_index_into_array
842
+								|| $obj->ID() === $object_to_remove_or_index_into_array->ID()
843
+							)
844
+						) {
845
+							$index_found_at = $index;
846
+							break;
847
+						}
848
+					}
849
+					if ($index_found_at) {
850
+						$index_in_cache = $index_found_at;
851
+					} else {
852
+						// it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
853
+						// if it wasn't in it to begin with. So we're done
854
+						return $object_to_remove_or_index_into_array;
855
+					}
856
+				}
857
+			} elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
858
+				// so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
859
+				foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
860
+					/** @noinspection TypeUnsafeComparisonInspection */
861
+					if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
862
+						$index_in_cache = $index;
863
+					}
864
+				}
865
+			} else {
866
+				$index_in_cache = $object_to_remove_or_index_into_array;
867
+			}
868
+			// supposedly we've found it. But it could just be that the client code
869
+			// provided a bad index/object
870
+			if (isset($this->_model_relations[ $relationName ][ $index_in_cache ])) {
871
+				$obj_removed = $this->_model_relations[ $relationName ][ $index_in_cache ];
872
+				unset($this->_model_relations[ $relationName ][ $index_in_cache ]);
873
+			} else {
874
+				// that thing was never cached anyways.
875
+				$obj_removed = null;
876
+			}
877
+		}
878
+		return $obj_removed;
879
+	}
880
+
881
+
882
+	/**
883
+	 * update_cache_after_object_save
884
+	 * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
885
+	 * obtained after being saved to the db
886
+	 *
887
+	 * @param string        $relationName       - the type of object that is cached
888
+	 * @param EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
889
+	 * @param string        $current_cache_id   - the ID that was used when originally caching the object
890
+	 * @return boolean TRUE on success, FALSE on fail
891
+	 * @throws ReflectionException
892
+	 * @throws InvalidArgumentException
893
+	 * @throws InvalidInterfaceException
894
+	 * @throws InvalidDataTypeException
895
+	 * @throws EE_Error
896
+	 */
897
+	public function update_cache_after_object_save(
898
+		$relationName,
899
+		EE_Base_Class $newly_saved_object,
900
+		$current_cache_id = ''
901
+	) {
902
+		// verify that incoming object is of the correct type
903
+		$obj_class = 'EE_' . $relationName;
904
+		if ($newly_saved_object instanceof $obj_class) {
905
+			/* @type EE_Base_Class $newly_saved_object */
906
+			// now get the type of relation
907
+			$relationship_to_model = $this->get_model()->related_settings_for($relationName);
908
+			// if this is a 1:1 relationship
909
+			if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
910
+				// then just replace the cached object with the newly saved object
911
+				$this->_model_relations[ $relationName ] = $newly_saved_object;
912
+				return true;
913
+				// or if it's some kind of sordid feral polyamorous relationship...
914
+			}
915
+			if (is_array($this->_model_relations[ $relationName ])
916
+				&& isset($this->_model_relations[ $relationName ][ $current_cache_id ])
917
+			) {
918
+				// then remove the current cached item
919
+				unset($this->_model_relations[ $relationName ][ $current_cache_id ]);
920
+				// and cache the newly saved object using it's new ID
921
+				$this->_model_relations[ $relationName ][ $newly_saved_object->ID() ] = $newly_saved_object;
922
+				return true;
923
+			}
924
+		}
925
+		return false;
926
+	}
927
+
928
+
929
+	/**
930
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
931
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
932
+	 *
933
+	 * @param string $relationName
934
+	 * @return EE_Base_Class
935
+	 */
936
+	public function get_one_from_cache($relationName)
937
+	{
938
+		$cached_array_or_object = isset($this->_model_relations[ $relationName ])
939
+			? $this->_model_relations[ $relationName ]
940
+			: null;
941
+		if (is_array($cached_array_or_object)) {
942
+			return array_shift($cached_array_or_object);
943
+		}
944
+		return $cached_array_or_object;
945
+	}
946
+
947
+
948
+	/**
949
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
950
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
951
+	 *
952
+	 * @param string $relationName
953
+	 * @throws ReflectionException
954
+	 * @throws InvalidArgumentException
955
+	 * @throws InvalidInterfaceException
956
+	 * @throws InvalidDataTypeException
957
+	 * @throws EE_Error
958
+	 * @return EE_Base_Class[] NOT necessarily indexed by primary keys
959
+	 */
960
+	public function get_all_from_cache($relationName)
961
+	{
962
+		$objects = isset($this->_model_relations[ $relationName ]) ? $this->_model_relations[ $relationName ] : array();
963
+		// if the result is not an array, but exists, make it an array
964
+		$objects = is_array($objects) ? $objects : array($objects);
965
+		// bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
966
+		// basically, if this model object was stored in the session, and these cached model objects
967
+		// already have IDs, let's make sure they're in their model's entity mapper
968
+		// otherwise we will have duplicates next time we call
969
+		// EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
970
+		$model = EE_Registry::instance()->load_model($relationName);
971
+		foreach ($objects as $model_object) {
972
+			if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
973
+				// ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
974
+				if ($model_object->ID()) {
975
+					$model->add_to_entity_map($model_object);
976
+				}
977
+			} else {
978
+				throw new EE_Error(
979
+					sprintf(
980
+						esc_html__(
981
+							'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
982
+							'event_espresso'
983
+						),
984
+						$relationName,
985
+						gettype($model_object)
986
+					)
987
+				);
988
+			}
989
+		}
990
+		return $objects;
991
+	}
992
+
993
+
994
+	/**
995
+	 * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
996
+	 * matching the given query conditions.
997
+	 *
998
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
999
+	 * @param int   $limit              How many objects to return.
1000
+	 * @param array $query_params       Any additional conditions on the query.
1001
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1002
+	 *                                  you can indicate just the columns you want returned
1003
+	 * @return array|EE_Base_Class[]
1004
+	 * @throws ReflectionException
1005
+	 * @throws InvalidArgumentException
1006
+	 * @throws InvalidInterfaceException
1007
+	 * @throws InvalidDataTypeException
1008
+	 * @throws EE_Error
1009
+	 */
1010
+	public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
1011
+	{
1012
+		$model = $this->get_model();
1013
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1014
+			? $model->get_primary_key_field()->get_name()
1015
+			: $field_to_order_by;
1016
+		$current_value = ! empty($field) ? $this->get($field) : null;
1017
+		if (empty($field) || empty($current_value)) {
1018
+			return array();
1019
+		}
1020
+		return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
1021
+	}
1022
+
1023
+
1024
+	/**
1025
+	 * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
1026
+	 * matching the given query conditions.
1027
+	 *
1028
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1029
+	 * @param int   $limit              How many objects to return.
1030
+	 * @param array $query_params       Any additional conditions on the query.
1031
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1032
+	 *                                  you can indicate just the columns you want returned
1033
+	 * @return array|EE_Base_Class[]
1034
+	 * @throws ReflectionException
1035
+	 * @throws InvalidArgumentException
1036
+	 * @throws InvalidInterfaceException
1037
+	 * @throws InvalidDataTypeException
1038
+	 * @throws EE_Error
1039
+	 */
1040
+	public function previous_x(
1041
+		$field_to_order_by = null,
1042
+		$limit = 1,
1043
+		$query_params = array(),
1044
+		$columns_to_select = null
1045
+	) {
1046
+		$model = $this->get_model();
1047
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1048
+			? $model->get_primary_key_field()->get_name()
1049
+			: $field_to_order_by;
1050
+		$current_value = ! empty($field) ? $this->get($field) : null;
1051
+		if (empty($field) || empty($current_value)) {
1052
+			return array();
1053
+		}
1054
+		return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
1055
+	}
1056
+
1057
+
1058
+	/**
1059
+	 * Returns the next EE_Base_Class object in sequence from this object as found in the database
1060
+	 * matching the given query conditions.
1061
+	 *
1062
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1063
+	 * @param array $query_params       Any additional conditions on the query.
1064
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1065
+	 *                                  you can indicate just the columns you want returned
1066
+	 * @return array|EE_Base_Class
1067
+	 * @throws ReflectionException
1068
+	 * @throws InvalidArgumentException
1069
+	 * @throws InvalidInterfaceException
1070
+	 * @throws InvalidDataTypeException
1071
+	 * @throws EE_Error
1072
+	 */
1073
+	public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1074
+	{
1075
+		$model = $this->get_model();
1076
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1077
+			? $model->get_primary_key_field()->get_name()
1078
+			: $field_to_order_by;
1079
+		$current_value = ! empty($field) ? $this->get($field) : null;
1080
+		if (empty($field) || empty($current_value)) {
1081
+			return array();
1082
+		}
1083
+		return $model->next($current_value, $field, $query_params, $columns_to_select);
1084
+	}
1085
+
1086
+
1087
+	/**
1088
+	 * Returns the previous EE_Base_Class object in sequence from this object as found in the database
1089
+	 * matching the given query conditions.
1090
+	 *
1091
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1092
+	 * @param array $query_params       Any additional conditions on the query.
1093
+	 * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1094
+	 *                                  you can indicate just the column you want returned
1095
+	 * @return array|EE_Base_Class
1096
+	 * @throws ReflectionException
1097
+	 * @throws InvalidArgumentException
1098
+	 * @throws InvalidInterfaceException
1099
+	 * @throws InvalidDataTypeException
1100
+	 * @throws EE_Error
1101
+	 */
1102
+	public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1103
+	{
1104
+		$model = $this->get_model();
1105
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1106
+			? $model->get_primary_key_field()->get_name()
1107
+			: $field_to_order_by;
1108
+		$current_value = ! empty($field) ? $this->get($field) : null;
1109
+		if (empty($field) || empty($current_value)) {
1110
+			return array();
1111
+		}
1112
+		return $model->previous($current_value, $field, $query_params, $columns_to_select);
1113
+	}
1114
+
1115
+
1116
+	/**
1117
+	 * Overrides parent because parent expects old models.
1118
+	 * This also doesn't do any validation, and won't work for serialized arrays
1119
+	 *
1120
+	 * @param string $field_name
1121
+	 * @param mixed  $field_value_from_db
1122
+	 * @throws ReflectionException
1123
+	 * @throws InvalidArgumentException
1124
+	 * @throws InvalidInterfaceException
1125
+	 * @throws InvalidDataTypeException
1126
+	 * @throws EE_Error
1127
+	 */
1128
+	public function set_from_db($field_name, $field_value_from_db)
1129
+	{
1130
+		$field_obj = $this->get_model()->field_settings_for($field_name);
1131
+		if ($field_obj instanceof EE_Model_Field_Base) {
1132
+			// you would think the DB has no NULLs for non-null label fields right? wrong!
1133
+			// eg, a CPT model object could have an entry in the posts table, but no
1134
+			// entry in the meta table. Meaning that all its columns in the meta table
1135
+			// are null! yikes! so when we find one like that, use defaults for its meta columns
1136
+			if ($field_value_from_db === null) {
1137
+				if ($field_obj->is_nullable()) {
1138
+					// if the field allows nulls, then let it be null
1139
+					$field_value = null;
1140
+				} else {
1141
+					$field_value = $field_obj->get_default_value();
1142
+				}
1143
+			} else {
1144
+				$field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1145
+			}
1146
+			$this->_fields[ $field_name ] = $field_value;
1147
+			$this->_clear_cached_property($field_name);
1148
+		}
1149
+	}
1150
+
1151
+
1152
+	/**
1153
+	 * verifies that the specified field is of the correct type
1154
+	 *
1155
+	 * @param string $field_name
1156
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1157
+	 *                                (in cases where the same property may be used for different outputs
1158
+	 *                                - i.e. datetime, money etc.)
1159
+	 * @return mixed
1160
+	 * @throws ReflectionException
1161
+	 * @throws InvalidArgumentException
1162
+	 * @throws InvalidInterfaceException
1163
+	 * @throws InvalidDataTypeException
1164
+	 * @throws EE_Error
1165
+	 */
1166
+	public function get($field_name, $extra_cache_ref = null)
1167
+	{
1168
+		return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1169
+	}
1170
+
1171
+
1172
+	/**
1173
+	 * This method simply returns the RAW unprocessed value for the given property in this class
1174
+	 *
1175
+	 * @param  string $field_name A valid fieldname
1176
+	 * @return mixed              Whatever the raw value stored on the property is.
1177
+	 * @throws ReflectionException
1178
+	 * @throws InvalidArgumentException
1179
+	 * @throws InvalidInterfaceException
1180
+	 * @throws InvalidDataTypeException
1181
+	 * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1182
+	 */
1183
+	public function get_raw($field_name)
1184
+	{
1185
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1186
+		return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1187
+			? $this->_fields[ $field_name ]->format('U')
1188
+			: $this->_fields[ $field_name ];
1189
+	}
1190
+
1191
+
1192
+	/**
1193
+	 * This is used to return the internal DateTime object used for a field that is a
1194
+	 * EE_Datetime_Field.
1195
+	 *
1196
+	 * @param string $field_name               The field name retrieving the DateTime object.
1197
+	 * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1198
+	 * @throws EE_Error an error is set and false returned.  If the field IS an
1199
+	 *                                         EE_Datetime_Field and but the field value is null, then
1200
+	 *                                         just null is returned (because that indicates that likely
1201
+	 *                                         this field is nullable).
1202
+	 * @throws InvalidArgumentException
1203
+	 * @throws InvalidDataTypeException
1204
+	 * @throws InvalidInterfaceException
1205
+	 * @throws ReflectionException
1206
+	 */
1207
+	public function get_DateTime_object($field_name)
1208
+	{
1209
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1210
+		if (! $field_settings instanceof EE_Datetime_Field) {
1211
+			EE_Error::add_error(
1212
+				sprintf(
1213
+					esc_html__(
1214
+						'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1215
+						'event_espresso'
1216
+					),
1217
+					$field_name
1218
+				),
1219
+				__FILE__,
1220
+				__FUNCTION__,
1221
+				__LINE__
1222
+			);
1223
+			return false;
1224
+		}
1225
+		return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1226
+			? clone $this->_fields[ $field_name ]
1227
+			: null;
1228
+	}
1229
+
1230
+
1231
+	/**
1232
+	 * To be used in template to immediately echo out the value, and format it for output.
1233
+	 * Eg, should call stripslashes and whatnot before echoing
1234
+	 *
1235
+	 * @param string $field_name      the name of the field as it appears in the DB
1236
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1237
+	 *                                (in cases where the same property may be used for different outputs
1238
+	 *                                - i.e. datetime, money etc.)
1239
+	 * @return void
1240
+	 * @throws ReflectionException
1241
+	 * @throws InvalidArgumentException
1242
+	 * @throws InvalidInterfaceException
1243
+	 * @throws InvalidDataTypeException
1244
+	 * @throws EE_Error
1245
+	 */
1246
+	public function e($field_name, $extra_cache_ref = null)
1247
+	{
1248
+		echo $this->get_pretty($field_name, $extra_cache_ref);
1249
+	}
1250
+
1251
+
1252
+	/**
1253
+	 * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1254
+	 * can be easily used as the value of form input.
1255
+	 *
1256
+	 * @param string $field_name
1257
+	 * @return void
1258
+	 * @throws ReflectionException
1259
+	 * @throws InvalidArgumentException
1260
+	 * @throws InvalidInterfaceException
1261
+	 * @throws InvalidDataTypeException
1262
+	 * @throws EE_Error
1263
+	 */
1264
+	public function f($field_name)
1265
+	{
1266
+		$this->e($field_name, 'form_input');
1267
+	}
1268
+
1269
+
1270
+	/**
1271
+	 * Same as `f()` but just returns the value instead of echoing it
1272
+	 *
1273
+	 * @param string $field_name
1274
+	 * @return string
1275
+	 * @throws ReflectionException
1276
+	 * @throws InvalidArgumentException
1277
+	 * @throws InvalidInterfaceException
1278
+	 * @throws InvalidDataTypeException
1279
+	 * @throws EE_Error
1280
+	 */
1281
+	public function get_f($field_name)
1282
+	{
1283
+		return (string) $this->get_pretty($field_name, 'form_input');
1284
+	}
1285
+
1286
+
1287
+	/**
1288
+	 * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1289
+	 * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1290
+	 * to see what options are available.
1291
+	 *
1292
+	 * @param string $field_name
1293
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1294
+	 *                                (in cases where the same property may be used for different outputs
1295
+	 *                                - i.e. datetime, money etc.)
1296
+	 * @return mixed
1297
+	 * @throws ReflectionException
1298
+	 * @throws InvalidArgumentException
1299
+	 * @throws InvalidInterfaceException
1300
+	 * @throws InvalidDataTypeException
1301
+	 * @throws EE_Error
1302
+	 */
1303
+	public function get_pretty($field_name, $extra_cache_ref = null)
1304
+	{
1305
+		return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1306
+	}
1307
+
1308
+
1309
+	/**
1310
+	 * This simply returns the datetime for the given field name
1311
+	 * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1312
+	 * (and the equivalent e_date, e_time, e_datetime).
1313
+	 *
1314
+	 * @access   protected
1315
+	 * @param string   $field_name   Field on the instantiated EE_Base_Class child object
1316
+	 * @param string   $dt_frmt      valid datetime format used for date
1317
+	 *                               (if '' then we just use the default on the field,
1318
+	 *                               if NULL we use the last-used format)
1319
+	 * @param string   $tm_frmt      Same as above except this is for time format
1320
+	 * @param string   $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1321
+	 * @param  boolean $echo         Whether the dtt is echoing using pretty echoing or just returned using vanilla get
1322
+	 * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1323
+	 *                               if field is not a valid dtt field, or void if echoing
1324
+	 * @throws ReflectionException
1325
+	 * @throws InvalidArgumentException
1326
+	 * @throws InvalidInterfaceException
1327
+	 * @throws InvalidDataTypeException
1328
+	 * @throws EE_Error
1329
+	 */
1330
+	protected function _get_datetime($field_name, $dt_frmt = '', $tm_frmt = '', $date_or_time = '', $echo = false)
1331
+	{
1332
+		// clear cached property
1333
+		$this->_clear_cached_property($field_name);
1334
+		// reset format properties because they are used in get()
1335
+		$this->_dt_frmt = $dt_frmt !== '' ? $dt_frmt : $this->_dt_frmt;
1336
+		$this->_tm_frmt = $tm_frmt !== '' ? $tm_frmt : $this->_tm_frmt;
1337
+		if ($echo) {
1338
+			$this->e($field_name, $date_or_time);
1339
+			return '';
1340
+		}
1341
+		return $this->get($field_name, $date_or_time);
1342
+	}
1343
+
1344
+
1345
+	/**
1346
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1347
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1348
+	 * other echoes the pretty value for dtt)
1349
+	 *
1350
+	 * @param  string $field_name name of model object datetime field holding the value
1351
+	 * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1352
+	 * @return string            datetime value formatted
1353
+	 * @throws ReflectionException
1354
+	 * @throws InvalidArgumentException
1355
+	 * @throws InvalidInterfaceException
1356
+	 * @throws InvalidDataTypeException
1357
+	 * @throws EE_Error
1358
+	 */
1359
+	public function get_date($field_name, $format = '')
1360
+	{
1361
+		return $this->_get_datetime($field_name, $format, null, 'D');
1362
+	}
1363
+
1364
+
1365
+	/**
1366
+	 * @param        $field_name
1367
+	 * @param string $format
1368
+	 * @throws ReflectionException
1369
+	 * @throws InvalidArgumentException
1370
+	 * @throws InvalidInterfaceException
1371
+	 * @throws InvalidDataTypeException
1372
+	 * @throws EE_Error
1373
+	 */
1374
+	public function e_date($field_name, $format = '')
1375
+	{
1376
+		$this->_get_datetime($field_name, $format, null, 'D', true);
1377
+	}
1378
+
1379
+
1380
+	/**
1381
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1382
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1383
+	 * other echoes the pretty value for dtt)
1384
+	 *
1385
+	 * @param  string $field_name name of model object datetime field holding the value
1386
+	 * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1387
+	 * @return string             datetime value formatted
1388
+	 * @throws ReflectionException
1389
+	 * @throws InvalidArgumentException
1390
+	 * @throws InvalidInterfaceException
1391
+	 * @throws InvalidDataTypeException
1392
+	 * @throws EE_Error
1393
+	 */
1394
+	public function get_time($field_name, $format = '')
1395
+	{
1396
+		return $this->_get_datetime($field_name, null, $format, 'T');
1397
+	}
1398
+
1399
+
1400
+	/**
1401
+	 * @param        $field_name
1402
+	 * @param string $format
1403
+	 * @throws ReflectionException
1404
+	 * @throws InvalidArgumentException
1405
+	 * @throws InvalidInterfaceException
1406
+	 * @throws InvalidDataTypeException
1407
+	 * @throws EE_Error
1408
+	 */
1409
+	public function e_time($field_name, $format = '')
1410
+	{
1411
+		$this->_get_datetime($field_name, null, $format, 'T', true);
1412
+	}
1413
+
1414
+
1415
+	/**
1416
+	 * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1417
+	 * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1418
+	 * other echoes the pretty value for dtt)
1419
+	 *
1420
+	 * @param  string $field_name name of model object datetime field holding the value
1421
+	 * @param  string $dt_frmt    format for the date returned (if NULL we use default in dt_frmt property)
1422
+	 * @param  string $tm_frmt    format for the time returned (if NULL we use default in tm_frmt property)
1423
+	 * @return string             datetime value formatted
1424
+	 * @throws ReflectionException
1425
+	 * @throws InvalidArgumentException
1426
+	 * @throws InvalidInterfaceException
1427
+	 * @throws InvalidDataTypeException
1428
+	 * @throws EE_Error
1429
+	 */
1430
+	public function get_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1431
+	{
1432
+		return $this->_get_datetime($field_name, $dt_frmt, $tm_frmt);
1433
+	}
1434
+
1435
+
1436
+	/**
1437
+	 * @param string $field_name
1438
+	 * @param string $dt_frmt
1439
+	 * @param string $tm_frmt
1440
+	 * @throws ReflectionException
1441
+	 * @throws InvalidArgumentException
1442
+	 * @throws InvalidInterfaceException
1443
+	 * @throws InvalidDataTypeException
1444
+	 * @throws EE_Error
1445
+	 */
1446
+	public function e_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1447
+	{
1448
+		$this->_get_datetime($field_name, $dt_frmt, $tm_frmt, null, true);
1449
+	}
1450
+
1451
+
1452
+	/**
1453
+	 * Get the i8ln value for a date using the WordPress @see date_i18n function.
1454
+	 *
1455
+	 * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1456
+	 * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1457
+	 *                           on the object will be used.
1458
+	 * @return string Date and time string in set locale or false if no field exists for the given
1459
+	 * @throws ReflectionException
1460
+	 * @throws InvalidArgumentException
1461
+	 * @throws InvalidInterfaceException
1462
+	 * @throws InvalidDataTypeException
1463
+	 * @throws EE_Error
1464
+	 *                           field name.
1465
+	 */
1466
+	public function get_i18n_datetime($field_name, $format = '')
1467
+	{
1468
+		$format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1469
+		return date_i18n(
1470
+			$format,
1471
+			EEH_DTT_Helper::get_timestamp_with_offset(
1472
+				$this->get_raw($field_name),
1473
+				$this->_timezone
1474
+			)
1475
+		);
1476
+	}
1477
+
1478
+
1479
+	/**
1480
+	 * This method validates whether the given field name is a valid field on the model object as well as it is of a
1481
+	 * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1482
+	 * thrown.
1483
+	 *
1484
+	 * @param  string $field_name The field name being checked
1485
+	 * @throws ReflectionException
1486
+	 * @throws InvalidArgumentException
1487
+	 * @throws InvalidInterfaceException
1488
+	 * @throws InvalidDataTypeException
1489
+	 * @throws EE_Error
1490
+	 * @return EE_Datetime_Field
1491
+	 */
1492
+	protected function _get_dtt_field_settings($field_name)
1493
+	{
1494
+		$field = $this->get_model()->field_settings_for($field_name);
1495
+		// check if field is dtt
1496
+		if ($field instanceof EE_Datetime_Field) {
1497
+			return $field;
1498
+		}
1499
+		throw new EE_Error(
1500
+			sprintf(
1501
+				esc_html__(
1502
+					'The field name "%s" has been requested for the EE_Base_Class datetime functions and it is not a valid EE_Datetime_Field.  Please check the spelling of the field and make sure it has been setup as a EE_Datetime_Field in the %s model constructor',
1503
+					'event_espresso'
1504
+				),
1505
+				$field_name,
1506
+				self::_get_model_classname(get_class($this))
1507
+			)
1508
+		);
1509
+	}
1510
+
1511
+
1512
+
1513
+
1514
+	/**
1515
+	 * NOTE ABOUT BELOW:
1516
+	 * These convenience date and time setters are for setting date and time independently.  In other words you might
1517
+	 * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1518
+	 * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1519
+	 * method and make sure you send the entire datetime value for setting.
1520
+	 */
1521
+	/**
1522
+	 * sets the time on a datetime property
1523
+	 *
1524
+	 * @access protected
1525
+	 * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1526
+	 * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1527
+	 * @throws ReflectionException
1528
+	 * @throws InvalidArgumentException
1529
+	 * @throws InvalidInterfaceException
1530
+	 * @throws InvalidDataTypeException
1531
+	 * @throws EE_Error
1532
+	 */
1533
+	protected function _set_time_for($time, $fieldname)
1534
+	{
1535
+		$this->_set_date_time('T', $time, $fieldname);
1536
+	}
1537
+
1538
+
1539
+	/**
1540
+	 * sets the date on a datetime property
1541
+	 *
1542
+	 * @access protected
1543
+	 * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1544
+	 * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1545
+	 * @throws ReflectionException
1546
+	 * @throws InvalidArgumentException
1547
+	 * @throws InvalidInterfaceException
1548
+	 * @throws InvalidDataTypeException
1549
+	 * @throws EE_Error
1550
+	 */
1551
+	protected function _set_date_for($date, $fieldname)
1552
+	{
1553
+		$this->_set_date_time('D', $date, $fieldname);
1554
+	}
1555
+
1556
+
1557
+	/**
1558
+	 * This takes care of setting a date or time independently on a given model object property. This method also
1559
+	 * verifies that the given fieldname matches a model object property and is for a EE_Datetime_Field field
1560
+	 *
1561
+	 * @access protected
1562
+	 * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1563
+	 * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1564
+	 * @param string          $fieldname      the name of the field the date OR time is being set on (must match a
1565
+	 *                                        EE_Datetime_Field property)
1566
+	 * @throws ReflectionException
1567
+	 * @throws InvalidArgumentException
1568
+	 * @throws InvalidInterfaceException
1569
+	 * @throws InvalidDataTypeException
1570
+	 * @throws EE_Error
1571
+	 */
1572
+	protected function _set_date_time($what = 'T', $datetime_value, $fieldname)
1573
+	{
1574
+		$field = $this->_get_dtt_field_settings($fieldname);
1575
+		$field->set_timezone($this->_timezone);
1576
+		$field->set_date_format($this->_dt_frmt);
1577
+		$field->set_time_format($this->_tm_frmt);
1578
+		switch ($what) {
1579
+			case 'T':
1580
+				$this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_time(
1581
+					$datetime_value,
1582
+					$this->_fields[ $fieldname ]
1583
+				);
1584
+				break;
1585
+			case 'D':
1586
+				$this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_date(
1587
+					$datetime_value,
1588
+					$this->_fields[ $fieldname ]
1589
+				);
1590
+				break;
1591
+			case 'B':
1592
+				$this->_fields[ $fieldname ] = $field->prepare_for_set($datetime_value);
1593
+				break;
1594
+		}
1595
+		$this->_clear_cached_property($fieldname);
1596
+	}
1597
+
1598
+
1599
+	/**
1600
+	 * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1601
+	 * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1602
+	 * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1603
+	 * that could lead to some unexpected results!
1604
+	 *
1605
+	 * @access public
1606
+	 * @param string $field_name               This is the name of the field on the object that contains the date/time
1607
+	 *                                         value being returned.
1608
+	 * @param string $callback                 must match a valid method in this class (defaults to get_datetime)
1609
+	 * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1610
+	 * @param string $prepend                  You can include something to prepend on the timestamp
1611
+	 * @param string $append                   You can include something to append on the timestamp
1612
+	 * @throws ReflectionException
1613
+	 * @throws InvalidArgumentException
1614
+	 * @throws InvalidInterfaceException
1615
+	 * @throws InvalidDataTypeException
1616
+	 * @throws EE_Error
1617
+	 * @return string timestamp
1618
+	 */
1619
+	public function display_in_my_timezone(
1620
+		$field_name,
1621
+		$callback = 'get_datetime',
1622
+		$args = null,
1623
+		$prepend = '',
1624
+		$append = ''
1625
+	) {
1626
+		$timezone = EEH_DTT_Helper::get_timezone();
1627
+		if ($timezone === $this->_timezone) {
1628
+			return '';
1629
+		}
1630
+		$original_timezone = $this->_timezone;
1631
+		$this->set_timezone($timezone);
1632
+		$fn = (array) $field_name;
1633
+		$args = array_merge($fn, (array) $args);
1634
+		if (! method_exists($this, $callback)) {
1635
+			throw new EE_Error(
1636
+				sprintf(
1637
+					esc_html__(
1638
+						'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1639
+						'event_espresso'
1640
+					),
1641
+					$callback
1642
+				)
1643
+			);
1644
+		}
1645
+		$args = (array) $args;
1646
+		$return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1647
+		$this->set_timezone($original_timezone);
1648
+		return $return;
1649
+	}
1650
+
1651
+
1652
+	/**
1653
+	 * Deletes this model object.
1654
+	 * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1655
+	 * override
1656
+	 * `EE_Base_Class::_delete` NOT this class.
1657
+	 *
1658
+	 * @return boolean | int
1659
+	 * @throws ReflectionException
1660
+	 * @throws InvalidArgumentException
1661
+	 * @throws InvalidInterfaceException
1662
+	 * @throws InvalidDataTypeException
1663
+	 * @throws EE_Error
1664
+	 */
1665
+	public function delete()
1666
+	{
1667
+		/**
1668
+		 * Called just before the `EE_Base_Class::_delete` method call.
1669
+		 * Note:
1670
+		 * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1671
+		 * should be aware that `_delete` may not always result in a permanent delete.
1672
+		 * For example, `EE_Soft_Delete_Base_Class::_delete`
1673
+		 * soft deletes (trash) the object and does not permanently delete it.
1674
+		 *
1675
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1676
+		 */
1677
+		do_action('AHEE__EE_Base_Class__delete__before', $this);
1678
+		$result = $this->_delete();
1679
+		/**
1680
+		 * Called just after the `EE_Base_Class::_delete` method call.
1681
+		 * Note:
1682
+		 * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1683
+		 * should be aware that `_delete` may not always result in a permanent delete.
1684
+		 * For example `EE_Soft_Base_Class::_delete`
1685
+		 * soft deletes (trash) the object and does not permanently delete it.
1686
+		 *
1687
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1688
+		 * @param boolean       $result
1689
+		 */
1690
+		do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1691
+		return $result;
1692
+	}
1693
+
1694
+
1695
+	/**
1696
+	 * Calls the specific delete method for the instantiated class.
1697
+	 * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1698
+	 * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1699
+	 * `EE_Base_Class::delete`
1700
+	 *
1701
+	 * @return bool|int
1702
+	 * @throws ReflectionException
1703
+	 * @throws InvalidArgumentException
1704
+	 * @throws InvalidInterfaceException
1705
+	 * @throws InvalidDataTypeException
1706
+	 * @throws EE_Error
1707
+	 */
1708
+	protected function _delete()
1709
+	{
1710
+		return $this->delete_permanently();
1711
+	}
1712
+
1713
+
1714
+	/**
1715
+	 * Deletes this model object permanently from db
1716
+	 * (but keep in mind related models may block the delete and return an error)
1717
+	 *
1718
+	 * @return bool | int
1719
+	 * @throws ReflectionException
1720
+	 * @throws InvalidArgumentException
1721
+	 * @throws InvalidInterfaceException
1722
+	 * @throws InvalidDataTypeException
1723
+	 * @throws EE_Error
1724
+	 */
1725
+	public function delete_permanently()
1726
+	{
1727
+		/**
1728
+		 * Called just before HARD deleting a model object
1729
+		 *
1730
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1731
+		 */
1732
+		do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1733
+		$model = $this->get_model();
1734
+		$result = $model->delete_permanently_by_ID($this->ID());
1735
+		$this->refresh_cache_of_related_objects();
1736
+		/**
1737
+		 * Called just after HARD deleting a model object
1738
+		 *
1739
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1740
+		 * @param boolean       $result
1741
+		 */
1742
+		do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1743
+		return $result;
1744
+	}
1745
+
1746
+
1747
+	/**
1748
+	 * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1749
+	 * related model objects
1750
+	 *
1751
+	 * @throws ReflectionException
1752
+	 * @throws InvalidArgumentException
1753
+	 * @throws InvalidInterfaceException
1754
+	 * @throws InvalidDataTypeException
1755
+	 * @throws EE_Error
1756
+	 */
1757
+	public function refresh_cache_of_related_objects()
1758
+	{
1759
+		$model = $this->get_model();
1760
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1761
+			if (! empty($this->_model_relations[ $relation_name ])) {
1762
+				$related_objects = $this->_model_relations[ $relation_name ];
1763
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
1764
+					// this relation only stores a single model object, not an array
1765
+					// but let's make it consistent
1766
+					$related_objects = array($related_objects);
1767
+				}
1768
+				foreach ($related_objects as $related_object) {
1769
+					// only refresh their cache if they're in memory
1770
+					if ($related_object instanceof EE_Base_Class) {
1771
+						$related_object->clear_cache(
1772
+							$model->get_this_model_name(),
1773
+							$this
1774
+						);
1775
+					}
1776
+				}
1777
+			}
1778
+		}
1779
+	}
1780
+
1781
+
1782
+	/**
1783
+	 *        Saves this object to the database. An array may be supplied to set some values on this
1784
+	 * object just before saving.
1785
+	 *
1786
+	 * @access public
1787
+	 * @param array $set_cols_n_values keys are field names, values are their new values,
1788
+	 *                                 if provided during the save() method (often client code will change the fields'
1789
+	 *                                 values before calling save)
1790
+	 * @throws InvalidArgumentException
1791
+	 * @throws InvalidInterfaceException
1792
+	 * @throws InvalidDataTypeException
1793
+	 * @throws EE_Error
1794
+	 * @return int , 1 on a successful update, the ID of the new entry on insert; 0 on failure or if the model object
1795
+	 *                                 isn't allowed to persist (as determined by EE_Base_Class::allow_persist())
1796
+	 * @throws ReflectionException
1797
+	 * @throws ReflectionException
1798
+	 * @throws ReflectionException
1799
+	 */
1800
+	public function save($set_cols_n_values = array())
1801
+	{
1802
+		$model = $this->get_model();
1803
+		/**
1804
+		 * Filters the fields we're about to save on the model object
1805
+		 *
1806
+		 * @param array         $set_cols_n_values
1807
+		 * @param EE_Base_Class $model_object
1808
+		 */
1809
+		$set_cols_n_values = (array) apply_filters(
1810
+			'FHEE__EE_Base_Class__save__set_cols_n_values',
1811
+			$set_cols_n_values,
1812
+			$this
1813
+		);
1814
+		// set attributes as provided in $set_cols_n_values
1815
+		foreach ($set_cols_n_values as $column => $value) {
1816
+			$this->set($column, $value);
1817
+		}
1818
+		// no changes ? then don't do anything
1819
+		if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1820
+			return 0;
1821
+		}
1822
+		/**
1823
+		 * Saving a model object.
1824
+		 * Before we perform a save, this action is fired.
1825
+		 *
1826
+		 * @param EE_Base_Class $model_object the model object about to be saved.
1827
+		 */
1828
+		do_action('AHEE__EE_Base_Class__save__begin', $this);
1829
+		if (! $this->allow_persist()) {
1830
+			return 0;
1831
+		}
1832
+		// now get current attribute values
1833
+		$save_cols_n_values = $this->_fields;
1834
+		// if the object already has an ID, update it. Otherwise, insert it
1835
+		// also: change the assumption about values passed to the model NOT being prepare dby the model object.
1836
+		// They have been
1837
+		$old_assumption_concerning_value_preparation = $model
1838
+			->get_assumption_concerning_values_already_prepared_by_model_object();
1839
+		$model->assume_values_already_prepared_by_model_object(true);
1840
+		// does this model have an autoincrement PK?
1841
+		if ($model->has_primary_key_field()) {
1842
+			if ($model->get_primary_key_field()->is_auto_increment()) {
1843
+				// ok check if it's set, if so: update; if not, insert
1844
+				if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1845
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1846
+				} else {
1847
+					unset($save_cols_n_values[ $model->primary_key_name() ]);
1848
+					$results = $model->insert($save_cols_n_values);
1849
+					if ($results) {
1850
+						// if successful, set the primary key
1851
+						// but don't use the normal SET method, because it will check if
1852
+						// an item with the same ID exists in the mapper & db, then
1853
+						// will find it in the db (because we just added it) and THAT object
1854
+						// will get added to the mapper before we can add this one!
1855
+						// but if we just avoid using the SET method, all that headache can be avoided
1856
+						$pk_field_name = $model->primary_key_name();
1857
+						$this->_fields[ $pk_field_name ] = $results;
1858
+						$this->_clear_cached_property($pk_field_name);
1859
+						$model->add_to_entity_map($this);
1860
+						$this->_update_cached_related_model_objs_fks();
1861
+					}
1862
+				}
1863
+			} else {// PK is NOT auto-increment
1864
+				// so check if one like it already exists in the db
1865
+				if ($model->exists_by_ID($this->ID())) {
1866
+					if (WP_DEBUG && ! $this->in_entity_map()) {
1867
+						throw new EE_Error(
1868
+							sprintf(
1869
+								esc_html__(
1870
+									'Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1871
+									'event_espresso'
1872
+								),
1873
+								get_class($this),
1874
+								get_class($model) . '::instance()->add_to_entity_map()',
1875
+								get_class($model) . '::instance()->get_one_by_ID()',
1876
+								'<br />'
1877
+							)
1878
+						);
1879
+					}
1880
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1881
+				} else {
1882
+					$results = $model->insert($save_cols_n_values);
1883
+					$this->_update_cached_related_model_objs_fks();
1884
+				}
1885
+			}
1886
+		} else {// there is NO primary key
1887
+			$already_in_db = false;
1888
+			foreach ($model->unique_indexes() as $index) {
1889
+				$uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1890
+				if ($model->exists(array($uniqueness_where_params))) {
1891
+					$already_in_db = true;
1892
+				}
1893
+			}
1894
+			if ($already_in_db) {
1895
+				$combined_pk_fields_n_values = array_intersect_key(
1896
+					$save_cols_n_values,
1897
+					$model->get_combined_primary_key_fields()
1898
+				);
1899
+				$results = $model->update(
1900
+					$save_cols_n_values,
1901
+					$combined_pk_fields_n_values
1902
+				);
1903
+			} else {
1904
+				$results = $model->insert($save_cols_n_values);
1905
+			}
1906
+		}
1907
+		// restore the old assumption about values being prepared by the model object
1908
+		$model->assume_values_already_prepared_by_model_object(
1909
+			$old_assumption_concerning_value_preparation
1910
+		);
1911
+		/**
1912
+		 * After saving the model object this action is called
1913
+		 *
1914
+		 * @param EE_Base_Class $model_object which was just saved
1915
+		 * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1916
+		 *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1917
+		 */
1918
+		do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1919
+		$this->_has_changes = false;
1920
+		return $results;
1921
+	}
1922
+
1923
+
1924
+	/**
1925
+	 * Updates the foreign key on related models objects pointing to this to have this model object's ID
1926
+	 * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1927
+	 * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1928
+	 * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1929
+	 * saved it to the db. We also create a registration and don't save it to the DB, but we DO cache it on the
1930
+	 * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1931
+	 * or not they exist in the DB (if they do, their DB records will be automatically updated)
1932
+	 *
1933
+	 * @return void
1934
+	 * @throws ReflectionException
1935
+	 * @throws InvalidArgumentException
1936
+	 * @throws InvalidInterfaceException
1937
+	 * @throws InvalidDataTypeException
1938
+	 * @throws EE_Error
1939
+	 */
1940
+	protected function _update_cached_related_model_objs_fks()
1941
+	{
1942
+		$model = $this->get_model();
1943
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1944
+			if ($relation_obj instanceof EE_Has_Many_Relation) {
1945
+				foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1946
+					$fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1947
+						$model->get_this_model_name()
1948
+					);
1949
+					$related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1950
+					if ($related_model_obj_in_cache->ID()) {
1951
+						$related_model_obj_in_cache->save();
1952
+					}
1953
+				}
1954
+			}
1955
+		}
1956
+	}
1957
+
1958
+
1959
+	/**
1960
+	 * Saves this model object and its NEW cached relations to the database.
1961
+	 * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1962
+	 * In order for that to work, we would need to mark model objects as dirty/clean...
1963
+	 * because otherwise, there's a potential for infinite looping of saving
1964
+	 * Saves the cached related model objects, and ensures the relation between them
1965
+	 * and this object and properly setup
1966
+	 *
1967
+	 * @return int ID of new model object on save; 0 on failure+
1968
+	 * @throws ReflectionException
1969
+	 * @throws InvalidArgumentException
1970
+	 * @throws InvalidInterfaceException
1971
+	 * @throws InvalidDataTypeException
1972
+	 * @throws EE_Error
1973
+	 */
1974
+	public function save_new_cached_related_model_objs()
1975
+	{
1976
+		// make sure this has been saved
1977
+		if (! $this->ID()) {
1978
+			$id = $this->save();
1979
+		} else {
1980
+			$id = $this->ID();
1981
+		}
1982
+		// now save all the NEW cached model objects  (ie they don't exist in the DB)
1983
+		foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1984
+			if ($this->_model_relations[ $relationName ]) {
1985
+				// is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
1986
+				// or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
1987
+				/* @var $related_model_obj EE_Base_Class */
1988
+				if ($relationObj instanceof EE_Belongs_To_Relation) {
1989
+					// add a relation to that relation type (which saves the appropriate thing in the process)
1990
+					// but ONLY if it DOES NOT exist in the DB
1991
+					$related_model_obj = $this->_model_relations[ $relationName ];
1992
+					// if( ! $related_model_obj->ID()){
1993
+					$this->_add_relation_to($related_model_obj, $relationName);
1994
+					$related_model_obj->save_new_cached_related_model_objs();
1995
+					// }
1996
+				} else {
1997
+					foreach ($this->_model_relations[ $relationName ] as $related_model_obj) {
1998
+						// add a relation to that relation type (which saves the appropriate thing in the process)
1999
+						// but ONLY if it DOES NOT exist in the DB
2000
+						// if( ! $related_model_obj->ID()){
2001
+						$this->_add_relation_to($related_model_obj, $relationName);
2002
+						$related_model_obj->save_new_cached_related_model_objs();
2003
+						// }
2004
+					}
2005
+				}
2006
+			}
2007
+		}
2008
+		return $id;
2009
+	}
2010
+
2011
+
2012
+	/**
2013
+	 * for getting a model while instantiated.
2014
+	 *
2015
+	 * @return EEM_Base | EEM_CPT_Base
2016
+	 * @throws ReflectionException
2017
+	 * @throws InvalidArgumentException
2018
+	 * @throws InvalidInterfaceException
2019
+	 * @throws InvalidDataTypeException
2020
+	 * @throws EE_Error
2021
+	 */
2022
+	public function get_model()
2023
+	{
2024
+		if (! $this->_model) {
2025
+			$modelName = self::_get_model_classname(get_class($this));
2026
+			$this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2027
+		} else {
2028
+			$this->_model->set_timezone($this->_timezone);
2029
+		}
2030
+		return $this->_model;
2031
+	}
2032
+
2033
+
2034
+	/**
2035
+	 * @param $props_n_values
2036
+	 * @param $classname
2037
+	 * @return mixed bool|EE_Base_Class|EEM_CPT_Base
2038
+	 * @throws ReflectionException
2039
+	 * @throws InvalidArgumentException
2040
+	 * @throws InvalidInterfaceException
2041
+	 * @throws InvalidDataTypeException
2042
+	 * @throws EE_Error
2043
+	 */
2044
+	protected static function _get_object_from_entity_mapper($props_n_values, $classname)
2045
+	{
2046
+		// TODO: will not work for Term_Relationships because they have no PK!
2047
+		$primary_id_ref = self::_get_primary_key_name($classname);
2048
+		if (array_key_exists($primary_id_ref, $props_n_values)
2049
+			&& ! empty($props_n_values[ $primary_id_ref ])
2050
+		) {
2051
+			$id = $props_n_values[ $primary_id_ref ];
2052
+			return self::_get_model($classname)->get_from_entity_map($id);
2053
+		}
2054
+		return false;
2055
+	}
2056
+
2057
+
2058
+	/**
2059
+	 * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
2060
+	 * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
2061
+	 * primary key for the model AND it is not null, then we check the db. If there's a an object we return it.  If not
2062
+	 * we return false.
2063
+	 *
2064
+	 * @param  array  $props_n_values   incoming array of properties and their values
2065
+	 * @param  string $classname        the classname of the child class
2066
+	 * @param null    $timezone
2067
+	 * @param array   $date_formats     incoming date_formats in an array where the first value is the
2068
+	 *                                  date_format and the second value is the time format
2069
+	 * @return mixed (EE_Base_Class|bool)
2070
+	 * @throws InvalidArgumentException
2071
+	 * @throws InvalidInterfaceException
2072
+	 * @throws InvalidDataTypeException
2073
+	 * @throws EE_Error
2074
+	 * @throws ReflectionException
2075
+	 * @throws ReflectionException
2076
+	 * @throws ReflectionException
2077
+	 */
2078
+	protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
2079
+	{
2080
+		$existing = null;
2081
+		$model = self::_get_model($classname, $timezone);
2082
+		if ($model->has_primary_key_field()) {
2083
+			$primary_id_ref = self::_get_primary_key_name($classname);
2084
+			if (array_key_exists($primary_id_ref, $props_n_values)
2085
+				&& ! empty($props_n_values[ $primary_id_ref ])
2086
+			) {
2087
+				$existing = $model->get_one_by_ID(
2088
+					$props_n_values[ $primary_id_ref ]
2089
+				);
2090
+			}
2091
+		} elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
2092
+			// no primary key on this model, but there's still a matching item in the DB
2093
+			$existing = self::_get_model($classname, $timezone)->get_one_by_ID(
2094
+				self::_get_model($classname, $timezone)
2095
+					->get_index_primary_key_string($props_n_values)
2096
+			);
2097
+		}
2098
+		if ($existing) {
2099
+			// set date formats if present before setting values
2100
+			if (! empty($date_formats) && is_array($date_formats)) {
2101
+				$existing->set_date_format($date_formats[0]);
2102
+				$existing->set_time_format($date_formats[1]);
2103
+			} else {
2104
+				// set default formats for date and time
2105
+				$existing->set_date_format(get_option('date_format'));
2106
+				$existing->set_time_format(get_option('time_format'));
2107
+			}
2108
+			foreach ($props_n_values as $property => $field_value) {
2109
+				$existing->set($property, $field_value);
2110
+			}
2111
+			return $existing;
2112
+		}
2113
+		return false;
2114
+	}
2115
+
2116
+
2117
+	/**
2118
+	 * Gets the EEM_*_Model for this class
2119
+	 *
2120
+	 * @access public now, as this is more convenient
2121
+	 * @param      $classname
2122
+	 * @param null $timezone
2123
+	 * @throws ReflectionException
2124
+	 * @throws InvalidArgumentException
2125
+	 * @throws InvalidInterfaceException
2126
+	 * @throws InvalidDataTypeException
2127
+	 * @throws EE_Error
2128
+	 * @return EEM_Base
2129
+	 */
2130
+	protected static function _get_model($classname, $timezone = null)
2131
+	{
2132
+		// find model for this class
2133
+		if (! $classname) {
2134
+			throw new EE_Error(
2135
+				sprintf(
2136
+					esc_html__(
2137
+						'What were you thinking calling _get_model(%s)?? You need to specify the class name',
2138
+						'event_espresso'
2139
+					),
2140
+					$classname
2141
+				)
2142
+			);
2143
+		}
2144
+		$modelName = self::_get_model_classname($classname);
2145
+		return self::_get_model_instance_with_name($modelName, $timezone);
2146
+	}
2147
+
2148
+
2149
+	/**
2150
+	 * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
2151
+	 *
2152
+	 * @param string $model_classname
2153
+	 * @param null   $timezone
2154
+	 * @return EEM_Base
2155
+	 * @throws ReflectionException
2156
+	 * @throws InvalidArgumentException
2157
+	 * @throws InvalidInterfaceException
2158
+	 * @throws InvalidDataTypeException
2159
+	 * @throws EE_Error
2160
+	 */
2161
+	protected static function _get_model_instance_with_name($model_classname, $timezone = null)
2162
+	{
2163
+		$model_classname = str_replace('EEM_', '', $model_classname);
2164
+		$model = EE_Registry::instance()->load_model($model_classname);
2165
+		$model->set_timezone($timezone);
2166
+		return $model;
2167
+	}
2168
+
2169
+
2170
+	/**
2171
+	 * If a model name is provided (eg Registration), gets the model classname for that model.
2172
+	 * Also works if a model class's classname is provided (eg EE_Registration).
2173
+	 *
2174
+	 * @param null $model_name
2175
+	 * @return string like EEM_Attendee
2176
+	 */
2177
+	private static function _get_model_classname($model_name = null)
2178
+	{
2179
+		if (strpos($model_name, 'EE_') === 0) {
2180
+			$model_classname = str_replace('EE_', 'EEM_', $model_name);
2181
+		} else {
2182
+			$model_classname = 'EEM_' . $model_name;
2183
+		}
2184
+		return $model_classname;
2185
+	}
2186
+
2187
+
2188
+	/**
2189
+	 * returns the name of the primary key attribute
2190
+	 *
2191
+	 * @param null $classname
2192
+	 * @throws ReflectionException
2193
+	 * @throws InvalidArgumentException
2194
+	 * @throws InvalidInterfaceException
2195
+	 * @throws InvalidDataTypeException
2196
+	 * @throws EE_Error
2197
+	 * @return string
2198
+	 */
2199
+	protected static function _get_primary_key_name($classname = null)
2200
+	{
2201
+		if (! $classname) {
2202
+			throw new EE_Error(
2203
+				sprintf(
2204
+					esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
2205
+					$classname
2206
+				)
2207
+			);
2208
+		}
2209
+		return self::_get_model($classname)->get_primary_key_field()->get_name();
2210
+	}
2211
+
2212
+
2213
+	/**
2214
+	 * Gets the value of the primary key.
2215
+	 * If the object hasn't yet been saved, it should be whatever the model field's default was
2216
+	 * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
2217
+	 * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
2218
+	 *
2219
+	 * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
2220
+	 * @throws ReflectionException
2221
+	 * @throws InvalidArgumentException
2222
+	 * @throws InvalidInterfaceException
2223
+	 * @throws InvalidDataTypeException
2224
+	 * @throws EE_Error
2225
+	 */
2226
+	public function ID()
2227
+	{
2228
+		$model = $this->get_model();
2229
+		// now that we know the name of the variable, use a variable variable to get its value and return its
2230
+		if ($model->has_primary_key_field()) {
2231
+			return $this->_fields[ $model->primary_key_name() ];
2232
+		}
2233
+		return $model->get_index_primary_key_string($this->_fields);
2234
+	}
2235
+
2236
+
2237
+	/**
2238
+	 * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2239
+	 * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
2240
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2241
+	 *
2242
+	 * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2243
+	 * @param string $relationName                     eg 'Events','Question',etc.
2244
+	 *                                                 an attendee to a group, you also want to specify which role they
2245
+	 *                                                 will have in that group. So you would use this parameter to
2246
+	 *                                                 specify array('role-column-name'=>'role-id')
2247
+	 * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2248
+	 *                                                 allow you to further constrict the relation to being added.
2249
+	 *                                                 However, keep in mind that the columns (keys) given must match a
2250
+	 *                                                 column on the JOIN table and currently only the HABTM models
2251
+	 *                                                 accept these additional conditions.  Also remember that if an
2252
+	 *                                                 exact match isn't found for these extra cols/val pairs, then a
2253
+	 *                                                 NEW row is created in the join table.
2254
+	 * @param null   $cache_id
2255
+	 * @throws ReflectionException
2256
+	 * @throws InvalidArgumentException
2257
+	 * @throws InvalidInterfaceException
2258
+	 * @throws InvalidDataTypeException
2259
+	 * @throws EE_Error
2260
+	 * @return EE_Base_Class the object the relation was added to
2261
+	 */
2262
+	public function _add_relation_to(
2263
+		$otherObjectModelObjectOrID,
2264
+		$relationName,
2265
+		$extra_join_model_fields_n_values = array(),
2266
+		$cache_id = null
2267
+	) {
2268
+		$model = $this->get_model();
2269
+		// if this thing exists in the DB, save the relation to the DB
2270
+		if ($this->ID()) {
2271
+			$otherObject = $model->add_relationship_to(
2272
+				$this,
2273
+				$otherObjectModelObjectOrID,
2274
+				$relationName,
2275
+				$extra_join_model_fields_n_values
2276
+			);
2277
+			// clear cache so future get_many_related and get_first_related() return new results.
2278
+			$this->clear_cache($relationName, $otherObject, true);
2279
+			if ($otherObject instanceof EE_Base_Class) {
2280
+				$otherObject->clear_cache($model->get_this_model_name(), $this);
2281
+			}
2282
+		} else {
2283
+			// this thing doesn't exist in the DB,  so just cache it
2284
+			if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2285
+				throw new EE_Error(
2286
+					sprintf(
2287
+						esc_html__(
2288
+							'Before a model object is saved to the database, calls to _add_relation_to must be passed an actual object, not just an ID. You provided %s as the model object to a %s',
2289
+							'event_espresso'
2290
+						),
2291
+						$otherObjectModelObjectOrID,
2292
+						get_class($this)
2293
+					)
2294
+				);
2295
+			}
2296
+			$otherObject = $otherObjectModelObjectOrID;
2297
+			$this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
2298
+		}
2299
+		if ($otherObject instanceof EE_Base_Class) {
2300
+			// fix the reciprocal relation too
2301
+			if ($otherObject->ID()) {
2302
+				// its saved so assumed relations exist in the DB, so we can just
2303
+				// clear the cache so future queries use the updated info in the DB
2304
+				$otherObject->clear_cache(
2305
+					$model->get_this_model_name(),
2306
+					null,
2307
+					true
2308
+				);
2309
+			} else {
2310
+				// it's not saved, so it caches relations like this
2311
+				$otherObject->cache($model->get_this_model_name(), $this);
2312
+			}
2313
+		}
2314
+		return $otherObject;
2315
+	}
2316
+
2317
+
2318
+	/**
2319
+	 * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2320
+	 * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
2321
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2322
+	 * from the cache
2323
+	 *
2324
+	 * @param mixed  $otherObjectModelObjectOrID
2325
+	 *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2326
+	 *                to the DB yet
2327
+	 * @param string $relationName
2328
+	 * @param array  $where_query
2329
+	 *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2330
+	 *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2331
+	 *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2332
+	 *                remember that if an exact match isn't found for these extra cols/val pairs, then no row is
2333
+	 *                deleted.
2334
+	 * @return EE_Base_Class the relation was removed from
2335
+	 * @throws ReflectionException
2336
+	 * @throws InvalidArgumentException
2337
+	 * @throws InvalidInterfaceException
2338
+	 * @throws InvalidDataTypeException
2339
+	 * @throws EE_Error
2340
+	 */
2341
+	public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2342
+	{
2343
+		if ($this->ID()) {
2344
+			// if this exists in the DB, save the relation change to the DB too
2345
+			$otherObject = $this->get_model()->remove_relationship_to(
2346
+				$this,
2347
+				$otherObjectModelObjectOrID,
2348
+				$relationName,
2349
+				$where_query
2350
+			);
2351
+			$this->clear_cache(
2352
+				$relationName,
2353
+				$otherObject
2354
+			);
2355
+		} else {
2356
+			// this doesn't exist in the DB, just remove it from the cache
2357
+			$otherObject = $this->clear_cache(
2358
+				$relationName,
2359
+				$otherObjectModelObjectOrID
2360
+			);
2361
+		}
2362
+		if ($otherObject instanceof EE_Base_Class) {
2363
+			$otherObject->clear_cache(
2364
+				$this->get_model()->get_this_model_name(),
2365
+				$this
2366
+			);
2367
+		}
2368
+		return $otherObject;
2369
+	}
2370
+
2371
+
2372
+	/**
2373
+	 * Removes ALL the related things for the $relationName.
2374
+	 *
2375
+	 * @param string $relationName
2376
+	 * @param array  $where_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2377
+	 * @return EE_Base_Class
2378
+	 * @throws ReflectionException
2379
+	 * @throws InvalidArgumentException
2380
+	 * @throws InvalidInterfaceException
2381
+	 * @throws InvalidDataTypeException
2382
+	 * @throws EE_Error
2383
+	 */
2384
+	public function _remove_relations($relationName, $where_query_params = array())
2385
+	{
2386
+		if ($this->ID()) {
2387
+			// if this exists in the DB, save the relation change to the DB too
2388
+			$otherObjects = $this->get_model()->remove_relations(
2389
+				$this,
2390
+				$relationName,
2391
+				$where_query_params
2392
+			);
2393
+			$this->clear_cache(
2394
+				$relationName,
2395
+				null,
2396
+				true
2397
+			);
2398
+		} else {
2399
+			// this doesn't exist in the DB, just remove it from the cache
2400
+			$otherObjects = $this->clear_cache(
2401
+				$relationName,
2402
+				null,
2403
+				true
2404
+			);
2405
+		}
2406
+		if (is_array($otherObjects)) {
2407
+			foreach ($otherObjects as $otherObject) {
2408
+				$otherObject->clear_cache(
2409
+					$this->get_model()->get_this_model_name(),
2410
+					$this
2411
+				);
2412
+			}
2413
+		}
2414
+		return $otherObjects;
2415
+	}
2416
+
2417
+
2418
+	/**
2419
+	 * Gets all the related model objects of the specified type. Eg, if the current class if
2420
+	 * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2421
+	 * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2422
+	 * because we want to get even deleted items etc.
2423
+	 *
2424
+	 * @param string $relationName key in the model's _model_relations array
2425
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2426
+	 * @return EE_Base_Class[]     Results not necessarily indexed by IDs, because some results might not have primary
2427
+	 *                             keys or might not be saved yet. Consider using EEM_Base::get_IDs() on these
2428
+	 *                             results if you want IDs
2429
+	 * @throws ReflectionException
2430
+	 * @throws InvalidArgumentException
2431
+	 * @throws InvalidInterfaceException
2432
+	 * @throws InvalidDataTypeException
2433
+	 * @throws EE_Error
2434
+	 */
2435
+	public function get_many_related($relationName, $query_params = array())
2436
+	{
2437
+		if ($this->ID()) {
2438
+			// this exists in the DB, so get the related things from either the cache or the DB
2439
+			// if there are query parameters, forget about caching the related model objects.
2440
+			if ($query_params) {
2441
+				$related_model_objects = $this->get_model()->get_all_related(
2442
+					$this,
2443
+					$relationName,
2444
+					$query_params
2445
+				);
2446
+			} else {
2447
+				// did we already cache the result of this query?
2448
+				$cached_results = $this->get_all_from_cache($relationName);
2449
+				if (! $cached_results) {
2450
+					$related_model_objects = $this->get_model()->get_all_related(
2451
+						$this,
2452
+						$relationName,
2453
+						$query_params
2454
+					);
2455
+					// if no query parameters were passed, then we got all the related model objects
2456
+					// for that relation. We can cache them then.
2457
+					foreach ($related_model_objects as $related_model_object) {
2458
+						$this->cache($relationName, $related_model_object);
2459
+					}
2460
+				} else {
2461
+					$related_model_objects = $cached_results;
2462
+				}
2463
+			}
2464
+		} else {
2465
+			// this doesn't exist in the DB, so just get the related things from the cache
2466
+			$related_model_objects = $this->get_all_from_cache($relationName);
2467
+		}
2468
+		return $related_model_objects;
2469
+	}
2470
+
2471
+
2472
+	/**
2473
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2474
+	 * unless otherwise specified in the $query_params
2475
+	 *
2476
+	 * @param string $relation_name  model_name like 'Event', or 'Registration'
2477
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2478
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2479
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2480
+	 *                               that by the setting $distinct to TRUE;
2481
+	 * @return int
2482
+	 * @throws ReflectionException
2483
+	 * @throws InvalidArgumentException
2484
+	 * @throws InvalidInterfaceException
2485
+	 * @throws InvalidDataTypeException
2486
+	 * @throws EE_Error
2487
+	 */
2488
+	public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2489
+	{
2490
+		return $this->get_model()->count_related(
2491
+			$this,
2492
+			$relation_name,
2493
+			$query_params,
2494
+			$field_to_count,
2495
+			$distinct
2496
+		);
2497
+	}
2498
+
2499
+
2500
+	/**
2501
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2502
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2503
+	 *
2504
+	 * @param string $relation_name model_name like 'Event', or 'Registration'
2505
+	 * @param array  $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2506
+	 * @param string $field_to_sum  name of field to count by.
2507
+	 *                              By default, uses primary key
2508
+	 *                              (which doesn't make much sense, so you should probably change it)
2509
+	 * @return int
2510
+	 * @throws ReflectionException
2511
+	 * @throws InvalidArgumentException
2512
+	 * @throws InvalidInterfaceException
2513
+	 * @throws InvalidDataTypeException
2514
+	 * @throws EE_Error
2515
+	 */
2516
+	public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2517
+	{
2518
+		return $this->get_model()->sum_related(
2519
+			$this,
2520
+			$relation_name,
2521
+			$query_params,
2522
+			$field_to_sum
2523
+		);
2524
+	}
2525
+
2526
+
2527
+	/**
2528
+	 * Gets the first (ie, one) related model object of the specified type.
2529
+	 *
2530
+	 * @param string $relationName key in the model's _model_relations array
2531
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2532
+	 * @return EE_Base_Class (not an array, a single object)
2533
+	 * @throws ReflectionException
2534
+	 * @throws InvalidArgumentException
2535
+	 * @throws InvalidInterfaceException
2536
+	 * @throws InvalidDataTypeException
2537
+	 * @throws EE_Error
2538
+	 */
2539
+	public function get_first_related($relationName, $query_params = array())
2540
+	{
2541
+		$model = $this->get_model();
2542
+		if ($this->ID()) {// this exists in the DB, get from the cache OR the DB
2543
+			// if they've provided some query parameters, don't bother trying to cache the result
2544
+			// also make sure we're not caching the result of get_first_related
2545
+			// on a relation which should have an array of objects (because the cache might have an array of objects)
2546
+			if ($query_params
2547
+				|| ! $model->related_settings_for($relationName)
2548
+					 instanceof
2549
+					 EE_Belongs_To_Relation
2550
+			) {
2551
+				$related_model_object = $model->get_first_related(
2552
+					$this,
2553
+					$relationName,
2554
+					$query_params
2555
+				);
2556
+			} else {
2557
+				// first, check if we've already cached the result of this query
2558
+				$cached_result = $this->get_one_from_cache($relationName);
2559
+				if (! $cached_result) {
2560
+					$related_model_object = $model->get_first_related(
2561
+						$this,
2562
+						$relationName,
2563
+						$query_params
2564
+					);
2565
+					$this->cache($relationName, $related_model_object);
2566
+				} else {
2567
+					$related_model_object = $cached_result;
2568
+				}
2569
+			}
2570
+		} else {
2571
+			$related_model_object = null;
2572
+			// this doesn't exist in the Db,
2573
+			// but maybe the relation is of type belongs to, and so the related thing might
2574
+			if ($model->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2575
+				$related_model_object = $model->get_first_related(
2576
+					$this,
2577
+					$relationName,
2578
+					$query_params
2579
+				);
2580
+			}
2581
+			// this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2582
+			// just get what's cached on this object
2583
+			if (! $related_model_object) {
2584
+				$related_model_object = $this->get_one_from_cache($relationName);
2585
+			}
2586
+		}
2587
+		return $related_model_object;
2588
+	}
2589
+
2590
+
2591
+	/**
2592
+	 * Does a delete on all related objects of type $relationName and removes
2593
+	 * the current model object's relation to them. If they can't be deleted (because
2594
+	 * of blocking related model objects) does nothing. If the related model objects are
2595
+	 * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2596
+	 * If this model object doesn't exist yet in the DB, just removes its related things
2597
+	 *
2598
+	 * @param string $relationName
2599
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2600
+	 * @return int how many deleted
2601
+	 * @throws ReflectionException
2602
+	 * @throws InvalidArgumentException
2603
+	 * @throws InvalidInterfaceException
2604
+	 * @throws InvalidDataTypeException
2605
+	 * @throws EE_Error
2606
+	 */
2607
+	public function delete_related($relationName, $query_params = array())
2608
+	{
2609
+		if ($this->ID()) {
2610
+			$count = $this->get_model()->delete_related(
2611
+				$this,
2612
+				$relationName,
2613
+				$query_params
2614
+			);
2615
+		} else {
2616
+			$count = count($this->get_all_from_cache($relationName));
2617
+			$this->clear_cache($relationName, null, true);
2618
+		}
2619
+		return $count;
2620
+	}
2621
+
2622
+
2623
+	/**
2624
+	 * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2625
+	 * the current model object's relation to them. If they can't be deleted (because
2626
+	 * of blocking related model objects) just does a soft delete on it instead, if possible.
2627
+	 * If the related thing isn't a soft-deletable model object, this function is identical
2628
+	 * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2629
+	 *
2630
+	 * @param string $relationName
2631
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2632
+	 * @return int how many deleted (including those soft deleted)
2633
+	 * @throws ReflectionException
2634
+	 * @throws InvalidArgumentException
2635
+	 * @throws InvalidInterfaceException
2636
+	 * @throws InvalidDataTypeException
2637
+	 * @throws EE_Error
2638
+	 */
2639
+	public function delete_related_permanently($relationName, $query_params = array())
2640
+	{
2641
+		if ($this->ID()) {
2642
+			$count = $this->get_model()->delete_related_permanently(
2643
+				$this,
2644
+				$relationName,
2645
+				$query_params
2646
+			);
2647
+		} else {
2648
+			$count = count($this->get_all_from_cache($relationName));
2649
+		}
2650
+		$this->clear_cache($relationName, null, true);
2651
+		return $count;
2652
+	}
2653
+
2654
+
2655
+	/**
2656
+	 * is_set
2657
+	 * Just a simple utility function children can use for checking if property exists
2658
+	 *
2659
+	 * @access  public
2660
+	 * @param  string $field_name property to check
2661
+	 * @return bool                              TRUE if existing,FALSE if not.
2662
+	 */
2663
+	public function is_set($field_name)
2664
+	{
2665
+		return isset($this->_fields[ $field_name ]);
2666
+	}
2667
+
2668
+
2669
+	/**
2670
+	 * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2671
+	 * EE_Error exception if they don't
2672
+	 *
2673
+	 * @param  mixed (string|array) $properties properties to check
2674
+	 * @throws EE_Error
2675
+	 * @return bool                              TRUE if existing, throw EE_Error if not.
2676
+	 */
2677
+	protected function _property_exists($properties)
2678
+	{
2679
+		foreach ((array) $properties as $property_name) {
2680
+			// first make sure this property exists
2681
+			if (! $this->_fields[ $property_name ]) {
2682
+				throw new EE_Error(
2683
+					sprintf(
2684
+						esc_html__(
2685
+							'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2686
+							'event_espresso'
2687
+						),
2688
+						$property_name
2689
+					)
2690
+				);
2691
+			}
2692
+		}
2693
+		return true;
2694
+	}
2695
+
2696
+
2697
+	/**
2698
+	 * This simply returns an array of model fields for this object
2699
+	 *
2700
+	 * @return array
2701
+	 * @throws ReflectionException
2702
+	 * @throws InvalidArgumentException
2703
+	 * @throws InvalidInterfaceException
2704
+	 * @throws InvalidDataTypeException
2705
+	 * @throws EE_Error
2706
+	 */
2707
+	public function model_field_array()
2708
+	{
2709
+		$fields = $this->get_model()->field_settings(false);
2710
+		$properties = array();
2711
+		// remove prepended underscore
2712
+		foreach ($fields as $field_name => $settings) {
2713
+			$properties[ $field_name ] = $this->get($field_name);
2714
+		}
2715
+		return $properties;
2716
+	}
2717
+
2718
+
2719
+	/**
2720
+	 * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2721
+	 * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2722
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments.
2723
+	 * Instead of requiring a plugin to extend the EE_Base_Class
2724
+	 * (which works fine is there's only 1 plugin, but when will that happen?)
2725
+	 * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}'
2726
+	 * (eg, filters_hook_espresso__EE_Answer__my_great_function)
2727
+	 * and accepts 2 arguments: the object on which the function was called,
2728
+	 * and an array of the original arguments passed to the function.
2729
+	 * Whatever their callback function returns will be returned by this function.
2730
+	 * Example: in functions.php (or in a plugin):
2731
+	 *      add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3);
2732
+	 *      function my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2733
+	 *          $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2734
+	 *          return $previousReturnValue.$returnString;
2735
+	 *      }
2736
+	 * require('EE_Answer.class.php');
2737
+	 * $answer= EE_Answer::new_instance(array('REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'));
2738
+	 * echo $answer->my_callback('monkeys',100);
2739
+	 * //will output "you called my_callback! and passed args:monkeys,100"
2740
+	 *
2741
+	 * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2742
+	 * @param array  $args       array of original arguments passed to the function
2743
+	 * @throws EE_Error
2744
+	 * @return mixed whatever the plugin which calls add_filter decides
2745
+	 */
2746
+	public function __call($methodName, $args)
2747
+	{
2748
+		$className = get_class($this);
2749
+		$tagName = "FHEE__{$className}__{$methodName}";
2750
+		if (! has_filter($tagName)) {
2751
+			throw new EE_Error(
2752
+				sprintf(
2753
+					esc_html__(
2754
+						"Method %s on class %s does not exist! You can create one with the following code in functions.php or in a plugin: add_filter('%s','my_callback',10,3);function my_callback(\$previousReturnValue,EE_Base_Class \$object, \$argsArray){/*function body*/return \$whatever;}",
2755
+						'event_espresso'
2756
+					),
2757
+					$methodName,
2758
+					$className,
2759
+					$tagName
2760
+				)
2761
+			);
2762
+		}
2763
+		return apply_filters($tagName, null, $this, $args);
2764
+	}
2765
+
2766
+
2767
+	/**
2768
+	 * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2769
+	 * A $previous_value can be specified in case there are many meta rows with the same key
2770
+	 *
2771
+	 * @param string $meta_key
2772
+	 * @param mixed  $meta_value
2773
+	 * @param mixed  $previous_value
2774
+	 * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2775
+	 *                  NOTE: if the values haven't changed, returns 0
2776
+	 * @throws InvalidArgumentException
2777
+	 * @throws InvalidInterfaceException
2778
+	 * @throws InvalidDataTypeException
2779
+	 * @throws EE_Error
2780
+	 * @throws ReflectionException
2781
+	 */
2782
+	public function update_extra_meta($meta_key, $meta_value, $previous_value = null)
2783
+	{
2784
+		$query_params = array(
2785
+			array(
2786
+				'EXM_key'  => $meta_key,
2787
+				'OBJ_ID'   => $this->ID(),
2788
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2789
+			),
2790
+		);
2791
+		if ($previous_value !== null) {
2792
+			$query_params[0]['EXM_value'] = $meta_value;
2793
+		}
2794
+		$existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2795
+		if (! $existing_rows_like_that) {
2796
+			return $this->add_extra_meta($meta_key, $meta_value);
2797
+		}
2798
+		foreach ($existing_rows_like_that as $existing_row) {
2799
+			$existing_row->save(array('EXM_value' => $meta_value));
2800
+		}
2801
+		return count($existing_rows_like_that);
2802
+	}
2803
+
2804
+
2805
+	/**
2806
+	 * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2807
+	 * no other extra meta for this model object have the same key. Returns TRUE if the
2808
+	 * extra meta row was entered, false if not
2809
+	 *
2810
+	 * @param string  $meta_key
2811
+	 * @param mixed   $meta_value
2812
+	 * @param boolean $unique
2813
+	 * @return boolean
2814
+	 * @throws InvalidArgumentException
2815
+	 * @throws InvalidInterfaceException
2816
+	 * @throws InvalidDataTypeException
2817
+	 * @throws EE_Error
2818
+	 * @throws ReflectionException
2819
+	 * @throws ReflectionException
2820
+	 */
2821
+	public function add_extra_meta($meta_key, $meta_value, $unique = false)
2822
+	{
2823
+		if ($unique) {
2824
+			$existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2825
+				array(
2826
+					array(
2827
+						'EXM_key'  => $meta_key,
2828
+						'OBJ_ID'   => $this->ID(),
2829
+						'EXM_type' => $this->get_model()->get_this_model_name(),
2830
+					),
2831
+				)
2832
+			);
2833
+			if ($existing_extra_meta) {
2834
+				return false;
2835
+			}
2836
+		}
2837
+		$new_extra_meta = EE_Extra_Meta::new_instance(
2838
+			array(
2839
+				'EXM_key'   => $meta_key,
2840
+				'EXM_value' => $meta_value,
2841
+				'OBJ_ID'    => $this->ID(),
2842
+				'EXM_type'  => $this->get_model()->get_this_model_name(),
2843
+			)
2844
+		);
2845
+		$new_extra_meta->save();
2846
+		return true;
2847
+	}
2848
+
2849
+
2850
+	/**
2851
+	 * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2852
+	 * is specified, only deletes extra meta records with that value.
2853
+	 *
2854
+	 * @param string $meta_key
2855
+	 * @param mixed  $meta_value
2856
+	 * @return int number of extra meta rows deleted
2857
+	 * @throws InvalidArgumentException
2858
+	 * @throws InvalidInterfaceException
2859
+	 * @throws InvalidDataTypeException
2860
+	 * @throws EE_Error
2861
+	 * @throws ReflectionException
2862
+	 */
2863
+	public function delete_extra_meta($meta_key, $meta_value = null)
2864
+	{
2865
+		$query_params = array(
2866
+			array(
2867
+				'EXM_key'  => $meta_key,
2868
+				'OBJ_ID'   => $this->ID(),
2869
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2870
+			),
2871
+		);
2872
+		if ($meta_value !== null) {
2873
+			$query_params[0]['EXM_value'] = $meta_value;
2874
+		}
2875
+		return EEM_Extra_Meta::instance()->delete($query_params);
2876
+	}
2877
+
2878
+
2879
+	/**
2880
+	 * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2881
+	 * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2882
+	 * You can specify $default is case you haven't found the extra meta
2883
+	 *
2884
+	 * @param string  $meta_key
2885
+	 * @param boolean $single
2886
+	 * @param mixed   $default if we don't find anything, what should we return?
2887
+	 * @return mixed single value if $single; array if ! $single
2888
+	 * @throws ReflectionException
2889
+	 * @throws InvalidArgumentException
2890
+	 * @throws InvalidInterfaceException
2891
+	 * @throws InvalidDataTypeException
2892
+	 * @throws EE_Error
2893
+	 */
2894
+	public function get_extra_meta($meta_key, $single = false, $default = null)
2895
+	{
2896
+		if ($single) {
2897
+			$result = $this->get_first_related(
2898
+				'Extra_Meta',
2899
+				array(array('EXM_key' => $meta_key))
2900
+			);
2901
+			if ($result instanceof EE_Extra_Meta) {
2902
+				return $result->value();
2903
+			}
2904
+		} else {
2905
+			$results = $this->get_many_related(
2906
+				'Extra_Meta',
2907
+				array(array('EXM_key' => $meta_key))
2908
+			);
2909
+			if ($results) {
2910
+				$values = array();
2911
+				foreach ($results as $result) {
2912
+					if ($result instanceof EE_Extra_Meta) {
2913
+						$values[ $result->ID() ] = $result->value();
2914
+					}
2915
+				}
2916
+				return $values;
2917
+			}
2918
+		}
2919
+		// if nothing discovered yet return default.
2920
+		return apply_filters(
2921
+			'FHEE__EE_Base_Class__get_extra_meta__default_value',
2922
+			$default,
2923
+			$meta_key,
2924
+			$single,
2925
+			$this
2926
+		);
2927
+	}
2928
+
2929
+
2930
+	/**
2931
+	 * Returns a simple array of all the extra meta associated with this model object.
2932
+	 * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2933
+	 * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2934
+	 * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2935
+	 * If $one_of_each_key is false, it will return an array with the top-level keys being
2936
+	 * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2937
+	 * finally the extra meta's value as each sub-value. (eg
2938
+	 * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2939
+	 *
2940
+	 * @param boolean $one_of_each_key
2941
+	 * @return array
2942
+	 * @throws ReflectionException
2943
+	 * @throws InvalidArgumentException
2944
+	 * @throws InvalidInterfaceException
2945
+	 * @throws InvalidDataTypeException
2946
+	 * @throws EE_Error
2947
+	 */
2948
+	public function all_extra_meta_array($one_of_each_key = true)
2949
+	{
2950
+		$return_array = array();
2951
+		if ($one_of_each_key) {
2952
+			$extra_meta_objs = $this->get_many_related(
2953
+				'Extra_Meta',
2954
+				array('group_by' => 'EXM_key')
2955
+			);
2956
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2957
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2958
+					$return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2959
+				}
2960
+			}
2961
+		} else {
2962
+			$extra_meta_objs = $this->get_many_related('Extra_Meta');
2963
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2964
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2965
+					if (! isset($return_array[ $extra_meta_obj->key() ])) {
2966
+						$return_array[ $extra_meta_obj->key() ] = array();
2967
+					}
2968
+					$return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2969
+				}
2970
+			}
2971
+		}
2972
+		return $return_array;
2973
+	}
2974
+
2975
+
2976
+	/**
2977
+	 * Gets a pretty nice displayable nice for this model object. Often overridden
2978
+	 *
2979
+	 * @return string
2980
+	 * @throws ReflectionException
2981
+	 * @throws InvalidArgumentException
2982
+	 * @throws InvalidInterfaceException
2983
+	 * @throws InvalidDataTypeException
2984
+	 * @throws EE_Error
2985
+	 */
2986
+	public function name()
2987
+	{
2988
+		// find a field that's not a text field
2989
+		$field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
2990
+		if ($field_we_can_use) {
2991
+			return $this->get($field_we_can_use->get_name());
2992
+		}
2993
+		$first_few_properties = $this->model_field_array();
2994
+		$first_few_properties = array_slice($first_few_properties, 0, 3);
2995
+		$name_parts = array();
2996
+		foreach ($first_few_properties as $name => $value) {
2997
+			$name_parts[] = "$name:$value";
2998
+		}
2999
+		return implode(',', $name_parts);
3000
+	}
3001
+
3002
+
3003
+	/**
3004
+	 * in_entity_map
3005
+	 * Checks if this model object has been proven to already be in the entity map
3006
+	 *
3007
+	 * @return boolean
3008
+	 * @throws ReflectionException
3009
+	 * @throws InvalidArgumentException
3010
+	 * @throws InvalidInterfaceException
3011
+	 * @throws InvalidDataTypeException
3012
+	 * @throws EE_Error
3013
+	 */
3014
+	public function in_entity_map()
3015
+	{
3016
+		// well, if we looked, did we find it in the entity map?
3017
+		return $this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this;
3018
+	}
3019
+
3020
+
3021
+	/**
3022
+	 * refresh_from_db
3023
+	 * Makes sure the fields and values on this model object are in-sync with what's in the database.
3024
+	 *
3025
+	 * @throws ReflectionException
3026
+	 * @throws InvalidArgumentException
3027
+	 * @throws InvalidInterfaceException
3028
+	 * @throws InvalidDataTypeException
3029
+	 * @throws EE_Error if this model object isn't in the entity mapper (because then you should
3030
+	 * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
3031
+	 */
3032
+	public function refresh_from_db()
3033
+	{
3034
+		if ($this->ID() && $this->in_entity_map()) {
3035
+			$this->get_model()->refresh_entity_map_from_db($this->ID());
3036
+		} else {
3037
+			// if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
3038
+			// if it has an ID but it's not in the map, and you're asking me to refresh it
3039
+			// that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
3040
+			// absolutely nothing in it for this ID
3041
+			if (WP_DEBUG) {
3042
+				throw new EE_Error(
3043
+					sprintf(
3044
+						esc_html__(
3045
+							'Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
3046
+							'event_espresso'
3047
+						),
3048
+						$this->ID(),
3049
+						get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3050
+						get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3051
+					)
3052
+				);
3053
+			}
3054
+		}
3055
+	}
3056
+
3057
+
3058
+	/**
3059
+	 * Change $fields' values to $new_value_sql (which is a string of raw SQL)
3060
+	 *
3061
+	 * @since 4.9.80.p
3062
+	 * @param EE_Model_Field_Base[] $fields
3063
+	 * @param string $new_value_sql
3064
+	 *      example: 'column_name=123',
3065
+	 *      or 'column_name=column_name+1',
3066
+	 *      or 'column_name= CASE
3067
+	 *          WHEN (`column_name` + `other_column` + 5) <= `yet_another_column`
3068
+	 *          THEN `column_name` + 5
3069
+	 *          ELSE `column_name`
3070
+	 *      END'
3071
+	 *      Also updates $field on this model object with the latest value from the database.
3072
+	 * @return bool
3073
+	 * @throws EE_Error
3074
+	 * @throws InvalidArgumentException
3075
+	 * @throws InvalidDataTypeException
3076
+	 * @throws InvalidInterfaceException
3077
+	 * @throws ReflectionException
3078
+	 */
3079
+	protected function updateFieldsInDB($fields, $new_value_sql)
3080
+	{
3081
+		// First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3082
+		// if it wasn't even there to start off.
3083
+		if (! $this->ID()) {
3084
+			$this->save();
3085
+		}
3086
+		global $wpdb;
3087
+		if (empty($fields)) {
3088
+			throw new InvalidArgumentException(
3089
+				esc_html__(
3090
+					'EE_Base_Class::updateFieldsInDB was passed an empty array of fields.',
3091
+					'event_espresso'
3092
+				)
3093
+			);
3094
+		}
3095
+		$first_field = reset($fields);
3096
+		$table_alias = $first_field->get_table_alias();
3097
+		foreach ($fields as $field) {
3098
+			if ($table_alias !== $field->get_table_alias()) {
3099
+				throw new InvalidArgumentException(
3100
+					sprintf(
3101
+						esc_html__(
3102
+							// @codingStandardsIgnoreStart
3103
+							'EE_Base_Class::updateFieldsInDB was passed fields for different tables ("%1$s" and "%2$s"), which is not supported. Instead, please call the method multiple times.',
3104
+							// @codingStandardsIgnoreEnd
3105
+							'event_espresso'
3106
+						),
3107
+						$table_alias,
3108
+						$field->get_table_alias()
3109
+					)
3110
+				);
3111
+			}
3112
+		}
3113
+		// Ok the fields are now known to all be for the same table. Proceed with creating the SQL to update it.
3114
+		$table_obj = $this->get_model()->get_table_obj_by_alias($table_alias);
3115
+		$table_pk_value = $this->ID();
3116
+		$table_name = $table_obj->get_table_name();
3117
+		if ($table_obj instanceof EE_Secondary_Table) {
3118
+			$table_pk_field_name = $table_obj->get_fk_on_table();
3119
+		} else {
3120
+			$table_pk_field_name = $table_obj->get_pk_column();
3121
+		}
3122
+
3123
+		$query =
3124
+			"UPDATE `{$table_name}`
3125 3125
             SET "
3126
-            . $new_value_sql
3127
-            . $wpdb->prepare(
3128
-                "
3126
+			. $new_value_sql
3127
+			. $wpdb->prepare(
3128
+				"
3129 3129
             WHERE `{$table_pk_field_name}` = %d;",
3130
-                $table_pk_value
3131
-            );
3132
-        $result = $wpdb->query($query);
3133
-        foreach ($fields as $field) {
3134
-            // If it was successful, we'd like to know the new value.
3135
-            // If it failed, we'd also like to know the new value.
3136
-            $new_value = $this->get_model()->get_var(
3137
-                $this->get_model()->alter_query_params_to_restrict_by_ID(
3138
-                    $this->get_model()->get_index_primary_key_string(
3139
-                        $this->model_field_array()
3140
-                    ),
3141
-                    array(
3142
-                        'default_where_conditions' => 'minimum',
3143
-                    )
3144
-                ),
3145
-                $field->get_name()
3146
-            );
3147
-            $this->set_from_db(
3148
-                $field->get_name(),
3149
-                $new_value
3150
-            );
3151
-        }
3152
-        return (bool) $result;
3153
-    }
3154
-
3155
-
3156
-    /**
3157
-     * Nudges $field_name's value by $quantity, without any conditionals (in comparison to bumpConditionally()).
3158
-     * Does not allow negative values, however.
3159
-     *
3160
-     * @since 4.9.80.p
3161
-     * @param array $fields_n_quantities keys are the field names, and values are the amount by which to bump them
3162
-     *                                   (positive or negative). One important gotcha: all these values must be
3163
-     *                                   on the same table (eg don't pass in one field for the posts table and
3164
-     *                                   another for the event meta table.)
3165
-     * @return bool
3166
-     * @throws EE_Error
3167
-     * @throws InvalidArgumentException
3168
-     * @throws InvalidDataTypeException
3169
-     * @throws InvalidInterfaceException
3170
-     * @throws ReflectionException
3171
-     */
3172
-    public function adjustNumericFieldsInDb(array $fields_n_quantities)
3173
-    {
3174
-        global $wpdb;
3175
-        if (empty($fields_n_quantities)) {
3176
-            // No fields to update? Well sure, we updated them to that value just fine.
3177
-            return true;
3178
-        }
3179
-        $fields = [];
3180
-        $set_sql_statements = [];
3181
-        foreach ($fields_n_quantities as $field_name => $quantity) {
3182
-            $field = $this->get_model()->field_settings_for($field_name, true);
3183
-            $fields[] = $field;
3184
-            $column_name = $field->get_table_column();
3185
-
3186
-            $abs_qty = absint($quantity);
3187
-            if ($quantity > 0) {
3188
-                // don't let the value be negative as often these fields are unsigned
3189
-                $set_sql_statements[] = $wpdb->prepare(
3190
-                    "`{$column_name}` = `{$column_name}` + %d",
3191
-                    $abs_qty
3192
-                );
3193
-            } else {
3194
-                $set_sql_statements[] = $wpdb->prepare(
3195
-                    "`{$column_name}` = CASE
3130
+				$table_pk_value
3131
+			);
3132
+		$result = $wpdb->query($query);
3133
+		foreach ($fields as $field) {
3134
+			// If it was successful, we'd like to know the new value.
3135
+			// If it failed, we'd also like to know the new value.
3136
+			$new_value = $this->get_model()->get_var(
3137
+				$this->get_model()->alter_query_params_to_restrict_by_ID(
3138
+					$this->get_model()->get_index_primary_key_string(
3139
+						$this->model_field_array()
3140
+					),
3141
+					array(
3142
+						'default_where_conditions' => 'minimum',
3143
+					)
3144
+				),
3145
+				$field->get_name()
3146
+			);
3147
+			$this->set_from_db(
3148
+				$field->get_name(),
3149
+				$new_value
3150
+			);
3151
+		}
3152
+		return (bool) $result;
3153
+	}
3154
+
3155
+
3156
+	/**
3157
+	 * Nudges $field_name's value by $quantity, without any conditionals (in comparison to bumpConditionally()).
3158
+	 * Does not allow negative values, however.
3159
+	 *
3160
+	 * @since 4.9.80.p
3161
+	 * @param array $fields_n_quantities keys are the field names, and values are the amount by which to bump them
3162
+	 *                                   (positive or negative). One important gotcha: all these values must be
3163
+	 *                                   on the same table (eg don't pass in one field for the posts table and
3164
+	 *                                   another for the event meta table.)
3165
+	 * @return bool
3166
+	 * @throws EE_Error
3167
+	 * @throws InvalidArgumentException
3168
+	 * @throws InvalidDataTypeException
3169
+	 * @throws InvalidInterfaceException
3170
+	 * @throws ReflectionException
3171
+	 */
3172
+	public function adjustNumericFieldsInDb(array $fields_n_quantities)
3173
+	{
3174
+		global $wpdb;
3175
+		if (empty($fields_n_quantities)) {
3176
+			// No fields to update? Well sure, we updated them to that value just fine.
3177
+			return true;
3178
+		}
3179
+		$fields = [];
3180
+		$set_sql_statements = [];
3181
+		foreach ($fields_n_quantities as $field_name => $quantity) {
3182
+			$field = $this->get_model()->field_settings_for($field_name, true);
3183
+			$fields[] = $field;
3184
+			$column_name = $field->get_table_column();
3185
+
3186
+			$abs_qty = absint($quantity);
3187
+			if ($quantity > 0) {
3188
+				// don't let the value be negative as often these fields are unsigned
3189
+				$set_sql_statements[] = $wpdb->prepare(
3190
+					"`{$column_name}` = `{$column_name}` + %d",
3191
+					$abs_qty
3192
+				);
3193
+			} else {
3194
+				$set_sql_statements[] = $wpdb->prepare(
3195
+					"`{$column_name}` = CASE
3196 3196
                        WHEN (`{$column_name}` >= %d)
3197 3197
                        THEN `{$column_name}` - %d
3198 3198
                        ELSE 0
3199 3199
                     END",
3200
-                    $abs_qty,
3201
-                    $abs_qty
3202
-                );
3203
-            }
3204
-        }
3205
-        return $this->updateFieldsInDB(
3206
-            $fields,
3207
-            implode(', ', $set_sql_statements)
3208
-        );
3209
-    }
3210
-
3211
-
3212
-    /**
3213
-     * Increases the value of the field $field_name_to_bump by $quantity, but only if the values of
3214
-     * $field_name_to_bump plus $field_name_affecting_total and $quantity won't exceed $limit_field_name's value.
3215
-     * For example, this is useful when bumping the value of TKT_reserved, TKT_sold, DTT_reserved or DTT_sold.
3216
-     * Returns true if the value was successfully bumped, and updates the value on this model object.
3217
-     * Otherwise returns false.
3218
-     *
3219
-     * @since 4.9.80.p
3220
-     * @param string $field_name_to_bump
3221
-     * @param string $field_name_affecting_total
3222
-     * @param string $limit_field_name
3223
-     * @param int    $quantity
3224
-     * @return bool
3225
-     * @throws EE_Error
3226
-     * @throws InvalidArgumentException
3227
-     * @throws InvalidDataTypeException
3228
-     * @throws InvalidInterfaceException
3229
-     * @throws ReflectionException
3230
-     */
3231
-    public function incrementFieldConditionallyInDb($field_name_to_bump, $field_name_affecting_total, $limit_field_name, $quantity)
3232
-    {
3233
-        global $wpdb;
3234
-        $field = $this->get_model()->field_settings_for($field_name_to_bump, true);
3235
-        $column_name = $field->get_table_column();
3236
-
3237
-        $field_affecting_total = $this->get_model()->field_settings_for($field_name_affecting_total, true);
3238
-        $column_affecting_total = $field_affecting_total->get_table_column();
3239
-
3240
-        $limiting_field = $this->get_model()->field_settings_for($limit_field_name, true);
3241
-        $limiting_column = $limiting_field->get_table_column();
3242
-        return $this->updateFieldsInDB(
3243
-            [$field],
3244
-            $wpdb->prepare(
3245
-                "`{$column_name}` =
3200
+					$abs_qty,
3201
+					$abs_qty
3202
+				);
3203
+			}
3204
+		}
3205
+		return $this->updateFieldsInDB(
3206
+			$fields,
3207
+			implode(', ', $set_sql_statements)
3208
+		);
3209
+	}
3210
+
3211
+
3212
+	/**
3213
+	 * Increases the value of the field $field_name_to_bump by $quantity, but only if the values of
3214
+	 * $field_name_to_bump plus $field_name_affecting_total and $quantity won't exceed $limit_field_name's value.
3215
+	 * For example, this is useful when bumping the value of TKT_reserved, TKT_sold, DTT_reserved or DTT_sold.
3216
+	 * Returns true if the value was successfully bumped, and updates the value on this model object.
3217
+	 * Otherwise returns false.
3218
+	 *
3219
+	 * @since 4.9.80.p
3220
+	 * @param string $field_name_to_bump
3221
+	 * @param string $field_name_affecting_total
3222
+	 * @param string $limit_field_name
3223
+	 * @param int    $quantity
3224
+	 * @return bool
3225
+	 * @throws EE_Error
3226
+	 * @throws InvalidArgumentException
3227
+	 * @throws InvalidDataTypeException
3228
+	 * @throws InvalidInterfaceException
3229
+	 * @throws ReflectionException
3230
+	 */
3231
+	public function incrementFieldConditionallyInDb($field_name_to_bump, $field_name_affecting_total, $limit_field_name, $quantity)
3232
+	{
3233
+		global $wpdb;
3234
+		$field = $this->get_model()->field_settings_for($field_name_to_bump, true);
3235
+		$column_name = $field->get_table_column();
3236
+
3237
+		$field_affecting_total = $this->get_model()->field_settings_for($field_name_affecting_total, true);
3238
+		$column_affecting_total = $field_affecting_total->get_table_column();
3239
+
3240
+		$limiting_field = $this->get_model()->field_settings_for($limit_field_name, true);
3241
+		$limiting_column = $limiting_field->get_table_column();
3242
+		return $this->updateFieldsInDB(
3243
+			[$field],
3244
+			$wpdb->prepare(
3245
+				"`{$column_name}` =
3246 3246
             CASE
3247 3247
                WHEN ((`{$column_name}` + `{$column_affecting_total}` + %d) <= `{$limiting_column}`) OR `{$limiting_column}` = %d
3248 3248
                THEN `{$column_name}` + %d
3249 3249
                ELSE `{$column_name}`
3250 3250
             END",
3251
-                $quantity,
3252
-                EE_INF_IN_DB,
3253
-                $quantity
3254
-            )
3255
-        );
3256
-    }
3257
-
3258
-
3259
-    /**
3260
-     * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
3261
-     * (probably a bad assumption they have made, oh well)
3262
-     *
3263
-     * @return string
3264
-     */
3265
-    public function __toString()
3266
-    {
3267
-        try {
3268
-            return sprintf('%s (%s)', $this->name(), $this->ID());
3269
-        } catch (Exception $e) {
3270
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
3271
-            return '';
3272
-        }
3273
-    }
3274
-
3275
-
3276
-    /**
3277
-     * Clear related model objects if they're already in the DB, because otherwise when we
3278
-     * UN-serialize this model object we'll need to be careful to add them to the entity map.
3279
-     * This means if we have made changes to those related model objects, and want to unserialize
3280
-     * the this model object on a subsequent request, changes to those related model objects will be lost.
3281
-     * Instead, those related model objects should be directly serialized and stored.
3282
-     * Eg, the following won't work:
3283
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3284
-     * $att = $reg->attendee();
3285
-     * $att->set( 'ATT_fname', 'Dirk' );
3286
-     * update_option( 'my_option', serialize( $reg ) );
3287
-     * //END REQUEST
3288
-     * //START NEXT REQUEST
3289
-     * $reg = get_option( 'my_option' );
3290
-     * $reg->attendee()->save();
3291
-     * And would need to be replace with:
3292
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3293
-     * $att = $reg->attendee();
3294
-     * $att->set( 'ATT_fname', 'Dirk' );
3295
-     * update_option( 'my_option', serialize( $reg ) );
3296
-     * //END REQUEST
3297
-     * //START NEXT REQUEST
3298
-     * $att = get_option( 'my_option' );
3299
-     * $att->save();
3300
-     *
3301
-     * @return array
3302
-     * @throws ReflectionException
3303
-     * @throws InvalidArgumentException
3304
-     * @throws InvalidInterfaceException
3305
-     * @throws InvalidDataTypeException
3306
-     * @throws EE_Error
3307
-     */
3308
-    public function __sleep()
3309
-    {
3310
-        $model = $this->get_model();
3311
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3312
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
3313
-                $classname = 'EE_' . $model->get_this_model_name();
3314
-                if ($this->get_one_from_cache($relation_name) instanceof $classname
3315
-                    && $this->get_one_from_cache($relation_name)->ID()
3316
-                ) {
3317
-                    $this->clear_cache(
3318
-                        $relation_name,
3319
-                        $this->get_one_from_cache($relation_name)->ID()
3320
-                    );
3321
-                }
3322
-            }
3323
-        }
3324
-        $this->_props_n_values_provided_in_constructor = array();
3325
-        $properties_to_serialize = get_object_vars($this);
3326
-        // don't serialize the model. It's big and that risks recursion
3327
-        unset($properties_to_serialize['_model']);
3328
-        return array_keys($properties_to_serialize);
3329
-    }
3330
-
3331
-
3332
-    /**
3333
-     * restore _props_n_values_provided_in_constructor
3334
-     * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
3335
-     * and therefore should NOT be used to determine if state change has occurred since initial construction.
3336
-     * At best, you would only be able to detect if state change has occurred during THIS request.
3337
-     */
3338
-    public function __wakeup()
3339
-    {
3340
-        $this->_props_n_values_provided_in_constructor = $this->_fields;
3341
-    }
3342
-
3343
-
3344
-    /**
3345
-     * Usage of this magic method is to ensure any internally cached references to object instances that must remain
3346
-     * distinct with the clone host instance are also cloned.
3347
-     */
3348
-    public function __clone()
3349
-    {
3350
-        // handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3351
-        foreach ($this->_fields as $field => $value) {
3352
-            if ($value instanceof DateTime) {
3353
-                $this->_fields[ $field ] = clone $value;
3354
-            }
3355
-        }
3356
-    }
3251
+				$quantity,
3252
+				EE_INF_IN_DB,
3253
+				$quantity
3254
+			)
3255
+		);
3256
+	}
3257
+
3258
+
3259
+	/**
3260
+	 * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
3261
+	 * (probably a bad assumption they have made, oh well)
3262
+	 *
3263
+	 * @return string
3264
+	 */
3265
+	public function __toString()
3266
+	{
3267
+		try {
3268
+			return sprintf('%s (%s)', $this->name(), $this->ID());
3269
+		} catch (Exception $e) {
3270
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
3271
+			return '';
3272
+		}
3273
+	}
3274
+
3275
+
3276
+	/**
3277
+	 * Clear related model objects if they're already in the DB, because otherwise when we
3278
+	 * UN-serialize this model object we'll need to be careful to add them to the entity map.
3279
+	 * This means if we have made changes to those related model objects, and want to unserialize
3280
+	 * the this model object on a subsequent request, changes to those related model objects will be lost.
3281
+	 * Instead, those related model objects should be directly serialized and stored.
3282
+	 * Eg, the following won't work:
3283
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3284
+	 * $att = $reg->attendee();
3285
+	 * $att->set( 'ATT_fname', 'Dirk' );
3286
+	 * update_option( 'my_option', serialize( $reg ) );
3287
+	 * //END REQUEST
3288
+	 * //START NEXT REQUEST
3289
+	 * $reg = get_option( 'my_option' );
3290
+	 * $reg->attendee()->save();
3291
+	 * And would need to be replace with:
3292
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3293
+	 * $att = $reg->attendee();
3294
+	 * $att->set( 'ATT_fname', 'Dirk' );
3295
+	 * update_option( 'my_option', serialize( $reg ) );
3296
+	 * //END REQUEST
3297
+	 * //START NEXT REQUEST
3298
+	 * $att = get_option( 'my_option' );
3299
+	 * $att->save();
3300
+	 *
3301
+	 * @return array
3302
+	 * @throws ReflectionException
3303
+	 * @throws InvalidArgumentException
3304
+	 * @throws InvalidInterfaceException
3305
+	 * @throws InvalidDataTypeException
3306
+	 * @throws EE_Error
3307
+	 */
3308
+	public function __sleep()
3309
+	{
3310
+		$model = $this->get_model();
3311
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3312
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
3313
+				$classname = 'EE_' . $model->get_this_model_name();
3314
+				if ($this->get_one_from_cache($relation_name) instanceof $classname
3315
+					&& $this->get_one_from_cache($relation_name)->ID()
3316
+				) {
3317
+					$this->clear_cache(
3318
+						$relation_name,
3319
+						$this->get_one_from_cache($relation_name)->ID()
3320
+					);
3321
+				}
3322
+			}
3323
+		}
3324
+		$this->_props_n_values_provided_in_constructor = array();
3325
+		$properties_to_serialize = get_object_vars($this);
3326
+		// don't serialize the model. It's big and that risks recursion
3327
+		unset($properties_to_serialize['_model']);
3328
+		return array_keys($properties_to_serialize);
3329
+	}
3330
+
3331
+
3332
+	/**
3333
+	 * restore _props_n_values_provided_in_constructor
3334
+	 * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
3335
+	 * and therefore should NOT be used to determine if state change has occurred since initial construction.
3336
+	 * At best, you would only be able to detect if state change has occurred during THIS request.
3337
+	 */
3338
+	public function __wakeup()
3339
+	{
3340
+		$this->_props_n_values_provided_in_constructor = $this->_fields;
3341
+	}
3342
+
3343
+
3344
+	/**
3345
+	 * Usage of this magic method is to ensure any internally cached references to object instances that must remain
3346
+	 * distinct with the clone host instance are also cloned.
3347
+	 */
3348
+	public function __clone()
3349
+	{
3350
+		// handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3351
+		foreach ($this->_fields as $field => $value) {
3352
+			if ($value instanceof DateTime) {
3353
+				$this->_fields[ $field ] = clone $value;
3354
+			}
3355
+		}
3356
+	}
3357 3357
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Datetime.class.php 1 patch
Indentation   +1402 added lines, -1402 removed lines patch added patch discarded remove patch
@@ -13,1410 +13,1410 @@
 block discarded – undo
13 13
 class EE_Datetime extends EE_Soft_Delete_Base_Class
14 14
 {
15 15
 
16
-    /**
17
-     * constant used by get_active_status, indicates datetime has no more available spaces
18
-     */
19
-    const sold_out = 'DTS';
20
-
21
-    /**
22
-     * constant used by get_active_status, indicating datetime is still active (even is not over, can be registered-for)
23
-     */
24
-    const active = 'DTA';
25
-
26
-    /**
27
-     * constant used by get_active_status, indicating the datetime cannot be used for registrations yet, but has not
28
-     * expired
29
-     */
30
-    const upcoming = 'DTU';
31
-
32
-    /**
33
-     * Datetime is postponed
34
-     */
35
-    const postponed = 'DTP';
36
-
37
-    /**
38
-     * Datetime is cancelled
39
-     */
40
-    const cancelled = 'DTC';
41
-
42
-    /**
43
-     * constant used by get_active_status, indicates datetime has expired (event is over)
44
-     */
45
-    const expired = 'DTE';
46
-
47
-    /**
48
-     * constant used in various places indicating that an event is INACTIVE (not yet ready to be published)
49
-     */
50
-    const inactive = 'DTI';
51
-
52
-
53
-    /**
54
-     * @param array  $props_n_values    incoming values
55
-     * @param string $timezone          incoming timezone (if not set the timezone set for the website will be used.)
56
-     * @param array  $date_formats      incoming date_formats in an array where the first value is the date_format
57
-     *                                  and the second value is the time format
58
-     * @return EE_Datetime
59
-     * @throws ReflectionException
60
-     * @throws InvalidArgumentException
61
-     * @throws InvalidInterfaceException
62
-     * @throws InvalidDataTypeException
63
-     * @throws EE_Error
64
-     */
65
-    public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
66
-    {
67
-        $has_object = parent::_check_for_object(
68
-            $props_n_values,
69
-            __CLASS__,
70
-            $timezone,
71
-            $date_formats
72
-        );
73
-        return $has_object
74
-            ? $has_object
75
-            : new self($props_n_values, false, $timezone, $date_formats);
76
-    }
77
-
78
-
79
-    /**
80
-     * @param array  $props_n_values  incoming values from the database
81
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
82
-     *                                the website will be used.
83
-     * @return EE_Datetime
84
-     * @throws ReflectionException
85
-     * @throws InvalidArgumentException
86
-     * @throws InvalidInterfaceException
87
-     * @throws InvalidDataTypeException
88
-     * @throws EE_Error
89
-     */
90
-    public static function new_instance_from_db($props_n_values = array(), $timezone = null)
91
-    {
92
-        return new self($props_n_values, true, $timezone);
93
-    }
94
-
95
-
96
-    /**
97
-     * @param $name
98
-     * @throws ReflectionException
99
-     * @throws InvalidArgumentException
100
-     * @throws InvalidInterfaceException
101
-     * @throws InvalidDataTypeException
102
-     * @throws EE_Error
103
-     */
104
-    public function set_name($name)
105
-    {
106
-        $this->set('DTT_name', $name);
107
-    }
108
-
109
-
110
-    /**
111
-     * @param $description
112
-     * @throws ReflectionException
113
-     * @throws InvalidArgumentException
114
-     * @throws InvalidInterfaceException
115
-     * @throws InvalidDataTypeException
116
-     * @throws EE_Error
117
-     */
118
-    public function set_description($description)
119
-    {
120
-        $this->set('DTT_description', $description);
121
-    }
122
-
123
-
124
-    /**
125
-     * Set event start date
126
-     * set the start date for an event
127
-     *
128
-     * @param string $date a string representation of the event's date ex:  Dec. 25, 2025 or 12-25-2025
129
-     * @throws ReflectionException
130
-     * @throws InvalidArgumentException
131
-     * @throws InvalidInterfaceException
132
-     * @throws InvalidDataTypeException
133
-     * @throws EE_Error
134
-     */
135
-    public function set_start_date($date)
136
-    {
137
-        $this->_set_date_for($date, 'DTT_EVT_start');
138
-    }
139
-
140
-
141
-    /**
142
-     * Set event start time
143
-     * set the start time for an event
144
-     *
145
-     * @param string $time a string representation of the event time ex:  9am  or  7:30 PM
146
-     * @throws ReflectionException
147
-     * @throws InvalidArgumentException
148
-     * @throws InvalidInterfaceException
149
-     * @throws InvalidDataTypeException
150
-     * @throws EE_Error
151
-     */
152
-    public function set_start_time($time)
153
-    {
154
-        $this->_set_time_for($time, 'DTT_EVT_start');
155
-    }
156
-
157
-
158
-    /**
159
-     * Set event end date
160
-     * set the end date for an event
161
-     *
162
-     * @param string $date a string representation of the event's date ex:  Dec. 25, 2025 or 12-25-2025
163
-     * @throws ReflectionException
164
-     * @throws InvalidArgumentException
165
-     * @throws InvalidInterfaceException
166
-     * @throws InvalidDataTypeException
167
-     * @throws EE_Error
168
-     */
169
-    public function set_end_date($date)
170
-    {
171
-        $this->_set_date_for($date, 'DTT_EVT_end');
172
-    }
173
-
174
-
175
-    /**
176
-     * Set event end time
177
-     * set the end time for an event
178
-     *
179
-     * @param string $time a string representation of the event time ex:  9am  or  7:30 PM
180
-     * @throws ReflectionException
181
-     * @throws InvalidArgumentException
182
-     * @throws InvalidInterfaceException
183
-     * @throws InvalidDataTypeException
184
-     * @throws EE_Error
185
-     */
186
-    public function set_end_time($time)
187
-    {
188
-        $this->_set_time_for($time, 'DTT_EVT_end');
189
-    }
190
-
191
-
192
-    /**
193
-     * Set registration limit
194
-     * set the maximum number of attendees that can be registered for this datetime slot
195
-     *
196
-     * @param int $reg_limit
197
-     * @throws ReflectionException
198
-     * @throws InvalidArgumentException
199
-     * @throws InvalidInterfaceException
200
-     * @throws InvalidDataTypeException
201
-     * @throws EE_Error
202
-     */
203
-    public function set_reg_limit($reg_limit)
204
-    {
205
-        $this->set('DTT_reg_limit', $reg_limit);
206
-    }
207
-
208
-
209
-    /**
210
-     * get the number of tickets sold for this datetime slot
211
-     *
212
-     * @return mixed int on success, FALSE on fail
213
-     * @throws ReflectionException
214
-     * @throws InvalidArgumentException
215
-     * @throws InvalidInterfaceException
216
-     * @throws InvalidDataTypeException
217
-     * @throws EE_Error
218
-     */
219
-    public function sold()
220
-    {
221
-        return $this->get_raw('DTT_sold');
222
-    }
223
-
224
-
225
-    /**
226
-     * @param int $sold
227
-     * @throws ReflectionException
228
-     * @throws InvalidArgumentException
229
-     * @throws InvalidInterfaceException
230
-     * @throws InvalidDataTypeException
231
-     * @throws EE_Error
232
-     */
233
-    public function set_sold($sold)
234
-    {
235
-        // sold can not go below zero
236
-        $sold = max(0, $sold);
237
-        $this->set('DTT_sold', $sold);
238
-    }
239
-
240
-
241
-    /**
242
-     * Increments sold by amount passed by $qty, and persists it immediately to the database.
243
-     * Simultaneously decreases the reserved count, unless $also_decrease_reserved is false.
244
-     *
245
-     * @param int $qty
246
-     * @param boolean $also_decrease_reserved
247
-     * @return boolean indicating success
248
-     * @throws ReflectionException
249
-     * @throws InvalidArgumentException
250
-     * @throws InvalidInterfaceException
251
-     * @throws InvalidDataTypeException
252
-     * @throws EE_Error
253
-     */
254
-    public function increaseSold($qty = 1, $also_decrease_reserved = true)
255
-    {
256
-        $qty = absint($qty);
257
-        if ($also_decrease_reserved) {
258
-            $success = $this->adjustNumericFieldsInDb(
259
-                [
260
-                    'DTT_reserved' => $qty * -1,
261
-                    'DTT_sold' => $qty
262
-                ]
263
-            );
264
-        } else {
265
-            $success = $this->adjustNumericFieldsInDb(
266
-                [
267
-                    'DTT_sold' => $qty
268
-                ]
269
-            );
270
-        }
271
-
272
-        do_action(
273
-            'AHEE__EE_Datetime__increase_sold',
274
-            $this,
275
-            $qty,
276
-            $this->sold(),
277
-            $success
278
-        );
279
-        return $success;
280
-    }
281
-
282
-
283
-    /**
284
-     * Decrements (subtracts) sold amount passed by $qty directly in the DB and on the model object. (Ie, no need
285
-     * to save afterwards.)
286
-     *
287
-     * @param int $qty
288
-     * @return boolean indicating success
289
-     * @throws ReflectionException
290
-     * @throws InvalidArgumentException
291
-     * @throws InvalidInterfaceException
292
-     * @throws InvalidDataTypeException
293
-     * @throws EE_Error
294
-     */
295
-    public function decreaseSold($qty = 1)
296
-    {
297
-        $qty = absint($qty);
298
-        $success = $this->adjustNumericFieldsInDb(
299
-            [
300
-                'DTT_sold' => $qty * -1
301
-            ]
302
-        );
303
-        do_action(
304
-            'AHEE__EE_Datetime__decrease_sold',
305
-            $this,
306
-            $qty,
307
-            $this->sold(),
308
-            $success
309
-        );
310
-        return $success;
311
-    }
312
-
313
-
314
-    /**
315
-     * Gets qty of reserved tickets for this datetime
316
-     *
317
-     * @return int
318
-     * @throws ReflectionException
319
-     * @throws InvalidArgumentException
320
-     * @throws InvalidInterfaceException
321
-     * @throws InvalidDataTypeException
322
-     * @throws EE_Error
323
-     */
324
-    public function reserved()
325
-    {
326
-        return $this->get_raw('DTT_reserved');
327
-    }
328
-
329
-
330
-    /**
331
-     * Sets qty of reserved tickets for this datetime
332
-     *
333
-     * @param int $reserved
334
-     * @throws ReflectionException
335
-     * @throws InvalidArgumentException
336
-     * @throws InvalidInterfaceException
337
-     * @throws InvalidDataTypeException
338
-     * @throws EE_Error
339
-     */
340
-    public function set_reserved($reserved)
341
-    {
342
-        // reserved can not go below zero
343
-        $reserved = max(0, (int) $reserved);
344
-        $this->set('DTT_reserved', $reserved);
345
-    }
346
-
347
-
348
-    /**
349
-     * Increments reserved by amount passed by $qty, and persists it immediately to the database.
350
-     *
351
-     * @param int $qty
352
-     * @return boolean indicating success
353
-     * @throws ReflectionException
354
-     * @throws InvalidArgumentException
355
-     * @throws InvalidInterfaceException
356
-     * @throws InvalidDataTypeException
357
-     * @throws EE_Error
358
-     */
359
-    public function increaseReserved($qty = 1)
360
-    {
361
-        $qty = absint($qty);
362
-        $success = $this->incrementFieldConditionallyInDb(
363
-            'DTT_reserved',
364
-            'DTT_sold',
365
-            'DTT_reg_limit',
366
-            $qty
367
-        );
368
-        do_action(
369
-            'AHEE__EE_Datetime__increase_reserved',
370
-            $this,
371
-            $qty,
372
-            $this->reserved(),
373
-            $success
374
-        );
375
-        return $success;
376
-    }
377
-
378
-
379
-    /**
380
-     * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
381
-     *
382
-     * @param int $qty
383
-     * @return boolean indicating success
384
-     * @throws ReflectionException
385
-     * @throws InvalidArgumentException
386
-     * @throws InvalidInterfaceException
387
-     * @throws InvalidDataTypeException
388
-     * @throws EE_Error
389
-     */
390
-    public function decreaseReserved($qty = 1)
391
-    {
392
-        $qty = absint($qty);
393
-        $success = $this->adjustNumericFieldsInDb(
394
-            [
395
-                'DTT_reserved' => $qty * -1
396
-            ]
397
-        );
398
-        do_action(
399
-            'AHEE__EE_Datetime__decrease_reserved',
400
-            $this,
401
-            $qty,
402
-            $this->reserved(),
403
-            $success
404
-        );
405
-        return $success;
406
-    }
407
-
408
-
409
-    /**
410
-     * total sold and reserved tickets
411
-     *
412
-     * @return int
413
-     * @throws ReflectionException
414
-     * @throws InvalidArgumentException
415
-     * @throws InvalidInterfaceException
416
-     * @throws InvalidDataTypeException
417
-     * @throws EE_Error
418
-     */
419
-    public function sold_and_reserved()
420
-    {
421
-        return $this->sold() + $this->reserved();
422
-    }
423
-
424
-
425
-    /**
426
-     * returns the datetime name
427
-     *
428
-     * @return string
429
-     * @throws ReflectionException
430
-     * @throws InvalidArgumentException
431
-     * @throws InvalidInterfaceException
432
-     * @throws InvalidDataTypeException
433
-     * @throws EE_Error
434
-     */
435
-    public function name()
436
-    {
437
-        return $this->get('DTT_name');
438
-    }
439
-
440
-
441
-    /**
442
-     * returns the datetime description
443
-     *
444
-     * @return string
445
-     * @throws ReflectionException
446
-     * @throws InvalidArgumentException
447
-     * @throws InvalidInterfaceException
448
-     * @throws InvalidDataTypeException
449
-     * @throws EE_Error
450
-     */
451
-    public function description()
452
-    {
453
-        return $this->get('DTT_description');
454
-    }
455
-
456
-
457
-    /**
458
-     * This helper simply returns whether the event_datetime for the current datetime is a primary datetime
459
-     *
460
-     * @return boolean  TRUE if is primary, FALSE if not.
461
-     * @throws ReflectionException
462
-     * @throws InvalidArgumentException
463
-     * @throws InvalidInterfaceException
464
-     * @throws InvalidDataTypeException
465
-     * @throws EE_Error
466
-     */
467
-    public function is_primary()
468
-    {
469
-        return $this->get('DTT_is_primary');
470
-    }
471
-
472
-
473
-    /**
474
-     * This helper simply returns the order for the datetime
475
-     *
476
-     * @return int  The order of the datetime for this event.
477
-     * @throws ReflectionException
478
-     * @throws InvalidArgumentException
479
-     * @throws InvalidInterfaceException
480
-     * @throws InvalidDataTypeException
481
-     * @throws EE_Error
482
-     */
483
-    public function order()
484
-    {
485
-        return $this->get('DTT_order');
486
-    }
487
-
488
-
489
-    /**
490
-     * This helper simply returns the parent id for the datetime
491
-     *
492
-     * @return int
493
-     * @throws ReflectionException
494
-     * @throws InvalidArgumentException
495
-     * @throws InvalidInterfaceException
496
-     * @throws InvalidDataTypeException
497
-     * @throws EE_Error
498
-     */
499
-    public function parent()
500
-    {
501
-        return $this->get('DTT_parent');
502
-    }
503
-
504
-
505
-    /**
506
-     * show date and/or time
507
-     *
508
-     * @param string $date_or_time    whether to display a date or time or both
509
-     * @param string $start_or_end    whether to display start or end datetimes
510
-     * @param string $dt_frmt
511
-     * @param string $tm_frmt
512
-     * @param bool   $echo            whether we echo or return (note echoing uses "pretty" formats,
513
-     *                                otherwise we use the standard formats)
514
-     * @return string|bool  string on success, FALSE on fail
515
-     * @throws ReflectionException
516
-     * @throws InvalidArgumentException
517
-     * @throws InvalidInterfaceException
518
-     * @throws InvalidDataTypeException
519
-     * @throws EE_Error
520
-     */
521
-    private function _show_datetime(
522
-        $date_or_time = null,
523
-        $start_or_end = 'start',
524
-        $dt_frmt = '',
525
-        $tm_frmt = '',
526
-        $echo = false
527
-    ) {
528
-        $field_name = "DTT_EVT_{$start_or_end}";
529
-        $dtt = $this->_get_datetime(
530
-            $field_name,
531
-            $dt_frmt,
532
-            $tm_frmt,
533
-            $date_or_time,
534
-            $echo
535
-        );
536
-        if (! $echo) {
537
-            return $dtt;
538
-        }
539
-        return '';
540
-    }
541
-
542
-
543
-    /**
544
-     * get event start date.  Provide either the date format, or NULL to re-use the
545
-     * last-used format, or '' to use the default date format
546
-     *
547
-     * @param string $dt_frmt string representation of date format defaults to 'F j, Y'
548
-     * @return mixed            string on success, FALSE on fail
549
-     * @throws ReflectionException
550
-     * @throws InvalidArgumentException
551
-     * @throws InvalidInterfaceException
552
-     * @throws InvalidDataTypeException
553
-     * @throws EE_Error
554
-     */
555
-    public function start_date($dt_frmt = '')
556
-    {
557
-        return $this->_show_datetime('D', 'start', $dt_frmt);
558
-    }
559
-
560
-
561
-    /**
562
-     * Echoes start_date()
563
-     *
564
-     * @param string $dt_frmt
565
-     * @throws ReflectionException
566
-     * @throws InvalidArgumentException
567
-     * @throws InvalidInterfaceException
568
-     * @throws InvalidDataTypeException
569
-     * @throws EE_Error
570
-     */
571
-    public function e_start_date($dt_frmt = '')
572
-    {
573
-        $this->_show_datetime('D', 'start', $dt_frmt, null, true);
574
-    }
575
-
576
-
577
-    /**
578
-     * get end date. Provide either the date format, or NULL to re-use the
579
-     * last-used format, or '' to use the default date format
580
-     *
581
-     * @param string $dt_frmt string representation of date format defaults to 'F j, Y'
582
-     * @return mixed            string on success, FALSE on fail
583
-     * @throws ReflectionException
584
-     * @throws InvalidArgumentException
585
-     * @throws InvalidInterfaceException
586
-     * @throws InvalidDataTypeException
587
-     * @throws EE_Error
588
-     */
589
-    public function end_date($dt_frmt = '')
590
-    {
591
-        return $this->_show_datetime('D', 'end', $dt_frmt);
592
-    }
593
-
594
-
595
-    /**
596
-     * Echoes the end date. See end_date()
597
-     *
598
-     * @param string $dt_frmt
599
-     * @throws ReflectionException
600
-     * @throws InvalidArgumentException
601
-     * @throws InvalidInterfaceException
602
-     * @throws InvalidDataTypeException
603
-     * @throws EE_Error
604
-     */
605
-    public function e_end_date($dt_frmt = '')
606
-    {
607
-        $this->_show_datetime('D', 'end', $dt_frmt, null, true);
608
-    }
609
-
610
-
611
-    /**
612
-     * get date_range - meaning the start AND end date
613
-     *
614
-     * @access public
615
-     * @param string $dt_frmt     string representation of date format defaults to WP settings
616
-     * @param string $conjunction conjunction junction what's your function ?
617
-     *                            this string joins the start date with the end date ie: Jan 01 "to" Dec 31
618
-     * @return mixed              string on success, FALSE on fail
619
-     * @throws ReflectionException
620
-     * @throws InvalidArgumentException
621
-     * @throws InvalidInterfaceException
622
-     * @throws InvalidDataTypeException
623
-     * @throws EE_Error
624
-     */
625
-    public function date_range($dt_frmt = '', $conjunction = ' - ')
626
-    {
627
-        $dt_frmt = ! empty($dt_frmt) ? $dt_frmt : $this->_dt_frmt;
628
-        $start = str_replace(
629
-            ' ',
630
-            '&nbsp;',
631
-            $this->get_i18n_datetime('DTT_EVT_start', $dt_frmt)
632
-        );
633
-        $end = str_replace(
634
-            ' ',
635
-            '&nbsp;',
636
-            $this->get_i18n_datetime('DTT_EVT_end', $dt_frmt)
637
-        );
638
-        return $start !== $end ? $start . $conjunction . $end : $start;
639
-    }
640
-
641
-
642
-    /**
643
-     * @param string $dt_frmt
644
-     * @param string $conjunction
645
-     * @throws ReflectionException
646
-     * @throws InvalidArgumentException
647
-     * @throws InvalidInterfaceException
648
-     * @throws InvalidDataTypeException
649
-     * @throws EE_Error
650
-     */
651
-    public function e_date_range($dt_frmt = '', $conjunction = ' - ')
652
-    {
653
-        echo $this->date_range($dt_frmt, $conjunction);
654
-    }
655
-
656
-
657
-    /**
658
-     * get start time
659
-     *
660
-     * @param string $tm_format - string representation of time format defaults to 'g:i a'
661
-     * @return mixed        string on success, FALSE on fail
662
-     * @throws ReflectionException
663
-     * @throws InvalidArgumentException
664
-     * @throws InvalidInterfaceException
665
-     * @throws InvalidDataTypeException
666
-     * @throws EE_Error
667
-     */
668
-    public function start_time($tm_format = '')
669
-    {
670
-        return $this->_show_datetime('T', 'start', null, $tm_format);
671
-    }
672
-
673
-
674
-    /**
675
-     * @param string $tm_format
676
-     * @throws ReflectionException
677
-     * @throws InvalidArgumentException
678
-     * @throws InvalidInterfaceException
679
-     * @throws InvalidDataTypeException
680
-     * @throws EE_Error
681
-     */
682
-    public function e_start_time($tm_format = '')
683
-    {
684
-        $this->_show_datetime('T', 'start', null, $tm_format, true);
685
-    }
686
-
687
-
688
-    /**
689
-     * get end time
690
-     *
691
-     * @param string $tm_format string representation of time format defaults to 'g:i a'
692
-     * @return mixed                string on success, FALSE on fail
693
-     * @throws ReflectionException
694
-     * @throws InvalidArgumentException
695
-     * @throws InvalidInterfaceException
696
-     * @throws InvalidDataTypeException
697
-     * @throws EE_Error
698
-     */
699
-    public function end_time($tm_format = '')
700
-    {
701
-        return $this->_show_datetime('T', 'end', null, $tm_format);
702
-    }
703
-
704
-
705
-    /**
706
-     * @param string $tm_format
707
-     * @throws ReflectionException
708
-     * @throws InvalidArgumentException
709
-     * @throws InvalidInterfaceException
710
-     * @throws InvalidDataTypeException
711
-     * @throws EE_Error
712
-     */
713
-    public function e_end_time($tm_format = '')
714
-    {
715
-        $this->_show_datetime('T', 'end', null, $tm_format, true);
716
-    }
717
-
718
-
719
-    /**
720
-     * get time_range
721
-     *
722
-     * @access public
723
-     * @param string $tm_format   string representation of time format defaults to 'g:i a'
724
-     * @param string $conjunction conjunction junction what's your function ?
725
-     *                            this string joins the start date with the end date ie: Jan 01 "to" Dec 31
726
-     * @return mixed              string on success, FALSE on fail
727
-     * @throws ReflectionException
728
-     * @throws InvalidArgumentException
729
-     * @throws InvalidInterfaceException
730
-     * @throws InvalidDataTypeException
731
-     * @throws EE_Error
732
-     */
733
-    public function time_range($tm_format = '', $conjunction = ' - ')
734
-    {
735
-        $tm_format = ! empty($tm_format) ? $tm_format : $this->_tm_frmt;
736
-        $start = str_replace(
737
-            ' ',
738
-            '&nbsp;',
739
-            $this->get_i18n_datetime('DTT_EVT_start', $tm_format)
740
-        );
741
-        $end = str_replace(
742
-            ' ',
743
-            '&nbsp;',
744
-            $this->get_i18n_datetime('DTT_EVT_end', $tm_format)
745
-        );
746
-        return $start !== $end ? $start . $conjunction . $end : $start;
747
-    }
748
-
749
-
750
-    /**
751
-     * @param string $tm_format
752
-     * @param string $conjunction
753
-     * @throws ReflectionException
754
-     * @throws InvalidArgumentException
755
-     * @throws InvalidInterfaceException
756
-     * @throws InvalidDataTypeException
757
-     * @throws EE_Error
758
-     */
759
-    public function e_time_range($tm_format = '', $conjunction = ' - ')
760
-    {
761
-        echo $this->time_range($tm_format, $conjunction);
762
-    }
763
-
764
-
765
-    /**
766
-     * This returns a range representation of the date and times.
767
-     * Output is dependent on the difference (or similarity) between DTT_EVT_start and DTT_EVT_end.
768
-     * Also, the return value is localized.
769
-     *
770
-     * @param string $dt_format
771
-     * @param string $tm_format
772
-     * @param string $conjunction used between two different dates or times.
773
-     *                            ex: Dec 1{$conjunction}}Dec 6, or 2pm{$conjunction}3pm
774
-     * @param string $separator   used between the date and time formats.
775
-     *                            ex: Dec 1, 2016{$separator}2pm
776
-     * @return string
777
-     * @throws ReflectionException
778
-     * @throws InvalidArgumentException
779
-     * @throws InvalidInterfaceException
780
-     * @throws InvalidDataTypeException
781
-     * @throws EE_Error
782
-     */
783
-    public function date_and_time_range(
784
-        $dt_format = '',
785
-        $tm_format = '',
786
-        $conjunction = ' - ',
787
-        $separator = ' '
788
-    ) {
789
-        $dt_format = ! empty($dt_format) ? $dt_format : $this->_dt_frmt;
790
-        $tm_format = ! empty($tm_format) ? $tm_format : $this->_tm_frmt;
791
-        $full_format = $dt_format . $separator . $tm_format;
792
-        // the range output depends on various conditions
793
-        switch (true) {
794
-            // start date timestamp and end date timestamp are the same.
795
-            case ($this->get_raw('DTT_EVT_start') === $this->get_raw('DTT_EVT_end')):
796
-                $output = $this->get_i18n_datetime('DTT_EVT_start', $full_format);
797
-                break;
798
-            // start and end date are the same but times are different
799
-            case ($this->start_date() === $this->end_date()):
800
-                $output = $this->get_i18n_datetime('DTT_EVT_start', $full_format)
801
-                          . $conjunction
802
-                          . $this->get_i18n_datetime('DTT_EVT_end', $tm_format);
803
-                break;
804
-            // all other conditions
805
-            default:
806
-                $output = $this->get_i18n_datetime('DTT_EVT_start', $full_format)
807
-                          . $conjunction
808
-                          . $this->get_i18n_datetime('DTT_EVT_end', $full_format);
809
-                break;
810
-        }
811
-        return $output;
812
-    }
813
-
814
-
815
-    /**
816
-     * This echos the results of date and time range.
817
-     *
818
-     * @see date_and_time_range() for more details on purpose.
819
-     * @param string $dt_format
820
-     * @param string $tm_format
821
-     * @param string $conjunction
822
-     * @return void
823
-     * @throws ReflectionException
824
-     * @throws InvalidArgumentException
825
-     * @throws InvalidInterfaceException
826
-     * @throws InvalidDataTypeException
827
-     * @throws EE_Error
828
-     */
829
-    public function e_date_and_time_range($dt_format = '', $tm_format = '', $conjunction = ' - ')
830
-    {
831
-        echo $this->date_and_time_range($dt_format, $tm_format, $conjunction);
832
-    }
833
-
834
-
835
-    /**
836
-     * get start date and start time
837
-     *
838
-     * @param    string $dt_format - string representation of date format defaults to 'F j, Y'
839
-     * @param    string $tm_format - string representation of time format defaults to 'g:i a'
840
-     * @return    mixed    string on success, FALSE on fail
841
-     * @throws ReflectionException
842
-     * @throws InvalidArgumentException
843
-     * @throws InvalidInterfaceException
844
-     * @throws InvalidDataTypeException
845
-     * @throws EE_Error
846
-     */
847
-    public function start_date_and_time($dt_format = '', $tm_format = '')
848
-    {
849
-        return $this->_show_datetime('', 'start', $dt_format, $tm_format);
850
-    }
851
-
852
-
853
-    /**
854
-     * @param string $dt_frmt
855
-     * @param string $tm_format
856
-     * @throws ReflectionException
857
-     * @throws InvalidArgumentException
858
-     * @throws InvalidInterfaceException
859
-     * @throws InvalidDataTypeException
860
-     * @throws EE_Error
861
-     */
862
-    public function e_start_date_and_time($dt_frmt = '', $tm_format = '')
863
-    {
864
-        $this->_show_datetime('', 'start', $dt_frmt, $tm_format, true);
865
-    }
866
-
867
-
868
-    /**
869
-     * Shows the length of the event (start to end time).
870
-     * Can be shown in 'seconds','minutes','hours', or 'days'.
871
-     * By default, rounds up. (So if you use 'days', and then event
872
-     * only occurs for 1 hour, it will return 1 day).
873
-     *
874
-     * @param string $units 'seconds','minutes','hours','days'
875
-     * @param bool   $round_up
876
-     * @return float|int|mixed
877
-     * @throws ReflectionException
878
-     * @throws InvalidArgumentException
879
-     * @throws InvalidInterfaceException
880
-     * @throws InvalidDataTypeException
881
-     * @throws EE_Error
882
-     */
883
-    public function length($units = 'seconds', $round_up = false)
884
-    {
885
-        $start = $this->get_raw('DTT_EVT_start');
886
-        $end = $this->get_raw('DTT_EVT_end');
887
-        $length_in_units = $end - $start;
888
-        switch ($units) {
889
-            // NOTE: We purposefully don't use "break;" in order to chain the divisions
890
-            /** @noinspection PhpMissingBreakStatementInspection */
891
-            // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
892
-            case 'days':
893
-                $length_in_units /= 24;
894
-            /** @noinspection PhpMissingBreakStatementInspection */
895
-            case 'hours':
896
-                // fall through is intentional
897
-                $length_in_units /= 60;
898
-            /** @noinspection PhpMissingBreakStatementInspection */
899
-            case 'minutes':
900
-                // fall through is intentional
901
-                $length_in_units /= 60;
902
-            case 'seconds':
903
-            default:
904
-                $length_in_units = ceil($length_in_units);
905
-        }
906
-        // phpcs:enable
907
-        if ($round_up) {
908
-            $length_in_units = max($length_in_units, 1);
909
-        }
910
-        return $length_in_units;
911
-    }
912
-
913
-
914
-    /**
915
-     *        get end date and time
916
-     *
917
-     * @param string $dt_frmt   - string representation of date format defaults to 'F j, Y'
918
-     * @param string $tm_format - string representation of time format defaults to 'g:i a'
919
-     * @return    mixed                string on success, FALSE on fail
920
-     * @throws ReflectionException
921
-     * @throws InvalidArgumentException
922
-     * @throws InvalidInterfaceException
923
-     * @throws InvalidDataTypeException
924
-     * @throws EE_Error
925
-     */
926
-    public function end_date_and_time($dt_frmt = '', $tm_format = '')
927
-    {
928
-        return $this->_show_datetime('', 'end', $dt_frmt, $tm_format);
929
-    }
930
-
931
-
932
-    /**
933
-     * @param string $dt_frmt
934
-     * @param string $tm_format
935
-     * @throws ReflectionException
936
-     * @throws InvalidArgumentException
937
-     * @throws InvalidInterfaceException
938
-     * @throws InvalidDataTypeException
939
-     * @throws EE_Error
940
-     */
941
-    public function e_end_date_and_time($dt_frmt = '', $tm_format = '')
942
-    {
943
-        $this->_show_datetime('', 'end', $dt_frmt, $tm_format, true);
944
-    }
945
-
946
-
947
-    /**
948
-     *        get start timestamp
949
-     *
950
-     * @return        int
951
-     * @throws ReflectionException
952
-     * @throws InvalidArgumentException
953
-     * @throws InvalidInterfaceException
954
-     * @throws InvalidDataTypeException
955
-     * @throws EE_Error
956
-     */
957
-    public function start()
958
-    {
959
-        return $this->get_raw('DTT_EVT_start');
960
-    }
961
-
962
-
963
-    /**
964
-     *        get end timestamp
965
-     *
966
-     * @return        int
967
-     * @throws ReflectionException
968
-     * @throws InvalidArgumentException
969
-     * @throws InvalidInterfaceException
970
-     * @throws InvalidDataTypeException
971
-     * @throws EE_Error
972
-     */
973
-    public function end()
974
-    {
975
-        return $this->get_raw('DTT_EVT_end');
976
-    }
977
-
978
-
979
-    /**
980
-     *    get the registration limit for this datetime slot
981
-     *
982
-     * @return        mixed        int on success, FALSE on fail
983
-     * @throws ReflectionException
984
-     * @throws InvalidArgumentException
985
-     * @throws InvalidInterfaceException
986
-     * @throws InvalidDataTypeException
987
-     * @throws EE_Error
988
-     */
989
-    public function reg_limit()
990
-    {
991
-        return $this->get_raw('DTT_reg_limit');
992
-    }
993
-
994
-
995
-    /**
996
-     *    have the tickets sold for this datetime, met or exceed the registration limit ?
997
-     *
998
-     * @return        boolean
999
-     * @throws ReflectionException
1000
-     * @throws InvalidArgumentException
1001
-     * @throws InvalidInterfaceException
1002
-     * @throws InvalidDataTypeException
1003
-     * @throws EE_Error
1004
-     */
1005
-    public function sold_out()
1006
-    {
1007
-        return $this->reg_limit() > 0 && $this->sold() >= $this->reg_limit();
1008
-    }
1009
-
1010
-
1011
-    /**
1012
-     * return the total number of spaces remaining at this venue.
1013
-     * This only takes the venue's capacity into account, NOT the tickets available for sale
1014
-     *
1015
-     * @param bool $consider_tickets Whether to consider tickets remaining when determining if there are any spaces left
1016
-     *                               Because if all tickets attached to this datetime have no spaces left,
1017
-     *                               then this datetime IS effectively sold out.
1018
-     *                               However, there are cases where we just want to know the spaces
1019
-     *                               remaining for this particular datetime, hence the flag.
1020
-     * @return int
1021
-     * @throws ReflectionException
1022
-     * @throws InvalidArgumentException
1023
-     * @throws InvalidInterfaceException
1024
-     * @throws InvalidDataTypeException
1025
-     * @throws EE_Error
1026
-     */
1027
-    public function spaces_remaining($consider_tickets = false)
1028
-    {
1029
-        // tickets remaining available for purchase
1030
-        // no need for special checks for infinite, because if DTT_reg_limit == EE_INF, then EE_INF - x = EE_INF
1031
-        $dtt_remaining = $this->reg_limit() - $this->sold_and_reserved();
1032
-        if (! $consider_tickets) {
1033
-            return $dtt_remaining;
1034
-        }
1035
-        $tickets_remaining = $this->tickets_remaining();
1036
-        return min($dtt_remaining, $tickets_remaining);
1037
-    }
1038
-
1039
-
1040
-    /**
1041
-     * Counts the total tickets available
1042
-     * (from all the different types of tickets which are available for this datetime).
1043
-     *
1044
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1045
-     * @return int
1046
-     * @throws ReflectionException
1047
-     * @throws InvalidArgumentException
1048
-     * @throws InvalidInterfaceException
1049
-     * @throws InvalidDataTypeException
1050
-     * @throws EE_Error
1051
-     */
1052
-    public function tickets_remaining($query_params = array())
1053
-    {
1054
-        $sum = 0;
1055
-        $tickets = $this->tickets($query_params);
1056
-        if (! empty($tickets)) {
1057
-            foreach ($tickets as $ticket) {
1058
-                if ($ticket instanceof EE_Ticket) {
1059
-                    // get the actual amount of tickets that can be sold
1060
-                    $qty = $ticket->qty('saleable');
1061
-                    if ($qty === EE_INF) {
1062
-                        return EE_INF;
1063
-                    }
1064
-                    // no negative ticket quantities plz
1065
-                    if ($qty > 0) {
1066
-                        $sum += $qty;
1067
-                    }
1068
-                }
1069
-            }
1070
-        }
1071
-        return $sum;
1072
-    }
1073
-
1074
-
1075
-    /**
1076
-     * Gets the count of all the tickets available at this datetime (not ticket types)
1077
-     * before any were sold
1078
-     *
1079
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1080
-     * @return int
1081
-     * @throws ReflectionException
1082
-     * @throws InvalidArgumentException
1083
-     * @throws InvalidInterfaceException
1084
-     * @throws InvalidDataTypeException
1085
-     * @throws EE_Error
1086
-     */
1087
-    public function sum_tickets_initially_available($query_params = array())
1088
-    {
1089
-        return $this->sum_related('Ticket', $query_params, 'TKT_qty');
1090
-    }
1091
-
1092
-
1093
-    /**
1094
-     * Returns the lesser-of-the two: spaces remaining at this datetime, or
1095
-     * the total tickets remaining (a sum of the tickets remaining for each ticket type
1096
-     * that is available for this datetime).
1097
-     *
1098
-     * @return int
1099
-     * @throws ReflectionException
1100
-     * @throws InvalidArgumentException
1101
-     * @throws InvalidInterfaceException
1102
-     * @throws InvalidDataTypeException
1103
-     * @throws EE_Error
1104
-     */
1105
-    public function total_tickets_available_at_this_datetime()
1106
-    {
1107
-        return $this->spaces_remaining(true);
1108
-    }
1109
-
1110
-
1111
-    /**
1112
-     * This simply compares the internal dtt for the given string with NOW
1113
-     * and determines if the date is upcoming or not.
1114
-     *
1115
-     * @access public
1116
-     * @return boolean
1117
-     * @throws ReflectionException
1118
-     * @throws InvalidArgumentException
1119
-     * @throws InvalidInterfaceException
1120
-     * @throws InvalidDataTypeException
1121
-     * @throws EE_Error
1122
-     */
1123
-    public function is_upcoming()
1124
-    {
1125
-        return ($this->get_raw('DTT_EVT_start') > time());
1126
-    }
1127
-
1128
-
1129
-    /**
1130
-     * This simply compares the internal datetime for the given string with NOW
1131
-     * and returns if the date is active (i.e. start and end time)
1132
-     *
1133
-     * @return boolean
1134
-     * @throws ReflectionException
1135
-     * @throws InvalidArgumentException
1136
-     * @throws InvalidInterfaceException
1137
-     * @throws InvalidDataTypeException
1138
-     * @throws EE_Error
1139
-     */
1140
-    public function is_active()
1141
-    {
1142
-        return ($this->get_raw('DTT_EVT_start') < time() && $this->get_raw('DTT_EVT_end') > time());
1143
-    }
1144
-
1145
-
1146
-    /**
1147
-     * This simply compares the internal dtt for the given string with NOW
1148
-     * and determines if the date is expired or not.
1149
-     *
1150
-     * @return boolean
1151
-     * @throws ReflectionException
1152
-     * @throws InvalidArgumentException
1153
-     * @throws InvalidInterfaceException
1154
-     * @throws InvalidDataTypeException
1155
-     * @throws EE_Error
1156
-     */
1157
-    public function is_expired()
1158
-    {
1159
-        return ($this->get_raw('DTT_EVT_end') < time());
1160
-    }
1161
-
1162
-
1163
-    /**
1164
-     * This returns the active status for whether an event is active, upcoming, or expired
1165
-     *
1166
-     * @return int return value will be one of the EE_Datetime status constants.
1167
-     * @throws ReflectionException
1168
-     * @throws InvalidArgumentException
1169
-     * @throws InvalidInterfaceException
1170
-     * @throws InvalidDataTypeException
1171
-     * @throws EE_Error
1172
-     */
1173
-    public function get_active_status()
1174
-    {
1175
-        $total_tickets_for_this_dtt = $this->total_tickets_available_at_this_datetime();
1176
-        if ($total_tickets_for_this_dtt !== false && $total_tickets_for_this_dtt < 1) {
1177
-            return EE_Datetime::sold_out;
1178
-        }
1179
-        if ($this->is_expired()) {
1180
-            return EE_Datetime::expired;
1181
-        }
1182
-        if ($this->is_upcoming()) {
1183
-            return EE_Datetime::upcoming;
1184
-        }
1185
-        if ($this->is_active()) {
1186
-            return EE_Datetime::active;
1187
-        }
1188
-        return null;
1189
-    }
1190
-
1191
-
1192
-    /**
1193
-     * This returns a nice display name for the datetime that is contingent on the span between the dates and times.
1194
-     *
1195
-     * @param  boolean $use_dtt_name if TRUE then we'll use DTT->name() if its not empty.
1196
-     * @return string
1197
-     * @throws ReflectionException
1198
-     * @throws InvalidArgumentException
1199
-     * @throws InvalidInterfaceException
1200
-     * @throws InvalidDataTypeException
1201
-     * @throws EE_Error
1202
-     */
1203
-    public function get_dtt_display_name($use_dtt_name = false)
1204
-    {
1205
-        if ($use_dtt_name) {
1206
-            $dtt_name = $this->name();
1207
-            if (! empty($dtt_name)) {
1208
-                return $dtt_name;
1209
-            }
1210
-        }
1211
-        // first condition is to see if the months are different
1212
-        if (date('m', $this->get_raw('DTT_EVT_start')) !== date('m', $this->get_raw('DTT_EVT_end'))
1213
-        ) {
1214
-            $display_date = $this->start_date('M j\, Y g:i a') . ' - ' . $this->end_date('M j\, Y g:i a');
1215
-            // next condition is if its the same month but different day
1216
-        } else {
1217
-            if (date('m', $this->get_raw('DTT_EVT_start')) === date('m', $this->get_raw('DTT_EVT_end'))
1218
-                && date('d', $this->get_raw('DTT_EVT_start')) !== date('d', $this->get_raw('DTT_EVT_end'))
1219
-            ) {
1220
-                $display_date = $this->start_date('M j\, g:i a') . ' - ' . $this->end_date('M j\, g:i a Y');
1221
-            } else {
1222
-                $display_date = $this->start_date('F j\, Y')
1223
-                                . ' @ '
1224
-                                . $this->start_date('g:i a')
1225
-                                . ' - '
1226
-                                . $this->end_date('g:i a');
1227
-            }
1228
-        }
1229
-        return $display_date;
1230
-    }
1231
-
1232
-
1233
-    /**
1234
-     * Gets all the tickets for this datetime
1235
-     *
1236
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1237
-     * @return EE_Base_Class[]|EE_Ticket[]
1238
-     * @throws ReflectionException
1239
-     * @throws InvalidArgumentException
1240
-     * @throws InvalidInterfaceException
1241
-     * @throws InvalidDataTypeException
1242
-     * @throws EE_Error
1243
-     */
1244
-    public function tickets($query_params = array())
1245
-    {
1246
-        return $this->get_many_related('Ticket', $query_params);
1247
-    }
1248
-
1249
-
1250
-    /**
1251
-     * Gets all the ticket types currently available for purchase
1252
-     *
1253
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1254
-     * @return EE_Ticket[]
1255
-     * @throws ReflectionException
1256
-     * @throws InvalidArgumentException
1257
-     * @throws InvalidInterfaceException
1258
-     * @throws InvalidDataTypeException
1259
-     * @throws EE_Error
1260
-     */
1261
-    public function ticket_types_available_for_purchase($query_params = array())
1262
-    {
1263
-        // first check if datetime is valid
1264
-        if ($this->sold_out() || ! ($this->is_upcoming() || $this->is_active())) {
1265
-            return array();
1266
-        }
1267
-        if (empty($query_params)) {
1268
-            $query_params = array(
1269
-                array(
1270
-                    'TKT_start_date' => array('<=', EEM_Ticket::instance()->current_time_for_query('TKT_start_date')),
1271
-                    'TKT_end_date'   => array('>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')),
1272
-                    'TKT_deleted'    => false,
1273
-                ),
1274
-            );
1275
-        }
1276
-        return $this->tickets($query_params);
1277
-    }
1278
-
1279
-
1280
-    /**
1281
-     * @return EE_Base_Class|EE_Event
1282
-     * @throws ReflectionException
1283
-     * @throws InvalidArgumentException
1284
-     * @throws InvalidInterfaceException
1285
-     * @throws InvalidDataTypeException
1286
-     * @throws EE_Error
1287
-     */
1288
-    public function event()
1289
-    {
1290
-        return $this->get_first_related('Event');
1291
-    }
1292
-
1293
-
1294
-    /**
1295
-     * Updates the DTT_sold attribute (and saves) based on the number of registrations for this datetime
1296
-     * (via the tickets).
1297
-     *
1298
-     * @return int
1299
-     * @throws ReflectionException
1300
-     * @throws InvalidArgumentException
1301
-     * @throws InvalidInterfaceException
1302
-     * @throws InvalidDataTypeException
1303
-     * @throws EE_Error
1304
-     */
1305
-    public function update_sold()
1306
-    {
1307
-        $count_regs_for_this_datetime = EEM_Registration::instance()->count(
1308
-            array(
1309
-                array(
1310
-                    'STS_ID'                 => EEM_Registration::status_id_approved,
1311
-                    'REG_deleted'            => 0,
1312
-                    'Ticket.Datetime.DTT_ID' => $this->ID(),
1313
-                ),
1314
-            )
1315
-        );
1316
-        $this->set_sold($count_regs_for_this_datetime);
1317
-        $this->save();
1318
-        return $count_regs_for_this_datetime;
1319
-    }
1320
-
1321
-
1322
-    /*******************************************************************
16
+	/**
17
+	 * constant used by get_active_status, indicates datetime has no more available spaces
18
+	 */
19
+	const sold_out = 'DTS';
20
+
21
+	/**
22
+	 * constant used by get_active_status, indicating datetime is still active (even is not over, can be registered-for)
23
+	 */
24
+	const active = 'DTA';
25
+
26
+	/**
27
+	 * constant used by get_active_status, indicating the datetime cannot be used for registrations yet, but has not
28
+	 * expired
29
+	 */
30
+	const upcoming = 'DTU';
31
+
32
+	/**
33
+	 * Datetime is postponed
34
+	 */
35
+	const postponed = 'DTP';
36
+
37
+	/**
38
+	 * Datetime is cancelled
39
+	 */
40
+	const cancelled = 'DTC';
41
+
42
+	/**
43
+	 * constant used by get_active_status, indicates datetime has expired (event is over)
44
+	 */
45
+	const expired = 'DTE';
46
+
47
+	/**
48
+	 * constant used in various places indicating that an event is INACTIVE (not yet ready to be published)
49
+	 */
50
+	const inactive = 'DTI';
51
+
52
+
53
+	/**
54
+	 * @param array  $props_n_values    incoming values
55
+	 * @param string $timezone          incoming timezone (if not set the timezone set for the website will be used.)
56
+	 * @param array  $date_formats      incoming date_formats in an array where the first value is the date_format
57
+	 *                                  and the second value is the time format
58
+	 * @return EE_Datetime
59
+	 * @throws ReflectionException
60
+	 * @throws InvalidArgumentException
61
+	 * @throws InvalidInterfaceException
62
+	 * @throws InvalidDataTypeException
63
+	 * @throws EE_Error
64
+	 */
65
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
66
+	{
67
+		$has_object = parent::_check_for_object(
68
+			$props_n_values,
69
+			__CLASS__,
70
+			$timezone,
71
+			$date_formats
72
+		);
73
+		return $has_object
74
+			? $has_object
75
+			: new self($props_n_values, false, $timezone, $date_formats);
76
+	}
77
+
78
+
79
+	/**
80
+	 * @param array  $props_n_values  incoming values from the database
81
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
82
+	 *                                the website will be used.
83
+	 * @return EE_Datetime
84
+	 * @throws ReflectionException
85
+	 * @throws InvalidArgumentException
86
+	 * @throws InvalidInterfaceException
87
+	 * @throws InvalidDataTypeException
88
+	 * @throws EE_Error
89
+	 */
90
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null)
91
+	{
92
+		return new self($props_n_values, true, $timezone);
93
+	}
94
+
95
+
96
+	/**
97
+	 * @param $name
98
+	 * @throws ReflectionException
99
+	 * @throws InvalidArgumentException
100
+	 * @throws InvalidInterfaceException
101
+	 * @throws InvalidDataTypeException
102
+	 * @throws EE_Error
103
+	 */
104
+	public function set_name($name)
105
+	{
106
+		$this->set('DTT_name', $name);
107
+	}
108
+
109
+
110
+	/**
111
+	 * @param $description
112
+	 * @throws ReflectionException
113
+	 * @throws InvalidArgumentException
114
+	 * @throws InvalidInterfaceException
115
+	 * @throws InvalidDataTypeException
116
+	 * @throws EE_Error
117
+	 */
118
+	public function set_description($description)
119
+	{
120
+		$this->set('DTT_description', $description);
121
+	}
122
+
123
+
124
+	/**
125
+	 * Set event start date
126
+	 * set the start date for an event
127
+	 *
128
+	 * @param string $date a string representation of the event's date ex:  Dec. 25, 2025 or 12-25-2025
129
+	 * @throws ReflectionException
130
+	 * @throws InvalidArgumentException
131
+	 * @throws InvalidInterfaceException
132
+	 * @throws InvalidDataTypeException
133
+	 * @throws EE_Error
134
+	 */
135
+	public function set_start_date($date)
136
+	{
137
+		$this->_set_date_for($date, 'DTT_EVT_start');
138
+	}
139
+
140
+
141
+	/**
142
+	 * Set event start time
143
+	 * set the start time for an event
144
+	 *
145
+	 * @param string $time a string representation of the event time ex:  9am  or  7:30 PM
146
+	 * @throws ReflectionException
147
+	 * @throws InvalidArgumentException
148
+	 * @throws InvalidInterfaceException
149
+	 * @throws InvalidDataTypeException
150
+	 * @throws EE_Error
151
+	 */
152
+	public function set_start_time($time)
153
+	{
154
+		$this->_set_time_for($time, 'DTT_EVT_start');
155
+	}
156
+
157
+
158
+	/**
159
+	 * Set event end date
160
+	 * set the end date for an event
161
+	 *
162
+	 * @param string $date a string representation of the event's date ex:  Dec. 25, 2025 or 12-25-2025
163
+	 * @throws ReflectionException
164
+	 * @throws InvalidArgumentException
165
+	 * @throws InvalidInterfaceException
166
+	 * @throws InvalidDataTypeException
167
+	 * @throws EE_Error
168
+	 */
169
+	public function set_end_date($date)
170
+	{
171
+		$this->_set_date_for($date, 'DTT_EVT_end');
172
+	}
173
+
174
+
175
+	/**
176
+	 * Set event end time
177
+	 * set the end time for an event
178
+	 *
179
+	 * @param string $time a string representation of the event time ex:  9am  or  7:30 PM
180
+	 * @throws ReflectionException
181
+	 * @throws InvalidArgumentException
182
+	 * @throws InvalidInterfaceException
183
+	 * @throws InvalidDataTypeException
184
+	 * @throws EE_Error
185
+	 */
186
+	public function set_end_time($time)
187
+	{
188
+		$this->_set_time_for($time, 'DTT_EVT_end');
189
+	}
190
+
191
+
192
+	/**
193
+	 * Set registration limit
194
+	 * set the maximum number of attendees that can be registered for this datetime slot
195
+	 *
196
+	 * @param int $reg_limit
197
+	 * @throws ReflectionException
198
+	 * @throws InvalidArgumentException
199
+	 * @throws InvalidInterfaceException
200
+	 * @throws InvalidDataTypeException
201
+	 * @throws EE_Error
202
+	 */
203
+	public function set_reg_limit($reg_limit)
204
+	{
205
+		$this->set('DTT_reg_limit', $reg_limit);
206
+	}
207
+
208
+
209
+	/**
210
+	 * get the number of tickets sold for this datetime slot
211
+	 *
212
+	 * @return mixed int on success, FALSE on fail
213
+	 * @throws ReflectionException
214
+	 * @throws InvalidArgumentException
215
+	 * @throws InvalidInterfaceException
216
+	 * @throws InvalidDataTypeException
217
+	 * @throws EE_Error
218
+	 */
219
+	public function sold()
220
+	{
221
+		return $this->get_raw('DTT_sold');
222
+	}
223
+
224
+
225
+	/**
226
+	 * @param int $sold
227
+	 * @throws ReflectionException
228
+	 * @throws InvalidArgumentException
229
+	 * @throws InvalidInterfaceException
230
+	 * @throws InvalidDataTypeException
231
+	 * @throws EE_Error
232
+	 */
233
+	public function set_sold($sold)
234
+	{
235
+		// sold can not go below zero
236
+		$sold = max(0, $sold);
237
+		$this->set('DTT_sold', $sold);
238
+	}
239
+
240
+
241
+	/**
242
+	 * Increments sold by amount passed by $qty, and persists it immediately to the database.
243
+	 * Simultaneously decreases the reserved count, unless $also_decrease_reserved is false.
244
+	 *
245
+	 * @param int $qty
246
+	 * @param boolean $also_decrease_reserved
247
+	 * @return boolean indicating success
248
+	 * @throws ReflectionException
249
+	 * @throws InvalidArgumentException
250
+	 * @throws InvalidInterfaceException
251
+	 * @throws InvalidDataTypeException
252
+	 * @throws EE_Error
253
+	 */
254
+	public function increaseSold($qty = 1, $also_decrease_reserved = true)
255
+	{
256
+		$qty = absint($qty);
257
+		if ($also_decrease_reserved) {
258
+			$success = $this->adjustNumericFieldsInDb(
259
+				[
260
+					'DTT_reserved' => $qty * -1,
261
+					'DTT_sold' => $qty
262
+				]
263
+			);
264
+		} else {
265
+			$success = $this->adjustNumericFieldsInDb(
266
+				[
267
+					'DTT_sold' => $qty
268
+				]
269
+			);
270
+		}
271
+
272
+		do_action(
273
+			'AHEE__EE_Datetime__increase_sold',
274
+			$this,
275
+			$qty,
276
+			$this->sold(),
277
+			$success
278
+		);
279
+		return $success;
280
+	}
281
+
282
+
283
+	/**
284
+	 * Decrements (subtracts) sold amount passed by $qty directly in the DB and on the model object. (Ie, no need
285
+	 * to save afterwards.)
286
+	 *
287
+	 * @param int $qty
288
+	 * @return boolean indicating success
289
+	 * @throws ReflectionException
290
+	 * @throws InvalidArgumentException
291
+	 * @throws InvalidInterfaceException
292
+	 * @throws InvalidDataTypeException
293
+	 * @throws EE_Error
294
+	 */
295
+	public function decreaseSold($qty = 1)
296
+	{
297
+		$qty = absint($qty);
298
+		$success = $this->adjustNumericFieldsInDb(
299
+			[
300
+				'DTT_sold' => $qty * -1
301
+			]
302
+		);
303
+		do_action(
304
+			'AHEE__EE_Datetime__decrease_sold',
305
+			$this,
306
+			$qty,
307
+			$this->sold(),
308
+			$success
309
+		);
310
+		return $success;
311
+	}
312
+
313
+
314
+	/**
315
+	 * Gets qty of reserved tickets for this datetime
316
+	 *
317
+	 * @return int
318
+	 * @throws ReflectionException
319
+	 * @throws InvalidArgumentException
320
+	 * @throws InvalidInterfaceException
321
+	 * @throws InvalidDataTypeException
322
+	 * @throws EE_Error
323
+	 */
324
+	public function reserved()
325
+	{
326
+		return $this->get_raw('DTT_reserved');
327
+	}
328
+
329
+
330
+	/**
331
+	 * Sets qty of reserved tickets for this datetime
332
+	 *
333
+	 * @param int $reserved
334
+	 * @throws ReflectionException
335
+	 * @throws InvalidArgumentException
336
+	 * @throws InvalidInterfaceException
337
+	 * @throws InvalidDataTypeException
338
+	 * @throws EE_Error
339
+	 */
340
+	public function set_reserved($reserved)
341
+	{
342
+		// reserved can not go below zero
343
+		$reserved = max(0, (int) $reserved);
344
+		$this->set('DTT_reserved', $reserved);
345
+	}
346
+
347
+
348
+	/**
349
+	 * Increments reserved by amount passed by $qty, and persists it immediately to the database.
350
+	 *
351
+	 * @param int $qty
352
+	 * @return boolean indicating success
353
+	 * @throws ReflectionException
354
+	 * @throws InvalidArgumentException
355
+	 * @throws InvalidInterfaceException
356
+	 * @throws InvalidDataTypeException
357
+	 * @throws EE_Error
358
+	 */
359
+	public function increaseReserved($qty = 1)
360
+	{
361
+		$qty = absint($qty);
362
+		$success = $this->incrementFieldConditionallyInDb(
363
+			'DTT_reserved',
364
+			'DTT_sold',
365
+			'DTT_reg_limit',
366
+			$qty
367
+		);
368
+		do_action(
369
+			'AHEE__EE_Datetime__increase_reserved',
370
+			$this,
371
+			$qty,
372
+			$this->reserved(),
373
+			$success
374
+		);
375
+		return $success;
376
+	}
377
+
378
+
379
+	/**
380
+	 * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
381
+	 *
382
+	 * @param int $qty
383
+	 * @return boolean indicating success
384
+	 * @throws ReflectionException
385
+	 * @throws InvalidArgumentException
386
+	 * @throws InvalidInterfaceException
387
+	 * @throws InvalidDataTypeException
388
+	 * @throws EE_Error
389
+	 */
390
+	public function decreaseReserved($qty = 1)
391
+	{
392
+		$qty = absint($qty);
393
+		$success = $this->adjustNumericFieldsInDb(
394
+			[
395
+				'DTT_reserved' => $qty * -1
396
+			]
397
+		);
398
+		do_action(
399
+			'AHEE__EE_Datetime__decrease_reserved',
400
+			$this,
401
+			$qty,
402
+			$this->reserved(),
403
+			$success
404
+		);
405
+		return $success;
406
+	}
407
+
408
+
409
+	/**
410
+	 * total sold and reserved tickets
411
+	 *
412
+	 * @return int
413
+	 * @throws ReflectionException
414
+	 * @throws InvalidArgumentException
415
+	 * @throws InvalidInterfaceException
416
+	 * @throws InvalidDataTypeException
417
+	 * @throws EE_Error
418
+	 */
419
+	public function sold_and_reserved()
420
+	{
421
+		return $this->sold() + $this->reserved();
422
+	}
423
+
424
+
425
+	/**
426
+	 * returns the datetime name
427
+	 *
428
+	 * @return string
429
+	 * @throws ReflectionException
430
+	 * @throws InvalidArgumentException
431
+	 * @throws InvalidInterfaceException
432
+	 * @throws InvalidDataTypeException
433
+	 * @throws EE_Error
434
+	 */
435
+	public function name()
436
+	{
437
+		return $this->get('DTT_name');
438
+	}
439
+
440
+
441
+	/**
442
+	 * returns the datetime description
443
+	 *
444
+	 * @return string
445
+	 * @throws ReflectionException
446
+	 * @throws InvalidArgumentException
447
+	 * @throws InvalidInterfaceException
448
+	 * @throws InvalidDataTypeException
449
+	 * @throws EE_Error
450
+	 */
451
+	public function description()
452
+	{
453
+		return $this->get('DTT_description');
454
+	}
455
+
456
+
457
+	/**
458
+	 * This helper simply returns whether the event_datetime for the current datetime is a primary datetime
459
+	 *
460
+	 * @return boolean  TRUE if is primary, FALSE if not.
461
+	 * @throws ReflectionException
462
+	 * @throws InvalidArgumentException
463
+	 * @throws InvalidInterfaceException
464
+	 * @throws InvalidDataTypeException
465
+	 * @throws EE_Error
466
+	 */
467
+	public function is_primary()
468
+	{
469
+		return $this->get('DTT_is_primary');
470
+	}
471
+
472
+
473
+	/**
474
+	 * This helper simply returns the order for the datetime
475
+	 *
476
+	 * @return int  The order of the datetime for this event.
477
+	 * @throws ReflectionException
478
+	 * @throws InvalidArgumentException
479
+	 * @throws InvalidInterfaceException
480
+	 * @throws InvalidDataTypeException
481
+	 * @throws EE_Error
482
+	 */
483
+	public function order()
484
+	{
485
+		return $this->get('DTT_order');
486
+	}
487
+
488
+
489
+	/**
490
+	 * This helper simply returns the parent id for the datetime
491
+	 *
492
+	 * @return int
493
+	 * @throws ReflectionException
494
+	 * @throws InvalidArgumentException
495
+	 * @throws InvalidInterfaceException
496
+	 * @throws InvalidDataTypeException
497
+	 * @throws EE_Error
498
+	 */
499
+	public function parent()
500
+	{
501
+		return $this->get('DTT_parent');
502
+	}
503
+
504
+
505
+	/**
506
+	 * show date and/or time
507
+	 *
508
+	 * @param string $date_or_time    whether to display a date or time or both
509
+	 * @param string $start_or_end    whether to display start or end datetimes
510
+	 * @param string $dt_frmt
511
+	 * @param string $tm_frmt
512
+	 * @param bool   $echo            whether we echo or return (note echoing uses "pretty" formats,
513
+	 *                                otherwise we use the standard formats)
514
+	 * @return string|bool  string on success, FALSE on fail
515
+	 * @throws ReflectionException
516
+	 * @throws InvalidArgumentException
517
+	 * @throws InvalidInterfaceException
518
+	 * @throws InvalidDataTypeException
519
+	 * @throws EE_Error
520
+	 */
521
+	private function _show_datetime(
522
+		$date_or_time = null,
523
+		$start_or_end = 'start',
524
+		$dt_frmt = '',
525
+		$tm_frmt = '',
526
+		$echo = false
527
+	) {
528
+		$field_name = "DTT_EVT_{$start_or_end}";
529
+		$dtt = $this->_get_datetime(
530
+			$field_name,
531
+			$dt_frmt,
532
+			$tm_frmt,
533
+			$date_or_time,
534
+			$echo
535
+		);
536
+		if (! $echo) {
537
+			return $dtt;
538
+		}
539
+		return '';
540
+	}
541
+
542
+
543
+	/**
544
+	 * get event start date.  Provide either the date format, or NULL to re-use the
545
+	 * last-used format, or '' to use the default date format
546
+	 *
547
+	 * @param string $dt_frmt string representation of date format defaults to 'F j, Y'
548
+	 * @return mixed            string on success, FALSE on fail
549
+	 * @throws ReflectionException
550
+	 * @throws InvalidArgumentException
551
+	 * @throws InvalidInterfaceException
552
+	 * @throws InvalidDataTypeException
553
+	 * @throws EE_Error
554
+	 */
555
+	public function start_date($dt_frmt = '')
556
+	{
557
+		return $this->_show_datetime('D', 'start', $dt_frmt);
558
+	}
559
+
560
+
561
+	/**
562
+	 * Echoes start_date()
563
+	 *
564
+	 * @param string $dt_frmt
565
+	 * @throws ReflectionException
566
+	 * @throws InvalidArgumentException
567
+	 * @throws InvalidInterfaceException
568
+	 * @throws InvalidDataTypeException
569
+	 * @throws EE_Error
570
+	 */
571
+	public function e_start_date($dt_frmt = '')
572
+	{
573
+		$this->_show_datetime('D', 'start', $dt_frmt, null, true);
574
+	}
575
+
576
+
577
+	/**
578
+	 * get end date. Provide either the date format, or NULL to re-use the
579
+	 * last-used format, or '' to use the default date format
580
+	 *
581
+	 * @param string $dt_frmt string representation of date format defaults to 'F j, Y'
582
+	 * @return mixed            string on success, FALSE on fail
583
+	 * @throws ReflectionException
584
+	 * @throws InvalidArgumentException
585
+	 * @throws InvalidInterfaceException
586
+	 * @throws InvalidDataTypeException
587
+	 * @throws EE_Error
588
+	 */
589
+	public function end_date($dt_frmt = '')
590
+	{
591
+		return $this->_show_datetime('D', 'end', $dt_frmt);
592
+	}
593
+
594
+
595
+	/**
596
+	 * Echoes the end date. See end_date()
597
+	 *
598
+	 * @param string $dt_frmt
599
+	 * @throws ReflectionException
600
+	 * @throws InvalidArgumentException
601
+	 * @throws InvalidInterfaceException
602
+	 * @throws InvalidDataTypeException
603
+	 * @throws EE_Error
604
+	 */
605
+	public function e_end_date($dt_frmt = '')
606
+	{
607
+		$this->_show_datetime('D', 'end', $dt_frmt, null, true);
608
+	}
609
+
610
+
611
+	/**
612
+	 * get date_range - meaning the start AND end date
613
+	 *
614
+	 * @access public
615
+	 * @param string $dt_frmt     string representation of date format defaults to WP settings
616
+	 * @param string $conjunction conjunction junction what's your function ?
617
+	 *                            this string joins the start date with the end date ie: Jan 01 "to" Dec 31
618
+	 * @return mixed              string on success, FALSE on fail
619
+	 * @throws ReflectionException
620
+	 * @throws InvalidArgumentException
621
+	 * @throws InvalidInterfaceException
622
+	 * @throws InvalidDataTypeException
623
+	 * @throws EE_Error
624
+	 */
625
+	public function date_range($dt_frmt = '', $conjunction = ' - ')
626
+	{
627
+		$dt_frmt = ! empty($dt_frmt) ? $dt_frmt : $this->_dt_frmt;
628
+		$start = str_replace(
629
+			' ',
630
+			'&nbsp;',
631
+			$this->get_i18n_datetime('DTT_EVT_start', $dt_frmt)
632
+		);
633
+		$end = str_replace(
634
+			' ',
635
+			'&nbsp;',
636
+			$this->get_i18n_datetime('DTT_EVT_end', $dt_frmt)
637
+		);
638
+		return $start !== $end ? $start . $conjunction . $end : $start;
639
+	}
640
+
641
+
642
+	/**
643
+	 * @param string $dt_frmt
644
+	 * @param string $conjunction
645
+	 * @throws ReflectionException
646
+	 * @throws InvalidArgumentException
647
+	 * @throws InvalidInterfaceException
648
+	 * @throws InvalidDataTypeException
649
+	 * @throws EE_Error
650
+	 */
651
+	public function e_date_range($dt_frmt = '', $conjunction = ' - ')
652
+	{
653
+		echo $this->date_range($dt_frmt, $conjunction);
654
+	}
655
+
656
+
657
+	/**
658
+	 * get start time
659
+	 *
660
+	 * @param string $tm_format - string representation of time format defaults to 'g:i a'
661
+	 * @return mixed        string on success, FALSE on fail
662
+	 * @throws ReflectionException
663
+	 * @throws InvalidArgumentException
664
+	 * @throws InvalidInterfaceException
665
+	 * @throws InvalidDataTypeException
666
+	 * @throws EE_Error
667
+	 */
668
+	public function start_time($tm_format = '')
669
+	{
670
+		return $this->_show_datetime('T', 'start', null, $tm_format);
671
+	}
672
+
673
+
674
+	/**
675
+	 * @param string $tm_format
676
+	 * @throws ReflectionException
677
+	 * @throws InvalidArgumentException
678
+	 * @throws InvalidInterfaceException
679
+	 * @throws InvalidDataTypeException
680
+	 * @throws EE_Error
681
+	 */
682
+	public function e_start_time($tm_format = '')
683
+	{
684
+		$this->_show_datetime('T', 'start', null, $tm_format, true);
685
+	}
686
+
687
+
688
+	/**
689
+	 * get end time
690
+	 *
691
+	 * @param string $tm_format string representation of time format defaults to 'g:i a'
692
+	 * @return mixed                string on success, FALSE on fail
693
+	 * @throws ReflectionException
694
+	 * @throws InvalidArgumentException
695
+	 * @throws InvalidInterfaceException
696
+	 * @throws InvalidDataTypeException
697
+	 * @throws EE_Error
698
+	 */
699
+	public function end_time($tm_format = '')
700
+	{
701
+		return $this->_show_datetime('T', 'end', null, $tm_format);
702
+	}
703
+
704
+
705
+	/**
706
+	 * @param string $tm_format
707
+	 * @throws ReflectionException
708
+	 * @throws InvalidArgumentException
709
+	 * @throws InvalidInterfaceException
710
+	 * @throws InvalidDataTypeException
711
+	 * @throws EE_Error
712
+	 */
713
+	public function e_end_time($tm_format = '')
714
+	{
715
+		$this->_show_datetime('T', 'end', null, $tm_format, true);
716
+	}
717
+
718
+
719
+	/**
720
+	 * get time_range
721
+	 *
722
+	 * @access public
723
+	 * @param string $tm_format   string representation of time format defaults to 'g:i a'
724
+	 * @param string $conjunction conjunction junction what's your function ?
725
+	 *                            this string joins the start date with the end date ie: Jan 01 "to" Dec 31
726
+	 * @return mixed              string on success, FALSE on fail
727
+	 * @throws ReflectionException
728
+	 * @throws InvalidArgumentException
729
+	 * @throws InvalidInterfaceException
730
+	 * @throws InvalidDataTypeException
731
+	 * @throws EE_Error
732
+	 */
733
+	public function time_range($tm_format = '', $conjunction = ' - ')
734
+	{
735
+		$tm_format = ! empty($tm_format) ? $tm_format : $this->_tm_frmt;
736
+		$start = str_replace(
737
+			' ',
738
+			'&nbsp;',
739
+			$this->get_i18n_datetime('DTT_EVT_start', $tm_format)
740
+		);
741
+		$end = str_replace(
742
+			' ',
743
+			'&nbsp;',
744
+			$this->get_i18n_datetime('DTT_EVT_end', $tm_format)
745
+		);
746
+		return $start !== $end ? $start . $conjunction . $end : $start;
747
+	}
748
+
749
+
750
+	/**
751
+	 * @param string $tm_format
752
+	 * @param string $conjunction
753
+	 * @throws ReflectionException
754
+	 * @throws InvalidArgumentException
755
+	 * @throws InvalidInterfaceException
756
+	 * @throws InvalidDataTypeException
757
+	 * @throws EE_Error
758
+	 */
759
+	public function e_time_range($tm_format = '', $conjunction = ' - ')
760
+	{
761
+		echo $this->time_range($tm_format, $conjunction);
762
+	}
763
+
764
+
765
+	/**
766
+	 * This returns a range representation of the date and times.
767
+	 * Output is dependent on the difference (or similarity) between DTT_EVT_start and DTT_EVT_end.
768
+	 * Also, the return value is localized.
769
+	 *
770
+	 * @param string $dt_format
771
+	 * @param string $tm_format
772
+	 * @param string $conjunction used between two different dates or times.
773
+	 *                            ex: Dec 1{$conjunction}}Dec 6, or 2pm{$conjunction}3pm
774
+	 * @param string $separator   used between the date and time formats.
775
+	 *                            ex: Dec 1, 2016{$separator}2pm
776
+	 * @return string
777
+	 * @throws ReflectionException
778
+	 * @throws InvalidArgumentException
779
+	 * @throws InvalidInterfaceException
780
+	 * @throws InvalidDataTypeException
781
+	 * @throws EE_Error
782
+	 */
783
+	public function date_and_time_range(
784
+		$dt_format = '',
785
+		$tm_format = '',
786
+		$conjunction = ' - ',
787
+		$separator = ' '
788
+	) {
789
+		$dt_format = ! empty($dt_format) ? $dt_format : $this->_dt_frmt;
790
+		$tm_format = ! empty($tm_format) ? $tm_format : $this->_tm_frmt;
791
+		$full_format = $dt_format . $separator . $tm_format;
792
+		// the range output depends on various conditions
793
+		switch (true) {
794
+			// start date timestamp and end date timestamp are the same.
795
+			case ($this->get_raw('DTT_EVT_start') === $this->get_raw('DTT_EVT_end')):
796
+				$output = $this->get_i18n_datetime('DTT_EVT_start', $full_format);
797
+				break;
798
+			// start and end date are the same but times are different
799
+			case ($this->start_date() === $this->end_date()):
800
+				$output = $this->get_i18n_datetime('DTT_EVT_start', $full_format)
801
+						  . $conjunction
802
+						  . $this->get_i18n_datetime('DTT_EVT_end', $tm_format);
803
+				break;
804
+			// all other conditions
805
+			default:
806
+				$output = $this->get_i18n_datetime('DTT_EVT_start', $full_format)
807
+						  . $conjunction
808
+						  . $this->get_i18n_datetime('DTT_EVT_end', $full_format);
809
+				break;
810
+		}
811
+		return $output;
812
+	}
813
+
814
+
815
+	/**
816
+	 * This echos the results of date and time range.
817
+	 *
818
+	 * @see date_and_time_range() for more details on purpose.
819
+	 * @param string $dt_format
820
+	 * @param string $tm_format
821
+	 * @param string $conjunction
822
+	 * @return void
823
+	 * @throws ReflectionException
824
+	 * @throws InvalidArgumentException
825
+	 * @throws InvalidInterfaceException
826
+	 * @throws InvalidDataTypeException
827
+	 * @throws EE_Error
828
+	 */
829
+	public function e_date_and_time_range($dt_format = '', $tm_format = '', $conjunction = ' - ')
830
+	{
831
+		echo $this->date_and_time_range($dt_format, $tm_format, $conjunction);
832
+	}
833
+
834
+
835
+	/**
836
+	 * get start date and start time
837
+	 *
838
+	 * @param    string $dt_format - string representation of date format defaults to 'F j, Y'
839
+	 * @param    string $tm_format - string representation of time format defaults to 'g:i a'
840
+	 * @return    mixed    string on success, FALSE on fail
841
+	 * @throws ReflectionException
842
+	 * @throws InvalidArgumentException
843
+	 * @throws InvalidInterfaceException
844
+	 * @throws InvalidDataTypeException
845
+	 * @throws EE_Error
846
+	 */
847
+	public function start_date_and_time($dt_format = '', $tm_format = '')
848
+	{
849
+		return $this->_show_datetime('', 'start', $dt_format, $tm_format);
850
+	}
851
+
852
+
853
+	/**
854
+	 * @param string $dt_frmt
855
+	 * @param string $tm_format
856
+	 * @throws ReflectionException
857
+	 * @throws InvalidArgumentException
858
+	 * @throws InvalidInterfaceException
859
+	 * @throws InvalidDataTypeException
860
+	 * @throws EE_Error
861
+	 */
862
+	public function e_start_date_and_time($dt_frmt = '', $tm_format = '')
863
+	{
864
+		$this->_show_datetime('', 'start', $dt_frmt, $tm_format, true);
865
+	}
866
+
867
+
868
+	/**
869
+	 * Shows the length of the event (start to end time).
870
+	 * Can be shown in 'seconds','minutes','hours', or 'days'.
871
+	 * By default, rounds up. (So if you use 'days', and then event
872
+	 * only occurs for 1 hour, it will return 1 day).
873
+	 *
874
+	 * @param string $units 'seconds','minutes','hours','days'
875
+	 * @param bool   $round_up
876
+	 * @return float|int|mixed
877
+	 * @throws ReflectionException
878
+	 * @throws InvalidArgumentException
879
+	 * @throws InvalidInterfaceException
880
+	 * @throws InvalidDataTypeException
881
+	 * @throws EE_Error
882
+	 */
883
+	public function length($units = 'seconds', $round_up = false)
884
+	{
885
+		$start = $this->get_raw('DTT_EVT_start');
886
+		$end = $this->get_raw('DTT_EVT_end');
887
+		$length_in_units = $end - $start;
888
+		switch ($units) {
889
+			// NOTE: We purposefully don't use "break;" in order to chain the divisions
890
+			/** @noinspection PhpMissingBreakStatementInspection */
891
+			// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
892
+			case 'days':
893
+				$length_in_units /= 24;
894
+			/** @noinspection PhpMissingBreakStatementInspection */
895
+			case 'hours':
896
+				// fall through is intentional
897
+				$length_in_units /= 60;
898
+			/** @noinspection PhpMissingBreakStatementInspection */
899
+			case 'minutes':
900
+				// fall through is intentional
901
+				$length_in_units /= 60;
902
+			case 'seconds':
903
+			default:
904
+				$length_in_units = ceil($length_in_units);
905
+		}
906
+		// phpcs:enable
907
+		if ($round_up) {
908
+			$length_in_units = max($length_in_units, 1);
909
+		}
910
+		return $length_in_units;
911
+	}
912
+
913
+
914
+	/**
915
+	 *        get end date and time
916
+	 *
917
+	 * @param string $dt_frmt   - string representation of date format defaults to 'F j, Y'
918
+	 * @param string $tm_format - string representation of time format defaults to 'g:i a'
919
+	 * @return    mixed                string on success, FALSE on fail
920
+	 * @throws ReflectionException
921
+	 * @throws InvalidArgumentException
922
+	 * @throws InvalidInterfaceException
923
+	 * @throws InvalidDataTypeException
924
+	 * @throws EE_Error
925
+	 */
926
+	public function end_date_and_time($dt_frmt = '', $tm_format = '')
927
+	{
928
+		return $this->_show_datetime('', 'end', $dt_frmt, $tm_format);
929
+	}
930
+
931
+
932
+	/**
933
+	 * @param string $dt_frmt
934
+	 * @param string $tm_format
935
+	 * @throws ReflectionException
936
+	 * @throws InvalidArgumentException
937
+	 * @throws InvalidInterfaceException
938
+	 * @throws InvalidDataTypeException
939
+	 * @throws EE_Error
940
+	 */
941
+	public function e_end_date_and_time($dt_frmt = '', $tm_format = '')
942
+	{
943
+		$this->_show_datetime('', 'end', $dt_frmt, $tm_format, true);
944
+	}
945
+
946
+
947
+	/**
948
+	 *        get start timestamp
949
+	 *
950
+	 * @return        int
951
+	 * @throws ReflectionException
952
+	 * @throws InvalidArgumentException
953
+	 * @throws InvalidInterfaceException
954
+	 * @throws InvalidDataTypeException
955
+	 * @throws EE_Error
956
+	 */
957
+	public function start()
958
+	{
959
+		return $this->get_raw('DTT_EVT_start');
960
+	}
961
+
962
+
963
+	/**
964
+	 *        get end timestamp
965
+	 *
966
+	 * @return        int
967
+	 * @throws ReflectionException
968
+	 * @throws InvalidArgumentException
969
+	 * @throws InvalidInterfaceException
970
+	 * @throws InvalidDataTypeException
971
+	 * @throws EE_Error
972
+	 */
973
+	public function end()
974
+	{
975
+		return $this->get_raw('DTT_EVT_end');
976
+	}
977
+
978
+
979
+	/**
980
+	 *    get the registration limit for this datetime slot
981
+	 *
982
+	 * @return        mixed        int on success, FALSE on fail
983
+	 * @throws ReflectionException
984
+	 * @throws InvalidArgumentException
985
+	 * @throws InvalidInterfaceException
986
+	 * @throws InvalidDataTypeException
987
+	 * @throws EE_Error
988
+	 */
989
+	public function reg_limit()
990
+	{
991
+		return $this->get_raw('DTT_reg_limit');
992
+	}
993
+
994
+
995
+	/**
996
+	 *    have the tickets sold for this datetime, met or exceed the registration limit ?
997
+	 *
998
+	 * @return        boolean
999
+	 * @throws ReflectionException
1000
+	 * @throws InvalidArgumentException
1001
+	 * @throws InvalidInterfaceException
1002
+	 * @throws InvalidDataTypeException
1003
+	 * @throws EE_Error
1004
+	 */
1005
+	public function sold_out()
1006
+	{
1007
+		return $this->reg_limit() > 0 && $this->sold() >= $this->reg_limit();
1008
+	}
1009
+
1010
+
1011
+	/**
1012
+	 * return the total number of spaces remaining at this venue.
1013
+	 * This only takes the venue's capacity into account, NOT the tickets available for sale
1014
+	 *
1015
+	 * @param bool $consider_tickets Whether to consider tickets remaining when determining if there are any spaces left
1016
+	 *                               Because if all tickets attached to this datetime have no spaces left,
1017
+	 *                               then this datetime IS effectively sold out.
1018
+	 *                               However, there are cases where we just want to know the spaces
1019
+	 *                               remaining for this particular datetime, hence the flag.
1020
+	 * @return int
1021
+	 * @throws ReflectionException
1022
+	 * @throws InvalidArgumentException
1023
+	 * @throws InvalidInterfaceException
1024
+	 * @throws InvalidDataTypeException
1025
+	 * @throws EE_Error
1026
+	 */
1027
+	public function spaces_remaining($consider_tickets = false)
1028
+	{
1029
+		// tickets remaining available for purchase
1030
+		// no need for special checks for infinite, because if DTT_reg_limit == EE_INF, then EE_INF - x = EE_INF
1031
+		$dtt_remaining = $this->reg_limit() - $this->sold_and_reserved();
1032
+		if (! $consider_tickets) {
1033
+			return $dtt_remaining;
1034
+		}
1035
+		$tickets_remaining = $this->tickets_remaining();
1036
+		return min($dtt_remaining, $tickets_remaining);
1037
+	}
1038
+
1039
+
1040
+	/**
1041
+	 * Counts the total tickets available
1042
+	 * (from all the different types of tickets which are available for this datetime).
1043
+	 *
1044
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1045
+	 * @return int
1046
+	 * @throws ReflectionException
1047
+	 * @throws InvalidArgumentException
1048
+	 * @throws InvalidInterfaceException
1049
+	 * @throws InvalidDataTypeException
1050
+	 * @throws EE_Error
1051
+	 */
1052
+	public function tickets_remaining($query_params = array())
1053
+	{
1054
+		$sum = 0;
1055
+		$tickets = $this->tickets($query_params);
1056
+		if (! empty($tickets)) {
1057
+			foreach ($tickets as $ticket) {
1058
+				if ($ticket instanceof EE_Ticket) {
1059
+					// get the actual amount of tickets that can be sold
1060
+					$qty = $ticket->qty('saleable');
1061
+					if ($qty === EE_INF) {
1062
+						return EE_INF;
1063
+					}
1064
+					// no negative ticket quantities plz
1065
+					if ($qty > 0) {
1066
+						$sum += $qty;
1067
+					}
1068
+				}
1069
+			}
1070
+		}
1071
+		return $sum;
1072
+	}
1073
+
1074
+
1075
+	/**
1076
+	 * Gets the count of all the tickets available at this datetime (not ticket types)
1077
+	 * before any were sold
1078
+	 *
1079
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1080
+	 * @return int
1081
+	 * @throws ReflectionException
1082
+	 * @throws InvalidArgumentException
1083
+	 * @throws InvalidInterfaceException
1084
+	 * @throws InvalidDataTypeException
1085
+	 * @throws EE_Error
1086
+	 */
1087
+	public function sum_tickets_initially_available($query_params = array())
1088
+	{
1089
+		return $this->sum_related('Ticket', $query_params, 'TKT_qty');
1090
+	}
1091
+
1092
+
1093
+	/**
1094
+	 * Returns the lesser-of-the two: spaces remaining at this datetime, or
1095
+	 * the total tickets remaining (a sum of the tickets remaining for each ticket type
1096
+	 * that is available for this datetime).
1097
+	 *
1098
+	 * @return int
1099
+	 * @throws ReflectionException
1100
+	 * @throws InvalidArgumentException
1101
+	 * @throws InvalidInterfaceException
1102
+	 * @throws InvalidDataTypeException
1103
+	 * @throws EE_Error
1104
+	 */
1105
+	public function total_tickets_available_at_this_datetime()
1106
+	{
1107
+		return $this->spaces_remaining(true);
1108
+	}
1109
+
1110
+
1111
+	/**
1112
+	 * This simply compares the internal dtt for the given string with NOW
1113
+	 * and determines if the date is upcoming or not.
1114
+	 *
1115
+	 * @access public
1116
+	 * @return boolean
1117
+	 * @throws ReflectionException
1118
+	 * @throws InvalidArgumentException
1119
+	 * @throws InvalidInterfaceException
1120
+	 * @throws InvalidDataTypeException
1121
+	 * @throws EE_Error
1122
+	 */
1123
+	public function is_upcoming()
1124
+	{
1125
+		return ($this->get_raw('DTT_EVT_start') > time());
1126
+	}
1127
+
1128
+
1129
+	/**
1130
+	 * This simply compares the internal datetime for the given string with NOW
1131
+	 * and returns if the date is active (i.e. start and end time)
1132
+	 *
1133
+	 * @return boolean
1134
+	 * @throws ReflectionException
1135
+	 * @throws InvalidArgumentException
1136
+	 * @throws InvalidInterfaceException
1137
+	 * @throws InvalidDataTypeException
1138
+	 * @throws EE_Error
1139
+	 */
1140
+	public function is_active()
1141
+	{
1142
+		return ($this->get_raw('DTT_EVT_start') < time() && $this->get_raw('DTT_EVT_end') > time());
1143
+	}
1144
+
1145
+
1146
+	/**
1147
+	 * This simply compares the internal dtt for the given string with NOW
1148
+	 * and determines if the date is expired or not.
1149
+	 *
1150
+	 * @return boolean
1151
+	 * @throws ReflectionException
1152
+	 * @throws InvalidArgumentException
1153
+	 * @throws InvalidInterfaceException
1154
+	 * @throws InvalidDataTypeException
1155
+	 * @throws EE_Error
1156
+	 */
1157
+	public function is_expired()
1158
+	{
1159
+		return ($this->get_raw('DTT_EVT_end') < time());
1160
+	}
1161
+
1162
+
1163
+	/**
1164
+	 * This returns the active status for whether an event is active, upcoming, or expired
1165
+	 *
1166
+	 * @return int return value will be one of the EE_Datetime status constants.
1167
+	 * @throws ReflectionException
1168
+	 * @throws InvalidArgumentException
1169
+	 * @throws InvalidInterfaceException
1170
+	 * @throws InvalidDataTypeException
1171
+	 * @throws EE_Error
1172
+	 */
1173
+	public function get_active_status()
1174
+	{
1175
+		$total_tickets_for_this_dtt = $this->total_tickets_available_at_this_datetime();
1176
+		if ($total_tickets_for_this_dtt !== false && $total_tickets_for_this_dtt < 1) {
1177
+			return EE_Datetime::sold_out;
1178
+		}
1179
+		if ($this->is_expired()) {
1180
+			return EE_Datetime::expired;
1181
+		}
1182
+		if ($this->is_upcoming()) {
1183
+			return EE_Datetime::upcoming;
1184
+		}
1185
+		if ($this->is_active()) {
1186
+			return EE_Datetime::active;
1187
+		}
1188
+		return null;
1189
+	}
1190
+
1191
+
1192
+	/**
1193
+	 * This returns a nice display name for the datetime that is contingent on the span between the dates and times.
1194
+	 *
1195
+	 * @param  boolean $use_dtt_name if TRUE then we'll use DTT->name() if its not empty.
1196
+	 * @return string
1197
+	 * @throws ReflectionException
1198
+	 * @throws InvalidArgumentException
1199
+	 * @throws InvalidInterfaceException
1200
+	 * @throws InvalidDataTypeException
1201
+	 * @throws EE_Error
1202
+	 */
1203
+	public function get_dtt_display_name($use_dtt_name = false)
1204
+	{
1205
+		if ($use_dtt_name) {
1206
+			$dtt_name = $this->name();
1207
+			if (! empty($dtt_name)) {
1208
+				return $dtt_name;
1209
+			}
1210
+		}
1211
+		// first condition is to see if the months are different
1212
+		if (date('m', $this->get_raw('DTT_EVT_start')) !== date('m', $this->get_raw('DTT_EVT_end'))
1213
+		) {
1214
+			$display_date = $this->start_date('M j\, Y g:i a') . ' - ' . $this->end_date('M j\, Y g:i a');
1215
+			// next condition is if its the same month but different day
1216
+		} else {
1217
+			if (date('m', $this->get_raw('DTT_EVT_start')) === date('m', $this->get_raw('DTT_EVT_end'))
1218
+				&& date('d', $this->get_raw('DTT_EVT_start')) !== date('d', $this->get_raw('DTT_EVT_end'))
1219
+			) {
1220
+				$display_date = $this->start_date('M j\, g:i a') . ' - ' . $this->end_date('M j\, g:i a Y');
1221
+			} else {
1222
+				$display_date = $this->start_date('F j\, Y')
1223
+								. ' @ '
1224
+								. $this->start_date('g:i a')
1225
+								. ' - '
1226
+								. $this->end_date('g:i a');
1227
+			}
1228
+		}
1229
+		return $display_date;
1230
+	}
1231
+
1232
+
1233
+	/**
1234
+	 * Gets all the tickets for this datetime
1235
+	 *
1236
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1237
+	 * @return EE_Base_Class[]|EE_Ticket[]
1238
+	 * @throws ReflectionException
1239
+	 * @throws InvalidArgumentException
1240
+	 * @throws InvalidInterfaceException
1241
+	 * @throws InvalidDataTypeException
1242
+	 * @throws EE_Error
1243
+	 */
1244
+	public function tickets($query_params = array())
1245
+	{
1246
+		return $this->get_many_related('Ticket', $query_params);
1247
+	}
1248
+
1249
+
1250
+	/**
1251
+	 * Gets all the ticket types currently available for purchase
1252
+	 *
1253
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1254
+	 * @return EE_Ticket[]
1255
+	 * @throws ReflectionException
1256
+	 * @throws InvalidArgumentException
1257
+	 * @throws InvalidInterfaceException
1258
+	 * @throws InvalidDataTypeException
1259
+	 * @throws EE_Error
1260
+	 */
1261
+	public function ticket_types_available_for_purchase($query_params = array())
1262
+	{
1263
+		// first check if datetime is valid
1264
+		if ($this->sold_out() || ! ($this->is_upcoming() || $this->is_active())) {
1265
+			return array();
1266
+		}
1267
+		if (empty($query_params)) {
1268
+			$query_params = array(
1269
+				array(
1270
+					'TKT_start_date' => array('<=', EEM_Ticket::instance()->current_time_for_query('TKT_start_date')),
1271
+					'TKT_end_date'   => array('>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')),
1272
+					'TKT_deleted'    => false,
1273
+				),
1274
+			);
1275
+		}
1276
+		return $this->tickets($query_params);
1277
+	}
1278
+
1279
+
1280
+	/**
1281
+	 * @return EE_Base_Class|EE_Event
1282
+	 * @throws ReflectionException
1283
+	 * @throws InvalidArgumentException
1284
+	 * @throws InvalidInterfaceException
1285
+	 * @throws InvalidDataTypeException
1286
+	 * @throws EE_Error
1287
+	 */
1288
+	public function event()
1289
+	{
1290
+		return $this->get_first_related('Event');
1291
+	}
1292
+
1293
+
1294
+	/**
1295
+	 * Updates the DTT_sold attribute (and saves) based on the number of registrations for this datetime
1296
+	 * (via the tickets).
1297
+	 *
1298
+	 * @return int
1299
+	 * @throws ReflectionException
1300
+	 * @throws InvalidArgumentException
1301
+	 * @throws InvalidInterfaceException
1302
+	 * @throws InvalidDataTypeException
1303
+	 * @throws EE_Error
1304
+	 */
1305
+	public function update_sold()
1306
+	{
1307
+		$count_regs_for_this_datetime = EEM_Registration::instance()->count(
1308
+			array(
1309
+				array(
1310
+					'STS_ID'                 => EEM_Registration::status_id_approved,
1311
+					'REG_deleted'            => 0,
1312
+					'Ticket.Datetime.DTT_ID' => $this->ID(),
1313
+				),
1314
+			)
1315
+		);
1316
+		$this->set_sold($count_regs_for_this_datetime);
1317
+		$this->save();
1318
+		return $count_regs_for_this_datetime;
1319
+	}
1320
+
1321
+
1322
+	/*******************************************************************
1323 1323
      ***********************  DEPRECATED METHODS  **********************
1324 1324
      *******************************************************************/
1325 1325
 
1326 1326
 
1327
-    /**
1328
-     * Increments sold by amount passed by $qty, and persists it immediately to the database.
1329
-     *
1330
-     * @deprecated 4.9.80.p
1331
-     * @param int $qty
1332
-     * @return boolean
1333
-     * @throws ReflectionException
1334
-     * @throws InvalidArgumentException
1335
-     * @throws InvalidInterfaceException
1336
-     * @throws InvalidDataTypeException
1337
-     * @throws EE_Error
1338
-     */
1339
-    public function increase_sold($qty = 1)
1340
-    {
1341
-        EE_Error::doing_it_wrong(
1342
-            __FUNCTION__,
1343
-            esc_html__('Please use EE_Datetime::increaseSold() instead', 'event_espresso'),
1344
-            '4.9.80.p',
1345
-            '5.0.0.p'
1346
-        );
1347
-        return $this->increaseSold($qty);
1348
-    }
1349
-
1350
-
1351
-    /**
1352
-     * Decrements (subtracts) sold amount passed by $qty directly in the DB and on the model object. (Ie, no need
1353
-     * to save afterwards.)
1354
-     *
1355
-     * @deprecated 4.9.80.p
1356
-     * @param int $qty
1357
-     * @return boolean
1358
-     * @throws ReflectionException
1359
-     * @throws InvalidArgumentException
1360
-     * @throws InvalidInterfaceException
1361
-     * @throws InvalidDataTypeException
1362
-     * @throws EE_Error
1363
-     */
1364
-    public function decrease_sold($qty = 1)
1365
-    {
1366
-        EE_Error::doing_it_wrong(
1367
-            __FUNCTION__,
1368
-            esc_html__('Please use EE_Datetime::decreaseSold() instead', 'event_espresso'),
1369
-            '4.9.80.p',
1370
-            '5.0.0.p'
1371
-        );
1372
-        return $this->decreaseSold($qty);
1373
-    }
1374
-
1375
-
1376
-    /**
1377
-     * Increments reserved by amount passed by $qty, and persists it immediately to the database.
1378
-     *
1379
-     * @deprecated 4.9.80.p
1380
-     * @param int $qty
1381
-     * @return boolean indicating success
1382
-     * @throws ReflectionException
1383
-     * @throws InvalidArgumentException
1384
-     * @throws InvalidInterfaceException
1385
-     * @throws InvalidDataTypeException
1386
-     * @throws EE_Error
1387
-     */
1388
-    public function increase_reserved($qty = 1)
1389
-    {
1390
-        EE_Error::doing_it_wrong(
1391
-            __FUNCTION__,
1392
-            esc_html__('Please use EE_Datetime::increaseReserved() instead', 'event_espresso'),
1393
-            '4.9.80.p',
1394
-            '5.0.0.p'
1395
-        );
1396
-        return $this->increaseReserved($qty);
1397
-    }
1398
-
1399
-
1400
-    /**
1401
-     * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
1402
-     *
1403
-     * @deprecated 4.9.80.p
1404
-     * @param int $qty
1405
-     * @return boolean
1406
-     * @throws ReflectionException
1407
-     * @throws InvalidArgumentException
1408
-     * @throws InvalidInterfaceException
1409
-     * @throws InvalidDataTypeException
1410
-     * @throws EE_Error
1411
-     */
1412
-    public function decrease_reserved($qty = 1)
1413
-    {
1414
-        EE_Error::doing_it_wrong(
1415
-            __FUNCTION__,
1416
-            esc_html__('Please use EE_Datetime::decreaseReserved() instead', 'event_espresso'),
1417
-            '4.9.80.p',
1418
-            '5.0.0.p'
1419
-        );
1420
-        return $this->decreaseReserved($qty);
1421
-    }
1327
+	/**
1328
+	 * Increments sold by amount passed by $qty, and persists it immediately to the database.
1329
+	 *
1330
+	 * @deprecated 4.9.80.p
1331
+	 * @param int $qty
1332
+	 * @return boolean
1333
+	 * @throws ReflectionException
1334
+	 * @throws InvalidArgumentException
1335
+	 * @throws InvalidInterfaceException
1336
+	 * @throws InvalidDataTypeException
1337
+	 * @throws EE_Error
1338
+	 */
1339
+	public function increase_sold($qty = 1)
1340
+	{
1341
+		EE_Error::doing_it_wrong(
1342
+			__FUNCTION__,
1343
+			esc_html__('Please use EE_Datetime::increaseSold() instead', 'event_espresso'),
1344
+			'4.9.80.p',
1345
+			'5.0.0.p'
1346
+		);
1347
+		return $this->increaseSold($qty);
1348
+	}
1349
+
1350
+
1351
+	/**
1352
+	 * Decrements (subtracts) sold amount passed by $qty directly in the DB and on the model object. (Ie, no need
1353
+	 * to save afterwards.)
1354
+	 *
1355
+	 * @deprecated 4.9.80.p
1356
+	 * @param int $qty
1357
+	 * @return boolean
1358
+	 * @throws ReflectionException
1359
+	 * @throws InvalidArgumentException
1360
+	 * @throws InvalidInterfaceException
1361
+	 * @throws InvalidDataTypeException
1362
+	 * @throws EE_Error
1363
+	 */
1364
+	public function decrease_sold($qty = 1)
1365
+	{
1366
+		EE_Error::doing_it_wrong(
1367
+			__FUNCTION__,
1368
+			esc_html__('Please use EE_Datetime::decreaseSold() instead', 'event_espresso'),
1369
+			'4.9.80.p',
1370
+			'5.0.0.p'
1371
+		);
1372
+		return $this->decreaseSold($qty);
1373
+	}
1374
+
1375
+
1376
+	/**
1377
+	 * Increments reserved by amount passed by $qty, and persists it immediately to the database.
1378
+	 *
1379
+	 * @deprecated 4.9.80.p
1380
+	 * @param int $qty
1381
+	 * @return boolean indicating success
1382
+	 * @throws ReflectionException
1383
+	 * @throws InvalidArgumentException
1384
+	 * @throws InvalidInterfaceException
1385
+	 * @throws InvalidDataTypeException
1386
+	 * @throws EE_Error
1387
+	 */
1388
+	public function increase_reserved($qty = 1)
1389
+	{
1390
+		EE_Error::doing_it_wrong(
1391
+			__FUNCTION__,
1392
+			esc_html__('Please use EE_Datetime::increaseReserved() instead', 'event_espresso'),
1393
+			'4.9.80.p',
1394
+			'5.0.0.p'
1395
+		);
1396
+		return $this->increaseReserved($qty);
1397
+	}
1398
+
1399
+
1400
+	/**
1401
+	 * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
1402
+	 *
1403
+	 * @deprecated 4.9.80.p
1404
+	 * @param int $qty
1405
+	 * @return boolean
1406
+	 * @throws ReflectionException
1407
+	 * @throws InvalidArgumentException
1408
+	 * @throws InvalidInterfaceException
1409
+	 * @throws InvalidDataTypeException
1410
+	 * @throws EE_Error
1411
+	 */
1412
+	public function decrease_reserved($qty = 1)
1413
+	{
1414
+		EE_Error::doing_it_wrong(
1415
+			__FUNCTION__,
1416
+			esc_html__('Please use EE_Datetime::decreaseReserved() instead', 'event_espresso'),
1417
+			'4.9.80.p',
1418
+			'5.0.0.p'
1419
+		);
1420
+		return $this->decreaseReserved($qty);
1421
+	}
1422 1422
 }
Please login to merge, or discard this patch.
core/services/commands/CommandHandlerInterface.php 1 patch
Indentation   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -8,24 +8,24 @@
 block discarded – undo
8 8
  */
9 9
 interface CommandHandlerInterface
10 10
 {
11
-    /**
12
-     * verifies that the supplied command is the correct class for the handler.
13
-     *
14
-     * !!! IMPORTANT !!!
15
-     * Must return $this (ie: the handler itself)
16
-     * as the CommandBus utilizes method chaining
17
-     *
18
-     * @param CommandInterface $command
19
-     * @return CommandHandlerInterface
20
-     * @since 4.9.80.p
21
-     */
22
-    public function verify(CommandInterface $command);
11
+	/**
12
+	 * verifies that the supplied command is the correct class for the handler.
13
+	 *
14
+	 * !!! IMPORTANT !!!
15
+	 * Must return $this (ie: the handler itself)
16
+	 * as the CommandBus utilizes method chaining
17
+	 *
18
+	 * @param CommandInterface $command
19
+	 * @return CommandHandlerInterface
20
+	 * @since 4.9.80.p
21
+	 */
22
+	public function verify(CommandInterface $command);
23 23
 
24
-    /**
25
-     * Performs the command handler's logic.
26
-     *
27
-     * @param CommandInterface $command
28
-     * @return mixed
29
-     */
30
-    public function handle(CommandInterface $command);
24
+	/**
25
+	 * Performs the command handler's logic.
26
+	 *
27
+	 * @param CommandInterface $command
28
+	 * @return mixed
29
+	 */
30
+	public function handle(CommandInterface $command);
31 31
 }
Please login to merge, or discard this patch.