Completed
Branch BUG-10972-prefix-clearfix (829fe7)
by
unknown
21:57 queued 10:57
created
core/libraries/rest_api/controllers/model/Meta.php 1 patch
Indentation   +110 added lines, -110 removed lines patch added patch discarded remove patch
@@ -11,7 +11,7 @@  discard block
 block discarded – undo
11 11
 use EventEspresso\core\libraries\rest_api\ModelDataTranslator;
12 12
 
13 13
 if (! defined('EVENT_ESPRESSO_VERSION')) {
14
-    exit('No direct script access allowed');
14
+	exit('No direct script access allowed');
15 15
 }
16 16
 
17 17
 
@@ -28,124 +28,124 @@  discard block
 block discarded – undo
28 28
 {
29 29
 
30 30
 
31
-    /**
32
-     * @param \WP_REST_Request $request
33
-     * @param string           $version
34
-     * @return array|\WP_REST_Response
35
-     */
36
-    public static function handleRequestModelsMeta(\WP_REST_Request $request, $version)
37
-    {
38
-        $controller = new Meta();
39
-        try {
40
-            $controller->setRequestedVersion($version);
41
-            return $controller->sendResponse($controller->getModelsMetadataEntity());
42
-        } catch (Exception $e) {
43
-            return $controller->sendResponse($e);
44
-        }
45
-    }
31
+	/**
32
+	 * @param \WP_REST_Request $request
33
+	 * @param string           $version
34
+	 * @return array|\WP_REST_Response
35
+	 */
36
+	public static function handleRequestModelsMeta(\WP_REST_Request $request, $version)
37
+	{
38
+		$controller = new Meta();
39
+		try {
40
+			$controller->setRequestedVersion($version);
41
+			return $controller->sendResponse($controller->getModelsMetadataEntity());
42
+		} catch (Exception $e) {
43
+			return $controller->sendResponse($e);
44
+		}
45
+	}
46 46
 
47 47
 
48 48
 
49
-    /*
49
+	/*
50 50
      * Gets the model metadata resource entity
51 51
      * @return array for JSON response, describing all the models available in teh requested version
52 52
      */
53
-    protected function getModelsMetadataEntity()
54
-    {
55
-        $response = array();
56
-        foreach ($this->getModelVersionInfo()->modelsForRequestedVersion() as $model_name => $model_classname) {
57
-            $model = $this->getModelVersionInfo()->loadModel($model_name);
58
-            $fields_json = array();
59
-            foreach ($this->getModelVersionInfo()->fieldsOnModelInThisVersion($model) as $field_name => $field_obj) {
60
-                if ($this->getModelVersionInfo()->fieldIsIgnored($field_obj)) {
61
-                    continue;
62
-                }
63
-                if ($field_obj instanceof EE_Boolean_Field) {
64
-                    $datatype = 'Boolean';
65
-                } elseif ($field_obj->get_wpdb_data_type() == '%d') {
66
-                    $datatype = 'Number';
67
-                } elseif ($field_name instanceof EE_Serialized_Text_Field) {
68
-                    $datatype = 'Object';
69
-                } else {
70
-                    $datatype = 'String';
71
-                }
72
-                $default_value = ModelDataTranslator::prepareFieldValueForJson(
73
-                    $field_obj,
74
-                    $field_obj->get_default_value(),
75
-                    $this->getModelVersionInfo()->requestedVersion()
76
-                );
77
-                $field_json = array(
78
-                    'name'                => $field_name,
79
-                    'nicename'            => wp_specialchars_decode($field_obj->get_nicename(), ENT_QUOTES),
80
-                    'has_rendered_format' => $this->getModelVersionInfo()->fieldHasRenderedFormat($field_obj),
81
-                    'has_pretty_format'   => $this->getModelVersionInfo()->fieldHasPrettyFormat($field_obj),
82
-                    'type'                => str_replace('EE_', '', get_class($field_obj)),
83
-                    'datatype'            => $datatype,
84
-                    'nullable'            => $field_obj->is_nullable(),
85
-                    'default'             => $default_value,
86
-                    'table_alias'         => $field_obj->get_table_alias(),
87
-                    'table_column'        => $field_obj->get_table_column(),
88
-                );
89
-                $fields_json[$field_json['name']] = $field_json;
90
-            }
91
-            $fields_json = array_merge(
92
-                $fields_json,
93
-                $this->getModelVersionInfo()->extraResourcePropertiesForModel($model)
94
-            );
95
-            $response[$model_name]['fields'] = apply_filters(
96
-                'FHEE__Meta__handle_request_models_meta__fields',
97
-                $fields_json,
98
-                $model
99
-            );
100
-            $relations_json = array();
101
-            foreach ($model->relation_settings() as $relation_name => $relation_obj) {
102
-                $relation_json = array(
103
-                    'name'   => $relation_name,
104
-                    'type'   => str_replace('EE_', '', get_class($relation_obj)),
105
-                    'single' => $relation_obj instanceof \EE_Belongs_To_Relation ? true : false,
106
-                );
107
-                $relations_json[$relation_name] = $relation_json;
108
-            }
109
-            $response[$model_name]['relations'] = apply_filters(
110
-                'FHEE__Meta__handle_request_models_meta__relations',
111
-                $relations_json,
112
-                $model
113
-            );
114
-        }
115
-        return $response;
116
-    }
53
+	protected function getModelsMetadataEntity()
54
+	{
55
+		$response = array();
56
+		foreach ($this->getModelVersionInfo()->modelsForRequestedVersion() as $model_name => $model_classname) {
57
+			$model = $this->getModelVersionInfo()->loadModel($model_name);
58
+			$fields_json = array();
59
+			foreach ($this->getModelVersionInfo()->fieldsOnModelInThisVersion($model) as $field_name => $field_obj) {
60
+				if ($this->getModelVersionInfo()->fieldIsIgnored($field_obj)) {
61
+					continue;
62
+				}
63
+				if ($field_obj instanceof EE_Boolean_Field) {
64
+					$datatype = 'Boolean';
65
+				} elseif ($field_obj->get_wpdb_data_type() == '%d') {
66
+					$datatype = 'Number';
67
+				} elseif ($field_name instanceof EE_Serialized_Text_Field) {
68
+					$datatype = 'Object';
69
+				} else {
70
+					$datatype = 'String';
71
+				}
72
+				$default_value = ModelDataTranslator::prepareFieldValueForJson(
73
+					$field_obj,
74
+					$field_obj->get_default_value(),
75
+					$this->getModelVersionInfo()->requestedVersion()
76
+				);
77
+				$field_json = array(
78
+					'name'                => $field_name,
79
+					'nicename'            => wp_specialchars_decode($field_obj->get_nicename(), ENT_QUOTES),
80
+					'has_rendered_format' => $this->getModelVersionInfo()->fieldHasRenderedFormat($field_obj),
81
+					'has_pretty_format'   => $this->getModelVersionInfo()->fieldHasPrettyFormat($field_obj),
82
+					'type'                => str_replace('EE_', '', get_class($field_obj)),
83
+					'datatype'            => $datatype,
84
+					'nullable'            => $field_obj->is_nullable(),
85
+					'default'             => $default_value,
86
+					'table_alias'         => $field_obj->get_table_alias(),
87
+					'table_column'        => $field_obj->get_table_column(),
88
+				);
89
+				$fields_json[$field_json['name']] = $field_json;
90
+			}
91
+			$fields_json = array_merge(
92
+				$fields_json,
93
+				$this->getModelVersionInfo()->extraResourcePropertiesForModel($model)
94
+			);
95
+			$response[$model_name]['fields'] = apply_filters(
96
+				'FHEE__Meta__handle_request_models_meta__fields',
97
+				$fields_json,
98
+				$model
99
+			);
100
+			$relations_json = array();
101
+			foreach ($model->relation_settings() as $relation_name => $relation_obj) {
102
+				$relation_json = array(
103
+					'name'   => $relation_name,
104
+					'type'   => str_replace('EE_', '', get_class($relation_obj)),
105
+					'single' => $relation_obj instanceof \EE_Belongs_To_Relation ? true : false,
106
+				);
107
+				$relations_json[$relation_name] = $relation_json;
108
+			}
109
+			$response[$model_name]['relations'] = apply_filters(
110
+				'FHEE__Meta__handle_request_models_meta__relations',
111
+				$relations_json,
112
+				$model
113
+			);
114
+		}
115
+		return $response;
116
+	}
117 117
 
118 118
 
119 119
 
120
-    /**
121
-     * Adds EE metadata to the index
122
-     *
123
-     * @param \WP_REST_Response $rest_response_obj
124
-     * @return \WP_REST_Response
125
-     */
126
-    public static function filterEeMetadataIntoIndex(\WP_REST_Response $rest_response_obj)
127
-    {
128
-        $response_data = $rest_response_obj->get_data();
129
-        $addons = array();
130
-        foreach (EE_Registry::instance()->addons as $addon) {
131
-            $addon_json = array(
132
-                'name'    => $addon->name(),
133
-                'version' => $addon->version(),
134
-            );
135
-            $addons[$addon_json['name']] = $addon_json;
136
-        }
137
-        $response_data['ee'] = array(
138
-            'version'              => EEM_System_Status::instance()->get_ee_version(),
139
-            // @codingStandardsIgnoreStart
140
-            'documentation_url'    => 'https://github.com/eventespresso/event-espresso-core/tree/master/docs/C--REST-API',
141
-            // @codingStandardsIgnoreEnd
142
-            'addons'               => $addons,
143
-            'maintenance_mode'     => EE_Maintenance_Mode::instance()->real_level(),
144
-            'served_core_versions' => array_keys(EED_Core_Rest_Api::versions_served()),
145
-        );
146
-        $rest_response_obj->set_data($response_data);
147
-        return $rest_response_obj;
148
-    }
120
+	/**
121
+	 * Adds EE metadata to the index
122
+	 *
123
+	 * @param \WP_REST_Response $rest_response_obj
124
+	 * @return \WP_REST_Response
125
+	 */
126
+	public static function filterEeMetadataIntoIndex(\WP_REST_Response $rest_response_obj)
127
+	{
128
+		$response_data = $rest_response_obj->get_data();
129
+		$addons = array();
130
+		foreach (EE_Registry::instance()->addons as $addon) {
131
+			$addon_json = array(
132
+				'name'    => $addon->name(),
133
+				'version' => $addon->version(),
134
+			);
135
+			$addons[$addon_json['name']] = $addon_json;
136
+		}
137
+		$response_data['ee'] = array(
138
+			'version'              => EEM_System_Status::instance()->get_ee_version(),
139
+			// @codingStandardsIgnoreStart
140
+			'documentation_url'    => 'https://github.com/eventespresso/event-espresso-core/tree/master/docs/C--REST-API',
141
+			// @codingStandardsIgnoreEnd
142
+			'addons'               => $addons,
143
+			'maintenance_mode'     => EE_Maintenance_Mode::instance()->real_level(),
144
+			'served_core_versions' => array_keys(EED_Core_Rest_Api::versions_served()),
145
+		);
146
+		$rest_response_obj->set_data($response_data);
147
+		return $rest_response_obj;
148
+	}
149 149
 }
150 150
 
151 151
 
Please login to merge, or discard this patch.
core/db_classes/EE_Attendee.class.php 2 patches
Indentation   +665 added lines, -665 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if (! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 /**
5 5
  * Event Espresso
@@ -23,670 +23,670 @@  discard block
 block discarded – undo
23 23
 class EE_Attendee extends EE_CPT_Base implements EEI_Contact, EEI_Address, EEI_Admin_Links, EEI_Attendee
24 24
 {
25 25
 
26
-    /**
27
-     * Sets some dynamic defaults
28
-     *
29
-     * @param array  $fieldValues
30
-     * @param bool   $bydb
31
-     * @param string $timezone
32
-     * @param array  $date_formats
33
-     */
34
-    protected function __construct($fieldValues = null, $bydb = false, $timezone = null, $date_formats = array())
35
-    {
36
-        if (! isset($fieldValues['ATT_full_name'])) {
37
-            $fname                        = isset($fieldValues['ATT_fname']) ? $fieldValues['ATT_fname'] . ' ' : '';
38
-            $lname                        = isset($fieldValues['ATT_lname']) ? $fieldValues['ATT_lname'] : '';
39
-            $fieldValues['ATT_full_name'] = $fname . $lname;
40
-        }
41
-        if (! isset($fieldValues['ATT_slug'])) {
42
-            //			$fieldValues['ATT_slug'] = sanitize_key(wp_generate_password(20));
43
-            $fieldValues['ATT_slug'] = sanitize_title($fieldValues['ATT_full_name']);
44
-        }
45
-        if (! isset($fieldValues['ATT_short_bio']) && isset($fieldValues['ATT_bio'])) {
46
-            $fieldValues['ATT_short_bio'] = substr($fieldValues['ATT_bio'], 0, 50);
47
-        }
48
-        parent::__construct($fieldValues, $bydb, $timezone, $date_formats);
49
-    }
50
-
51
-
52
-    /**
53
-     * @param array  $props_n_values          incoming values
54
-     * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
55
-     *                                        used.)
56
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
57
-     *                                        date_format and the second value is the time format
58
-     * @return EE_Attendee
59
-     */
60
-    public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
61
-    {
62
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
63
-        return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
64
-    }
65
-
66
-
67
-    /**
68
-     * @param array  $props_n_values  incoming values from the database
69
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
70
-     *                                the website will be used.
71
-     * @return EE_Attendee
72
-     */
73
-    public static function new_instance_from_db($props_n_values = array(), $timezone = null)
74
-    {
75
-        return new self($props_n_values, true, $timezone);
76
-    }
77
-
78
-
79
-    /**
80
-     *        Set Attendee First Name
81
-     *
82
-     * @access        public
83
-     * @param string $fname
84
-     */
85
-    public function set_fname($fname = '')
86
-    {
87
-        $this->set('ATT_fname', $fname);
88
-    }
89
-
90
-
91
-    /**
92
-     *        Set Attendee Last Name
93
-     *
94
-     * @access        public
95
-     * @param string $lname
96
-     */
97
-    public function set_lname($lname = '')
98
-    {
99
-        $this->set('ATT_lname', $lname);
100
-    }
101
-
102
-
103
-    /**
104
-     *        Set Attendee Address
105
-     *
106
-     * @access        public
107
-     * @param string $address
108
-     */
109
-    public function set_address($address = '')
110
-    {
111
-        $this->set('ATT_address', $address);
112
-    }
113
-
114
-
115
-    /**
116
-     *        Set Attendee Address2
117
-     *
118
-     * @access        public
119
-     * @param        string $address2
120
-     */
121
-    public function set_address2($address2 = '')
122
-    {
123
-        $this->set('ATT_address2', $address2);
124
-    }
125
-
126
-
127
-    /**
128
-     *        Set Attendee City
129
-     *
130
-     * @access        public
131
-     * @param        string $city
132
-     */
133
-    public function set_city($city = '')
134
-    {
135
-        $this->set('ATT_city', $city);
136
-    }
137
-
138
-
139
-    /**
140
-     *        Set Attendee State ID
141
-     *
142
-     * @access        public
143
-     * @param        int $STA_ID
144
-     */
145
-    public function set_state($STA_ID = 0)
146
-    {
147
-        $this->set('STA_ID', $STA_ID);
148
-    }
149
-
150
-
151
-    /**
152
-     *        Set Attendee Country ISO Code
153
-     *
154
-     * @access        public
155
-     * @param        string $CNT_ISO
156
-     */
157
-    public function set_country($CNT_ISO = '')
158
-    {
159
-        $this->set('CNT_ISO', $CNT_ISO);
160
-    }
161
-
162
-
163
-    /**
164
-     *        Set Attendee Zip/Postal Code
165
-     *
166
-     * @access        public
167
-     * @param        string $zip
168
-     */
169
-    public function set_zip($zip = '')
170
-    {
171
-        $this->set('ATT_zip', $zip);
172
-    }
173
-
174
-
175
-    /**
176
-     *        Set Attendee Email Address
177
-     *
178
-     * @access        public
179
-     * @param        string $email
180
-     */
181
-    public function set_email($email = '')
182
-    {
183
-        $this->set('ATT_email', $email);
184
-    }
185
-
186
-
187
-    /**
188
-     *        Set Attendee Phone
189
-     *
190
-     * @access        public
191
-     * @param        string $phone
192
-     */
193
-    public function set_phone($phone = '')
194
-    {
195
-        $this->set('ATT_phone', $phone);
196
-    }
197
-
198
-
199
-    /**
200
-     *        set deleted
201
-     *
202
-     * @access        public
203
-     * @param        bool $ATT_deleted
204
-     */
205
-    public function set_deleted($ATT_deleted = false)
206
-    {
207
-        $this->set('ATT_deleted', $ATT_deleted);
208
-    }
209
-
210
-
211
-    /**
212
-     * Returns the value for the post_author id saved with the cpt
213
-     *
214
-     * @since 4.5.0
215
-     * @return int
216
-     */
217
-    public function wp_user()
218
-    {
219
-        return $this->get('ATT_author');
220
-    }
221
-
222
-
223
-    /**
224
-     *        get Attendee First Name
225
-     *
226
-     * @access        public
227
-     * @return string
228
-     */
229
-    public function fname()
230
-    {
231
-        return $this->get('ATT_fname');
232
-    }
233
-
234
-
235
-    /**
236
-     * echoes out the attendee's first name
237
-     *
238
-     * @return void
239
-     */
240
-    public function e_full_name()
241
-    {
242
-        echo $this->full_name();
243
-    }
244
-
245
-
246
-    /**
247
-     * Returns the first and last name concatenated together with a space.
248
-     *
249
-     * @param bool $apply_html_entities
250
-     * @return string
251
-     */
252
-    public function full_name($apply_html_entities = false)
253
-    {
254
-        $full_name = array(
255
-            $this->fname(),
256
-            $this->lname()
257
-        );
258
-        $full_name = array_filter($full_name);
259
-        $full_name = implode(' ', $full_name);
260
-        return $apply_html_entities ? htmlentities($full_name, ENT_QUOTES, 'UTF-8') : $full_name;
261
-    }
262
-
263
-
264
-    /**
265
-     * This returns the value of the `ATT_full_name` field which is usually equivalent to calling `full_name()` unless
266
-     * the post_title field has been directly modified in the db for the post (espresso_attendees post type) for this
267
-     * attendee.
268
-     *
269
-     * @param bool $apply_html_entities
270
-     * @return string
271
-     */
272
-    public function ATT_full_name($apply_html_entities = false)
273
-    {
274
-        return $apply_html_entities
275
-            ? htmlentities($this->get('ATT_full_name'), ENT_QUOTES, 'UTF-8')
276
-            : $this->get('ATT_full_name');
277
-    }
278
-
279
-
280
-    /**
281
-     *        get Attendee Last Name
282
-     *
283
-     * @access        public
284
-     * @return string
285
-     */
286
-    public function lname()
287
-    {
288
-        return $this->get('ATT_lname');
289
-    }
290
-
291
-
292
-    /**
293
-     * Gets the attendee's full address as an array so client code can decide hwo to display it
294
-     *
295
-     * @return array numerically indexed, with each part of the address that is known.
296
-     * Eg, if the user only responded to state and country,
297
-     * it would be array(0=>'Alabama',1=>'USA')
298
-     * @return array
299
-     */
300
-    public function full_address_as_array()
301
-    {
302
-        $full_address_array     = array();
303
-        $initial_address_fields = array('ATT_address', 'ATT_address2', 'ATT_city',);
304
-        foreach ($initial_address_fields as $address_field_name) {
305
-            $address_fields_value = $this->get($address_field_name);
306
-            if (! empty($address_fields_value)) {
307
-                $full_address_array[] = $address_fields_value;
308
-            }
309
-        }
310
-        //now handle state and country
311
-        $state_obj = $this->state_obj();
312
-        if (! empty($state_obj)) {
313
-            $full_address_array[] = $state_obj->name();
314
-        }
315
-        $country_obj = $this->country_obj();
316
-        if (! empty($country_obj)) {
317
-            $full_address_array[] = $country_obj->name();
318
-        }
319
-        //lastly get the xip
320
-        $zip_value = $this->zip();
321
-        if (! empty($zip_value)) {
322
-            $full_address_array[] = $zip_value;
323
-        }
324
-        return $full_address_array;
325
-    }
326
-
327
-
328
-    /**
329
-     *        get Attendee Address
330
-     *
331
-     * @return string
332
-     */
333
-    public function address()
334
-    {
335
-        return $this->get('ATT_address');
336
-    }
337
-
338
-
339
-    /**
340
-     *        get Attendee Address2
341
-     *
342
-     * @return string
343
-     */
344
-    public function address2()
345
-    {
346
-        return $this->get('ATT_address2');
347
-    }
348
-
349
-
350
-    /**
351
-     *        get Attendee City
352
-     *
353
-     * @return string
354
-     */
355
-    public function city()
356
-    {
357
-        return $this->get('ATT_city');
358
-    }
359
-
360
-
361
-    /**
362
-     *        get Attendee State ID
363
-     *
364
-     * @return string
365
-     */
366
-    public function state_ID()
367
-    {
368
-        return $this->get('STA_ID');
369
-    }
370
-
371
-
372
-    /**
373
-     * @return string
374
-     */
375
-    public function state_abbrev()
376
-    {
377
-        return $this->state_obj() instanceof EE_State ? $this->state_obj()->abbrev() : '';
378
-    }
379
-
380
-
381
-    /**
382
-     * Gets the state set to this attendee
383
-     *
384
-     * @return EE_State
385
-     */
386
-    public function state_obj()
387
-    {
388
-        return $this->get_first_related('State');
389
-    }
390
-
391
-
392
-    /**
393
-     * Returns the state's name, otherwise 'Unknown'
394
-     *
395
-     * @return string
396
-     */
397
-    public function state_name()
398
-    {
399
-        if ($this->state_obj()) {
400
-            return $this->state_obj()->name();
401
-        } else {
402
-            return '';
403
-        }
404
-    }
405
-
406
-
407
-    /**
408
-     * either displays the state abbreviation or the state name, as determined
409
-     * by the "FHEE__EEI_Address__state__use_abbreviation" filter.
410
-     * defaults to abbreviation
411
-     *
412
-     * @return string
413
-     */
414
-    public function state()
415
-    {
416
-        if (apply_filters('FHEE__EEI_Address__state__use_abbreviation', true, $this->state_obj())) {
417
-            return $this->state_abbrev();
418
-        } else {
419
-            return $this->state_name();
420
-        }
421
-    }
422
-
423
-
424
-    /**
425
-     *    get Attendee Country ISO Code
426
-     *
427
-     * @return string
428
-     */
429
-    public function country_ID()
430
-    {
431
-        return $this->get('CNT_ISO');
432
-    }
433
-
434
-
435
-    /**
436
-     * Gets country set for this attendee
437
-     *
438
-     * @return EE_Country
439
-     */
440
-    public function country_obj()
441
-    {
442
-        return $this->get_first_related('Country');
443
-    }
444
-
445
-
446
-    /**
447
-     * Returns the country's name if known, otherwise 'Unknown'
448
-     *
449
-     * @return string
450
-     */
451
-    public function country_name()
452
-    {
453
-        if ($this->country_obj()) {
454
-            return $this->country_obj()->name();
455
-        } else {
456
-            return '';
457
-        }
458
-    }
459
-
460
-
461
-    /**
462
-     * either displays the country ISO2 code or the country name, as determined
463
-     * by the "FHEE__EEI_Address__country__use_abbreviation" filter.
464
-     * defaults to abbreviation
465
-     *
466
-     * @return string
467
-     */
468
-    public function country()
469
-    {
470
-        if (apply_filters('FHEE__EEI_Address__country__use_abbreviation', true, $this->country_obj())) {
471
-            return $this->country_ID();
472
-        } else {
473
-            return $this->country_name();
474
-        }
475
-    }
476
-
477
-
478
-    /**
479
-     *        get Attendee Zip/Postal Code
480
-     *
481
-     * @return string
482
-     */
483
-    public function zip()
484
-    {
485
-        return $this->get('ATT_zip');
486
-    }
487
-
488
-
489
-    /**
490
-     *        get Attendee Email Address
491
-     *
492
-     * @return string
493
-     */
494
-    public function email()
495
-    {
496
-        return $this->get('ATT_email');
497
-    }
498
-
499
-
500
-    /**
501
-     *        get Attendee Phone #
502
-     *
503
-     * @return string
504
-     */
505
-    public function phone()
506
-    {
507
-        return $this->get('ATT_phone');
508
-    }
509
-
510
-
511
-    /**
512
-     *    get deleted
513
-     *
514
-     * @return        bool
515
-     */
516
-    public function deleted()
517
-    {
518
-        return $this->get('ATT_deleted');
519
-    }
520
-
521
-
522
-    /**
523
-     * Gets registrations of this attendee
524
-     *
525
-     * @param array $query_params
526
-     * @return EE_Registration[]
527
-     */
528
-    public function get_registrations($query_params = array())
529
-    {
530
-        return $this->get_many_related('Registration', $query_params);
531
-    }
532
-
533
-
534
-    /**
535
-     * Gets the most recent registration of this attendee
536
-     *
537
-     * @return EE_Registration
538
-     */
539
-    public function get_most_recent_registration()
540
-    {
541
-        return $this->get_first_related('Registration',
542
-            array('order_by' => array('REG_date' => 'DESC'))); //null, 'REG_date', 'DESC', '=', 'OBJECT_K');
543
-    }
544
-
545
-
546
-    /**
547
-     * Gets the most recent registration for this attend at this event
548
-     *
549
-     * @param int $event_id
550
-     * @return EE_Registration
551
-     */
552
-    public function get_most_recent_registration_for_event($event_id)
553
-    {
554
-        return $this->get_first_related('Registration',
555
-            array(array('EVT_ID' => $event_id), 'order_by' => array('REG_date' => 'DESC')));//, '=', 'OBJECT_K' );
556
-    }
557
-
558
-
559
-    /**
560
-     * returns any events attached to this attendee ($_Event property);
561
-     *
562
-     * @return array
563
-     */
564
-    public function events()
565
-    {
566
-        return $this->get_many_related('Event');
567
-    }
568
-
569
-
570
-    /**
571
-     * Gets the billing info array where keys match espresso_reg_page_billing_inputs(),
572
-     * and keys are their cleaned values. @see EE_Attendee::save_and_clean_billing_info_for_payment_method() which was
573
-     * used to save the billing info
574
-     *
575
-     * @param EE_Payment_Method $payment_method the _gateway_name property on the gateway class
576
-     * @return EE_Form_Section_Proper|null
577
-     */
578
-    public function billing_info_for_payment_method($payment_method)
579
-    {
580
-        $pm_type = $payment_method->type_obj();
581
-        if (! $pm_type instanceof EE_PMT_Base) {
582
-            return null;
583
-        }
584
-        $billing_info = $this->get_post_meta($this->get_billing_info_postmeta_name($payment_method), true);
585
-        if (! $billing_info) {
586
-            return null;
587
-        }
588
-        $billing_form = $pm_type->billing_form();
589
-        if ($billing_form instanceof EE_Form_Section_Proper) {
590
-            $billing_form->receive_form_submission(array($billing_form->name() => $billing_info), false);
591
-        }
592
-        return $billing_form;
593
-    }
594
-
595
-
596
-    /**
597
-     * Gets the postmeta key that holds this attendee's billing info for the
598
-     * specified payment method
599
-     *
600
-     * @param EE_Payment_Method $payment_method
601
-     * @return string
602
-     */
603
-    public function get_billing_info_postmeta_name($payment_method)
604
-    {
605
-        if ($payment_method->type_obj() instanceof EE_PMT_Base) {
606
-            return 'billing_info_' . $payment_method->type_obj()->system_name();
607
-        } else {
608
-            return null;
609
-        }
610
-    }
611
-
612
-
613
-    /**
614
-     * Saves the billing info to the attendee. @see EE_Attendee::billing_info_for_payment_method() which is used to
615
-     * retrieve it
616
-     *
617
-     * @param EE_Billing_Attendee_Info_Form $billing_form
618
-     * @param EE_Payment_Method             $payment_method
619
-     * @return boolean
620
-     */
621
-    public function save_and_clean_billing_info_for_payment_method($billing_form, $payment_method)
622
-    {
623
-        if (! $billing_form instanceof EE_Billing_Attendee_Info_Form) {
624
-            EE_Error::add_error(__('Cannot save billing info because there is none.', 'event_espresso'));
625
-            return false;
626
-        }
627
-        $billing_form->clean_sensitive_data();
628
-        return update_post_meta($this->ID(), $this->get_billing_info_postmeta_name($payment_method),
629
-            $billing_form->input_values(true));
630
-    }
631
-
632
-
633
-    /**
634
-     * Return the link to the admin details for the object.
635
-     *
636
-     * @return string
637
-     */
638
-    public function get_admin_details_link()
639
-    {
640
-        return $this->get_admin_edit_link();
641
-    }
642
-
643
-
644
-    /**
645
-     * Returns the link to the editor for the object.  Sometimes this is the same as the details.
646
-     *
647
-     * @return string
648
-     */
649
-    public function get_admin_edit_link()
650
-    {
651
-        EE_Registry::instance()->load_helper('URL');
652
-        return EEH_URL::add_query_args_and_nonce(
653
-            array(
654
-                'page'   => 'espresso_registrations',
655
-                'action' => 'edit_attendee',
656
-                'post'   => $this->ID(),
657
-            ),
658
-            admin_url('admin.php')
659
-        );
660
-    }
661
-
662
-
663
-    /**
664
-     * Returns the link to a settings page for the object.
665
-     *
666
-     * @return string
667
-     */
668
-    public function get_admin_settings_link()
669
-    {
670
-        return $this->get_admin_edit_link();
671
-    }
672
-
673
-
674
-    /**
675
-     * Returns the link to the "overview" for the object (typically the "list table" view).
676
-     *
677
-     * @return string
678
-     */
679
-    public function get_admin_overview_link()
680
-    {
681
-        EE_Registry::instance()->load_helper('URL');
682
-        return EEH_URL::add_query_args_and_nonce(
683
-            array(
684
-                'page'   => 'espresso_registrations',
685
-                'action' => 'contact_list',
686
-            ),
687
-            admin_url('admin.php')
688
-        );
689
-    }
26
+	/**
27
+	 * Sets some dynamic defaults
28
+	 *
29
+	 * @param array  $fieldValues
30
+	 * @param bool   $bydb
31
+	 * @param string $timezone
32
+	 * @param array  $date_formats
33
+	 */
34
+	protected function __construct($fieldValues = null, $bydb = false, $timezone = null, $date_formats = array())
35
+	{
36
+		if (! isset($fieldValues['ATT_full_name'])) {
37
+			$fname                        = isset($fieldValues['ATT_fname']) ? $fieldValues['ATT_fname'] . ' ' : '';
38
+			$lname                        = isset($fieldValues['ATT_lname']) ? $fieldValues['ATT_lname'] : '';
39
+			$fieldValues['ATT_full_name'] = $fname . $lname;
40
+		}
41
+		if (! isset($fieldValues['ATT_slug'])) {
42
+			//			$fieldValues['ATT_slug'] = sanitize_key(wp_generate_password(20));
43
+			$fieldValues['ATT_slug'] = sanitize_title($fieldValues['ATT_full_name']);
44
+		}
45
+		if (! isset($fieldValues['ATT_short_bio']) && isset($fieldValues['ATT_bio'])) {
46
+			$fieldValues['ATT_short_bio'] = substr($fieldValues['ATT_bio'], 0, 50);
47
+		}
48
+		parent::__construct($fieldValues, $bydb, $timezone, $date_formats);
49
+	}
50
+
51
+
52
+	/**
53
+	 * @param array  $props_n_values          incoming values
54
+	 * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
55
+	 *                                        used.)
56
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
57
+	 *                                        date_format and the second value is the time format
58
+	 * @return EE_Attendee
59
+	 */
60
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
61
+	{
62
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
63
+		return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
64
+	}
65
+
66
+
67
+	/**
68
+	 * @param array  $props_n_values  incoming values from the database
69
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
70
+	 *                                the website will be used.
71
+	 * @return EE_Attendee
72
+	 */
73
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null)
74
+	{
75
+		return new self($props_n_values, true, $timezone);
76
+	}
77
+
78
+
79
+	/**
80
+	 *        Set Attendee First Name
81
+	 *
82
+	 * @access        public
83
+	 * @param string $fname
84
+	 */
85
+	public function set_fname($fname = '')
86
+	{
87
+		$this->set('ATT_fname', $fname);
88
+	}
89
+
90
+
91
+	/**
92
+	 *        Set Attendee Last Name
93
+	 *
94
+	 * @access        public
95
+	 * @param string $lname
96
+	 */
97
+	public function set_lname($lname = '')
98
+	{
99
+		$this->set('ATT_lname', $lname);
100
+	}
101
+
102
+
103
+	/**
104
+	 *        Set Attendee Address
105
+	 *
106
+	 * @access        public
107
+	 * @param string $address
108
+	 */
109
+	public function set_address($address = '')
110
+	{
111
+		$this->set('ATT_address', $address);
112
+	}
113
+
114
+
115
+	/**
116
+	 *        Set Attendee Address2
117
+	 *
118
+	 * @access        public
119
+	 * @param        string $address2
120
+	 */
121
+	public function set_address2($address2 = '')
122
+	{
123
+		$this->set('ATT_address2', $address2);
124
+	}
125
+
126
+
127
+	/**
128
+	 *        Set Attendee City
129
+	 *
130
+	 * @access        public
131
+	 * @param        string $city
132
+	 */
133
+	public function set_city($city = '')
134
+	{
135
+		$this->set('ATT_city', $city);
136
+	}
137
+
138
+
139
+	/**
140
+	 *        Set Attendee State ID
141
+	 *
142
+	 * @access        public
143
+	 * @param        int $STA_ID
144
+	 */
145
+	public function set_state($STA_ID = 0)
146
+	{
147
+		$this->set('STA_ID', $STA_ID);
148
+	}
149
+
150
+
151
+	/**
152
+	 *        Set Attendee Country ISO Code
153
+	 *
154
+	 * @access        public
155
+	 * @param        string $CNT_ISO
156
+	 */
157
+	public function set_country($CNT_ISO = '')
158
+	{
159
+		$this->set('CNT_ISO', $CNT_ISO);
160
+	}
161
+
162
+
163
+	/**
164
+	 *        Set Attendee Zip/Postal Code
165
+	 *
166
+	 * @access        public
167
+	 * @param        string $zip
168
+	 */
169
+	public function set_zip($zip = '')
170
+	{
171
+		$this->set('ATT_zip', $zip);
172
+	}
173
+
174
+
175
+	/**
176
+	 *        Set Attendee Email Address
177
+	 *
178
+	 * @access        public
179
+	 * @param        string $email
180
+	 */
181
+	public function set_email($email = '')
182
+	{
183
+		$this->set('ATT_email', $email);
184
+	}
185
+
186
+
187
+	/**
188
+	 *        Set Attendee Phone
189
+	 *
190
+	 * @access        public
191
+	 * @param        string $phone
192
+	 */
193
+	public function set_phone($phone = '')
194
+	{
195
+		$this->set('ATT_phone', $phone);
196
+	}
197
+
198
+
199
+	/**
200
+	 *        set deleted
201
+	 *
202
+	 * @access        public
203
+	 * @param        bool $ATT_deleted
204
+	 */
205
+	public function set_deleted($ATT_deleted = false)
206
+	{
207
+		$this->set('ATT_deleted', $ATT_deleted);
208
+	}
209
+
210
+
211
+	/**
212
+	 * Returns the value for the post_author id saved with the cpt
213
+	 *
214
+	 * @since 4.5.0
215
+	 * @return int
216
+	 */
217
+	public function wp_user()
218
+	{
219
+		return $this->get('ATT_author');
220
+	}
221
+
222
+
223
+	/**
224
+	 *        get Attendee First Name
225
+	 *
226
+	 * @access        public
227
+	 * @return string
228
+	 */
229
+	public function fname()
230
+	{
231
+		return $this->get('ATT_fname');
232
+	}
233
+
234
+
235
+	/**
236
+	 * echoes out the attendee's first name
237
+	 *
238
+	 * @return void
239
+	 */
240
+	public function e_full_name()
241
+	{
242
+		echo $this->full_name();
243
+	}
244
+
245
+
246
+	/**
247
+	 * Returns the first and last name concatenated together with a space.
248
+	 *
249
+	 * @param bool $apply_html_entities
250
+	 * @return string
251
+	 */
252
+	public function full_name($apply_html_entities = false)
253
+	{
254
+		$full_name = array(
255
+			$this->fname(),
256
+			$this->lname()
257
+		);
258
+		$full_name = array_filter($full_name);
259
+		$full_name = implode(' ', $full_name);
260
+		return $apply_html_entities ? htmlentities($full_name, ENT_QUOTES, 'UTF-8') : $full_name;
261
+	}
262
+
263
+
264
+	/**
265
+	 * This returns the value of the `ATT_full_name` field which is usually equivalent to calling `full_name()` unless
266
+	 * the post_title field has been directly modified in the db for the post (espresso_attendees post type) for this
267
+	 * attendee.
268
+	 *
269
+	 * @param bool $apply_html_entities
270
+	 * @return string
271
+	 */
272
+	public function ATT_full_name($apply_html_entities = false)
273
+	{
274
+		return $apply_html_entities
275
+			? htmlentities($this->get('ATT_full_name'), ENT_QUOTES, 'UTF-8')
276
+			: $this->get('ATT_full_name');
277
+	}
278
+
279
+
280
+	/**
281
+	 *        get Attendee Last Name
282
+	 *
283
+	 * @access        public
284
+	 * @return string
285
+	 */
286
+	public function lname()
287
+	{
288
+		return $this->get('ATT_lname');
289
+	}
290
+
291
+
292
+	/**
293
+	 * Gets the attendee's full address as an array so client code can decide hwo to display it
294
+	 *
295
+	 * @return array numerically indexed, with each part of the address that is known.
296
+	 * Eg, if the user only responded to state and country,
297
+	 * it would be array(0=>'Alabama',1=>'USA')
298
+	 * @return array
299
+	 */
300
+	public function full_address_as_array()
301
+	{
302
+		$full_address_array     = array();
303
+		$initial_address_fields = array('ATT_address', 'ATT_address2', 'ATT_city',);
304
+		foreach ($initial_address_fields as $address_field_name) {
305
+			$address_fields_value = $this->get($address_field_name);
306
+			if (! empty($address_fields_value)) {
307
+				$full_address_array[] = $address_fields_value;
308
+			}
309
+		}
310
+		//now handle state and country
311
+		$state_obj = $this->state_obj();
312
+		if (! empty($state_obj)) {
313
+			$full_address_array[] = $state_obj->name();
314
+		}
315
+		$country_obj = $this->country_obj();
316
+		if (! empty($country_obj)) {
317
+			$full_address_array[] = $country_obj->name();
318
+		}
319
+		//lastly get the xip
320
+		$zip_value = $this->zip();
321
+		if (! empty($zip_value)) {
322
+			$full_address_array[] = $zip_value;
323
+		}
324
+		return $full_address_array;
325
+	}
326
+
327
+
328
+	/**
329
+	 *        get Attendee Address
330
+	 *
331
+	 * @return string
332
+	 */
333
+	public function address()
334
+	{
335
+		return $this->get('ATT_address');
336
+	}
337
+
338
+
339
+	/**
340
+	 *        get Attendee Address2
341
+	 *
342
+	 * @return string
343
+	 */
344
+	public function address2()
345
+	{
346
+		return $this->get('ATT_address2');
347
+	}
348
+
349
+
350
+	/**
351
+	 *        get Attendee City
352
+	 *
353
+	 * @return string
354
+	 */
355
+	public function city()
356
+	{
357
+		return $this->get('ATT_city');
358
+	}
359
+
360
+
361
+	/**
362
+	 *        get Attendee State ID
363
+	 *
364
+	 * @return string
365
+	 */
366
+	public function state_ID()
367
+	{
368
+		return $this->get('STA_ID');
369
+	}
370
+
371
+
372
+	/**
373
+	 * @return string
374
+	 */
375
+	public function state_abbrev()
376
+	{
377
+		return $this->state_obj() instanceof EE_State ? $this->state_obj()->abbrev() : '';
378
+	}
379
+
380
+
381
+	/**
382
+	 * Gets the state set to this attendee
383
+	 *
384
+	 * @return EE_State
385
+	 */
386
+	public function state_obj()
387
+	{
388
+		return $this->get_first_related('State');
389
+	}
390
+
391
+
392
+	/**
393
+	 * Returns the state's name, otherwise 'Unknown'
394
+	 *
395
+	 * @return string
396
+	 */
397
+	public function state_name()
398
+	{
399
+		if ($this->state_obj()) {
400
+			return $this->state_obj()->name();
401
+		} else {
402
+			return '';
403
+		}
404
+	}
405
+
406
+
407
+	/**
408
+	 * either displays the state abbreviation or the state name, as determined
409
+	 * by the "FHEE__EEI_Address__state__use_abbreviation" filter.
410
+	 * defaults to abbreviation
411
+	 *
412
+	 * @return string
413
+	 */
414
+	public function state()
415
+	{
416
+		if (apply_filters('FHEE__EEI_Address__state__use_abbreviation', true, $this->state_obj())) {
417
+			return $this->state_abbrev();
418
+		} else {
419
+			return $this->state_name();
420
+		}
421
+	}
422
+
423
+
424
+	/**
425
+	 *    get Attendee Country ISO Code
426
+	 *
427
+	 * @return string
428
+	 */
429
+	public function country_ID()
430
+	{
431
+		return $this->get('CNT_ISO');
432
+	}
433
+
434
+
435
+	/**
436
+	 * Gets country set for this attendee
437
+	 *
438
+	 * @return EE_Country
439
+	 */
440
+	public function country_obj()
441
+	{
442
+		return $this->get_first_related('Country');
443
+	}
444
+
445
+
446
+	/**
447
+	 * Returns the country's name if known, otherwise 'Unknown'
448
+	 *
449
+	 * @return string
450
+	 */
451
+	public function country_name()
452
+	{
453
+		if ($this->country_obj()) {
454
+			return $this->country_obj()->name();
455
+		} else {
456
+			return '';
457
+		}
458
+	}
459
+
460
+
461
+	/**
462
+	 * either displays the country ISO2 code or the country name, as determined
463
+	 * by the "FHEE__EEI_Address__country__use_abbreviation" filter.
464
+	 * defaults to abbreviation
465
+	 *
466
+	 * @return string
467
+	 */
468
+	public function country()
469
+	{
470
+		if (apply_filters('FHEE__EEI_Address__country__use_abbreviation', true, $this->country_obj())) {
471
+			return $this->country_ID();
472
+		} else {
473
+			return $this->country_name();
474
+		}
475
+	}
476
+
477
+
478
+	/**
479
+	 *        get Attendee Zip/Postal Code
480
+	 *
481
+	 * @return string
482
+	 */
483
+	public function zip()
484
+	{
485
+		return $this->get('ATT_zip');
486
+	}
487
+
488
+
489
+	/**
490
+	 *        get Attendee Email Address
491
+	 *
492
+	 * @return string
493
+	 */
494
+	public function email()
495
+	{
496
+		return $this->get('ATT_email');
497
+	}
498
+
499
+
500
+	/**
501
+	 *        get Attendee Phone #
502
+	 *
503
+	 * @return string
504
+	 */
505
+	public function phone()
506
+	{
507
+		return $this->get('ATT_phone');
508
+	}
509
+
510
+
511
+	/**
512
+	 *    get deleted
513
+	 *
514
+	 * @return        bool
515
+	 */
516
+	public function deleted()
517
+	{
518
+		return $this->get('ATT_deleted');
519
+	}
520
+
521
+
522
+	/**
523
+	 * Gets registrations of this attendee
524
+	 *
525
+	 * @param array $query_params
526
+	 * @return EE_Registration[]
527
+	 */
528
+	public function get_registrations($query_params = array())
529
+	{
530
+		return $this->get_many_related('Registration', $query_params);
531
+	}
532
+
533
+
534
+	/**
535
+	 * Gets the most recent registration of this attendee
536
+	 *
537
+	 * @return EE_Registration
538
+	 */
539
+	public function get_most_recent_registration()
540
+	{
541
+		return $this->get_first_related('Registration',
542
+			array('order_by' => array('REG_date' => 'DESC'))); //null, 'REG_date', 'DESC', '=', 'OBJECT_K');
543
+	}
544
+
545
+
546
+	/**
547
+	 * Gets the most recent registration for this attend at this event
548
+	 *
549
+	 * @param int $event_id
550
+	 * @return EE_Registration
551
+	 */
552
+	public function get_most_recent_registration_for_event($event_id)
553
+	{
554
+		return $this->get_first_related('Registration',
555
+			array(array('EVT_ID' => $event_id), 'order_by' => array('REG_date' => 'DESC')));//, '=', 'OBJECT_K' );
556
+	}
557
+
558
+
559
+	/**
560
+	 * returns any events attached to this attendee ($_Event property);
561
+	 *
562
+	 * @return array
563
+	 */
564
+	public function events()
565
+	{
566
+		return $this->get_many_related('Event');
567
+	}
568
+
569
+
570
+	/**
571
+	 * Gets the billing info array where keys match espresso_reg_page_billing_inputs(),
572
+	 * and keys are their cleaned values. @see EE_Attendee::save_and_clean_billing_info_for_payment_method() which was
573
+	 * used to save the billing info
574
+	 *
575
+	 * @param EE_Payment_Method $payment_method the _gateway_name property on the gateway class
576
+	 * @return EE_Form_Section_Proper|null
577
+	 */
578
+	public function billing_info_for_payment_method($payment_method)
579
+	{
580
+		$pm_type = $payment_method->type_obj();
581
+		if (! $pm_type instanceof EE_PMT_Base) {
582
+			return null;
583
+		}
584
+		$billing_info = $this->get_post_meta($this->get_billing_info_postmeta_name($payment_method), true);
585
+		if (! $billing_info) {
586
+			return null;
587
+		}
588
+		$billing_form = $pm_type->billing_form();
589
+		if ($billing_form instanceof EE_Form_Section_Proper) {
590
+			$billing_form->receive_form_submission(array($billing_form->name() => $billing_info), false);
591
+		}
592
+		return $billing_form;
593
+	}
594
+
595
+
596
+	/**
597
+	 * Gets the postmeta key that holds this attendee's billing info for the
598
+	 * specified payment method
599
+	 *
600
+	 * @param EE_Payment_Method $payment_method
601
+	 * @return string
602
+	 */
603
+	public function get_billing_info_postmeta_name($payment_method)
604
+	{
605
+		if ($payment_method->type_obj() instanceof EE_PMT_Base) {
606
+			return 'billing_info_' . $payment_method->type_obj()->system_name();
607
+		} else {
608
+			return null;
609
+		}
610
+	}
611
+
612
+
613
+	/**
614
+	 * Saves the billing info to the attendee. @see EE_Attendee::billing_info_for_payment_method() which is used to
615
+	 * retrieve it
616
+	 *
617
+	 * @param EE_Billing_Attendee_Info_Form $billing_form
618
+	 * @param EE_Payment_Method             $payment_method
619
+	 * @return boolean
620
+	 */
621
+	public function save_and_clean_billing_info_for_payment_method($billing_form, $payment_method)
622
+	{
623
+		if (! $billing_form instanceof EE_Billing_Attendee_Info_Form) {
624
+			EE_Error::add_error(__('Cannot save billing info because there is none.', 'event_espresso'));
625
+			return false;
626
+		}
627
+		$billing_form->clean_sensitive_data();
628
+		return update_post_meta($this->ID(), $this->get_billing_info_postmeta_name($payment_method),
629
+			$billing_form->input_values(true));
630
+	}
631
+
632
+
633
+	/**
634
+	 * Return the link to the admin details for the object.
635
+	 *
636
+	 * @return string
637
+	 */
638
+	public function get_admin_details_link()
639
+	{
640
+		return $this->get_admin_edit_link();
641
+	}
642
+
643
+
644
+	/**
645
+	 * Returns the link to the editor for the object.  Sometimes this is the same as the details.
646
+	 *
647
+	 * @return string
648
+	 */
649
+	public function get_admin_edit_link()
650
+	{
651
+		EE_Registry::instance()->load_helper('URL');
652
+		return EEH_URL::add_query_args_and_nonce(
653
+			array(
654
+				'page'   => 'espresso_registrations',
655
+				'action' => 'edit_attendee',
656
+				'post'   => $this->ID(),
657
+			),
658
+			admin_url('admin.php')
659
+		);
660
+	}
661
+
662
+
663
+	/**
664
+	 * Returns the link to a settings page for the object.
665
+	 *
666
+	 * @return string
667
+	 */
668
+	public function get_admin_settings_link()
669
+	{
670
+		return $this->get_admin_edit_link();
671
+	}
672
+
673
+
674
+	/**
675
+	 * Returns the link to the "overview" for the object (typically the "list table" view).
676
+	 *
677
+	 * @return string
678
+	 */
679
+	public function get_admin_overview_link()
680
+	{
681
+		EE_Registry::instance()->load_helper('URL');
682
+		return EEH_URL::add_query_args_and_nonce(
683
+			array(
684
+				'page'   => 'espresso_registrations',
685
+				'action' => 'contact_list',
686
+			),
687
+			admin_url('admin.php')
688
+		);
689
+	}
690 690
 
691 691
 
692 692
 }
Please login to merge, or discard this patch.
Spacing   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -1,4 +1,4 @@  discard block
 block discarded – undo
1
-<?php if (! defined('EVENT_ESPRESSO_VERSION')) {
1
+<?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2 2
     exit('No direct script access allowed');
3 3
 }
4 4
 /**
@@ -33,16 +33,16 @@  discard block
 block discarded – undo
33 33
      */
34 34
     protected function __construct($fieldValues = null, $bydb = false, $timezone = null, $date_formats = array())
35 35
     {
36
-        if (! isset($fieldValues['ATT_full_name'])) {
37
-            $fname                        = isset($fieldValues['ATT_fname']) ? $fieldValues['ATT_fname'] . ' ' : '';
36
+        if ( ! isset($fieldValues['ATT_full_name'])) {
37
+            $fname                        = isset($fieldValues['ATT_fname']) ? $fieldValues['ATT_fname'].' ' : '';
38 38
             $lname                        = isset($fieldValues['ATT_lname']) ? $fieldValues['ATT_lname'] : '';
39
-            $fieldValues['ATT_full_name'] = $fname . $lname;
39
+            $fieldValues['ATT_full_name'] = $fname.$lname;
40 40
         }
41
-        if (! isset($fieldValues['ATT_slug'])) {
41
+        if ( ! isset($fieldValues['ATT_slug'])) {
42 42
             //			$fieldValues['ATT_slug'] = sanitize_key(wp_generate_password(20));
43 43
             $fieldValues['ATT_slug'] = sanitize_title($fieldValues['ATT_full_name']);
44 44
         }
45
-        if (! isset($fieldValues['ATT_short_bio']) && isset($fieldValues['ATT_bio'])) {
45
+        if ( ! isset($fieldValues['ATT_short_bio']) && isset($fieldValues['ATT_bio'])) {
46 46
             $fieldValues['ATT_short_bio'] = substr($fieldValues['ATT_bio'], 0, 50);
47 47
         }
48 48
         parent::__construct($fieldValues, $bydb, $timezone, $date_formats);
@@ -303,22 +303,22 @@  discard block
 block discarded – undo
303 303
         $initial_address_fields = array('ATT_address', 'ATT_address2', 'ATT_city',);
304 304
         foreach ($initial_address_fields as $address_field_name) {
305 305
             $address_fields_value = $this->get($address_field_name);
306
-            if (! empty($address_fields_value)) {
306
+            if ( ! empty($address_fields_value)) {
307 307
                 $full_address_array[] = $address_fields_value;
308 308
             }
309 309
         }
310 310
         //now handle state and country
311 311
         $state_obj = $this->state_obj();
312
-        if (! empty($state_obj)) {
312
+        if ( ! empty($state_obj)) {
313 313
             $full_address_array[] = $state_obj->name();
314 314
         }
315 315
         $country_obj = $this->country_obj();
316
-        if (! empty($country_obj)) {
316
+        if ( ! empty($country_obj)) {
317 317
             $full_address_array[] = $country_obj->name();
318 318
         }
319 319
         //lastly get the xip
320 320
         $zip_value = $this->zip();
321
-        if (! empty($zip_value)) {
321
+        if ( ! empty($zip_value)) {
322 322
             $full_address_array[] = $zip_value;
323 323
         }
324 324
         return $full_address_array;
@@ -552,7 +552,7 @@  discard block
 block discarded – undo
552 552
     public function get_most_recent_registration_for_event($event_id)
553 553
     {
554 554
         return $this->get_first_related('Registration',
555
-            array(array('EVT_ID' => $event_id), 'order_by' => array('REG_date' => 'DESC')));//, '=', 'OBJECT_K' );
555
+            array(array('EVT_ID' => $event_id), 'order_by' => array('REG_date' => 'DESC'))); //, '=', 'OBJECT_K' );
556 556
     }
557 557
 
558 558
 
@@ -578,11 +578,11 @@  discard block
 block discarded – undo
578 578
     public function billing_info_for_payment_method($payment_method)
579 579
     {
580 580
         $pm_type = $payment_method->type_obj();
581
-        if (! $pm_type instanceof EE_PMT_Base) {
581
+        if ( ! $pm_type instanceof EE_PMT_Base) {
582 582
             return null;
583 583
         }
584 584
         $billing_info = $this->get_post_meta($this->get_billing_info_postmeta_name($payment_method), true);
585
-        if (! $billing_info) {
585
+        if ( ! $billing_info) {
586 586
             return null;
587 587
         }
588 588
         $billing_form = $pm_type->billing_form();
@@ -603,7 +603,7 @@  discard block
 block discarded – undo
603 603
     public function get_billing_info_postmeta_name($payment_method)
604 604
     {
605 605
         if ($payment_method->type_obj() instanceof EE_PMT_Base) {
606
-            return 'billing_info_' . $payment_method->type_obj()->system_name();
606
+            return 'billing_info_'.$payment_method->type_obj()->system_name();
607 607
         } else {
608 608
             return null;
609 609
         }
@@ -620,7 +620,7 @@  discard block
 block discarded – undo
620 620
      */
621 621
     public function save_and_clean_billing_info_for_payment_method($billing_form, $payment_method)
622 622
     {
623
-        if (! $billing_form instanceof EE_Billing_Attendee_Info_Form) {
623
+        if ( ! $billing_form instanceof EE_Billing_Attendee_Info_Form) {
624 624
             EE_Error::add_error(__('Cannot save billing info because there is none.', 'event_espresso'));
625 625
             return false;
626 626
         }
Please login to merge, or discard this patch.
form_sections/strategies/layout/EE_Div_Per_Section_Layout.strategy.php 2 patches
Indentation   +126 added lines, -126 removed lines patch added patch discarded remove patch
@@ -14,132 +14,132 @@
 block discarded – undo
14 14
 class EE_Div_Per_Section_Layout extends EE_Form_Section_Layout_Base
15 15
 {
16 16
 
17
-    /**
18
-     * opening div tag for a form
19
-     *
20
-     * @return string
21
-     */
22
-    public function layout_form_begin()
23
-    {
24
-        return EEH_HTML::div(
25
-            '',
26
-            $this->_form_section->html_id(),
27
-            $this->_form_section->html_class(),
28
-            $this->_form_section->html_style()
29
-        );
30
-    }
31
-
32
-
33
-
34
-    /**
35
-     * Lays out the row for the input, including label and errors
36
-     *
37
-     * @param EE_Form_Input_Base $input
38
-     * @return string
39
-     * @throws \EE_Error
40
-     */
41
-    public function layout_input($input)
42
-    {
43
-        $html = '';
44
-        // set something unique for the id
45
-        $html_id = (string)$input->html_id() !== ''
46
-            ? (string)$input->html_id()
47
-            : spl_object_hash($input);
48
-        // and add a generic input type class
49
-        $html_class = sanitize_key(str_replace('_', '-', get_class($input))) . '-dv';
50
-        if ($input instanceof EE_Hidden_Input) {
51
-            $html .= EEH_HTML::nl() . $input->get_html_for_input();
52
-        } else if ($input instanceof EE_Submit_Input) {
53
-            $html .= EEH_HTML::div(
54
-                $input->get_html_for_input(),
55
-                $html_id . '-submit-dv',
56
-                "{$input->html_class()}-submit-dv {$html_class}"
57
-            );
58
-        } else if ($input instanceof EE_Select_Input) {
59
-            $html .= EEH_HTML::div(
60
-                EEH_HTML::nl(1) . $input->get_html_for_label() .
61
-                EEH_HTML::nl() . $input->get_html_for_errors() .
62
-                EEH_HTML::nl() . $input->get_html_for_input() .
63
-                EEH_HTML::nl() . $input->get_html_for_help(),
64
-                $html_id . '-input-dv',
65
-                "{$input->html_class()}-input-dv {$html_class}"
66
-            );
67
-        } else if ($input instanceof EE_Form_Input_With_Options_Base) {
68
-            $html .= EEH_HTML::div(
69
-                EEH_HTML::nl() . $this->_display_label_for_option_type_question($input) .
70
-                EEH_HTML::nl() . $input->get_html_for_errors() .
71
-                EEH_HTML::nl() . $input->get_html_for_input() .
72
-                EEH_HTML::nl() . $input->get_html_for_help(),
73
-                $html_id . '-input-dv',
74
-                "{$input->html_class()}-input-dv {$html_class}"
75
-            );
76
-        } else {
77
-            $html .= EEH_HTML::div(
78
-                EEH_HTML::nl(1) . $input->get_html_for_label() .
79
-                EEH_HTML::nl() . $input->get_html_for_errors() .
80
-                EEH_HTML::nl() . $input->get_html_for_input() .
81
-                EEH_HTML::nl() . $input->get_html_for_help(),
82
-                $html_id . '-input-dv',
83
-                "{$input->html_class()}-input-dv {$html_class}"
84
-            );
85
-        }
86
-        return $html;
87
-    }
88
-
89
-
90
-
91
-    /**
92
-     *
93
-     * _display_label_for_option_type_question
94
-     * Gets the HTML for the 'label', which is just text for this (because labels
95
-     * should be for each input)
96
-     *
97
-     * @param EE_Form_Input_With_Options_Base $input
98
-     * @return string
99
-     */
100
-    protected function _display_label_for_option_type_question(EE_Form_Input_With_Options_Base $input)
101
-    {
102
-        if ($input->display_html_label_text()) {
103
-            return EEH_HTML::div(
104
-                $input->required()
105
-                    ? $input->html_label_text() . EEH_HTML::span('*', '', 'ee-asterisk')
106
-                    : $input->html_label_text(),
107
-                $input->html_label_id(),
108
-                $input->required()
109
-                    ? 'ee-required-label ' . $input->html_label_class()
110
-                    : $input->html_label_class(),
111
-                $input->html_label_style(),
112
-                $input->html_other_attributes()
113
-            );
114
-        }
115
-        return '';
116
-    }
117
-
118
-
119
-
120
-    /**
121
-     * Lays out a row for the subsection
122
-     *
123
-     * @param EE_Form_Section_Proper $form_section
124
-     * @return string
125
-     */
126
-    public function layout_subsection($form_section)
127
-    {
128
-        //		d( $form_section );
129
-        return EEH_HTML::nl(1) . $form_section->get_html() . EEH_HTML::nl(-1);
130
-    }
131
-
132
-
133
-
134
-    /**
135
-     * closing div tag for a form
136
-     *
137
-     * @return string
138
-     */
139
-    public function layout_form_end()
140
-    {
141
-        return EEH_HTML::divx($this->_form_section->html_id(), $this->_form_section->html_class());
142
-    }
17
+	/**
18
+	 * opening div tag for a form
19
+	 *
20
+	 * @return string
21
+	 */
22
+	public function layout_form_begin()
23
+	{
24
+		return EEH_HTML::div(
25
+			'',
26
+			$this->_form_section->html_id(),
27
+			$this->_form_section->html_class(),
28
+			$this->_form_section->html_style()
29
+		);
30
+	}
31
+
32
+
33
+
34
+	/**
35
+	 * Lays out the row for the input, including label and errors
36
+	 *
37
+	 * @param EE_Form_Input_Base $input
38
+	 * @return string
39
+	 * @throws \EE_Error
40
+	 */
41
+	public function layout_input($input)
42
+	{
43
+		$html = '';
44
+		// set something unique for the id
45
+		$html_id = (string)$input->html_id() !== ''
46
+			? (string)$input->html_id()
47
+			: spl_object_hash($input);
48
+		// and add a generic input type class
49
+		$html_class = sanitize_key(str_replace('_', '-', get_class($input))) . '-dv';
50
+		if ($input instanceof EE_Hidden_Input) {
51
+			$html .= EEH_HTML::nl() . $input->get_html_for_input();
52
+		} else if ($input instanceof EE_Submit_Input) {
53
+			$html .= EEH_HTML::div(
54
+				$input->get_html_for_input(),
55
+				$html_id . '-submit-dv',
56
+				"{$input->html_class()}-submit-dv {$html_class}"
57
+			);
58
+		} else if ($input instanceof EE_Select_Input) {
59
+			$html .= EEH_HTML::div(
60
+				EEH_HTML::nl(1) . $input->get_html_for_label() .
61
+				EEH_HTML::nl() . $input->get_html_for_errors() .
62
+				EEH_HTML::nl() . $input->get_html_for_input() .
63
+				EEH_HTML::nl() . $input->get_html_for_help(),
64
+				$html_id . '-input-dv',
65
+				"{$input->html_class()}-input-dv {$html_class}"
66
+			);
67
+		} else if ($input instanceof EE_Form_Input_With_Options_Base) {
68
+			$html .= EEH_HTML::div(
69
+				EEH_HTML::nl() . $this->_display_label_for_option_type_question($input) .
70
+				EEH_HTML::nl() . $input->get_html_for_errors() .
71
+				EEH_HTML::nl() . $input->get_html_for_input() .
72
+				EEH_HTML::nl() . $input->get_html_for_help(),
73
+				$html_id . '-input-dv',
74
+				"{$input->html_class()}-input-dv {$html_class}"
75
+			);
76
+		} else {
77
+			$html .= EEH_HTML::div(
78
+				EEH_HTML::nl(1) . $input->get_html_for_label() .
79
+				EEH_HTML::nl() . $input->get_html_for_errors() .
80
+				EEH_HTML::nl() . $input->get_html_for_input() .
81
+				EEH_HTML::nl() . $input->get_html_for_help(),
82
+				$html_id . '-input-dv',
83
+				"{$input->html_class()}-input-dv {$html_class}"
84
+			);
85
+		}
86
+		return $html;
87
+	}
88
+
89
+
90
+
91
+	/**
92
+	 *
93
+	 * _display_label_for_option_type_question
94
+	 * Gets the HTML for the 'label', which is just text for this (because labels
95
+	 * should be for each input)
96
+	 *
97
+	 * @param EE_Form_Input_With_Options_Base $input
98
+	 * @return string
99
+	 */
100
+	protected function _display_label_for_option_type_question(EE_Form_Input_With_Options_Base $input)
101
+	{
102
+		if ($input->display_html_label_text()) {
103
+			return EEH_HTML::div(
104
+				$input->required()
105
+					? $input->html_label_text() . EEH_HTML::span('*', '', 'ee-asterisk')
106
+					: $input->html_label_text(),
107
+				$input->html_label_id(),
108
+				$input->required()
109
+					? 'ee-required-label ' . $input->html_label_class()
110
+					: $input->html_label_class(),
111
+				$input->html_label_style(),
112
+				$input->html_other_attributes()
113
+			);
114
+		}
115
+		return '';
116
+	}
117
+
118
+
119
+
120
+	/**
121
+	 * Lays out a row for the subsection
122
+	 *
123
+	 * @param EE_Form_Section_Proper $form_section
124
+	 * @return string
125
+	 */
126
+	public function layout_subsection($form_section)
127
+	{
128
+		//		d( $form_section );
129
+		return EEH_HTML::nl(1) . $form_section->get_html() . EEH_HTML::nl(-1);
130
+	}
131
+
132
+
133
+
134
+	/**
135
+	 * closing div tag for a form
136
+	 *
137
+	 * @return string
138
+	 */
139
+	public function layout_form_end()
140
+	{
141
+		return EEH_HTML::divx($this->_form_section->html_id(), $this->_form_section->html_class());
142
+	}
143 143
 
144 144
 
145 145
 
Please login to merge, or discard this patch.
Spacing   +23 added lines, -23 removed lines patch added patch discarded remove patch
@@ -42,44 +42,44 @@  discard block
 block discarded – undo
42 42
     {
43 43
         $html = '';
44 44
         // set something unique for the id
45
-        $html_id = (string)$input->html_id() !== ''
46
-            ? (string)$input->html_id()
45
+        $html_id = (string) $input->html_id() !== ''
46
+            ? (string) $input->html_id()
47 47
             : spl_object_hash($input);
48 48
         // and add a generic input type class
49
-        $html_class = sanitize_key(str_replace('_', '-', get_class($input))) . '-dv';
49
+        $html_class = sanitize_key(str_replace('_', '-', get_class($input))).'-dv';
50 50
         if ($input instanceof EE_Hidden_Input) {
51
-            $html .= EEH_HTML::nl() . $input->get_html_for_input();
51
+            $html .= EEH_HTML::nl().$input->get_html_for_input();
52 52
         } else if ($input instanceof EE_Submit_Input) {
53 53
             $html .= EEH_HTML::div(
54 54
                 $input->get_html_for_input(),
55
-                $html_id . '-submit-dv',
55
+                $html_id.'-submit-dv',
56 56
                 "{$input->html_class()}-submit-dv {$html_class}"
57 57
             );
58 58
         } else if ($input instanceof EE_Select_Input) {
59 59
             $html .= EEH_HTML::div(
60
-                EEH_HTML::nl(1) . $input->get_html_for_label() .
61
-                EEH_HTML::nl() . $input->get_html_for_errors() .
62
-                EEH_HTML::nl() . $input->get_html_for_input() .
63
-                EEH_HTML::nl() . $input->get_html_for_help(),
64
-                $html_id . '-input-dv',
60
+                EEH_HTML::nl(1).$input->get_html_for_label().
61
+                EEH_HTML::nl().$input->get_html_for_errors().
62
+                EEH_HTML::nl().$input->get_html_for_input().
63
+                EEH_HTML::nl().$input->get_html_for_help(),
64
+                $html_id.'-input-dv',
65 65
                 "{$input->html_class()}-input-dv {$html_class}"
66 66
             );
67 67
         } else if ($input instanceof EE_Form_Input_With_Options_Base) {
68 68
             $html .= EEH_HTML::div(
69
-                EEH_HTML::nl() . $this->_display_label_for_option_type_question($input) .
70
-                EEH_HTML::nl() . $input->get_html_for_errors() .
71
-                EEH_HTML::nl() . $input->get_html_for_input() .
72
-                EEH_HTML::nl() . $input->get_html_for_help(),
73
-                $html_id . '-input-dv',
69
+                EEH_HTML::nl().$this->_display_label_for_option_type_question($input).
70
+                EEH_HTML::nl().$input->get_html_for_errors().
71
+                EEH_HTML::nl().$input->get_html_for_input().
72
+                EEH_HTML::nl().$input->get_html_for_help(),
73
+                $html_id.'-input-dv',
74 74
                 "{$input->html_class()}-input-dv {$html_class}"
75 75
             );
76 76
         } else {
77 77
             $html .= EEH_HTML::div(
78
-                EEH_HTML::nl(1) . $input->get_html_for_label() .
79
-                EEH_HTML::nl() . $input->get_html_for_errors() .
80
-                EEH_HTML::nl() . $input->get_html_for_input() .
81
-                EEH_HTML::nl() . $input->get_html_for_help(),
82
-                $html_id . '-input-dv',
78
+                EEH_HTML::nl(1).$input->get_html_for_label().
79
+                EEH_HTML::nl().$input->get_html_for_errors().
80
+                EEH_HTML::nl().$input->get_html_for_input().
81
+                EEH_HTML::nl().$input->get_html_for_help(),
82
+                $html_id.'-input-dv',
83 83
                 "{$input->html_class()}-input-dv {$html_class}"
84 84
             );
85 85
         }
@@ -102,11 +102,11 @@  discard block
 block discarded – undo
102 102
         if ($input->display_html_label_text()) {
103 103
             return EEH_HTML::div(
104 104
                 $input->required()
105
-                    ? $input->html_label_text() . EEH_HTML::span('*', '', 'ee-asterisk')
105
+                    ? $input->html_label_text().EEH_HTML::span('*', '', 'ee-asterisk')
106 106
                     : $input->html_label_text(),
107 107
                 $input->html_label_id(),
108 108
                 $input->required()
109
-                    ? 'ee-required-label ' . $input->html_label_class()
109
+                    ? 'ee-required-label '.$input->html_label_class()
110 110
                     : $input->html_label_class(),
111 111
                 $input->html_label_style(),
112 112
                 $input->html_other_attributes()
@@ -126,7 +126,7 @@  discard block
 block discarded – undo
126 126
     public function layout_subsection($form_section)
127 127
     {
128 128
         //		d( $form_section );
129
-        return EEH_HTML::nl(1) . $form_section->get_html() . EEH_HTML::nl(-1);
129
+        return EEH_HTML::nl(1).$form_section->get_html().EEH_HTML::nl(-1);
130 130
     }
131 131
 
132 132
 
Please login to merge, or discard this patch.
core/db_classes/EE_Transaction.class.php 3 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -438,7 +438,7 @@  discard block
 block discarded – undo
438 438
      * Gets all the attendees for this transaction (handy for use with EE_Attendee's get_registrations_for_event
439 439
      * function for getting attendees and how many registrations they each have for an event)
440 440
      *
441
-     * @return mixed EE_Attendee[] by default, int if $output is set to 'COUNT'
441
+     * @return EE_Base_Class[] EE_Attendee[] by default, int if $output is set to 'COUNT'
442 442
      * @throws EE_Error
443 443
      */
444 444
     public function attendees()
@@ -489,7 +489,7 @@  discard block
 block discarded – undo
489 489
     /**
490 490
      * Gets all payments which have not been approved
491 491
      *
492
-     * @return EE_Base_Class[]|EEI_Payment[]
492
+     * @return EE_Base_Class[]
493 493
      * @throws EE_Error if a model is misconfigured somehow
494 494
      */
495 495
     public function pending_payments()
Please login to merge, or discard this patch.
Indentation   +1471 added lines, -1471 removed lines patch added patch discarded remove patch
@@ -17,1477 +17,1477 @@
 block discarded – undo
17 17
 class EE_Transaction extends EE_Base_Class implements EEI_Transaction
18 18
 {
19 19
 
20
-    /**
21
-     * The length of time in seconds that a lock is applied before being considered expired.
22
-     * It is not long because a transaction should only be locked for the duration of the request that locked it
23
-     */
24
-    const LOCK_EXPIRATION = 2;
25
-
26
-    /**
27
-     * txn status upon initial construction.
28
-     *
29
-     * @var string
30
-     */
31
-    protected $_old_txn_status;
32
-
33
-
34
-
35
-    /**
36
-     * @param array  $props_n_values          incoming values
37
-     * @param string $timezone                incoming timezone
38
-     *                                        (if not set the timezone set for the website will be used.)
39
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
40
-     *                                        date_format and the second value is the time format
41
-     * @return EE_Transaction
42
-     * @throws EE_Error
43
-     */
44
-    public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
45
-    {
46
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
47
-        $txn        = $has_object
48
-            ? $has_object
49
-            : new self($props_n_values, false, $timezone, $date_formats);
50
-        if (! $has_object) {
51
-            $txn->set_old_txn_status($txn->status_ID());
52
-        }
53
-        return $txn;
54
-    }
55
-
56
-
57
-
58
-    /**
59
-     * @param array  $props_n_values  incoming values from the database
60
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
61
-     *                                the website will be used.
62
-     * @return EE_Transaction
63
-     * @throws EE_Error
64
-     */
65
-    public static function new_instance_from_db($props_n_values = array(), $timezone = null)
66
-    {
67
-        $txn = new self($props_n_values, true, $timezone);
68
-        $txn->set_old_txn_status($txn->status_ID());
69
-        return $txn;
70
-    }
71
-
72
-
73
-
74
-    /**
75
-     * Sets a meta field indicating that this TXN is locked and should not be updated in the db.
76
-     * If a lock has already been set, then we will attempt to remove it in case it has expired.
77
-     * If that also fails, then an exception is thrown.
78
-     *
79
-     * @throws EE_Error
80
-     */
81
-    public function lock()
82
-    {
83
-        // attempt to set lock, but if that fails...
84
-        if (! $this->add_extra_meta('lock', time(), true)) {
85
-            // then attempt to remove the lock in case it is expired
86
-            if ($this->_remove_expired_lock()) {
87
-                // if removal was successful, then try setting lock again
88
-                $this->lock();
89
-            } else {
90
-                // but if the lock can not be removed, then throw an exception
91
-                throw new EE_Error(
92
-                    sprintf(
93
-                        __(
94
-                            'Could not lock Transaction %1$d because it is already locked, meaning another part of the system is currently editing it. It should already be unlocked by the time you read this, so please refresh the page and try again.',
95
-                            'event_espresso'
96
-                        ),
97
-                        $this->ID()
98
-                    )
99
-                );
100
-            }
101
-        }
102
-    }
103
-
104
-
105
-
106
-    /**
107
-     * removes transaction lock applied in EE_Transaction::lock()
108
-     *
109
-     * @return int
110
-     * @throws EE_Error
111
-     */
112
-    public function unlock()
113
-    {
114
-        return $this->delete_extra_meta('lock');
115
-    }
116
-
117
-
118
-
119
-    /**
120
-     * Decides whether or not now is the right time to update the transaction.
121
-     * This is useful because we don't always know if it is safe to update the transaction
122
-     * and its related data. why?
123
-     * because it's possible that the transaction is being used in another
124
-     * request and could overwrite anything we save.
125
-     * So we want to only update the txn once we know that won't happen.
126
-     * We also check that the lock isn't expired, and remove it if it is
127
-     *
128
-     * @return boolean
129
-     * @throws EE_Error
130
-     */
131
-    public function is_locked()
132
-    {
133
-        // if TXN is not locked, then return false immediately
134
-        if (! $this->_get_lock()) {
135
-            return false;
136
-        }
137
-        // if not, then let's try and remove the lock in case it's expired...
138
-        // _remove_expired_lock() returns 0 when lock is valid (ie: removed = false)
139
-        // and a positive number if the lock was removed (ie: number of locks deleted),
140
-        // so we need to return the opposite
141
-        return ! $this->_remove_expired_lock() ? true : false;
142
-    }
143
-
144
-
145
-
146
-    /**
147
-     * Gets the meta field indicating that this TXN is locked
148
-     *
149
-     * @return int
150
-     * @throws EE_Error
151
-     */
152
-    protected function _get_lock()
153
-    {
154
-        return (int)$this->get_extra_meta('lock', true, 0);
155
-    }
156
-
157
-
158
-
159
-    /**
160
-     * If the lock on this transaction is expired, then we want to remove it so that the transaction can be updated
161
-     *
162
-     * @return int
163
-     * @throws EE_Error
164
-     */
165
-    protected function _remove_expired_lock()
166
-    {
167
-        $locked = $this->_get_lock();
168
-        if ($locked && time() - EE_Transaction::LOCK_EXPIRATION > $locked) {
169
-            return $this->unlock();
170
-        }
171
-        return 0;
172
-    }
173
-
174
-
175
-
176
-    /**
177
-     * Set transaction total
178
-     *
179
-     * @param float $total total value of transaction
180
-     * @throws EE_Error
181
-     */
182
-    public function set_total($total = 0.00)
183
-    {
184
-        $this->set('TXN_total', (float)$total);
185
-    }
186
-
187
-
188
-
189
-    /**
190
-     * Set Total Amount Paid to Date
191
-     *
192
-     * @param float $total_paid total amount paid to date (sum of all payments)
193
-     * @throws EE_Error
194
-     */
195
-    public function set_paid($total_paid = 0.00)
196
-    {
197
-        $this->set('TXN_paid', (float)$total_paid);
198
-    }
199
-
200
-
201
-
202
-    /**
203
-     * Set transaction status
204
-     *
205
-     * @param string $status        whether the transaction is open, declined, accepted,
206
-     *                              or any number of custom values that can be set
207
-     * @throws EE_Error
208
-     */
209
-    public function set_status($status = '')
210
-    {
211
-        $this->set('STS_ID', $status);
212
-    }
213
-
214
-
215
-
216
-    /**
217
-     * Set hash salt
218
-     *
219
-     * @param string $hash_salt required for some payment gateways
220
-     * @throws EE_Error
221
-     */
222
-    public function set_hash_salt($hash_salt = '')
223
-    {
224
-        $this->set('TXN_hash_salt', $hash_salt);
225
-    }
226
-
227
-
228
-
229
-    /**
230
-     * Sets TXN_reg_steps array
231
-     *
232
-     * @param array $txn_reg_steps
233
-     * @throws EE_Error
234
-     */
235
-    public function set_reg_steps(array $txn_reg_steps)
236
-    {
237
-        $this->set('TXN_reg_steps', $txn_reg_steps);
238
-    }
239
-
240
-
241
-
242
-    /**
243
-     * Gets TXN_reg_steps
244
-     *
245
-     * @return array
246
-     * @throws EE_Error
247
-     */
248
-    public function reg_steps()
249
-    {
250
-        $TXN_reg_steps = $this->get('TXN_reg_steps');
251
-        return is_array($TXN_reg_steps) ? (array)$TXN_reg_steps : array();
252
-    }
253
-
254
-
255
-
256
-    /**
257
-     * @return string of transaction's total cost, with currency symbol and decimal
258
-     * @throws EE_Error
259
-     */
260
-    public function pretty_total()
261
-    {
262
-        return $this->get_pretty('TXN_total');
263
-    }
264
-
265
-
266
-
267
-    /**
268
-     * Gets the amount paid in a pretty string (formatted and with currency symbol)
269
-     *
270
-     * @return string
271
-     * @throws EE_Error
272
-     */
273
-    public function pretty_paid()
274
-    {
275
-        return $this->get_pretty('TXN_paid');
276
-    }
277
-
278
-
279
-
280
-    /**
281
-     * calculate the amount remaining for this transaction and return;
282
-     *
283
-     * @return float amount remaining
284
-     * @throws EE_Error
285
-     */
286
-    public function remaining()
287
-    {
288
-        return $this->total() - $this->paid();
289
-    }
290
-
291
-
292
-
293
-    /**
294
-     * get Transaction Total
295
-     *
296
-     * @return float
297
-     * @throws EE_Error
298
-     */
299
-    public function total()
300
-    {
301
-        return (float)$this->get('TXN_total');
302
-    }
303
-
304
-
305
-
306
-    /**
307
-     * get Total Amount Paid to Date
308
-     *
309
-     * @return float
310
-     * @throws EE_Error
311
-     */
312
-    public function paid()
313
-    {
314
-        return (float)$this->get('TXN_paid');
315
-    }
316
-
317
-
318
-
319
-    /**
320
-     * @throws EE_Error
321
-     */
322
-    public function get_cart_session()
323
-    {
324
-        $session_data = (array)$this->get('TXN_session_data');
325
-        return isset($session_data['cart']) && $session_data['cart'] instanceof EE_Cart
326
-            ? $session_data['cart']
327
-            : null;
328
-    }
329
-
330
-
331
-
332
-    /**
333
-     * get Transaction session data
334
-     *
335
-     * @throws EE_Error
336
-     */
337
-    public function session_data()
338
-    {
339
-        $session_data = $this->get('TXN_session_data');
340
-        if (empty($session_data)) {
341
-            $session_data = array(
342
-                'id'            => null,
343
-                'user_id'       => null,
344
-                'ip_address'    => null,
345
-                'user_agent'    => null,
346
-                'init_access'   => null,
347
-                'last_access'   => null,
348
-                'pages_visited' => array(),
349
-            );
350
-        }
351
-        return $session_data;
352
-    }
353
-
354
-
355
-
356
-    /**
357
-     * Set session data within the TXN object
358
-     *
359
-     * @param EE_Session|array $session_data
360
-     * @throws EE_Error
361
-     */
362
-    public function set_txn_session_data($session_data)
363
-    {
364
-        if ($session_data instanceof EE_Session) {
365
-            $this->set('TXN_session_data', $session_data->get_session_data(null, true));
366
-        } else {
367
-            $this->set('TXN_session_data', $session_data);
368
-        }
369
-    }
370
-
371
-
372
-
373
-    /**
374
-     * get Transaction hash salt
375
-     *
376
-     * @throws EE_Error
377
-     */
378
-    public function hash_salt_()
379
-    {
380
-        return $this->get('TXN_hash_salt');
381
-    }
382
-
383
-
384
-
385
-    /**
386
-     * Returns the transaction datetime as either:
387
-     *            - unix timestamp format ($format = false, $gmt = true)
388
-     *            - formatted date string including the UTC (timezone) offset ($format = true ($gmt
389
-     *              has no affect with this option)), this also may include a timezone abbreviation if the
390
-     *              set timezone in this class differs from what the timezone is on the blog.
391
-     *            - formatted date string including the UTC (timezone) offset (default).
392
-     *
393
-     * @param boolean $format - whether to return a unix timestamp (default) or formatted date string
394
-     * @param boolean $gmt    - whether to return a unix timestamp with UTC offset applied (default)
395
-     *                          or no UTC offset applied
396
-     * @return string | int
397
-     * @throws EE_Error
398
-     */
399
-    public function datetime($format = false, $gmt = false)
400
-    {
401
-        if ($format) {
402
-            return $this->get_pretty('TXN_timestamp');
403
-        }
404
-        if ($gmt) {
405
-            return $this->get_raw('TXN_timestamp');
406
-        }
407
-        return $this->get('TXN_timestamp');
408
-    }
409
-
410
-
411
-
412
-    /**
413
-     * Gets registrations on this transaction
414
-     *
415
-     * @param array   $query_params array of query parameters
416
-     * @param boolean $get_cached   TRUE to retrieve cached registrations or FALSE to pull from the db
417
-     * @return EE_Base_Class[]|EE_Registration[]
418
-     * @throws EE_Error
419
-     */
420
-    public function registrations($query_params = array(), $get_cached = false)
421
-    {
422
-        $query_params = (empty($query_params) || ! is_array($query_params))
423
-            ? array(
424
-                'order_by' => array(
425
-                    'Event.EVT_name'     => 'ASC',
426
-                    'Attendee.ATT_lname' => 'ASC',
427
-                    'Attendee.ATT_fname' => 'ASC',
428
-                ),
429
-            )
430
-            : $query_params;
431
-        $query_params = $get_cached ? array() : $query_params;
432
-        return $this->get_many_related('Registration', $query_params);
433
-    }
434
-
435
-
436
-
437
-    /**
438
-     * Gets all the attendees for this transaction (handy for use with EE_Attendee's get_registrations_for_event
439
-     * function for getting attendees and how many registrations they each have for an event)
440
-     *
441
-     * @return mixed EE_Attendee[] by default, int if $output is set to 'COUNT'
442
-     * @throws EE_Error
443
-     */
444
-    public function attendees()
445
-    {
446
-        return $this->get_many_related('Attendee', array(array('Registration.Transaction.TXN_ID' => $this->ID())));
447
-    }
448
-
449
-
450
-
451
-    /**
452
-     * Gets payments for this transaction. Unlike other such functions, order by 'DESC' by default
453
-     *
454
-     * @param array $query_params like EEM_Base::get_all
455
-     * @return EE_Base_Class[]|EE_Payment[]
456
-     * @throws EE_Error
457
-     */
458
-    public function payments($query_params = array())
459
-    {
460
-        return $this->get_many_related('Payment', $query_params);
461
-    }
462
-
463
-
464
-
465
-    /**
466
-     * gets only approved payments for this transaction
467
-     *
468
-     * @return EE_Base_Class[]|EE_Payment[]
469
-     * @throws EE_Error
470
-     * @throws InvalidArgumentException
471
-     * @throws ReflectionException
472
-     * @throws InvalidDataTypeException
473
-     * @throws InvalidInterfaceException
474
-     */
475
-    public function approved_payments()
476
-    {
477
-        EE_Registry::instance()->load_model('Payment');
478
-        return $this->get_many_related(
479
-            'Payment',
480
-            array(
481
-                array('STS_ID' => EEM_Payment::status_id_approved),
482
-                'order_by' => array('PAY_timestamp' => 'DESC'),
483
-            )
484
-        );
485
-    }
486
-
487
-
488
-
489
-    /**
490
-     * Gets all payments which have not been approved
491
-     *
492
-     * @return EE_Base_Class[]|EEI_Payment[]
493
-     * @throws EE_Error if a model is misconfigured somehow
494
-     */
495
-    public function pending_payments()
496
-    {
497
-        return $this->get_many_related(
498
-            'Payment',
499
-            array(
500
-                array(
501
-                    'STS_ID' => EEM_Payment::status_id_pending,
502
-                ),
503
-                'order_by' => array(
504
-                    'PAY_timestamp' => 'DESC',
505
-                ),
506
-            )
507
-        );
508
-    }
509
-
510
-
511
-
512
-    /**
513
-     * echoes $this->pretty_status()
514
-     *
515
-     * @param bool $show_icons
516
-     * @throws EE_Error
517
-     * @throws InvalidArgumentException
518
-     * @throws InvalidDataTypeException
519
-     * @throws InvalidInterfaceException
520
-     */
521
-    public function e_pretty_status($show_icons = false)
522
-    {
523
-        echo $this->pretty_status($show_icons);
524
-    }
525
-
526
-
527
-
528
-    /**
529
-     * returns a pretty version of the status, good for displaying to users
530
-     *
531
-     * @param bool $show_icons
532
-     * @return string
533
-     * @throws EE_Error
534
-     * @throws InvalidArgumentException
535
-     * @throws InvalidDataTypeException
536
-     * @throws InvalidInterfaceException
537
-     */
538
-    public function pretty_status($show_icons = false)
539
-    {
540
-        $status = EEM_Status::instance()->localized_status(
541
-            array($this->status_ID() => __('unknown', 'event_espresso')),
542
-            false,
543
-            'sentence'
544
-        );
545
-        $icon   = '';
546
-        switch ($this->status_ID()) {
547
-            case EEM_Transaction::complete_status_code:
548
-                $icon = $show_icons ? '<span class="dashicons dashicons-yes ee-icon-size-24 green-text"></span>' : '';
549
-                break;
550
-            case EEM_Transaction::incomplete_status_code:
551
-                $icon = $show_icons ? '<span class="dashicons dashicons-marker ee-icon-size-16 lt-blue-text"></span>'
552
-                    : '';
553
-                break;
554
-            case EEM_Transaction::abandoned_status_code:
555
-                $icon = $show_icons ? '<span class="dashicons dashicons-marker ee-icon-size-16 red-text"></span>' : '';
556
-                break;
557
-            case EEM_Transaction::failed_status_code:
558
-                $icon = $show_icons ? '<span class="dashicons dashicons-no ee-icon-size-16 red-text"></span>' : '';
559
-                break;
560
-            case EEM_Transaction::overpaid_status_code:
561
-                $icon = $show_icons ? '<span class="dashicons dashicons-plus ee-icon-size-16 orange-text"></span>' : '';
562
-                break;
563
-        }
564
-        return $icon . $status[$this->status_ID()];
565
-    }
566
-
567
-
568
-
569
-    /**
570
-     * get Transaction Status
571
-     *
572
-     * @throws EE_Error
573
-     */
574
-    public function status_ID()
575
-    {
576
-        return $this->get('STS_ID');
577
-    }
578
-
579
-
580
-
581
-    /**
582
-     * Returns TRUE or FALSE for whether or not this transaction cost any money
583
-     *
584
-     * @return boolean
585
-     * @throws EE_Error
586
-     */
587
-    public function is_free()
588
-    {
589
-        return EEH_Money::compare_floats($this->get('TXN_total'), 0, '==');
590
-    }
591
-
592
-
593
-
594
-    /**
595
-     * Returns whether this transaction is complete
596
-     * Useful in templates and other logic for deciding if we should ask for another payment...
597
-     *
598
-     * @return boolean
599
-     * @throws EE_Error
600
-     */
601
-    public function is_completed()
602
-    {
603
-        return $this->status_ID() === EEM_Transaction::complete_status_code;
604
-    }
605
-
606
-
607
-
608
-    /**
609
-     * Returns whether this transaction is incomplete
610
-     * Useful in templates and other logic for deciding if we should ask for another payment...
611
-     *
612
-     * @return boolean
613
-     * @throws EE_Error
614
-     */
615
-    public function is_incomplete()
616
-    {
617
-        return $this->status_ID() === EEM_Transaction::incomplete_status_code;
618
-    }
619
-
620
-
621
-
622
-    /**
623
-     * Returns whether this transaction is overpaid
624
-     * Useful in templates and other logic for deciding if monies need to be refunded
625
-     *
626
-     * @return boolean
627
-     * @throws EE_Error
628
-     */
629
-    public function is_overpaid()
630
-    {
631
-        return $this->status_ID() === EEM_Transaction::overpaid_status_code;
632
-    }
633
-
634
-
635
-
636
-    /**
637
-     * Returns whether this transaction was abandoned
638
-     * meaning that the transaction/registration process was somehow interrupted and never completed
639
-     * but that contact information exists for at least one registrant
640
-     *
641
-     * @return boolean
642
-     * @throws EE_Error
643
-     */
644
-    public function is_abandoned()
645
-    {
646
-        return $this->status_ID() === EEM_Transaction::abandoned_status_code;
647
-    }
648
-
649
-
650
-
651
-    /**
652
-     * Returns whether this transaction failed
653
-     * meaning that the transaction/registration process was somehow interrupted and never completed
654
-     * and that NO contact information exists for any registrants
655
-     *
656
-     * @return boolean
657
-     * @throws EE_Error
658
-     */
659
-    public function failed()
660
-    {
661
-        return $this->status_ID() === EEM_Transaction::failed_status_code;
662
-    }
663
-
664
-
665
-
666
-    /**
667
-     * This returns the url for the invoice of this transaction
668
-     *
669
-     * @param string $type 'html' or 'pdf' (default is pdf)
670
-     * @return string
671
-     * @throws EE_Error
672
-     */
673
-    public function invoice_url($type = 'html')
674
-    {
675
-        $REG = $this->primary_registration();
676
-        if (! $REG instanceof EE_Registration) {
677
-            return '';
678
-        }
679
-        return $REG->invoice_url($type);
680
-    }
681
-
682
-
683
-
684
-    /**
685
-     * Gets the primary registration only
686
-     *
687
-     * @return EE_Base_Class|EE_Registration
688
-     * @throws EE_Error
689
-     */
690
-    public function primary_registration()
691
-    {
692
-        $registrations = (array)$this->get_many_related(
693
-            'Registration',
694
-            array(array('REG_count' => EEM_Registration::PRIMARY_REGISTRANT_COUNT))
695
-        );
696
-        foreach ($registrations as $registration) {
697
-            // valid registration that is NOT cancelled or declined ?
698
-            if (
699
-                $registration instanceof EE_Registration
700
-                && ! in_array($registration->status_ID(), EEM_Registration::closed_reg_statuses(), true)
701
-            ) {
702
-                return $registration;
703
-            }
704
-        }
705
-        // nothing valid found, so just return first thing from array of results
706
-        return reset($registrations);
707
-    }
708
-
709
-
710
-
711
-    /**
712
-     * Gets the URL for viewing the receipt
713
-     *
714
-     * @param string $type 'pdf' or 'html' (default is 'html')
715
-     * @return string
716
-     * @throws EE_Error
717
-     */
718
-    public function receipt_url($type = 'html')
719
-    {
720
-        $REG = $this->primary_registration();
721
-        if (! $REG instanceof EE_Registration) {
722
-            return '';
723
-        }
724
-        return $REG->receipt_url($type);
725
-    }
726
-
727
-
728
-
729
-    /**
730
-     * Gets the URL of the thank you page with this registration REG_url_link added as
731
-     * a query parameter
732
-     *
733
-     * @return string
734
-     * @throws EE_Error
735
-     */
736
-    public function payment_overview_url()
737
-    {
738
-        $primary_registration = $this->primary_registration();
739
-        return $primary_registration instanceof EE_Registration ? $primary_registration->payment_overview_url() : false;
740
-    }
741
-
742
-
743
-
744
-    /**
745
-     * @return string
746
-     * @throws EE_Error
747
-     */
748
-    public function gateway_response_on_transaction()
749
-    {
750
-        $payment = $this->get_first_related('Payment');
751
-        return $payment instanceof EE_Payment ? $payment->gateway_response() : '';
752
-    }
753
-
754
-
755
-
756
-    /**
757
-     * Get the status object of this object
758
-     *
759
-     * @return EE_Base_Class|EE_Status
760
-     * @throws EE_Error
761
-     */
762
-    public function status_obj()
763
-    {
764
-        return $this->get_first_related('Status');
765
-    }
766
-
767
-
768
-
769
-    /**
770
-     * Gets all the extra meta info on this payment
771
-     *
772
-     * @param array $query_params like EEM_Base::get_all
773
-     * @return EE_Base_Class[]|EE_Extra_Meta
774
-     * @throws EE_Error
775
-     */
776
-    public function extra_meta($query_params = array())
777
-    {
778
-        return $this->get_many_related('Extra_Meta', $query_params);
779
-    }
780
-
781
-
782
-
783
-    /**
784
-     * Wrapper for _add_relation_to
785
-     *
786
-     * @param EE_Registration $registration
787
-     * @return EE_Base_Class the relation was added to
788
-     * @throws EE_Error
789
-     */
790
-    public function add_registration(EE_Registration $registration)
791
-    {
792
-        return $this->_add_relation_to($registration, 'Registration');
793
-    }
794
-
795
-
796
-
797
-    /**
798
-     * Removes the given registration from being related (even before saving this transaction).
799
-     * If an ID/index is provided and this transaction isn't saved yet, removes it from list of cached relations
800
-     *
801
-     * @param int $registration_or_id
802
-     * @return EE_Base_Class that was removed from being related
803
-     * @throws EE_Error
804
-     */
805
-    public function remove_registration_with_id($registration_or_id)
806
-    {
807
-        return $this->_remove_relation_to($registration_or_id, 'Registration');
808
-    }
809
-
810
-
811
-
812
-    /**
813
-     * Gets all the line items which are for ACTUAL items
814
-     *
815
-     * @return EE_Line_Item[]
816
-     * @throws EE_Error
817
-     */
818
-    public function items_purchased()
819
-    {
820
-        return $this->line_items(array(array('LIN_type' => EEM_Line_Item::type_line_item)));
821
-    }
822
-
823
-
824
-
825
-    /**
826
-     * Wrapper for _add_relation_to
827
-     *
828
-     * @param EE_Line_Item $line_item
829
-     * @return EE_Base_Class the relation was added to
830
-     * @throws EE_Error
831
-     */
832
-    public function add_line_item(EE_Line_Item $line_item)
833
-    {
834
-        return $this->_add_relation_to($line_item, 'Line_Item');
835
-    }
836
-
837
-
838
-
839
-    /**
840
-     * Gets ALL the line items related to this transaction (unstructured)
841
-     *
842
-     * @param array $query_params
843
-     * @return EE_Base_Class[]|EE_Line_Item[]
844
-     * @throws EE_Error
845
-     */
846
-    public function line_items($query_params = array())
847
-    {
848
-        return $this->get_many_related('Line_Item', $query_params);
849
-    }
850
-
851
-
852
-
853
-    /**
854
-     * Gets all the line items which are taxes on the total
855
-     *
856
-     * @return EE_Line_Item[]
857
-     * @throws EE_Error
858
-     */
859
-    public function tax_items()
860
-    {
861
-        return $this->line_items(array(array('LIN_type' => EEM_Line_Item::type_tax)));
862
-    }
863
-
864
-
865
-
866
-    /**
867
-     * Gets the total line item (which is a parent of all other related line items,
868
-     * meaning it takes them all into account on its total)
869
-     *
870
-     * @param bool $create_if_not_found
871
-     * @return \EE_Line_Item
872
-     * @throws EE_Error
873
-     */
874
-    public function total_line_item($create_if_not_found = true)
875
-    {
876
-        $item = $this->get_first_related('Line_Item', array(array('LIN_type' => EEM_Line_Item::type_total)));
877
-        if (! $item && $create_if_not_found) {
878
-            $item = EEH_Line_Item::create_total_line_item($this);
879
-        }
880
-        return $item;
881
-    }
882
-
883
-
884
-
885
-    /**
886
-     * Returns the total amount of tax on this transaction
887
-     * (assumes there's only one tax subtotal line item)
888
-     *
889
-     * @return float
890
-     * @throws EE_Error
891
-     */
892
-    public function tax_total()
893
-    {
894
-        $tax_line_item = $this->tax_total_line_item();
895
-        if ($tax_line_item) {
896
-            return (float)$tax_line_item->total();
897
-        }
898
-        return (float)0;
899
-    }
900
-
901
-
902
-
903
-    /**
904
-     * Gets the tax subtotal line item (assumes there's only one)
905
-     *
906
-     * @return EE_Line_Item
907
-     * @throws EE_Error
908
-     */
909
-    public function tax_total_line_item()
910
-    {
911
-        return EEH_Line_Item::get_taxes_subtotal($this->total_line_item());
912
-    }
913
-
914
-
915
-
916
-    /**
917
-     * Gets the array of billing info for the gateway and for this transaction's primary registration's attendee.
918
-     *
919
-     * @return EE_Form_Section_Proper
920
-     * @throws EE_Error
921
-     */
922
-    public function billing_info()
923
-    {
924
-        $payment_method = $this->payment_method();
925
-        if (! $payment_method) {
926
-            EE_Error::add_error(
927
-                __(
928
-                    'Could not find billing info for transaction because no gateway has been used for it yet',
929
-                    'event_espresso'
930
-                ),
931
-                __FILE__,
932
-                __FUNCTION__,
933
-                __LINE__
934
-            );
935
-            return null;
936
-        }
937
-        $primary_reg = $this->primary_registration();
938
-        if (! $primary_reg) {
939
-            EE_Error::add_error(
940
-                __(
941
-                    'Cannot get billing info for gateway %s on transaction because no primary registration exists',
942
-                    'event_espresso'
943
-                ),
944
-                __FILE__,
945
-                __FUNCTION__,
946
-                __LINE__
947
-            );
948
-            return null;
949
-        }
950
-        $attendee = $primary_reg->attendee();
951
-        if (! $attendee) {
952
-            EE_Error::add_error(
953
-                __(
954
-                    'Cannot get billing info for gateway %s on transaction because the primary registration has no attendee exists',
955
-                    'event_espresso'
956
-                ),
957
-                __FILE__,
958
-                __FUNCTION__,
959
-                __LINE__
960
-            );
961
-            return null;
962
-        }
963
-        return $attendee->billing_info_for_payment_method($payment_method);
964
-    }
965
-
966
-
967
-
968
-    /**
969
-     * Gets PMD_ID
970
-     *
971
-     * @return int
972
-     * @throws EE_Error
973
-     */
974
-    public function payment_method_ID()
975
-    {
976
-        return $this->get('PMD_ID');
977
-    }
978
-
979
-
980
-
981
-    /**
982
-     * Sets PMD_ID
983
-     *
984
-     * @param int $PMD_ID
985
-     * @throws EE_Error
986
-     */
987
-    public function set_payment_method_ID($PMD_ID)
988
-    {
989
-        $this->set('PMD_ID', $PMD_ID);
990
-    }
991
-
992
-
993
-
994
-    /**
995
-     * Gets the last-used payment method on this transaction
996
-     * (we COULD just use the last-made payment, but some payment methods, namely
997
-     * offline ones, dont' create payments)
998
-     *
999
-     * @return EE_Payment_Method
1000
-     * @throws EE_Error
1001
-     */
1002
-    public function payment_method()
1003
-    {
1004
-        $pm = $this->get_first_related('Payment_Method');
1005
-        if ($pm instanceof EE_Payment_Method) {
1006
-            return $pm;
1007
-        }
1008
-        $last_payment = $this->last_payment();
1009
-        if ($last_payment instanceof EE_Payment && $last_payment->payment_method()) {
1010
-            return $last_payment->payment_method();
1011
-        }
1012
-        return null;
1013
-    }
1014
-
1015
-
1016
-
1017
-    /**
1018
-     * Gets the last payment made
1019
-     *
1020
-     * @return EE_Base_Class|EE_Payment
1021
-     * @throws EE_Error
1022
-     */
1023
-    public function last_payment()
1024
-    {
1025
-        return $this->get_first_related('Payment', array('order_by' => array('PAY_ID' => 'desc')));
1026
-    }
1027
-
1028
-
1029
-
1030
-    /**
1031
-     * Gets all the line items which are unrelated to tickets on this transaction
1032
-     *
1033
-     * @return EE_Line_Item[]
1034
-     * @throws EE_Error
1035
-     * @throws InvalidArgumentException
1036
-     * @throws InvalidDataTypeException
1037
-     * @throws InvalidInterfaceException
1038
-     */
1039
-    public function non_ticket_line_items()
1040
-    {
1041
-        return EEM_Line_Item::instance()->get_all_non_ticket_line_items_for_transaction($this->ID());
1042
-    }
1043
-
1044
-
1045
-
1046
-    /**
1047
-     * possibly toggles TXN status
1048
-     *
1049
-     * @param  boolean $update whether to save the TXN
1050
-     * @return bool whether the TXN was saved
1051
-     * @throws EE_Error
1052
-     * @throws RuntimeException
1053
-     */
1054
-    public function update_status_based_on_total_paid($update = true)
1055
-    {
1056
-        // set transaction status based on comparison of TXN_paid vs TXN_total
1057
-        if (EEH_Money::compare_floats($this->paid(), $this->total(), '>')) {
1058
-            $new_txn_status = EEM_Transaction::overpaid_status_code;
1059
-        } elseif (EEH_Money::compare_floats($this->paid(), $this->total())) {
1060
-            $new_txn_status = EEM_Transaction::complete_status_code;
1061
-        } elseif (EEH_Money::compare_floats($this->paid(), $this->total(), '<')) {
1062
-            $new_txn_status = EEM_Transaction::incomplete_status_code;
1063
-        } else {
1064
-            throw new RuntimeException(
1065
-                __('The total paid calculation for this transaction is inaccurate.', 'event_espresso')
1066
-            );
1067
-        }
1068
-        if ($new_txn_status !== $this->status_ID()) {
1069
-            $this->set_status($new_txn_status);
1070
-            if ($update) {
1071
-                return $this->save() ? true : false;
1072
-            }
1073
-        }
1074
-        return false;
1075
-    }
1076
-
1077
-
1078
-
1079
-    /**
1080
-     * Updates the transaction's status and total_paid based on all the payments
1081
-     * that apply to it
1082
-     *
1083
-     * @deprecated
1084
-     * @return array|bool
1085
-     * @throws EE_Error
1086
-     * @throws InvalidArgumentException
1087
-     * @throws ReflectionException
1088
-     * @throws InvalidDataTypeException
1089
-     * @throws InvalidInterfaceException
1090
-     */
1091
-    public function update_based_on_payments()
1092
-    {
1093
-        EE_Error::doing_it_wrong(
1094
-            __CLASS__ . '::' . __FUNCTION__,
1095
-            sprintf(
1096
-                __('This method is deprecated. Please use "%s" instead', 'event_espresso'),
1097
-                'EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()'
1098
-            ),
1099
-            '4.6.0'
1100
-        );
1101
-        /** @type EE_Transaction_Processor $transaction_processor */
1102
-        $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
1103
-        return $transaction_processor->update_transaction_and_registrations_after_checkout_or_payment($this);
1104
-    }
1105
-
1106
-
1107
-
1108
-    /**
1109
-     * @return string
1110
-     */
1111
-    public function old_txn_status()
1112
-    {
1113
-        return $this->_old_txn_status;
1114
-    }
1115
-
1116
-
1117
-
1118
-    /**
1119
-     * @param string $old_txn_status
1120
-     */
1121
-    public function set_old_txn_status($old_txn_status)
1122
-    {
1123
-        // only set the first time
1124
-        if ($this->_old_txn_status === null) {
1125
-            $this->_old_txn_status = $old_txn_status;
1126
-        }
1127
-    }
1128
-
1129
-
1130
-
1131
-    /**
1132
-     * reg_status_updated
1133
-     *
1134
-     * @return bool
1135
-     * @throws EE_Error
1136
-     */
1137
-    public function txn_status_updated()
1138
-    {
1139
-        return $this->status_ID() !== $this->_old_txn_status && $this->_old_txn_status !== null;
1140
-    }
1141
-
1142
-
1143
-
1144
-    /**
1145
-     * _reg_steps_completed
1146
-     * if $check_all is TRUE, then returns TRUE if ALL reg steps have been marked as completed,
1147
-     * if a $reg_step_slug is provided, then this step will be skipped when testing for completion
1148
-     * if $check_all is FALSE and a $reg_step_slug is provided, then ONLY that reg step will be tested for completion
1149
-     *
1150
-     * @param string $reg_step_slug
1151
-     * @param bool   $check_all
1152
-     * @return bool|int
1153
-     * @throws EE_Error
1154
-     */
1155
-    private function _reg_steps_completed($reg_step_slug = '', $check_all = true)
1156
-    {
1157
-        $reg_steps = $this->reg_steps();
1158
-        if (! is_array($reg_steps) || empty($reg_steps)) {
1159
-            return false;
1160
-        }
1161
-        // loop thru reg steps array)
1162
-        foreach ($reg_steps as $slug => $reg_step_completed) {
1163
-            // if NOT checking ALL steps (only checking one step)
1164
-            if (! $check_all) {
1165
-                // and this is the one
1166
-                if ($slug === $reg_step_slug) {
1167
-                    return $reg_step_completed;
1168
-                }
1169
-                // skip to next reg step in loop
1170
-                continue;
1171
-            }
1172
-            // $check_all must be true, else we would never have gotten to this point
1173
-            if ($slug === $reg_step_slug) {
1174
-                // if we reach this point, then we are testing either:
1175
-                // all_reg_steps_completed_except() or
1176
-                // all_reg_steps_completed_except_final_step(),
1177
-                // and since this is the reg step EXCEPTION being tested
1178
-                // we want to return true (yes true) if this reg step is NOT completed
1179
-                // ie: "is everything completed except the final step?"
1180
-                // "that is correct... the final step is not completed, but all others are."
1181
-                return $reg_step_completed !== true;
1182
-            }
1183
-            if ($reg_step_completed !== true) {
1184
-                // if any reg step is NOT completed, then ALL steps are not completed
1185
-                return false;
1186
-            }
1187
-        }
1188
-        return true;
1189
-    }
1190
-
1191
-
1192
-
1193
-    /**
1194
-     * all_reg_steps_completed
1195
-     * returns:
1196
-     *    true if ALL reg steps have been marked as completed
1197
-     *        or false if any step is not completed
1198
-     *
1199
-     * @return bool
1200
-     * @throws EE_Error
1201
-     */
1202
-    public function all_reg_steps_completed()
1203
-    {
1204
-        return $this->_reg_steps_completed();
1205
-    }
1206
-
1207
-
1208
-
1209
-    /**
1210
-     * all_reg_steps_completed_except
1211
-     * returns:
1212
-     *        true if ALL reg steps, except a particular step that you wish to skip over, have been marked as completed
1213
-     *        or false if any other step is not completed
1214
-     *        or false if ALL steps are completed including the exception you are testing !!!
1215
-     *
1216
-     * @param string $exception
1217
-     * @return bool
1218
-     * @throws EE_Error
1219
-     */
1220
-    public function all_reg_steps_completed_except($exception = '')
1221
-    {
1222
-        return $this->_reg_steps_completed($exception);
1223
-    }
1224
-
1225
-
1226
-
1227
-    /**
1228
-     * all_reg_steps_completed_except
1229
-     * returns:
1230
-     *        true if ALL reg steps, except the final step, have been marked as completed
1231
-     *        or false if any step is not completed
1232
-     *    or false if ALL steps are completed including the final step !!!
1233
-     *
1234
-     * @return bool
1235
-     * @throws EE_Error
1236
-     */
1237
-    public function all_reg_steps_completed_except_final_step()
1238
-    {
1239
-        return $this->_reg_steps_completed('finalize_registration');
1240
-    }
1241
-
1242
-
1243
-
1244
-    /**
1245
-     * reg_step_completed
1246
-     * returns:
1247
-     *    true if a specific reg step has been marked as completed
1248
-     *    a Unix timestamp if it has been initialized but not yet completed,
1249
-     *    or false if it has not yet been initialized
1250
-     *
1251
-     * @param string $reg_step_slug
1252
-     * @return bool|int
1253
-     * @throws EE_Error
1254
-     */
1255
-    public function reg_step_completed($reg_step_slug)
1256
-    {
1257
-        return $this->_reg_steps_completed($reg_step_slug, false);
1258
-    }
1259
-
1260
-
1261
-
1262
-    /**
1263
-     * completed_final_reg_step
1264
-     * returns:
1265
-     *    true if the finalize_registration reg step has been marked as completed
1266
-     *    a Unix timestamp if it has been initialized but not yet completed,
1267
-     *    or false if it has not yet been initialized
1268
-     *
1269
-     * @return bool|int
1270
-     * @throws EE_Error
1271
-     */
1272
-    public function final_reg_step_completed()
1273
-    {
1274
-        return $this->_reg_steps_completed('finalize_registration', false);
1275
-    }
1276
-
1277
-
1278
-
1279
-    /**
1280
-     * set_reg_step_initiated
1281
-     * given a valid TXN_reg_step, this sets it's value to a unix timestamp
1282
-     *
1283
-     * @param string $reg_step_slug
1284
-     * @return boolean
1285
-     * @throws EE_Error
1286
-     */
1287
-    public function set_reg_step_initiated($reg_step_slug)
1288
-    {
1289
-        return $this->_set_reg_step_completed_status($reg_step_slug, time());
1290
-    }
1291
-
1292
-
1293
-
1294
-    /**
1295
-     * set_reg_step_completed
1296
-     * given a valid TXN_reg_step, this sets the step as completed
1297
-     *
1298
-     * @param string $reg_step_slug
1299
-     * @return boolean
1300
-     * @throws EE_Error
1301
-     */
1302
-    public function set_reg_step_completed($reg_step_slug)
1303
-    {
1304
-        return $this->_set_reg_step_completed_status($reg_step_slug, true);
1305
-    }
1306
-
1307
-
1308
-
1309
-    /**
1310
-     * set_reg_step_completed
1311
-     * given a valid TXN_reg_step slug, this sets the step as NOT completed
1312
-     *
1313
-     * @param string $reg_step_slug
1314
-     * @return boolean
1315
-     * @throws EE_Error
1316
-     */
1317
-    public function set_reg_step_not_completed($reg_step_slug)
1318
-    {
1319
-        return $this->_set_reg_step_completed_status($reg_step_slug, false);
1320
-    }
1321
-
1322
-
1323
-
1324
-    /**
1325
-     * set_reg_step_completed
1326
-     * given a valid reg step slug, this sets the TXN_reg_step completed status which is either:
1327
-     *
1328
-     * @param  string      $reg_step_slug
1329
-     * @param  boolean|int $status
1330
-     * @return boolean
1331
-     * @throws EE_Error
1332
-     */
1333
-    private function _set_reg_step_completed_status($reg_step_slug, $status)
1334
-    {
1335
-        // validate status
1336
-        $status = is_bool($status) || is_int($status) ? $status : false;
1337
-        // get reg steps array
1338
-        $txn_reg_steps = $this->reg_steps();
1339
-        // if reg step does NOT exist
1340
-        if (! isset($txn_reg_steps[$reg_step_slug])) {
1341
-            return false;
1342
-        }
1343
-        // if  we're trying to complete a step that is already completed
1344
-        if ($txn_reg_steps[$reg_step_slug] === true) {
1345
-            return true;
1346
-        }
1347
-        // if  we're trying to complete a step that hasn't even started
1348
-        if ($status === true && $txn_reg_steps[$reg_step_slug] === false) {
1349
-            return false;
1350
-        }
1351
-        // if current status value matches the incoming value (no change)
1352
-        // type casting as int means values should collapse to either 0, 1, or a timestamp like 1234567890
1353
-        if ((int)$txn_reg_steps[$reg_step_slug] === (int)$status) {
1354
-            // this will happen in cases where multiple AJAX requests occur during the same step
1355
-            return true;
1356
-        }
1357
-        // if we're trying to set a start time, but it has already been set...
1358
-        if (is_numeric($status) && is_numeric($txn_reg_steps[$reg_step_slug])) {
1359
-            // skip the update below, but don't return FALSE so that errors won't be displayed
1360
-            return true;
1361
-        }
1362
-        // update completed status
1363
-        $txn_reg_steps[$reg_step_slug] = $status;
1364
-        $this->set_reg_steps($txn_reg_steps);
1365
-        $this->save();
1366
-        return true;
1367
-    }
1368
-
1369
-
1370
-
1371
-    /**
1372
-     * remove_reg_step
1373
-     * given a valid TXN_reg_step slug, this will remove (unset)
1374
-     * the reg step from the TXN reg step array
1375
-     *
1376
-     * @param string $reg_step_slug
1377
-     * @return void
1378
-     * @throws EE_Error
1379
-     */
1380
-    public function remove_reg_step($reg_step_slug)
1381
-    {
1382
-        // get reg steps array
1383
-        $txn_reg_steps = $this->reg_steps();
1384
-        unset($txn_reg_steps[$reg_step_slug]);
1385
-        $this->set_reg_steps($txn_reg_steps);
1386
-    }
1387
-
1388
-
1389
-
1390
-    /**
1391
-     * toggle_failed_transaction_status
1392
-     * upgrades a TXNs status from failed to abandoned,
1393
-     * meaning that contact information has been captured for at least one registrant
1394
-     *
1395
-     * @param bool $save
1396
-     * @return bool
1397
-     * @throws EE_Error
1398
-     */
1399
-    public function toggle_failed_transaction_status($save = true)
1400
-    {
1401
-        // if TXN status is still set as "failed"...
1402
-        if ($this->status_ID() === EEM_Transaction::failed_status_code) {
1403
-            $this->set_status(EEM_Transaction::abandoned_status_code);
1404
-            if ($save) {
1405
-                $this->save();
1406
-            }
1407
-            return true;
1408
-        }
1409
-        return false;
1410
-    }
1411
-
1412
-
1413
-
1414
-    /**
1415
-     * toggle_abandoned_transaction_status
1416
-     * upgrades a TXNs status from failed or abandoned to incomplete
1417
-     *
1418
-     * @return bool
1419
-     * @throws EE_Error
1420
-     */
1421
-    public function toggle_abandoned_transaction_status()
1422
-    {
1423
-        // if TXN status has not been updated already due to a payment, and is still set as "failed" or "abandoned"...
1424
-        $txn_status = $this->status_ID();
1425
-        if (
1426
-            $txn_status === EEM_Transaction::failed_status_code
1427
-            || $txn_status === EEM_Transaction::abandoned_status_code
1428
-        ) {
1429
-            // if a contact record for the primary registrant has been created
1430
-            if (
1431
-                $this->primary_registration() instanceof EE_Registration
1432
-                && $this->primary_registration()->attendee() instanceof EE_Attendee
1433
-            ) {
1434
-                $this->set_status(EEM_Transaction::incomplete_status_code);
1435
-            } else {
1436
-                // no contact record? yer abandoned!
1437
-                $this->set_status(EEM_Transaction::abandoned_status_code);
1438
-            }
1439
-            return true;
1440
-        }
1441
-        return false;
1442
-    }
1443
-
1444
-
1445
-
1446
-    /**
1447
-     * checks if an Abandoned TXN has any related payments, and if so,
1448
-     * updates the TXN status based on the amount paid
1449
-     *
1450
-     * @throws EE_Error
1451
-     * @throws InvalidDataTypeException
1452
-     * @throws InvalidInterfaceException
1453
-     * @throws InvalidArgumentException
1454
-     * @throws RuntimeException
1455
-     */
1456
-    public function verify_abandoned_transaction_status()
1457
-    {
1458
-        if ($this->status_ID() !== EEM_Transaction::abandoned_status_code) {
1459
-            return;
1460
-        }
1461
-        $payments = $this->get_many_related('Payment');
1462
-        if (! empty($payments)) {
1463
-            foreach ($payments as $payment) {
1464
-                if ($payment instanceof EE_Payment) {
1465
-                    // kk this TXN should NOT be abandoned
1466
-                    $this->update_status_based_on_total_paid();
1467
-                    if (! (defined('DOING_AJAX') && DOING_AJAX) && is_admin()) {
1468
-                        EE_Error::add_attention(
1469
-                            sprintf(
1470
-                                esc_html__(
1471
-                                    'The status for Transaction #%1$d has been updated from "Abandoned" to "%2$s", because at least one payment has been made towards it. If the payment appears in the "Payment Details" table below, you may need to edit its status and/or other details as well.',
1472
-                                    'event_espresso'
1473
-                                ),
1474
-                                $this->ID(),
1475
-                                $this->pretty_status()
1476
-                            )
1477
-                        );
1478
-                    }
1479
-                    // get final reg step status
1480
-                    $finalized = $this->final_reg_step_completed();
1481
-                    // if the 'finalize_registration' step has been initiated (has a timestamp)
1482
-                    // but has not yet been fully completed (TRUE)
1483
-                    if (is_int($finalized) && $finalized !== false && $finalized !== true) {
1484
-                        $this->set_reg_step_completed('finalize_registration');
1485
-                        $this->save();
1486
-                    }
1487
-                }
1488
-            }
1489
-        }
1490
-    }
20
+	/**
21
+	 * The length of time in seconds that a lock is applied before being considered expired.
22
+	 * It is not long because a transaction should only be locked for the duration of the request that locked it
23
+	 */
24
+	const LOCK_EXPIRATION = 2;
25
+
26
+	/**
27
+	 * txn status upon initial construction.
28
+	 *
29
+	 * @var string
30
+	 */
31
+	protected $_old_txn_status;
32
+
33
+
34
+
35
+	/**
36
+	 * @param array  $props_n_values          incoming values
37
+	 * @param string $timezone                incoming timezone
38
+	 *                                        (if not set the timezone set for the website will be used.)
39
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
40
+	 *                                        date_format and the second value is the time format
41
+	 * @return EE_Transaction
42
+	 * @throws EE_Error
43
+	 */
44
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
45
+	{
46
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
47
+		$txn        = $has_object
48
+			? $has_object
49
+			: new self($props_n_values, false, $timezone, $date_formats);
50
+		if (! $has_object) {
51
+			$txn->set_old_txn_status($txn->status_ID());
52
+		}
53
+		return $txn;
54
+	}
55
+
56
+
57
+
58
+	/**
59
+	 * @param array  $props_n_values  incoming values from the database
60
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
61
+	 *                                the website will be used.
62
+	 * @return EE_Transaction
63
+	 * @throws EE_Error
64
+	 */
65
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null)
66
+	{
67
+		$txn = new self($props_n_values, true, $timezone);
68
+		$txn->set_old_txn_status($txn->status_ID());
69
+		return $txn;
70
+	}
71
+
72
+
73
+
74
+	/**
75
+	 * Sets a meta field indicating that this TXN is locked and should not be updated in the db.
76
+	 * If a lock has already been set, then we will attempt to remove it in case it has expired.
77
+	 * If that also fails, then an exception is thrown.
78
+	 *
79
+	 * @throws EE_Error
80
+	 */
81
+	public function lock()
82
+	{
83
+		// attempt to set lock, but if that fails...
84
+		if (! $this->add_extra_meta('lock', time(), true)) {
85
+			// then attempt to remove the lock in case it is expired
86
+			if ($this->_remove_expired_lock()) {
87
+				// if removal was successful, then try setting lock again
88
+				$this->lock();
89
+			} else {
90
+				// but if the lock can not be removed, then throw an exception
91
+				throw new EE_Error(
92
+					sprintf(
93
+						__(
94
+							'Could not lock Transaction %1$d because it is already locked, meaning another part of the system is currently editing it. It should already be unlocked by the time you read this, so please refresh the page and try again.',
95
+							'event_espresso'
96
+						),
97
+						$this->ID()
98
+					)
99
+				);
100
+			}
101
+		}
102
+	}
103
+
104
+
105
+
106
+	/**
107
+	 * removes transaction lock applied in EE_Transaction::lock()
108
+	 *
109
+	 * @return int
110
+	 * @throws EE_Error
111
+	 */
112
+	public function unlock()
113
+	{
114
+		return $this->delete_extra_meta('lock');
115
+	}
116
+
117
+
118
+
119
+	/**
120
+	 * Decides whether or not now is the right time to update the transaction.
121
+	 * This is useful because we don't always know if it is safe to update the transaction
122
+	 * and its related data. why?
123
+	 * because it's possible that the transaction is being used in another
124
+	 * request and could overwrite anything we save.
125
+	 * So we want to only update the txn once we know that won't happen.
126
+	 * We also check that the lock isn't expired, and remove it if it is
127
+	 *
128
+	 * @return boolean
129
+	 * @throws EE_Error
130
+	 */
131
+	public function is_locked()
132
+	{
133
+		// if TXN is not locked, then return false immediately
134
+		if (! $this->_get_lock()) {
135
+			return false;
136
+		}
137
+		// if not, then let's try and remove the lock in case it's expired...
138
+		// _remove_expired_lock() returns 0 when lock is valid (ie: removed = false)
139
+		// and a positive number if the lock was removed (ie: number of locks deleted),
140
+		// so we need to return the opposite
141
+		return ! $this->_remove_expired_lock() ? true : false;
142
+	}
143
+
144
+
145
+
146
+	/**
147
+	 * Gets the meta field indicating that this TXN is locked
148
+	 *
149
+	 * @return int
150
+	 * @throws EE_Error
151
+	 */
152
+	protected function _get_lock()
153
+	{
154
+		return (int)$this->get_extra_meta('lock', true, 0);
155
+	}
156
+
157
+
158
+
159
+	/**
160
+	 * If the lock on this transaction is expired, then we want to remove it so that the transaction can be updated
161
+	 *
162
+	 * @return int
163
+	 * @throws EE_Error
164
+	 */
165
+	protected function _remove_expired_lock()
166
+	{
167
+		$locked = $this->_get_lock();
168
+		if ($locked && time() - EE_Transaction::LOCK_EXPIRATION > $locked) {
169
+			return $this->unlock();
170
+		}
171
+		return 0;
172
+	}
173
+
174
+
175
+
176
+	/**
177
+	 * Set transaction total
178
+	 *
179
+	 * @param float $total total value of transaction
180
+	 * @throws EE_Error
181
+	 */
182
+	public function set_total($total = 0.00)
183
+	{
184
+		$this->set('TXN_total', (float)$total);
185
+	}
186
+
187
+
188
+
189
+	/**
190
+	 * Set Total Amount Paid to Date
191
+	 *
192
+	 * @param float $total_paid total amount paid to date (sum of all payments)
193
+	 * @throws EE_Error
194
+	 */
195
+	public function set_paid($total_paid = 0.00)
196
+	{
197
+		$this->set('TXN_paid', (float)$total_paid);
198
+	}
199
+
200
+
201
+
202
+	/**
203
+	 * Set transaction status
204
+	 *
205
+	 * @param string $status        whether the transaction is open, declined, accepted,
206
+	 *                              or any number of custom values that can be set
207
+	 * @throws EE_Error
208
+	 */
209
+	public function set_status($status = '')
210
+	{
211
+		$this->set('STS_ID', $status);
212
+	}
213
+
214
+
215
+
216
+	/**
217
+	 * Set hash salt
218
+	 *
219
+	 * @param string $hash_salt required for some payment gateways
220
+	 * @throws EE_Error
221
+	 */
222
+	public function set_hash_salt($hash_salt = '')
223
+	{
224
+		$this->set('TXN_hash_salt', $hash_salt);
225
+	}
226
+
227
+
228
+
229
+	/**
230
+	 * Sets TXN_reg_steps array
231
+	 *
232
+	 * @param array $txn_reg_steps
233
+	 * @throws EE_Error
234
+	 */
235
+	public function set_reg_steps(array $txn_reg_steps)
236
+	{
237
+		$this->set('TXN_reg_steps', $txn_reg_steps);
238
+	}
239
+
240
+
241
+
242
+	/**
243
+	 * Gets TXN_reg_steps
244
+	 *
245
+	 * @return array
246
+	 * @throws EE_Error
247
+	 */
248
+	public function reg_steps()
249
+	{
250
+		$TXN_reg_steps = $this->get('TXN_reg_steps');
251
+		return is_array($TXN_reg_steps) ? (array)$TXN_reg_steps : array();
252
+	}
253
+
254
+
255
+
256
+	/**
257
+	 * @return string of transaction's total cost, with currency symbol and decimal
258
+	 * @throws EE_Error
259
+	 */
260
+	public function pretty_total()
261
+	{
262
+		return $this->get_pretty('TXN_total');
263
+	}
264
+
265
+
266
+
267
+	/**
268
+	 * Gets the amount paid in a pretty string (formatted and with currency symbol)
269
+	 *
270
+	 * @return string
271
+	 * @throws EE_Error
272
+	 */
273
+	public function pretty_paid()
274
+	{
275
+		return $this->get_pretty('TXN_paid');
276
+	}
277
+
278
+
279
+
280
+	/**
281
+	 * calculate the amount remaining for this transaction and return;
282
+	 *
283
+	 * @return float amount remaining
284
+	 * @throws EE_Error
285
+	 */
286
+	public function remaining()
287
+	{
288
+		return $this->total() - $this->paid();
289
+	}
290
+
291
+
292
+
293
+	/**
294
+	 * get Transaction Total
295
+	 *
296
+	 * @return float
297
+	 * @throws EE_Error
298
+	 */
299
+	public function total()
300
+	{
301
+		return (float)$this->get('TXN_total');
302
+	}
303
+
304
+
305
+
306
+	/**
307
+	 * get Total Amount Paid to Date
308
+	 *
309
+	 * @return float
310
+	 * @throws EE_Error
311
+	 */
312
+	public function paid()
313
+	{
314
+		return (float)$this->get('TXN_paid');
315
+	}
316
+
317
+
318
+
319
+	/**
320
+	 * @throws EE_Error
321
+	 */
322
+	public function get_cart_session()
323
+	{
324
+		$session_data = (array)$this->get('TXN_session_data');
325
+		return isset($session_data['cart']) && $session_data['cart'] instanceof EE_Cart
326
+			? $session_data['cart']
327
+			: null;
328
+	}
329
+
330
+
331
+
332
+	/**
333
+	 * get Transaction session data
334
+	 *
335
+	 * @throws EE_Error
336
+	 */
337
+	public function session_data()
338
+	{
339
+		$session_data = $this->get('TXN_session_data');
340
+		if (empty($session_data)) {
341
+			$session_data = array(
342
+				'id'            => null,
343
+				'user_id'       => null,
344
+				'ip_address'    => null,
345
+				'user_agent'    => null,
346
+				'init_access'   => null,
347
+				'last_access'   => null,
348
+				'pages_visited' => array(),
349
+			);
350
+		}
351
+		return $session_data;
352
+	}
353
+
354
+
355
+
356
+	/**
357
+	 * Set session data within the TXN object
358
+	 *
359
+	 * @param EE_Session|array $session_data
360
+	 * @throws EE_Error
361
+	 */
362
+	public function set_txn_session_data($session_data)
363
+	{
364
+		if ($session_data instanceof EE_Session) {
365
+			$this->set('TXN_session_data', $session_data->get_session_data(null, true));
366
+		} else {
367
+			$this->set('TXN_session_data', $session_data);
368
+		}
369
+	}
370
+
371
+
372
+
373
+	/**
374
+	 * get Transaction hash salt
375
+	 *
376
+	 * @throws EE_Error
377
+	 */
378
+	public function hash_salt_()
379
+	{
380
+		return $this->get('TXN_hash_salt');
381
+	}
382
+
383
+
384
+
385
+	/**
386
+	 * Returns the transaction datetime as either:
387
+	 *            - unix timestamp format ($format = false, $gmt = true)
388
+	 *            - formatted date string including the UTC (timezone) offset ($format = true ($gmt
389
+	 *              has no affect with this option)), this also may include a timezone abbreviation if the
390
+	 *              set timezone in this class differs from what the timezone is on the blog.
391
+	 *            - formatted date string including the UTC (timezone) offset (default).
392
+	 *
393
+	 * @param boolean $format - whether to return a unix timestamp (default) or formatted date string
394
+	 * @param boolean $gmt    - whether to return a unix timestamp with UTC offset applied (default)
395
+	 *                          or no UTC offset applied
396
+	 * @return string | int
397
+	 * @throws EE_Error
398
+	 */
399
+	public function datetime($format = false, $gmt = false)
400
+	{
401
+		if ($format) {
402
+			return $this->get_pretty('TXN_timestamp');
403
+		}
404
+		if ($gmt) {
405
+			return $this->get_raw('TXN_timestamp');
406
+		}
407
+		return $this->get('TXN_timestamp');
408
+	}
409
+
410
+
411
+
412
+	/**
413
+	 * Gets registrations on this transaction
414
+	 *
415
+	 * @param array   $query_params array of query parameters
416
+	 * @param boolean $get_cached   TRUE to retrieve cached registrations or FALSE to pull from the db
417
+	 * @return EE_Base_Class[]|EE_Registration[]
418
+	 * @throws EE_Error
419
+	 */
420
+	public function registrations($query_params = array(), $get_cached = false)
421
+	{
422
+		$query_params = (empty($query_params) || ! is_array($query_params))
423
+			? array(
424
+				'order_by' => array(
425
+					'Event.EVT_name'     => 'ASC',
426
+					'Attendee.ATT_lname' => 'ASC',
427
+					'Attendee.ATT_fname' => 'ASC',
428
+				),
429
+			)
430
+			: $query_params;
431
+		$query_params = $get_cached ? array() : $query_params;
432
+		return $this->get_many_related('Registration', $query_params);
433
+	}
434
+
435
+
436
+
437
+	/**
438
+	 * Gets all the attendees for this transaction (handy for use with EE_Attendee's get_registrations_for_event
439
+	 * function for getting attendees and how many registrations they each have for an event)
440
+	 *
441
+	 * @return mixed EE_Attendee[] by default, int if $output is set to 'COUNT'
442
+	 * @throws EE_Error
443
+	 */
444
+	public function attendees()
445
+	{
446
+		return $this->get_many_related('Attendee', array(array('Registration.Transaction.TXN_ID' => $this->ID())));
447
+	}
448
+
449
+
450
+
451
+	/**
452
+	 * Gets payments for this transaction. Unlike other such functions, order by 'DESC' by default
453
+	 *
454
+	 * @param array $query_params like EEM_Base::get_all
455
+	 * @return EE_Base_Class[]|EE_Payment[]
456
+	 * @throws EE_Error
457
+	 */
458
+	public function payments($query_params = array())
459
+	{
460
+		return $this->get_many_related('Payment', $query_params);
461
+	}
462
+
463
+
464
+
465
+	/**
466
+	 * gets only approved payments for this transaction
467
+	 *
468
+	 * @return EE_Base_Class[]|EE_Payment[]
469
+	 * @throws EE_Error
470
+	 * @throws InvalidArgumentException
471
+	 * @throws ReflectionException
472
+	 * @throws InvalidDataTypeException
473
+	 * @throws InvalidInterfaceException
474
+	 */
475
+	public function approved_payments()
476
+	{
477
+		EE_Registry::instance()->load_model('Payment');
478
+		return $this->get_many_related(
479
+			'Payment',
480
+			array(
481
+				array('STS_ID' => EEM_Payment::status_id_approved),
482
+				'order_by' => array('PAY_timestamp' => 'DESC'),
483
+			)
484
+		);
485
+	}
486
+
487
+
488
+
489
+	/**
490
+	 * Gets all payments which have not been approved
491
+	 *
492
+	 * @return EE_Base_Class[]|EEI_Payment[]
493
+	 * @throws EE_Error if a model is misconfigured somehow
494
+	 */
495
+	public function pending_payments()
496
+	{
497
+		return $this->get_many_related(
498
+			'Payment',
499
+			array(
500
+				array(
501
+					'STS_ID' => EEM_Payment::status_id_pending,
502
+				),
503
+				'order_by' => array(
504
+					'PAY_timestamp' => 'DESC',
505
+				),
506
+			)
507
+		);
508
+	}
509
+
510
+
511
+
512
+	/**
513
+	 * echoes $this->pretty_status()
514
+	 *
515
+	 * @param bool $show_icons
516
+	 * @throws EE_Error
517
+	 * @throws InvalidArgumentException
518
+	 * @throws InvalidDataTypeException
519
+	 * @throws InvalidInterfaceException
520
+	 */
521
+	public function e_pretty_status($show_icons = false)
522
+	{
523
+		echo $this->pretty_status($show_icons);
524
+	}
525
+
526
+
527
+
528
+	/**
529
+	 * returns a pretty version of the status, good for displaying to users
530
+	 *
531
+	 * @param bool $show_icons
532
+	 * @return string
533
+	 * @throws EE_Error
534
+	 * @throws InvalidArgumentException
535
+	 * @throws InvalidDataTypeException
536
+	 * @throws InvalidInterfaceException
537
+	 */
538
+	public function pretty_status($show_icons = false)
539
+	{
540
+		$status = EEM_Status::instance()->localized_status(
541
+			array($this->status_ID() => __('unknown', 'event_espresso')),
542
+			false,
543
+			'sentence'
544
+		);
545
+		$icon   = '';
546
+		switch ($this->status_ID()) {
547
+			case EEM_Transaction::complete_status_code:
548
+				$icon = $show_icons ? '<span class="dashicons dashicons-yes ee-icon-size-24 green-text"></span>' : '';
549
+				break;
550
+			case EEM_Transaction::incomplete_status_code:
551
+				$icon = $show_icons ? '<span class="dashicons dashicons-marker ee-icon-size-16 lt-blue-text"></span>'
552
+					: '';
553
+				break;
554
+			case EEM_Transaction::abandoned_status_code:
555
+				$icon = $show_icons ? '<span class="dashicons dashicons-marker ee-icon-size-16 red-text"></span>' : '';
556
+				break;
557
+			case EEM_Transaction::failed_status_code:
558
+				$icon = $show_icons ? '<span class="dashicons dashicons-no ee-icon-size-16 red-text"></span>' : '';
559
+				break;
560
+			case EEM_Transaction::overpaid_status_code:
561
+				$icon = $show_icons ? '<span class="dashicons dashicons-plus ee-icon-size-16 orange-text"></span>' : '';
562
+				break;
563
+		}
564
+		return $icon . $status[$this->status_ID()];
565
+	}
566
+
567
+
568
+
569
+	/**
570
+	 * get Transaction Status
571
+	 *
572
+	 * @throws EE_Error
573
+	 */
574
+	public function status_ID()
575
+	{
576
+		return $this->get('STS_ID');
577
+	}
578
+
579
+
580
+
581
+	/**
582
+	 * Returns TRUE or FALSE for whether or not this transaction cost any money
583
+	 *
584
+	 * @return boolean
585
+	 * @throws EE_Error
586
+	 */
587
+	public function is_free()
588
+	{
589
+		return EEH_Money::compare_floats($this->get('TXN_total'), 0, '==');
590
+	}
591
+
592
+
593
+
594
+	/**
595
+	 * Returns whether this transaction is complete
596
+	 * Useful in templates and other logic for deciding if we should ask for another payment...
597
+	 *
598
+	 * @return boolean
599
+	 * @throws EE_Error
600
+	 */
601
+	public function is_completed()
602
+	{
603
+		return $this->status_ID() === EEM_Transaction::complete_status_code;
604
+	}
605
+
606
+
607
+
608
+	/**
609
+	 * Returns whether this transaction is incomplete
610
+	 * Useful in templates and other logic for deciding if we should ask for another payment...
611
+	 *
612
+	 * @return boolean
613
+	 * @throws EE_Error
614
+	 */
615
+	public function is_incomplete()
616
+	{
617
+		return $this->status_ID() === EEM_Transaction::incomplete_status_code;
618
+	}
619
+
620
+
621
+
622
+	/**
623
+	 * Returns whether this transaction is overpaid
624
+	 * Useful in templates and other logic for deciding if monies need to be refunded
625
+	 *
626
+	 * @return boolean
627
+	 * @throws EE_Error
628
+	 */
629
+	public function is_overpaid()
630
+	{
631
+		return $this->status_ID() === EEM_Transaction::overpaid_status_code;
632
+	}
633
+
634
+
635
+
636
+	/**
637
+	 * Returns whether this transaction was abandoned
638
+	 * meaning that the transaction/registration process was somehow interrupted and never completed
639
+	 * but that contact information exists for at least one registrant
640
+	 *
641
+	 * @return boolean
642
+	 * @throws EE_Error
643
+	 */
644
+	public function is_abandoned()
645
+	{
646
+		return $this->status_ID() === EEM_Transaction::abandoned_status_code;
647
+	}
648
+
649
+
650
+
651
+	/**
652
+	 * Returns whether this transaction failed
653
+	 * meaning that the transaction/registration process was somehow interrupted and never completed
654
+	 * and that NO contact information exists for any registrants
655
+	 *
656
+	 * @return boolean
657
+	 * @throws EE_Error
658
+	 */
659
+	public function failed()
660
+	{
661
+		return $this->status_ID() === EEM_Transaction::failed_status_code;
662
+	}
663
+
664
+
665
+
666
+	/**
667
+	 * This returns the url for the invoice of this transaction
668
+	 *
669
+	 * @param string $type 'html' or 'pdf' (default is pdf)
670
+	 * @return string
671
+	 * @throws EE_Error
672
+	 */
673
+	public function invoice_url($type = 'html')
674
+	{
675
+		$REG = $this->primary_registration();
676
+		if (! $REG instanceof EE_Registration) {
677
+			return '';
678
+		}
679
+		return $REG->invoice_url($type);
680
+	}
681
+
682
+
683
+
684
+	/**
685
+	 * Gets the primary registration only
686
+	 *
687
+	 * @return EE_Base_Class|EE_Registration
688
+	 * @throws EE_Error
689
+	 */
690
+	public function primary_registration()
691
+	{
692
+		$registrations = (array)$this->get_many_related(
693
+			'Registration',
694
+			array(array('REG_count' => EEM_Registration::PRIMARY_REGISTRANT_COUNT))
695
+		);
696
+		foreach ($registrations as $registration) {
697
+			// valid registration that is NOT cancelled or declined ?
698
+			if (
699
+				$registration instanceof EE_Registration
700
+				&& ! in_array($registration->status_ID(), EEM_Registration::closed_reg_statuses(), true)
701
+			) {
702
+				return $registration;
703
+			}
704
+		}
705
+		// nothing valid found, so just return first thing from array of results
706
+		return reset($registrations);
707
+	}
708
+
709
+
710
+
711
+	/**
712
+	 * Gets the URL for viewing the receipt
713
+	 *
714
+	 * @param string $type 'pdf' or 'html' (default is 'html')
715
+	 * @return string
716
+	 * @throws EE_Error
717
+	 */
718
+	public function receipt_url($type = 'html')
719
+	{
720
+		$REG = $this->primary_registration();
721
+		if (! $REG instanceof EE_Registration) {
722
+			return '';
723
+		}
724
+		return $REG->receipt_url($type);
725
+	}
726
+
727
+
728
+
729
+	/**
730
+	 * Gets the URL of the thank you page with this registration REG_url_link added as
731
+	 * a query parameter
732
+	 *
733
+	 * @return string
734
+	 * @throws EE_Error
735
+	 */
736
+	public function payment_overview_url()
737
+	{
738
+		$primary_registration = $this->primary_registration();
739
+		return $primary_registration instanceof EE_Registration ? $primary_registration->payment_overview_url() : false;
740
+	}
741
+
742
+
743
+
744
+	/**
745
+	 * @return string
746
+	 * @throws EE_Error
747
+	 */
748
+	public function gateway_response_on_transaction()
749
+	{
750
+		$payment = $this->get_first_related('Payment');
751
+		return $payment instanceof EE_Payment ? $payment->gateway_response() : '';
752
+	}
753
+
754
+
755
+
756
+	/**
757
+	 * Get the status object of this object
758
+	 *
759
+	 * @return EE_Base_Class|EE_Status
760
+	 * @throws EE_Error
761
+	 */
762
+	public function status_obj()
763
+	{
764
+		return $this->get_first_related('Status');
765
+	}
766
+
767
+
768
+
769
+	/**
770
+	 * Gets all the extra meta info on this payment
771
+	 *
772
+	 * @param array $query_params like EEM_Base::get_all
773
+	 * @return EE_Base_Class[]|EE_Extra_Meta
774
+	 * @throws EE_Error
775
+	 */
776
+	public function extra_meta($query_params = array())
777
+	{
778
+		return $this->get_many_related('Extra_Meta', $query_params);
779
+	}
780
+
781
+
782
+
783
+	/**
784
+	 * Wrapper for _add_relation_to
785
+	 *
786
+	 * @param EE_Registration $registration
787
+	 * @return EE_Base_Class the relation was added to
788
+	 * @throws EE_Error
789
+	 */
790
+	public function add_registration(EE_Registration $registration)
791
+	{
792
+		return $this->_add_relation_to($registration, 'Registration');
793
+	}
794
+
795
+
796
+
797
+	/**
798
+	 * Removes the given registration from being related (even before saving this transaction).
799
+	 * If an ID/index is provided and this transaction isn't saved yet, removes it from list of cached relations
800
+	 *
801
+	 * @param int $registration_or_id
802
+	 * @return EE_Base_Class that was removed from being related
803
+	 * @throws EE_Error
804
+	 */
805
+	public function remove_registration_with_id($registration_or_id)
806
+	{
807
+		return $this->_remove_relation_to($registration_or_id, 'Registration');
808
+	}
809
+
810
+
811
+
812
+	/**
813
+	 * Gets all the line items which are for ACTUAL items
814
+	 *
815
+	 * @return EE_Line_Item[]
816
+	 * @throws EE_Error
817
+	 */
818
+	public function items_purchased()
819
+	{
820
+		return $this->line_items(array(array('LIN_type' => EEM_Line_Item::type_line_item)));
821
+	}
822
+
823
+
824
+
825
+	/**
826
+	 * Wrapper for _add_relation_to
827
+	 *
828
+	 * @param EE_Line_Item $line_item
829
+	 * @return EE_Base_Class the relation was added to
830
+	 * @throws EE_Error
831
+	 */
832
+	public function add_line_item(EE_Line_Item $line_item)
833
+	{
834
+		return $this->_add_relation_to($line_item, 'Line_Item');
835
+	}
836
+
837
+
838
+
839
+	/**
840
+	 * Gets ALL the line items related to this transaction (unstructured)
841
+	 *
842
+	 * @param array $query_params
843
+	 * @return EE_Base_Class[]|EE_Line_Item[]
844
+	 * @throws EE_Error
845
+	 */
846
+	public function line_items($query_params = array())
847
+	{
848
+		return $this->get_many_related('Line_Item', $query_params);
849
+	}
850
+
851
+
852
+
853
+	/**
854
+	 * Gets all the line items which are taxes on the total
855
+	 *
856
+	 * @return EE_Line_Item[]
857
+	 * @throws EE_Error
858
+	 */
859
+	public function tax_items()
860
+	{
861
+		return $this->line_items(array(array('LIN_type' => EEM_Line_Item::type_tax)));
862
+	}
863
+
864
+
865
+
866
+	/**
867
+	 * Gets the total line item (which is a parent of all other related line items,
868
+	 * meaning it takes them all into account on its total)
869
+	 *
870
+	 * @param bool $create_if_not_found
871
+	 * @return \EE_Line_Item
872
+	 * @throws EE_Error
873
+	 */
874
+	public function total_line_item($create_if_not_found = true)
875
+	{
876
+		$item = $this->get_first_related('Line_Item', array(array('LIN_type' => EEM_Line_Item::type_total)));
877
+		if (! $item && $create_if_not_found) {
878
+			$item = EEH_Line_Item::create_total_line_item($this);
879
+		}
880
+		return $item;
881
+	}
882
+
883
+
884
+
885
+	/**
886
+	 * Returns the total amount of tax on this transaction
887
+	 * (assumes there's only one tax subtotal line item)
888
+	 *
889
+	 * @return float
890
+	 * @throws EE_Error
891
+	 */
892
+	public function tax_total()
893
+	{
894
+		$tax_line_item = $this->tax_total_line_item();
895
+		if ($tax_line_item) {
896
+			return (float)$tax_line_item->total();
897
+		}
898
+		return (float)0;
899
+	}
900
+
901
+
902
+
903
+	/**
904
+	 * Gets the tax subtotal line item (assumes there's only one)
905
+	 *
906
+	 * @return EE_Line_Item
907
+	 * @throws EE_Error
908
+	 */
909
+	public function tax_total_line_item()
910
+	{
911
+		return EEH_Line_Item::get_taxes_subtotal($this->total_line_item());
912
+	}
913
+
914
+
915
+
916
+	/**
917
+	 * Gets the array of billing info for the gateway and for this transaction's primary registration's attendee.
918
+	 *
919
+	 * @return EE_Form_Section_Proper
920
+	 * @throws EE_Error
921
+	 */
922
+	public function billing_info()
923
+	{
924
+		$payment_method = $this->payment_method();
925
+		if (! $payment_method) {
926
+			EE_Error::add_error(
927
+				__(
928
+					'Could not find billing info for transaction because no gateway has been used for it yet',
929
+					'event_espresso'
930
+				),
931
+				__FILE__,
932
+				__FUNCTION__,
933
+				__LINE__
934
+			);
935
+			return null;
936
+		}
937
+		$primary_reg = $this->primary_registration();
938
+		if (! $primary_reg) {
939
+			EE_Error::add_error(
940
+				__(
941
+					'Cannot get billing info for gateway %s on transaction because no primary registration exists',
942
+					'event_espresso'
943
+				),
944
+				__FILE__,
945
+				__FUNCTION__,
946
+				__LINE__
947
+			);
948
+			return null;
949
+		}
950
+		$attendee = $primary_reg->attendee();
951
+		if (! $attendee) {
952
+			EE_Error::add_error(
953
+				__(
954
+					'Cannot get billing info for gateway %s on transaction because the primary registration has no attendee exists',
955
+					'event_espresso'
956
+				),
957
+				__FILE__,
958
+				__FUNCTION__,
959
+				__LINE__
960
+			);
961
+			return null;
962
+		}
963
+		return $attendee->billing_info_for_payment_method($payment_method);
964
+	}
965
+
966
+
967
+
968
+	/**
969
+	 * Gets PMD_ID
970
+	 *
971
+	 * @return int
972
+	 * @throws EE_Error
973
+	 */
974
+	public function payment_method_ID()
975
+	{
976
+		return $this->get('PMD_ID');
977
+	}
978
+
979
+
980
+
981
+	/**
982
+	 * Sets PMD_ID
983
+	 *
984
+	 * @param int $PMD_ID
985
+	 * @throws EE_Error
986
+	 */
987
+	public function set_payment_method_ID($PMD_ID)
988
+	{
989
+		$this->set('PMD_ID', $PMD_ID);
990
+	}
991
+
992
+
993
+
994
+	/**
995
+	 * Gets the last-used payment method on this transaction
996
+	 * (we COULD just use the last-made payment, but some payment methods, namely
997
+	 * offline ones, dont' create payments)
998
+	 *
999
+	 * @return EE_Payment_Method
1000
+	 * @throws EE_Error
1001
+	 */
1002
+	public function payment_method()
1003
+	{
1004
+		$pm = $this->get_first_related('Payment_Method');
1005
+		if ($pm instanceof EE_Payment_Method) {
1006
+			return $pm;
1007
+		}
1008
+		$last_payment = $this->last_payment();
1009
+		if ($last_payment instanceof EE_Payment && $last_payment->payment_method()) {
1010
+			return $last_payment->payment_method();
1011
+		}
1012
+		return null;
1013
+	}
1014
+
1015
+
1016
+
1017
+	/**
1018
+	 * Gets the last payment made
1019
+	 *
1020
+	 * @return EE_Base_Class|EE_Payment
1021
+	 * @throws EE_Error
1022
+	 */
1023
+	public function last_payment()
1024
+	{
1025
+		return $this->get_first_related('Payment', array('order_by' => array('PAY_ID' => 'desc')));
1026
+	}
1027
+
1028
+
1029
+
1030
+	/**
1031
+	 * Gets all the line items which are unrelated to tickets on this transaction
1032
+	 *
1033
+	 * @return EE_Line_Item[]
1034
+	 * @throws EE_Error
1035
+	 * @throws InvalidArgumentException
1036
+	 * @throws InvalidDataTypeException
1037
+	 * @throws InvalidInterfaceException
1038
+	 */
1039
+	public function non_ticket_line_items()
1040
+	{
1041
+		return EEM_Line_Item::instance()->get_all_non_ticket_line_items_for_transaction($this->ID());
1042
+	}
1043
+
1044
+
1045
+
1046
+	/**
1047
+	 * possibly toggles TXN status
1048
+	 *
1049
+	 * @param  boolean $update whether to save the TXN
1050
+	 * @return bool whether the TXN was saved
1051
+	 * @throws EE_Error
1052
+	 * @throws RuntimeException
1053
+	 */
1054
+	public function update_status_based_on_total_paid($update = true)
1055
+	{
1056
+		// set transaction status based on comparison of TXN_paid vs TXN_total
1057
+		if (EEH_Money::compare_floats($this->paid(), $this->total(), '>')) {
1058
+			$new_txn_status = EEM_Transaction::overpaid_status_code;
1059
+		} elseif (EEH_Money::compare_floats($this->paid(), $this->total())) {
1060
+			$new_txn_status = EEM_Transaction::complete_status_code;
1061
+		} elseif (EEH_Money::compare_floats($this->paid(), $this->total(), '<')) {
1062
+			$new_txn_status = EEM_Transaction::incomplete_status_code;
1063
+		} else {
1064
+			throw new RuntimeException(
1065
+				__('The total paid calculation for this transaction is inaccurate.', 'event_espresso')
1066
+			);
1067
+		}
1068
+		if ($new_txn_status !== $this->status_ID()) {
1069
+			$this->set_status($new_txn_status);
1070
+			if ($update) {
1071
+				return $this->save() ? true : false;
1072
+			}
1073
+		}
1074
+		return false;
1075
+	}
1076
+
1077
+
1078
+
1079
+	/**
1080
+	 * Updates the transaction's status and total_paid based on all the payments
1081
+	 * that apply to it
1082
+	 *
1083
+	 * @deprecated
1084
+	 * @return array|bool
1085
+	 * @throws EE_Error
1086
+	 * @throws InvalidArgumentException
1087
+	 * @throws ReflectionException
1088
+	 * @throws InvalidDataTypeException
1089
+	 * @throws InvalidInterfaceException
1090
+	 */
1091
+	public function update_based_on_payments()
1092
+	{
1093
+		EE_Error::doing_it_wrong(
1094
+			__CLASS__ . '::' . __FUNCTION__,
1095
+			sprintf(
1096
+				__('This method is deprecated. Please use "%s" instead', 'event_espresso'),
1097
+				'EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()'
1098
+			),
1099
+			'4.6.0'
1100
+		);
1101
+		/** @type EE_Transaction_Processor $transaction_processor */
1102
+		$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
1103
+		return $transaction_processor->update_transaction_and_registrations_after_checkout_or_payment($this);
1104
+	}
1105
+
1106
+
1107
+
1108
+	/**
1109
+	 * @return string
1110
+	 */
1111
+	public function old_txn_status()
1112
+	{
1113
+		return $this->_old_txn_status;
1114
+	}
1115
+
1116
+
1117
+
1118
+	/**
1119
+	 * @param string $old_txn_status
1120
+	 */
1121
+	public function set_old_txn_status($old_txn_status)
1122
+	{
1123
+		// only set the first time
1124
+		if ($this->_old_txn_status === null) {
1125
+			$this->_old_txn_status = $old_txn_status;
1126
+		}
1127
+	}
1128
+
1129
+
1130
+
1131
+	/**
1132
+	 * reg_status_updated
1133
+	 *
1134
+	 * @return bool
1135
+	 * @throws EE_Error
1136
+	 */
1137
+	public function txn_status_updated()
1138
+	{
1139
+		return $this->status_ID() !== $this->_old_txn_status && $this->_old_txn_status !== null;
1140
+	}
1141
+
1142
+
1143
+
1144
+	/**
1145
+	 * _reg_steps_completed
1146
+	 * if $check_all is TRUE, then returns TRUE if ALL reg steps have been marked as completed,
1147
+	 * if a $reg_step_slug is provided, then this step will be skipped when testing for completion
1148
+	 * if $check_all is FALSE and a $reg_step_slug is provided, then ONLY that reg step will be tested for completion
1149
+	 *
1150
+	 * @param string $reg_step_slug
1151
+	 * @param bool   $check_all
1152
+	 * @return bool|int
1153
+	 * @throws EE_Error
1154
+	 */
1155
+	private function _reg_steps_completed($reg_step_slug = '', $check_all = true)
1156
+	{
1157
+		$reg_steps = $this->reg_steps();
1158
+		if (! is_array($reg_steps) || empty($reg_steps)) {
1159
+			return false;
1160
+		}
1161
+		// loop thru reg steps array)
1162
+		foreach ($reg_steps as $slug => $reg_step_completed) {
1163
+			// if NOT checking ALL steps (only checking one step)
1164
+			if (! $check_all) {
1165
+				// and this is the one
1166
+				if ($slug === $reg_step_slug) {
1167
+					return $reg_step_completed;
1168
+				}
1169
+				// skip to next reg step in loop
1170
+				continue;
1171
+			}
1172
+			// $check_all must be true, else we would never have gotten to this point
1173
+			if ($slug === $reg_step_slug) {
1174
+				// if we reach this point, then we are testing either:
1175
+				// all_reg_steps_completed_except() or
1176
+				// all_reg_steps_completed_except_final_step(),
1177
+				// and since this is the reg step EXCEPTION being tested
1178
+				// we want to return true (yes true) if this reg step is NOT completed
1179
+				// ie: "is everything completed except the final step?"
1180
+				// "that is correct... the final step is not completed, but all others are."
1181
+				return $reg_step_completed !== true;
1182
+			}
1183
+			if ($reg_step_completed !== true) {
1184
+				// if any reg step is NOT completed, then ALL steps are not completed
1185
+				return false;
1186
+			}
1187
+		}
1188
+		return true;
1189
+	}
1190
+
1191
+
1192
+
1193
+	/**
1194
+	 * all_reg_steps_completed
1195
+	 * returns:
1196
+	 *    true if ALL reg steps have been marked as completed
1197
+	 *        or false if any step is not completed
1198
+	 *
1199
+	 * @return bool
1200
+	 * @throws EE_Error
1201
+	 */
1202
+	public function all_reg_steps_completed()
1203
+	{
1204
+		return $this->_reg_steps_completed();
1205
+	}
1206
+
1207
+
1208
+
1209
+	/**
1210
+	 * all_reg_steps_completed_except
1211
+	 * returns:
1212
+	 *        true if ALL reg steps, except a particular step that you wish to skip over, have been marked as completed
1213
+	 *        or false if any other step is not completed
1214
+	 *        or false if ALL steps are completed including the exception you are testing !!!
1215
+	 *
1216
+	 * @param string $exception
1217
+	 * @return bool
1218
+	 * @throws EE_Error
1219
+	 */
1220
+	public function all_reg_steps_completed_except($exception = '')
1221
+	{
1222
+		return $this->_reg_steps_completed($exception);
1223
+	}
1224
+
1225
+
1226
+
1227
+	/**
1228
+	 * all_reg_steps_completed_except
1229
+	 * returns:
1230
+	 *        true if ALL reg steps, except the final step, have been marked as completed
1231
+	 *        or false if any step is not completed
1232
+	 *    or false if ALL steps are completed including the final step !!!
1233
+	 *
1234
+	 * @return bool
1235
+	 * @throws EE_Error
1236
+	 */
1237
+	public function all_reg_steps_completed_except_final_step()
1238
+	{
1239
+		return $this->_reg_steps_completed('finalize_registration');
1240
+	}
1241
+
1242
+
1243
+
1244
+	/**
1245
+	 * reg_step_completed
1246
+	 * returns:
1247
+	 *    true if a specific reg step has been marked as completed
1248
+	 *    a Unix timestamp if it has been initialized but not yet completed,
1249
+	 *    or false if it has not yet been initialized
1250
+	 *
1251
+	 * @param string $reg_step_slug
1252
+	 * @return bool|int
1253
+	 * @throws EE_Error
1254
+	 */
1255
+	public function reg_step_completed($reg_step_slug)
1256
+	{
1257
+		return $this->_reg_steps_completed($reg_step_slug, false);
1258
+	}
1259
+
1260
+
1261
+
1262
+	/**
1263
+	 * completed_final_reg_step
1264
+	 * returns:
1265
+	 *    true if the finalize_registration reg step has been marked as completed
1266
+	 *    a Unix timestamp if it has been initialized but not yet completed,
1267
+	 *    or false if it has not yet been initialized
1268
+	 *
1269
+	 * @return bool|int
1270
+	 * @throws EE_Error
1271
+	 */
1272
+	public function final_reg_step_completed()
1273
+	{
1274
+		return $this->_reg_steps_completed('finalize_registration', false);
1275
+	}
1276
+
1277
+
1278
+
1279
+	/**
1280
+	 * set_reg_step_initiated
1281
+	 * given a valid TXN_reg_step, this sets it's value to a unix timestamp
1282
+	 *
1283
+	 * @param string $reg_step_slug
1284
+	 * @return boolean
1285
+	 * @throws EE_Error
1286
+	 */
1287
+	public function set_reg_step_initiated($reg_step_slug)
1288
+	{
1289
+		return $this->_set_reg_step_completed_status($reg_step_slug, time());
1290
+	}
1291
+
1292
+
1293
+
1294
+	/**
1295
+	 * set_reg_step_completed
1296
+	 * given a valid TXN_reg_step, this sets the step as completed
1297
+	 *
1298
+	 * @param string $reg_step_slug
1299
+	 * @return boolean
1300
+	 * @throws EE_Error
1301
+	 */
1302
+	public function set_reg_step_completed($reg_step_slug)
1303
+	{
1304
+		return $this->_set_reg_step_completed_status($reg_step_slug, true);
1305
+	}
1306
+
1307
+
1308
+
1309
+	/**
1310
+	 * set_reg_step_completed
1311
+	 * given a valid TXN_reg_step slug, this sets the step as NOT completed
1312
+	 *
1313
+	 * @param string $reg_step_slug
1314
+	 * @return boolean
1315
+	 * @throws EE_Error
1316
+	 */
1317
+	public function set_reg_step_not_completed($reg_step_slug)
1318
+	{
1319
+		return $this->_set_reg_step_completed_status($reg_step_slug, false);
1320
+	}
1321
+
1322
+
1323
+
1324
+	/**
1325
+	 * set_reg_step_completed
1326
+	 * given a valid reg step slug, this sets the TXN_reg_step completed status which is either:
1327
+	 *
1328
+	 * @param  string      $reg_step_slug
1329
+	 * @param  boolean|int $status
1330
+	 * @return boolean
1331
+	 * @throws EE_Error
1332
+	 */
1333
+	private function _set_reg_step_completed_status($reg_step_slug, $status)
1334
+	{
1335
+		// validate status
1336
+		$status = is_bool($status) || is_int($status) ? $status : false;
1337
+		// get reg steps array
1338
+		$txn_reg_steps = $this->reg_steps();
1339
+		// if reg step does NOT exist
1340
+		if (! isset($txn_reg_steps[$reg_step_slug])) {
1341
+			return false;
1342
+		}
1343
+		// if  we're trying to complete a step that is already completed
1344
+		if ($txn_reg_steps[$reg_step_slug] === true) {
1345
+			return true;
1346
+		}
1347
+		// if  we're trying to complete a step that hasn't even started
1348
+		if ($status === true && $txn_reg_steps[$reg_step_slug] === false) {
1349
+			return false;
1350
+		}
1351
+		// if current status value matches the incoming value (no change)
1352
+		// type casting as int means values should collapse to either 0, 1, or a timestamp like 1234567890
1353
+		if ((int)$txn_reg_steps[$reg_step_slug] === (int)$status) {
1354
+			// this will happen in cases where multiple AJAX requests occur during the same step
1355
+			return true;
1356
+		}
1357
+		// if we're trying to set a start time, but it has already been set...
1358
+		if (is_numeric($status) && is_numeric($txn_reg_steps[$reg_step_slug])) {
1359
+			// skip the update below, but don't return FALSE so that errors won't be displayed
1360
+			return true;
1361
+		}
1362
+		// update completed status
1363
+		$txn_reg_steps[$reg_step_slug] = $status;
1364
+		$this->set_reg_steps($txn_reg_steps);
1365
+		$this->save();
1366
+		return true;
1367
+	}
1368
+
1369
+
1370
+
1371
+	/**
1372
+	 * remove_reg_step
1373
+	 * given a valid TXN_reg_step slug, this will remove (unset)
1374
+	 * the reg step from the TXN reg step array
1375
+	 *
1376
+	 * @param string $reg_step_slug
1377
+	 * @return void
1378
+	 * @throws EE_Error
1379
+	 */
1380
+	public function remove_reg_step($reg_step_slug)
1381
+	{
1382
+		// get reg steps array
1383
+		$txn_reg_steps = $this->reg_steps();
1384
+		unset($txn_reg_steps[$reg_step_slug]);
1385
+		$this->set_reg_steps($txn_reg_steps);
1386
+	}
1387
+
1388
+
1389
+
1390
+	/**
1391
+	 * toggle_failed_transaction_status
1392
+	 * upgrades a TXNs status from failed to abandoned,
1393
+	 * meaning that contact information has been captured for at least one registrant
1394
+	 *
1395
+	 * @param bool $save
1396
+	 * @return bool
1397
+	 * @throws EE_Error
1398
+	 */
1399
+	public function toggle_failed_transaction_status($save = true)
1400
+	{
1401
+		// if TXN status is still set as "failed"...
1402
+		if ($this->status_ID() === EEM_Transaction::failed_status_code) {
1403
+			$this->set_status(EEM_Transaction::abandoned_status_code);
1404
+			if ($save) {
1405
+				$this->save();
1406
+			}
1407
+			return true;
1408
+		}
1409
+		return false;
1410
+	}
1411
+
1412
+
1413
+
1414
+	/**
1415
+	 * toggle_abandoned_transaction_status
1416
+	 * upgrades a TXNs status from failed or abandoned to incomplete
1417
+	 *
1418
+	 * @return bool
1419
+	 * @throws EE_Error
1420
+	 */
1421
+	public function toggle_abandoned_transaction_status()
1422
+	{
1423
+		// if TXN status has not been updated already due to a payment, and is still set as "failed" or "abandoned"...
1424
+		$txn_status = $this->status_ID();
1425
+		if (
1426
+			$txn_status === EEM_Transaction::failed_status_code
1427
+			|| $txn_status === EEM_Transaction::abandoned_status_code
1428
+		) {
1429
+			// if a contact record for the primary registrant has been created
1430
+			if (
1431
+				$this->primary_registration() instanceof EE_Registration
1432
+				&& $this->primary_registration()->attendee() instanceof EE_Attendee
1433
+			) {
1434
+				$this->set_status(EEM_Transaction::incomplete_status_code);
1435
+			} else {
1436
+				// no contact record? yer abandoned!
1437
+				$this->set_status(EEM_Transaction::abandoned_status_code);
1438
+			}
1439
+			return true;
1440
+		}
1441
+		return false;
1442
+	}
1443
+
1444
+
1445
+
1446
+	/**
1447
+	 * checks if an Abandoned TXN has any related payments, and if so,
1448
+	 * updates the TXN status based on the amount paid
1449
+	 *
1450
+	 * @throws EE_Error
1451
+	 * @throws InvalidDataTypeException
1452
+	 * @throws InvalidInterfaceException
1453
+	 * @throws InvalidArgumentException
1454
+	 * @throws RuntimeException
1455
+	 */
1456
+	public function verify_abandoned_transaction_status()
1457
+	{
1458
+		if ($this->status_ID() !== EEM_Transaction::abandoned_status_code) {
1459
+			return;
1460
+		}
1461
+		$payments = $this->get_many_related('Payment');
1462
+		if (! empty($payments)) {
1463
+			foreach ($payments as $payment) {
1464
+				if ($payment instanceof EE_Payment) {
1465
+					// kk this TXN should NOT be abandoned
1466
+					$this->update_status_based_on_total_paid();
1467
+					if (! (defined('DOING_AJAX') && DOING_AJAX) && is_admin()) {
1468
+						EE_Error::add_attention(
1469
+							sprintf(
1470
+								esc_html__(
1471
+									'The status for Transaction #%1$d has been updated from "Abandoned" to "%2$s", because at least one payment has been made towards it. If the payment appears in the "Payment Details" table below, you may need to edit its status and/or other details as well.',
1472
+									'event_espresso'
1473
+								),
1474
+								$this->ID(),
1475
+								$this->pretty_status()
1476
+							)
1477
+						);
1478
+					}
1479
+					// get final reg step status
1480
+					$finalized = $this->final_reg_step_completed();
1481
+					// if the 'finalize_registration' step has been initiated (has a timestamp)
1482
+					// but has not yet been fully completed (TRUE)
1483
+					if (is_int($finalized) && $finalized !== false && $finalized !== true) {
1484
+						$this->set_reg_step_completed('finalize_registration');
1485
+						$this->save();
1486
+					}
1487
+				}
1488
+			}
1489
+		}
1490
+	}
1491 1491
 
1492 1492
 }/* End of file EE_Transaction.class.php */
1493 1493
 /* Location: includes/classes/EE_Transaction.class.php */
Please login to merge, or discard this patch.
Spacing   +28 added lines, -28 removed lines patch added patch discarded remove patch
@@ -47,7 +47,7 @@  discard block
 block discarded – undo
47 47
         $txn        = $has_object
48 48
             ? $has_object
49 49
             : new self($props_n_values, false, $timezone, $date_formats);
50
-        if (! $has_object) {
50
+        if ( ! $has_object) {
51 51
             $txn->set_old_txn_status($txn->status_ID());
52 52
         }
53 53
         return $txn;
@@ -81,7 +81,7 @@  discard block
 block discarded – undo
81 81
     public function lock()
82 82
     {
83 83
         // attempt to set lock, but if that fails...
84
-        if (! $this->add_extra_meta('lock', time(), true)) {
84
+        if ( ! $this->add_extra_meta('lock', time(), true)) {
85 85
             // then attempt to remove the lock in case it is expired
86 86
             if ($this->_remove_expired_lock()) {
87 87
                 // if removal was successful, then try setting lock again
@@ -131,7 +131,7 @@  discard block
 block discarded – undo
131 131
     public function is_locked()
132 132
     {
133 133
         // if TXN is not locked, then return false immediately
134
-        if (! $this->_get_lock()) {
134
+        if ( ! $this->_get_lock()) {
135 135
             return false;
136 136
         }
137 137
         // if not, then let's try and remove the lock in case it's expired...
@@ -151,7 +151,7 @@  discard block
 block discarded – undo
151 151
      */
152 152
     protected function _get_lock()
153 153
     {
154
-        return (int)$this->get_extra_meta('lock', true, 0);
154
+        return (int) $this->get_extra_meta('lock', true, 0);
155 155
     }
156 156
 
157 157
 
@@ -181,7 +181,7 @@  discard block
 block discarded – undo
181 181
      */
182 182
     public function set_total($total = 0.00)
183 183
     {
184
-        $this->set('TXN_total', (float)$total);
184
+        $this->set('TXN_total', (float) $total);
185 185
     }
186 186
 
187 187
 
@@ -194,7 +194,7 @@  discard block
 block discarded – undo
194 194
      */
195 195
     public function set_paid($total_paid = 0.00)
196 196
     {
197
-        $this->set('TXN_paid', (float)$total_paid);
197
+        $this->set('TXN_paid', (float) $total_paid);
198 198
     }
199 199
 
200 200
 
@@ -248,7 +248,7 @@  discard block
 block discarded – undo
248 248
     public function reg_steps()
249 249
     {
250 250
         $TXN_reg_steps = $this->get('TXN_reg_steps');
251
-        return is_array($TXN_reg_steps) ? (array)$TXN_reg_steps : array();
251
+        return is_array($TXN_reg_steps) ? (array) $TXN_reg_steps : array();
252 252
     }
253 253
 
254 254
 
@@ -298,7 +298,7 @@  discard block
 block discarded – undo
298 298
      */
299 299
     public function total()
300 300
     {
301
-        return (float)$this->get('TXN_total');
301
+        return (float) $this->get('TXN_total');
302 302
     }
303 303
 
304 304
 
@@ -311,7 +311,7 @@  discard block
 block discarded – undo
311 311
      */
312 312
     public function paid()
313 313
     {
314
-        return (float)$this->get('TXN_paid');
314
+        return (float) $this->get('TXN_paid');
315 315
     }
316 316
 
317 317
 
@@ -321,7 +321,7 @@  discard block
 block discarded – undo
321 321
      */
322 322
     public function get_cart_session()
323 323
     {
324
-        $session_data = (array)$this->get('TXN_session_data');
324
+        $session_data = (array) $this->get('TXN_session_data');
325 325
         return isset($session_data['cart']) && $session_data['cart'] instanceof EE_Cart
326 326
             ? $session_data['cart']
327 327
             : null;
@@ -542,7 +542,7 @@  discard block
 block discarded – undo
542 542
             false,
543 543
             'sentence'
544 544
         );
545
-        $icon   = '';
545
+        $icon = '';
546 546
         switch ($this->status_ID()) {
547 547
             case EEM_Transaction::complete_status_code:
548 548
                 $icon = $show_icons ? '<span class="dashicons dashicons-yes ee-icon-size-24 green-text"></span>' : '';
@@ -561,7 +561,7 @@  discard block
 block discarded – undo
561 561
                 $icon = $show_icons ? '<span class="dashicons dashicons-plus ee-icon-size-16 orange-text"></span>' : '';
562 562
                 break;
563 563
         }
564
-        return $icon . $status[$this->status_ID()];
564
+        return $icon.$status[$this->status_ID()];
565 565
     }
566 566
 
567 567
 
@@ -673,7 +673,7 @@  discard block
 block discarded – undo
673 673
     public function invoice_url($type = 'html')
674 674
     {
675 675
         $REG = $this->primary_registration();
676
-        if (! $REG instanceof EE_Registration) {
676
+        if ( ! $REG instanceof EE_Registration) {
677 677
             return '';
678 678
         }
679 679
         return $REG->invoice_url($type);
@@ -689,7 +689,7 @@  discard block
 block discarded – undo
689 689
      */
690 690
     public function primary_registration()
691 691
     {
692
-        $registrations = (array)$this->get_many_related(
692
+        $registrations = (array) $this->get_many_related(
693 693
             'Registration',
694 694
             array(array('REG_count' => EEM_Registration::PRIMARY_REGISTRANT_COUNT))
695 695
         );
@@ -718,7 +718,7 @@  discard block
 block discarded – undo
718 718
     public function receipt_url($type = 'html')
719 719
     {
720 720
         $REG = $this->primary_registration();
721
-        if (! $REG instanceof EE_Registration) {
721
+        if ( ! $REG instanceof EE_Registration) {
722 722
             return '';
723 723
         }
724 724
         return $REG->receipt_url($type);
@@ -874,7 +874,7 @@  discard block
 block discarded – undo
874 874
     public function total_line_item($create_if_not_found = true)
875 875
     {
876 876
         $item = $this->get_first_related('Line_Item', array(array('LIN_type' => EEM_Line_Item::type_total)));
877
-        if (! $item && $create_if_not_found) {
877
+        if ( ! $item && $create_if_not_found) {
878 878
             $item = EEH_Line_Item::create_total_line_item($this);
879 879
         }
880 880
         return $item;
@@ -893,9 +893,9 @@  discard block
 block discarded – undo
893 893
     {
894 894
         $tax_line_item = $this->tax_total_line_item();
895 895
         if ($tax_line_item) {
896
-            return (float)$tax_line_item->total();
896
+            return (float) $tax_line_item->total();
897 897
         }
898
-        return (float)0;
898
+        return (float) 0;
899 899
     }
900 900
 
901 901
 
@@ -922,7 +922,7 @@  discard block
 block discarded – undo
922 922
     public function billing_info()
923 923
     {
924 924
         $payment_method = $this->payment_method();
925
-        if (! $payment_method) {
925
+        if ( ! $payment_method) {
926 926
             EE_Error::add_error(
927 927
                 __(
928 928
                     'Could not find billing info for transaction because no gateway has been used for it yet',
@@ -935,7 +935,7 @@  discard block
 block discarded – undo
935 935
             return null;
936 936
         }
937 937
         $primary_reg = $this->primary_registration();
938
-        if (! $primary_reg) {
938
+        if ( ! $primary_reg) {
939 939
             EE_Error::add_error(
940 940
                 __(
941 941
                     'Cannot get billing info for gateway %s on transaction because no primary registration exists',
@@ -948,7 +948,7 @@  discard block
 block discarded – undo
948 948
             return null;
949 949
         }
950 950
         $attendee = $primary_reg->attendee();
951
-        if (! $attendee) {
951
+        if ( ! $attendee) {
952 952
             EE_Error::add_error(
953 953
                 __(
954 954
                     'Cannot get billing info for gateway %s on transaction because the primary registration has no attendee exists',
@@ -1091,7 +1091,7 @@  discard block
 block discarded – undo
1091 1091
     public function update_based_on_payments()
1092 1092
     {
1093 1093
         EE_Error::doing_it_wrong(
1094
-            __CLASS__ . '::' . __FUNCTION__,
1094
+            __CLASS__.'::'.__FUNCTION__,
1095 1095
             sprintf(
1096 1096
                 __('This method is deprecated. Please use "%s" instead', 'event_espresso'),
1097 1097
                 'EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()'
@@ -1155,13 +1155,13 @@  discard block
 block discarded – undo
1155 1155
     private function _reg_steps_completed($reg_step_slug = '', $check_all = true)
1156 1156
     {
1157 1157
         $reg_steps = $this->reg_steps();
1158
-        if (! is_array($reg_steps) || empty($reg_steps)) {
1158
+        if ( ! is_array($reg_steps) || empty($reg_steps)) {
1159 1159
             return false;
1160 1160
         }
1161 1161
         // loop thru reg steps array)
1162 1162
         foreach ($reg_steps as $slug => $reg_step_completed) {
1163 1163
             // if NOT checking ALL steps (only checking one step)
1164
-            if (! $check_all) {
1164
+            if ( ! $check_all) {
1165 1165
                 // and this is the one
1166 1166
                 if ($slug === $reg_step_slug) {
1167 1167
                     return $reg_step_completed;
@@ -1337,7 +1337,7 @@  discard block
 block discarded – undo
1337 1337
         // get reg steps array
1338 1338
         $txn_reg_steps = $this->reg_steps();
1339 1339
         // if reg step does NOT exist
1340
-        if (! isset($txn_reg_steps[$reg_step_slug])) {
1340
+        if ( ! isset($txn_reg_steps[$reg_step_slug])) {
1341 1341
             return false;
1342 1342
         }
1343 1343
         // if  we're trying to complete a step that is already completed
@@ -1350,7 +1350,7 @@  discard block
 block discarded – undo
1350 1350
         }
1351 1351
         // if current status value matches the incoming value (no change)
1352 1352
         // type casting as int means values should collapse to either 0, 1, or a timestamp like 1234567890
1353
-        if ((int)$txn_reg_steps[$reg_step_slug] === (int)$status) {
1353
+        if ((int) $txn_reg_steps[$reg_step_slug] === (int) $status) {
1354 1354
             // this will happen in cases where multiple AJAX requests occur during the same step
1355 1355
             return true;
1356 1356
         }
@@ -1459,12 +1459,12 @@  discard block
 block discarded – undo
1459 1459
             return;
1460 1460
         }
1461 1461
         $payments = $this->get_many_related('Payment');
1462
-        if (! empty($payments)) {
1462
+        if ( ! empty($payments)) {
1463 1463
             foreach ($payments as $payment) {
1464 1464
                 if ($payment instanceof EE_Payment) {
1465 1465
                     // kk this TXN should NOT be abandoned
1466 1466
                     $this->update_status_based_on_total_paid();
1467
-                    if (! (defined('DOING_AJAX') && DOING_AJAX) && is_admin()) {
1467
+                    if ( ! (defined('DOING_AJAX') && DOING_AJAX) && is_admin()) {
1468 1468
                         EE_Error::add_attention(
1469 1469
                             sprintf(
1470 1470
                                 esc_html__(
Please login to merge, or discard this patch.
core/EE_Cron_Tasks.core.php 2 patches
Indentation   +581 added lines, -581 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if (! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 
5 5
 
@@ -14,586 +14,586 @@  discard block
 block discarded – undo
14 14
 class EE_Cron_Tasks extends EE_Base
15 15
 {
16 16
 
17
-    /**
18
-     * WordPress doesn't allow duplicate crons within 10 minutes of the original,
19
-     * so we'll set our retry time for just over 10 minutes to avoid that
20
-     */
21
-    const reschedule_timeout = 605;
22
-
23
-
24
-    /**
25
-     * @var EE_Cron_Tasks
26
-     */
27
-    private static $_instance;
28
-
29
-
30
-    /**
31
-     * @return EE_Cron_Tasks
32
-     * @throws \ReflectionException
33
-     * @throws \EE_Error
34
-     * @throws \InvalidArgumentException
35
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
36
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
37
-     */
38
-    public static function instance()
39
-    {
40
-        if (! self::$_instance instanceof EE_Cron_Tasks) {
41
-            self::$_instance = new self();
42
-        }
43
-        return self::$_instance;
44
-    }
45
-
46
-
47
-    /**
48
-     * @access private
49
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
50
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
51
-     * @throws \InvalidArgumentException
52
-     * @throws \EE_Error
53
-     * @throws \ReflectionException
54
-     */
55
-    private function __construct()
56
-    {
57
-        do_action('AHEE_log', __CLASS__, __FUNCTION__);
58
-        // verify that WP Cron is enabled
59
-        if (
60
-            defined('DISABLE_WP_CRON')
61
-            && DISABLE_WP_CRON
62
-            && is_admin()
63
-            && ! get_option('ee_disabled_wp_cron_check')
64
-        ) {
65
-            /**
66
-             * This needs to be delayed until after the config is loaded because EE_Cron_Tasks is constructed before
67
-             * config is loaded.
68
-             * This is intentionally using a anonymous function so that its not easily de-registered.  Client code
69
-             * wanting to not have this functionality can just register its own action at a priority after this one to
70
-             * reverse any changes.
71
-             */
72
-            add_action(
73
-                'AHEE__EE_System__load_core_configuration__complete',
74
-                function ()
75
-                {
76
-                    EE_Registry::instance()->NET_CFG->core->do_messages_on_same_request = true;
77
-                    EE_Registry::instance()->NET_CFG->update_config(true, false);
78
-                    add_option('ee_disabled_wp_cron_check', 1, '', false);
79
-                }
80
-            );
81
-        }
82
-        // UPDATE TRANSACTION WITH PAYMENT
83
-        add_action(
84
-            'AHEE__EE_Cron_Tasks__update_transaction_with_payment_2',
85
-            array('EE_Cron_Tasks', 'setup_update_for_transaction_with_payment'),
86
-            10,
87
-            2
88
-        );
89
-        // ABANDONED / EXPIRED TRANSACTION CHECK
90
-        add_action(
91
-            'AHEE__EE_Cron_Tasks__expired_transaction_check',
92
-            array('EE_Cron_Tasks', 'expired_transaction_check'),
93
-            10,
94
-            1
95
-        );
96
-        // CLEAN OUT JUNK TRANSACTIONS AND RELATED DATA
97
-        add_action(
98
-            'AHEE__EE_Cron_Tasks__clean_up_junk_transactions',
99
-            array('EE_Cron_Tasks', 'clean_out_junk_transactions')
100
-        );
101
-        // logging
102
-        add_action(
103
-            'AHEE__EE_System__load_core_configuration__complete',
104
-            array('EE_Cron_Tasks', 'log_scheduled_ee_crons')
105
-        );
106
-        EE_Registry::instance()->load_lib('Messages_Scheduler');
107
-        //clean out old gateway logs
108
-        add_action(
109
-            'AHEE_EE_Cron_Tasks__clean_out_old_gateway_logs',
110
-            array('EE_Cron_Tasks', 'clean_out_old_gateway_logs')
111
-        );
112
-    }
113
-
114
-
115
-    /**
116
-     * @access protected
117
-     * @return void
118
-     */
119
-    public static function log_scheduled_ee_crons()
120
-    {
121
-        $ee_crons = array(
122
-            'AHEE__EE_Cron_Tasks__update_transaction_with_payment',
123
-            'AHEE__EE_Cron_Tasks__finalize_abandoned_transactions',
124
-            'AHEE__EE_Cron_Tasks__clean_up_junk_transactions',
125
-        );
126
-        $crons    = (array)get_option('cron');
127
-        if (! is_array($crons)) {
128
-            return;
129
-        }
130
-        foreach ($crons as $timestamp => $cron) {
131
-            foreach ($ee_crons as $ee_cron) {
132
-                if (isset($cron[$ee_cron]) && is_array($cron[$ee_cron])) {
133
-                    do_action('AHEE_log', __CLASS__, __FUNCTION__, $ee_cron, 'scheduled EE cron');
134
-                    foreach ($cron[$ee_cron] as $ee_cron_details) {
135
-                        if (! empty($ee_cron_details['args'])) {
136
-                            do_action(
137
-                                'AHEE_log',
138
-                                __CLASS__,
139
-                                __FUNCTION__,
140
-                                print_r($ee_cron_details['args'], true),
141
-                                "{$ee_cron} args"
142
-                            );
143
-                        }
144
-                    }
145
-                }
146
-            }
147
-        }
148
-    }
149
-
150
-
151
-
152
-    /**
153
-     * reschedule_cron_for_transactions_if_maintenance_mode
154
-     * if Maintenance Mode is active, this will reschedule a cron to run again in 10 minutes
155
-     *
156
-     * @param string $cron_task
157
-     * @param array  $TXN_IDs
158
-     * @return bool
159
-     * @throws \DomainException
160
-     */
161
-    public static function reschedule_cron_for_transactions_if_maintenance_mode($cron_task, array $TXN_IDs)
162
-    {
163
-        if (! method_exists('EE_Cron_Tasks', $cron_task)) {
164
-            throw new \DomainException(
165
-                sprintf(
166
-                    __('"%1$s" is not valid method on EE_Cron_Tasks.', 'event_espresso'),
167
-                    $cron_task
168
-                )
169
-            );
170
-        }
171
-        // reschedule the cron if we can't hit the db right now
172
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
173
-            foreach ($TXN_IDs as $TXN_ID => $additional_vars) {
174
-                // ensure $additional_vars is an array
175
-                $additional_vars = is_array($additional_vars) ? $additional_vars : array($additional_vars);
176
-                // reset cron job for the TXN
177
-                call_user_func_array(
178
-                    array('EE_Cron_Tasks', $cron_task),
179
-                    array_merge(
180
-                        array(
181
-                            time() + (10 * MINUTE_IN_SECONDS),
182
-                            $TXN_ID,
183
-                        ),
184
-                        $additional_vars
185
-                    )
186
-                );
187
-            }
188
-            return true;
189
-        }
190
-        return false;
191
-    }
192
-
193
-
194
-
195
-
196
-    /****************  UPDATE TRANSACTION WITH PAYMENT ****************/
197
-    /**
198
-     * array of TXN IDs and the payment
199
-     *
200
-     * @var array
201
-     */
202
-    protected static $_update_transactions_with_payment = array();
203
-
204
-
205
-    /**
206
-     * schedule_update_transaction_with_payment
207
-     * sets a wp_schedule_single_event() for updating any TXNs that may
208
-     * require updating due to recently received payments
209
-     *
210
-     * @param int $timestamp
211
-     * @param int $TXN_ID
212
-     * @param int $PAY_ID
213
-     */
214
-    public static function schedule_update_transaction_with_payment(
215
-        $timestamp,
216
-        $TXN_ID,
217
-        $PAY_ID
218
-    ) {
219
-        do_action('AHEE_log', __CLASS__, __FUNCTION__);
220
-        // validate $TXN_ID and $timestamp
221
-        $TXN_ID    = absint($TXN_ID);
222
-        $timestamp = absint($timestamp);
223
-        if ($TXN_ID && $timestamp) {
224
-            wp_schedule_single_event(
225
-                $timestamp,
226
-                'AHEE__EE_Cron_Tasks__update_transaction_with_payment_2',
227
-                array($TXN_ID, $PAY_ID)
228
-            );
229
-        }
230
-    }
231
-
232
-
233
-    /**
234
-     * setup_update_for_transaction_with_payment
235
-     * this is the callback for the action hook:
236
-     * 'AHEE__EE_Cron_Tasks__update_transaction_with_payment'
237
-     * which is setup by EE_Cron_Tasks::schedule_update_transaction_with_payment().
238
-     * The passed TXN_ID and associated payment gets added to an array, and then
239
-     * the EE_Cron_Tasks::update_transaction_with_payment() function is hooked into
240
-     * 'shutdown' which will actually handle the processing of any
241
-     * transactions requiring updating, because doing so now would be too early
242
-     * and the required resources may not be available
243
-     *
244
-     * @param int $TXN_ID
245
-     * @param int $PAY_ID
246
-     */
247
-    public static function setup_update_for_transaction_with_payment($TXN_ID = 0, $PAY_ID = 0)
248
-    {
249
-        do_action('AHEE_log', __CLASS__, __FUNCTION__, $TXN_ID, '$TXN_ID');
250
-        if (absint($TXN_ID)) {
251
-            self::$_update_transactions_with_payment[$TXN_ID] = $PAY_ID;
252
-            add_action(
253
-                'shutdown',
254
-                array('EE_Cron_Tasks', 'update_transaction_with_payment'),
255
-                5
256
-            );
257
-        }
258
-    }
259
-
260
-
261
-    /**
262
-     * update_transaction_with_payment
263
-     * loops through the self::$_abandoned_transactions array
264
-     * and attempts to finalize any TXNs that have not been completed
265
-     * but have had their sessions expired, most likely due to a user not
266
-     * returning from an off-site payment gateway
267
-     *
268
-     * @throws \EE_Error
269
-     * @throws \DomainException
270
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
271
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
272
-     * @throws \InvalidArgumentException
273
-     * @throws \ReflectionException
274
-     */
275
-    public static function update_transaction_with_payment()
276
-    {
277
-        do_action('AHEE_log', __CLASS__, __FUNCTION__);
278
-        if (
279
-            // are there any TXNs that need cleaning up ?
280
-            empty(self::$_update_transactions_with_payment)
281
-            // reschedule the cron if we can't hit the db right now
282
-            || EE_Cron_Tasks::reschedule_cron_for_transactions_if_maintenance_mode(
283
-                'schedule_update_transaction_with_payment',
284
-                self::$_update_transactions_with_payment
285
-            )
286
-        ) {
287
-            return;
288
-        }
289
-        /** @type EE_Payment_Processor $payment_processor */
290
-        $payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
291
-        // set revisit flag for payment processor
292
-        $payment_processor->set_revisit();
293
-        // load EEM_Transaction
294
-        EE_Registry::instance()->load_model('Transaction');
295
-        foreach (self::$_update_transactions_with_payment as $TXN_ID => $PAY_ID) {
296
-            // reschedule the cron if we can't hit the db right now
297
-            if (! EE_Maintenance_Mode::instance()->models_can_query()) {
298
-                // reset cron job for updating the TXN
299
-                EE_Cron_Tasks::schedule_update_transaction_with_payment(
300
-                    time() + EE_Cron_Tasks::reschedule_timeout,
301
-                    $TXN_ID,
302
-                    $PAY_ID
303
-                );
304
-                continue;
305
-            }
306
-            $transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
307
-            $payment     = EEM_Payment::instance()->get_one_by_ID($PAY_ID);
308
-            // verify transaction
309
-            if ($transaction instanceof EE_Transaction && $payment instanceof EE_Payment) {
310
-                // now try to update the TXN with any payments
311
-                $payment_processor->update_txn_based_on_payment($transaction, $payment, true, true);
312
-            }
313
-            unset(self::$_update_transactions_with_payment[$TXN_ID]);
314
-        }
315
-    }
316
-
317
-
318
-
319
-    /************  END OF UPDATE TRANSACTION WITH PAYMENT  ************/
320
-    /*****************  EXPIRED TRANSACTION CHECK *****************/
321
-    /**
322
-     * array of TXN IDs
323
-     *
324
-     * @var array
325
-     */
326
-    protected static $_expired_transactions = array();
327
-
328
-
329
-
330
-    /**
331
-     * schedule_expired_transaction_check
332
-     * sets a wp_schedule_single_event() for following up on TXNs after their session has expired
333
-     *
334
-     * @param int $timestamp
335
-     * @param int $TXN_ID
336
-     */
337
-    public static function schedule_expired_transaction_check(
338
-        $timestamp,
339
-        $TXN_ID
340
-    ) {
341
-        // validate $TXN_ID and $timestamp
342
-        $TXN_ID    = absint($TXN_ID);
343
-        $timestamp = absint($timestamp);
344
-        if ($TXN_ID && $timestamp) {
345
-            wp_schedule_single_event(
346
-                $timestamp,
347
-                'AHEE__EE_Cron_Tasks__expired_transaction_check',
348
-                array($TXN_ID)
349
-            );
350
-        }
351
-    }
352
-
353
-
354
-
355
-    /**
356
-     * expired_transaction_check
357
-     * this is the callback for the action hook:
358
-     * 'AHEE__EE_Cron_Tasks__transaction_session_expiration_check'
359
-     * which is utilized by wp_schedule_single_event()
360
-     * in \EED_Single_Page_Checkout::_initialize_transaction().
361
-     * The passed TXN_ID gets added to an array, and then the
362
-     * process_expired_transactions() function is hooked into
363
-     * 'AHEE__EE_System__core_loaded_and_ready' which will actually handle the
364
-     * processing of any failed transactions, because doing so now would be
365
-     * too early and the required resources may not be available
366
-     *
367
-     * @param int $TXN_ID
368
-     */
369
-    public static function expired_transaction_check($TXN_ID = 0)
370
-    {
371
-        if (absint($TXN_ID)) {
372
-            self::$_expired_transactions[$TXN_ID] = $TXN_ID;
373
-            add_action(
374
-                'shutdown',
375
-                array('EE_Cron_Tasks', 'process_expired_transactions'),
376
-                5
377
-            );
378
-        }
379
-    }
380
-
381
-
382
-
383
-    /**
384
-     * process_expired_transactions
385
-     * loops through the self::$_expired_transactions array and processes any failed TXNs
386
-     *
387
-     * @throws \EE_Error
388
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
389
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
390
-     * @throws \InvalidArgumentException
391
-     * @throws \ReflectionException
392
-     * @throws \DomainException
393
-     */
394
-    public static function process_expired_transactions()
395
-    {
396
-        if (
397
-            // are there any TXNs that need cleaning up ?
398
-            empty(self::$_expired_transactions)
399
-            // reschedule the cron if we can't hit the db right now
400
-            || EE_Cron_Tasks::reschedule_cron_for_transactions_if_maintenance_mode(
401
-                'schedule_expired_transaction_check',
402
-                self::$_expired_transactions
403
-            )
404
-        ) {
405
-            return;
406
-        }
407
-        /** @type EE_Transaction_Processor $transaction_processor */
408
-        $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
409
-        // set revisit flag for txn processor
410
-        $transaction_processor->set_revisit();
411
-        // load EEM_Transaction
412
-        EE_Registry::instance()->load_model('Transaction');
413
-        foreach (self::$_expired_transactions as $TXN_ID) {
414
-            $transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
415
-            // verify transaction and whether it is failed or not
416
-            if ($transaction instanceof EE_Transaction) {
417
-                switch ($transaction->status_ID()) {
418
-                    // Completed TXNs
419
-                    case EEM_Transaction::complete_status_code :
420
-                        do_action(
421
-                            'AHEE__EE_Cron_Tasks__process_expired_transactions__completed_transaction',
422
-                            $transaction
423
-                        );
424
-                        break;
425
-                    // Overpaid TXNs
426
-                    case EEM_Transaction::overpaid_status_code :
427
-                        do_action(
428
-                            'AHEE__EE_Cron_Tasks__process_expired_transactions__overpaid_transaction',
429
-                            $transaction
430
-                        );
431
-                        break;
432
-                    // Incomplete TXNs
433
-                    case EEM_Transaction::incomplete_status_code :
434
-                        do_action(
435
-                            'AHEE__EE_Cron_Tasks__process_expired_transactions__incomplete_transaction',
436
-                            $transaction
437
-                        );
438
-                        // todo : move business logic into EE_Transaction_Processor for finalizing abandoned transactions
439
-                        break;
440
-                    // Abandoned TXNs
441
-                    case EEM_Transaction::abandoned_status_code :
442
-                        // run hook before updating transaction, primarily so
443
-                        // EED_Ticket_Sales_Monitor::process_abandoned_transactions() can release reserved tickets
444
-                        do_action(
445
-                            'AHEE__EE_Cron_Tasks__process_expired_transactions__abandoned_transaction',
446
-                            $transaction
447
-                        );
448
-                        // don't finalize the TXN if it has already been completed
449
-                        if ($transaction->all_reg_steps_completed() !== true) {
450
-                            /** @type EE_Payment_Processor $payment_processor */
451
-                            $payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
452
-                            // let's simulate an IPN here which will trigger any notifications that need to go out
453
-                            $payment_processor->update_txn_based_on_payment(
454
-                                $transaction,
455
-                                $transaction->last_payment(),
456
-                                true,
457
-                                true
458
-                            );
459
-                        }
460
-                        break;
461
-                    // Failed TXNs
462
-                    case EEM_Transaction::failed_status_code :
463
-                        do_action(
464
-                            'AHEE__EE_Cron_Tasks__process_expired_transactions__failed_transaction',
465
-                            $transaction
466
-                        );
467
-                        // todo : perform garbage collection here and remove clean_out_junk_transactions()
468
-                        //$registrations = $transaction->registrations();
469
-                        //if ( ! empty( $registrations ) ) {
470
-                        //	foreach ( $registrations as $registration ) {
471
-                        //		if ( $registration instanceof EE_Registration ) {
472
-                        //$delete_registration = true;
473
-                        //if ( $registration->attendee() instanceof EE_Attendee ) {
474
-                        //	$delete_registration = false;
475
-                        //}
476
-                        //if ( $delete_registration ) {
477
-                        //	$registration->delete_permanently();
478
-                        //	$registration->delete_related_permanently();
479
-                        //}
480
-                        //		}
481
-                        //	}
482
-                        //}
483
-                        break;
484
-                }
485
-            }
486
-            unset(self::$_expired_transactions[$TXN_ID]);
487
-        }
488
-    }
489
-
490
-
491
-
492
-    /*************  END OF EXPIRED TRANSACTION CHECK  *************/
493
-    /************* START CLEAN UP BOT TRANSACTIONS **********************/
494
-
495
-
496
-
497
-    /**
498
-     * when a transaction is initially made, schedule this check.
499
-     * if it has NO REG data by the time it has expired, forget about it
500
-     *
501
-     * @throws EE_Error
502
-     * @throws InvalidArgumentException
503
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
504
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
505
-     */
506
-    public static function clean_out_junk_transactions()
507
-    {
508
-        if (EE_Maintenance_Mode::instance()->models_can_query()) {
509
-            EEM_Transaction::instance('')->delete_junk_transactions();
510
-            EEM_Registration::instance('')->delete_registrations_with_no_transaction();
511
-            EEM_Line_Item::instance('')->delete_line_items_with_no_transaction();
512
-        }
513
-    }
514
-
515
-
516
-
517
-    /**
518
-     * Deletes old gateway logs. After about a week we usually don't need them for debugging. But folks can filter that.
519
-     *
520
-     * @throws \EE_Error
521
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
522
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
523
-     * @throws \InvalidArgumentException
524
-     */
525
-    public static function clean_out_old_gateway_logs()
526
-    {
527
-        if (EE_Maintenance_Mode::instance()->models_can_query()) {
528
-            $time_diff_for_comparison = apply_filters(
529
-                'FHEE__EE_Cron_Tasks__clean_out_old_gateway_logs__time_diff_for_comparison',
530
-                '-1 week'
531
-            );
532
-            EEM_Change_Log::instance()->delete_gateway_logs_older_than(new DateTime($time_diff_for_comparison));
533
-        }
534
-    }
535
-
536
-
537
-    /*****************  FINALIZE ABANDONED TRANSACTIONS *****************/
538
-    /**
539
-     * @var array
540
-     */
541
-    protected static $_abandoned_transactions = array();
542
-
543
-
544
-    /**
545
-     * @deprecated
546
-     * @param int $timestamp
547
-     * @param int $TXN_ID
548
-     */
549
-    public static function schedule_finalize_abandoned_transactions_check($timestamp, $TXN_ID)
550
-    {
551
-        EE_Cron_Tasks::schedule_expired_transaction_check($timestamp, $TXN_ID);
552
-    }
553
-
554
-
555
-    /**
556
-     * @deprecated
557
-     * @param int $TXN_ID
558
-     */
559
-    public static function check_for_abandoned_transactions($TXN_ID = 0)
560
-    {
561
-        EE_Cron_Tasks::expired_transaction_check($TXN_ID);
562
-    }
563
-
564
-
565
-    /**
566
-     * @deprecated
567
-     * @throws \EE_Error
568
-     * @throws \DomainException
569
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
570
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
571
-     * @throws \InvalidArgumentException
572
-     * @throws \ReflectionException
573
-     */
574
-    public static function finalize_abandoned_transactions()
575
-    {
576
-        do_action('AHEE_log', __CLASS__, __FUNCTION__);
577
-        if (
578
-            // are there any TXNs that need cleaning up ?
579
-            empty(self::$_abandoned_transactions)
580
-            // reschedule the cron if we can't hit the db right now
581
-            || EE_Cron_Tasks::reschedule_cron_for_transactions_if_maintenance_mode(
582
-                'schedule_expired_transaction_check',
583
-                self::$_abandoned_transactions
584
-            )
585
-        ) {
586
-            return;
587
-        }
588
-        // combine our arrays of transaction IDs
589
-        self::$_expired_transactions = self::$_abandoned_transactions + self::$_expired_transactions;
590
-        // and deal with abandoned transactions here now...
591
-        EE_Cron_Tasks::process_expired_transactions();
592
-    }
593
-
594
-
595
-
596
-    /*************  END OF FINALIZE ABANDONED TRANSACTIONS  *************/
17
+	/**
18
+	 * WordPress doesn't allow duplicate crons within 10 minutes of the original,
19
+	 * so we'll set our retry time for just over 10 minutes to avoid that
20
+	 */
21
+	const reschedule_timeout = 605;
22
+
23
+
24
+	/**
25
+	 * @var EE_Cron_Tasks
26
+	 */
27
+	private static $_instance;
28
+
29
+
30
+	/**
31
+	 * @return EE_Cron_Tasks
32
+	 * @throws \ReflectionException
33
+	 * @throws \EE_Error
34
+	 * @throws \InvalidArgumentException
35
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
36
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
37
+	 */
38
+	public static function instance()
39
+	{
40
+		if (! self::$_instance instanceof EE_Cron_Tasks) {
41
+			self::$_instance = new self();
42
+		}
43
+		return self::$_instance;
44
+	}
45
+
46
+
47
+	/**
48
+	 * @access private
49
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
50
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
51
+	 * @throws \InvalidArgumentException
52
+	 * @throws \EE_Error
53
+	 * @throws \ReflectionException
54
+	 */
55
+	private function __construct()
56
+	{
57
+		do_action('AHEE_log', __CLASS__, __FUNCTION__);
58
+		// verify that WP Cron is enabled
59
+		if (
60
+			defined('DISABLE_WP_CRON')
61
+			&& DISABLE_WP_CRON
62
+			&& is_admin()
63
+			&& ! get_option('ee_disabled_wp_cron_check')
64
+		) {
65
+			/**
66
+			 * This needs to be delayed until after the config is loaded because EE_Cron_Tasks is constructed before
67
+			 * config is loaded.
68
+			 * This is intentionally using a anonymous function so that its not easily de-registered.  Client code
69
+			 * wanting to not have this functionality can just register its own action at a priority after this one to
70
+			 * reverse any changes.
71
+			 */
72
+			add_action(
73
+				'AHEE__EE_System__load_core_configuration__complete',
74
+				function ()
75
+				{
76
+					EE_Registry::instance()->NET_CFG->core->do_messages_on_same_request = true;
77
+					EE_Registry::instance()->NET_CFG->update_config(true, false);
78
+					add_option('ee_disabled_wp_cron_check', 1, '', false);
79
+				}
80
+			);
81
+		}
82
+		// UPDATE TRANSACTION WITH PAYMENT
83
+		add_action(
84
+			'AHEE__EE_Cron_Tasks__update_transaction_with_payment_2',
85
+			array('EE_Cron_Tasks', 'setup_update_for_transaction_with_payment'),
86
+			10,
87
+			2
88
+		);
89
+		// ABANDONED / EXPIRED TRANSACTION CHECK
90
+		add_action(
91
+			'AHEE__EE_Cron_Tasks__expired_transaction_check',
92
+			array('EE_Cron_Tasks', 'expired_transaction_check'),
93
+			10,
94
+			1
95
+		);
96
+		// CLEAN OUT JUNK TRANSACTIONS AND RELATED DATA
97
+		add_action(
98
+			'AHEE__EE_Cron_Tasks__clean_up_junk_transactions',
99
+			array('EE_Cron_Tasks', 'clean_out_junk_transactions')
100
+		);
101
+		// logging
102
+		add_action(
103
+			'AHEE__EE_System__load_core_configuration__complete',
104
+			array('EE_Cron_Tasks', 'log_scheduled_ee_crons')
105
+		);
106
+		EE_Registry::instance()->load_lib('Messages_Scheduler');
107
+		//clean out old gateway logs
108
+		add_action(
109
+			'AHEE_EE_Cron_Tasks__clean_out_old_gateway_logs',
110
+			array('EE_Cron_Tasks', 'clean_out_old_gateway_logs')
111
+		);
112
+	}
113
+
114
+
115
+	/**
116
+	 * @access protected
117
+	 * @return void
118
+	 */
119
+	public static function log_scheduled_ee_crons()
120
+	{
121
+		$ee_crons = array(
122
+			'AHEE__EE_Cron_Tasks__update_transaction_with_payment',
123
+			'AHEE__EE_Cron_Tasks__finalize_abandoned_transactions',
124
+			'AHEE__EE_Cron_Tasks__clean_up_junk_transactions',
125
+		);
126
+		$crons    = (array)get_option('cron');
127
+		if (! is_array($crons)) {
128
+			return;
129
+		}
130
+		foreach ($crons as $timestamp => $cron) {
131
+			foreach ($ee_crons as $ee_cron) {
132
+				if (isset($cron[$ee_cron]) && is_array($cron[$ee_cron])) {
133
+					do_action('AHEE_log', __CLASS__, __FUNCTION__, $ee_cron, 'scheduled EE cron');
134
+					foreach ($cron[$ee_cron] as $ee_cron_details) {
135
+						if (! empty($ee_cron_details['args'])) {
136
+							do_action(
137
+								'AHEE_log',
138
+								__CLASS__,
139
+								__FUNCTION__,
140
+								print_r($ee_cron_details['args'], true),
141
+								"{$ee_cron} args"
142
+							);
143
+						}
144
+					}
145
+				}
146
+			}
147
+		}
148
+	}
149
+
150
+
151
+
152
+	/**
153
+	 * reschedule_cron_for_transactions_if_maintenance_mode
154
+	 * if Maintenance Mode is active, this will reschedule a cron to run again in 10 minutes
155
+	 *
156
+	 * @param string $cron_task
157
+	 * @param array  $TXN_IDs
158
+	 * @return bool
159
+	 * @throws \DomainException
160
+	 */
161
+	public static function reschedule_cron_for_transactions_if_maintenance_mode($cron_task, array $TXN_IDs)
162
+	{
163
+		if (! method_exists('EE_Cron_Tasks', $cron_task)) {
164
+			throw new \DomainException(
165
+				sprintf(
166
+					__('"%1$s" is not valid method on EE_Cron_Tasks.', 'event_espresso'),
167
+					$cron_task
168
+				)
169
+			);
170
+		}
171
+		// reschedule the cron if we can't hit the db right now
172
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
173
+			foreach ($TXN_IDs as $TXN_ID => $additional_vars) {
174
+				// ensure $additional_vars is an array
175
+				$additional_vars = is_array($additional_vars) ? $additional_vars : array($additional_vars);
176
+				// reset cron job for the TXN
177
+				call_user_func_array(
178
+					array('EE_Cron_Tasks', $cron_task),
179
+					array_merge(
180
+						array(
181
+							time() + (10 * MINUTE_IN_SECONDS),
182
+							$TXN_ID,
183
+						),
184
+						$additional_vars
185
+					)
186
+				);
187
+			}
188
+			return true;
189
+		}
190
+		return false;
191
+	}
192
+
193
+
194
+
195
+
196
+	/****************  UPDATE TRANSACTION WITH PAYMENT ****************/
197
+	/**
198
+	 * array of TXN IDs and the payment
199
+	 *
200
+	 * @var array
201
+	 */
202
+	protected static $_update_transactions_with_payment = array();
203
+
204
+
205
+	/**
206
+	 * schedule_update_transaction_with_payment
207
+	 * sets a wp_schedule_single_event() for updating any TXNs that may
208
+	 * require updating due to recently received payments
209
+	 *
210
+	 * @param int $timestamp
211
+	 * @param int $TXN_ID
212
+	 * @param int $PAY_ID
213
+	 */
214
+	public static function schedule_update_transaction_with_payment(
215
+		$timestamp,
216
+		$TXN_ID,
217
+		$PAY_ID
218
+	) {
219
+		do_action('AHEE_log', __CLASS__, __FUNCTION__);
220
+		// validate $TXN_ID and $timestamp
221
+		$TXN_ID    = absint($TXN_ID);
222
+		$timestamp = absint($timestamp);
223
+		if ($TXN_ID && $timestamp) {
224
+			wp_schedule_single_event(
225
+				$timestamp,
226
+				'AHEE__EE_Cron_Tasks__update_transaction_with_payment_2',
227
+				array($TXN_ID, $PAY_ID)
228
+			);
229
+		}
230
+	}
231
+
232
+
233
+	/**
234
+	 * setup_update_for_transaction_with_payment
235
+	 * this is the callback for the action hook:
236
+	 * 'AHEE__EE_Cron_Tasks__update_transaction_with_payment'
237
+	 * which is setup by EE_Cron_Tasks::schedule_update_transaction_with_payment().
238
+	 * The passed TXN_ID and associated payment gets added to an array, and then
239
+	 * the EE_Cron_Tasks::update_transaction_with_payment() function is hooked into
240
+	 * 'shutdown' which will actually handle the processing of any
241
+	 * transactions requiring updating, because doing so now would be too early
242
+	 * and the required resources may not be available
243
+	 *
244
+	 * @param int $TXN_ID
245
+	 * @param int $PAY_ID
246
+	 */
247
+	public static function setup_update_for_transaction_with_payment($TXN_ID = 0, $PAY_ID = 0)
248
+	{
249
+		do_action('AHEE_log', __CLASS__, __FUNCTION__, $TXN_ID, '$TXN_ID');
250
+		if (absint($TXN_ID)) {
251
+			self::$_update_transactions_with_payment[$TXN_ID] = $PAY_ID;
252
+			add_action(
253
+				'shutdown',
254
+				array('EE_Cron_Tasks', 'update_transaction_with_payment'),
255
+				5
256
+			);
257
+		}
258
+	}
259
+
260
+
261
+	/**
262
+	 * update_transaction_with_payment
263
+	 * loops through the self::$_abandoned_transactions array
264
+	 * and attempts to finalize any TXNs that have not been completed
265
+	 * but have had their sessions expired, most likely due to a user not
266
+	 * returning from an off-site payment gateway
267
+	 *
268
+	 * @throws \EE_Error
269
+	 * @throws \DomainException
270
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
271
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
272
+	 * @throws \InvalidArgumentException
273
+	 * @throws \ReflectionException
274
+	 */
275
+	public static function update_transaction_with_payment()
276
+	{
277
+		do_action('AHEE_log', __CLASS__, __FUNCTION__);
278
+		if (
279
+			// are there any TXNs that need cleaning up ?
280
+			empty(self::$_update_transactions_with_payment)
281
+			// reschedule the cron if we can't hit the db right now
282
+			|| EE_Cron_Tasks::reschedule_cron_for_transactions_if_maintenance_mode(
283
+				'schedule_update_transaction_with_payment',
284
+				self::$_update_transactions_with_payment
285
+			)
286
+		) {
287
+			return;
288
+		}
289
+		/** @type EE_Payment_Processor $payment_processor */
290
+		$payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
291
+		// set revisit flag for payment processor
292
+		$payment_processor->set_revisit();
293
+		// load EEM_Transaction
294
+		EE_Registry::instance()->load_model('Transaction');
295
+		foreach (self::$_update_transactions_with_payment as $TXN_ID => $PAY_ID) {
296
+			// reschedule the cron if we can't hit the db right now
297
+			if (! EE_Maintenance_Mode::instance()->models_can_query()) {
298
+				// reset cron job for updating the TXN
299
+				EE_Cron_Tasks::schedule_update_transaction_with_payment(
300
+					time() + EE_Cron_Tasks::reschedule_timeout,
301
+					$TXN_ID,
302
+					$PAY_ID
303
+				);
304
+				continue;
305
+			}
306
+			$transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
307
+			$payment     = EEM_Payment::instance()->get_one_by_ID($PAY_ID);
308
+			// verify transaction
309
+			if ($transaction instanceof EE_Transaction && $payment instanceof EE_Payment) {
310
+				// now try to update the TXN with any payments
311
+				$payment_processor->update_txn_based_on_payment($transaction, $payment, true, true);
312
+			}
313
+			unset(self::$_update_transactions_with_payment[$TXN_ID]);
314
+		}
315
+	}
316
+
317
+
318
+
319
+	/************  END OF UPDATE TRANSACTION WITH PAYMENT  ************/
320
+	/*****************  EXPIRED TRANSACTION CHECK *****************/
321
+	/**
322
+	 * array of TXN IDs
323
+	 *
324
+	 * @var array
325
+	 */
326
+	protected static $_expired_transactions = array();
327
+
328
+
329
+
330
+	/**
331
+	 * schedule_expired_transaction_check
332
+	 * sets a wp_schedule_single_event() for following up on TXNs after their session has expired
333
+	 *
334
+	 * @param int $timestamp
335
+	 * @param int $TXN_ID
336
+	 */
337
+	public static function schedule_expired_transaction_check(
338
+		$timestamp,
339
+		$TXN_ID
340
+	) {
341
+		// validate $TXN_ID and $timestamp
342
+		$TXN_ID    = absint($TXN_ID);
343
+		$timestamp = absint($timestamp);
344
+		if ($TXN_ID && $timestamp) {
345
+			wp_schedule_single_event(
346
+				$timestamp,
347
+				'AHEE__EE_Cron_Tasks__expired_transaction_check',
348
+				array($TXN_ID)
349
+			);
350
+		}
351
+	}
352
+
353
+
354
+
355
+	/**
356
+	 * expired_transaction_check
357
+	 * this is the callback for the action hook:
358
+	 * 'AHEE__EE_Cron_Tasks__transaction_session_expiration_check'
359
+	 * which is utilized by wp_schedule_single_event()
360
+	 * in \EED_Single_Page_Checkout::_initialize_transaction().
361
+	 * The passed TXN_ID gets added to an array, and then the
362
+	 * process_expired_transactions() function is hooked into
363
+	 * 'AHEE__EE_System__core_loaded_and_ready' which will actually handle the
364
+	 * processing of any failed transactions, because doing so now would be
365
+	 * too early and the required resources may not be available
366
+	 *
367
+	 * @param int $TXN_ID
368
+	 */
369
+	public static function expired_transaction_check($TXN_ID = 0)
370
+	{
371
+		if (absint($TXN_ID)) {
372
+			self::$_expired_transactions[$TXN_ID] = $TXN_ID;
373
+			add_action(
374
+				'shutdown',
375
+				array('EE_Cron_Tasks', 'process_expired_transactions'),
376
+				5
377
+			);
378
+		}
379
+	}
380
+
381
+
382
+
383
+	/**
384
+	 * process_expired_transactions
385
+	 * loops through the self::$_expired_transactions array and processes any failed TXNs
386
+	 *
387
+	 * @throws \EE_Error
388
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
389
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
390
+	 * @throws \InvalidArgumentException
391
+	 * @throws \ReflectionException
392
+	 * @throws \DomainException
393
+	 */
394
+	public static function process_expired_transactions()
395
+	{
396
+		if (
397
+			// are there any TXNs that need cleaning up ?
398
+			empty(self::$_expired_transactions)
399
+			// reschedule the cron if we can't hit the db right now
400
+			|| EE_Cron_Tasks::reschedule_cron_for_transactions_if_maintenance_mode(
401
+				'schedule_expired_transaction_check',
402
+				self::$_expired_transactions
403
+			)
404
+		) {
405
+			return;
406
+		}
407
+		/** @type EE_Transaction_Processor $transaction_processor */
408
+		$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
409
+		// set revisit flag for txn processor
410
+		$transaction_processor->set_revisit();
411
+		// load EEM_Transaction
412
+		EE_Registry::instance()->load_model('Transaction');
413
+		foreach (self::$_expired_transactions as $TXN_ID) {
414
+			$transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
415
+			// verify transaction and whether it is failed or not
416
+			if ($transaction instanceof EE_Transaction) {
417
+				switch ($transaction->status_ID()) {
418
+					// Completed TXNs
419
+					case EEM_Transaction::complete_status_code :
420
+						do_action(
421
+							'AHEE__EE_Cron_Tasks__process_expired_transactions__completed_transaction',
422
+							$transaction
423
+						);
424
+						break;
425
+					// Overpaid TXNs
426
+					case EEM_Transaction::overpaid_status_code :
427
+						do_action(
428
+							'AHEE__EE_Cron_Tasks__process_expired_transactions__overpaid_transaction',
429
+							$transaction
430
+						);
431
+						break;
432
+					// Incomplete TXNs
433
+					case EEM_Transaction::incomplete_status_code :
434
+						do_action(
435
+							'AHEE__EE_Cron_Tasks__process_expired_transactions__incomplete_transaction',
436
+							$transaction
437
+						);
438
+						// todo : move business logic into EE_Transaction_Processor for finalizing abandoned transactions
439
+						break;
440
+					// Abandoned TXNs
441
+					case EEM_Transaction::abandoned_status_code :
442
+						// run hook before updating transaction, primarily so
443
+						// EED_Ticket_Sales_Monitor::process_abandoned_transactions() can release reserved tickets
444
+						do_action(
445
+							'AHEE__EE_Cron_Tasks__process_expired_transactions__abandoned_transaction',
446
+							$transaction
447
+						);
448
+						// don't finalize the TXN if it has already been completed
449
+						if ($transaction->all_reg_steps_completed() !== true) {
450
+							/** @type EE_Payment_Processor $payment_processor */
451
+							$payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
452
+							// let's simulate an IPN here which will trigger any notifications that need to go out
453
+							$payment_processor->update_txn_based_on_payment(
454
+								$transaction,
455
+								$transaction->last_payment(),
456
+								true,
457
+								true
458
+							);
459
+						}
460
+						break;
461
+					// Failed TXNs
462
+					case EEM_Transaction::failed_status_code :
463
+						do_action(
464
+							'AHEE__EE_Cron_Tasks__process_expired_transactions__failed_transaction',
465
+							$transaction
466
+						);
467
+						// todo : perform garbage collection here and remove clean_out_junk_transactions()
468
+						//$registrations = $transaction->registrations();
469
+						//if ( ! empty( $registrations ) ) {
470
+						//	foreach ( $registrations as $registration ) {
471
+						//		if ( $registration instanceof EE_Registration ) {
472
+						//$delete_registration = true;
473
+						//if ( $registration->attendee() instanceof EE_Attendee ) {
474
+						//	$delete_registration = false;
475
+						//}
476
+						//if ( $delete_registration ) {
477
+						//	$registration->delete_permanently();
478
+						//	$registration->delete_related_permanently();
479
+						//}
480
+						//		}
481
+						//	}
482
+						//}
483
+						break;
484
+				}
485
+			}
486
+			unset(self::$_expired_transactions[$TXN_ID]);
487
+		}
488
+	}
489
+
490
+
491
+
492
+	/*************  END OF EXPIRED TRANSACTION CHECK  *************/
493
+	/************* START CLEAN UP BOT TRANSACTIONS **********************/
494
+
495
+
496
+
497
+	/**
498
+	 * when a transaction is initially made, schedule this check.
499
+	 * if it has NO REG data by the time it has expired, forget about it
500
+	 *
501
+	 * @throws EE_Error
502
+	 * @throws InvalidArgumentException
503
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
504
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
505
+	 */
506
+	public static function clean_out_junk_transactions()
507
+	{
508
+		if (EE_Maintenance_Mode::instance()->models_can_query()) {
509
+			EEM_Transaction::instance('')->delete_junk_transactions();
510
+			EEM_Registration::instance('')->delete_registrations_with_no_transaction();
511
+			EEM_Line_Item::instance('')->delete_line_items_with_no_transaction();
512
+		}
513
+	}
514
+
515
+
516
+
517
+	/**
518
+	 * Deletes old gateway logs. After about a week we usually don't need them for debugging. But folks can filter that.
519
+	 *
520
+	 * @throws \EE_Error
521
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
522
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
523
+	 * @throws \InvalidArgumentException
524
+	 */
525
+	public static function clean_out_old_gateway_logs()
526
+	{
527
+		if (EE_Maintenance_Mode::instance()->models_can_query()) {
528
+			$time_diff_for_comparison = apply_filters(
529
+				'FHEE__EE_Cron_Tasks__clean_out_old_gateway_logs__time_diff_for_comparison',
530
+				'-1 week'
531
+			);
532
+			EEM_Change_Log::instance()->delete_gateway_logs_older_than(new DateTime($time_diff_for_comparison));
533
+		}
534
+	}
535
+
536
+
537
+	/*****************  FINALIZE ABANDONED TRANSACTIONS *****************/
538
+	/**
539
+	 * @var array
540
+	 */
541
+	protected static $_abandoned_transactions = array();
542
+
543
+
544
+	/**
545
+	 * @deprecated
546
+	 * @param int $timestamp
547
+	 * @param int $TXN_ID
548
+	 */
549
+	public static function schedule_finalize_abandoned_transactions_check($timestamp, $TXN_ID)
550
+	{
551
+		EE_Cron_Tasks::schedule_expired_transaction_check($timestamp, $TXN_ID);
552
+	}
553
+
554
+
555
+	/**
556
+	 * @deprecated
557
+	 * @param int $TXN_ID
558
+	 */
559
+	public static function check_for_abandoned_transactions($TXN_ID = 0)
560
+	{
561
+		EE_Cron_Tasks::expired_transaction_check($TXN_ID);
562
+	}
563
+
564
+
565
+	/**
566
+	 * @deprecated
567
+	 * @throws \EE_Error
568
+	 * @throws \DomainException
569
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
570
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
571
+	 * @throws \InvalidArgumentException
572
+	 * @throws \ReflectionException
573
+	 */
574
+	public static function finalize_abandoned_transactions()
575
+	{
576
+		do_action('AHEE_log', __CLASS__, __FUNCTION__);
577
+		if (
578
+			// are there any TXNs that need cleaning up ?
579
+			empty(self::$_abandoned_transactions)
580
+			// reschedule the cron if we can't hit the db right now
581
+			|| EE_Cron_Tasks::reschedule_cron_for_transactions_if_maintenance_mode(
582
+				'schedule_expired_transaction_check',
583
+				self::$_abandoned_transactions
584
+			)
585
+		) {
586
+			return;
587
+		}
588
+		// combine our arrays of transaction IDs
589
+		self::$_expired_transactions = self::$_abandoned_transactions + self::$_expired_transactions;
590
+		// and deal with abandoned transactions here now...
591
+		EE_Cron_Tasks::process_expired_transactions();
592
+	}
593
+
594
+
595
+
596
+	/*************  END OF FINALIZE ABANDONED TRANSACTIONS  *************/
597 597
 }
598 598
 // End of file EE_Cron_Tasks.core.php
599 599
 // Location: /EE_Cron_Tasks.core.php
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -1,4 +1,4 @@  discard block
 block discarded – undo
1
-<?php if (! defined('EVENT_ESPRESSO_VERSION')) {
1
+<?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2 2
     exit('No direct script access allowed');
3 3
 }
4 4
 
@@ -37,7 +37,7 @@  discard block
 block discarded – undo
37 37
      */
38 38
     public static function instance()
39 39
     {
40
-        if (! self::$_instance instanceof EE_Cron_Tasks) {
40
+        if ( ! self::$_instance instanceof EE_Cron_Tasks) {
41 41
             self::$_instance = new self();
42 42
         }
43 43
         return self::$_instance;
@@ -71,7 +71,7 @@  discard block
 block discarded – undo
71 71
              */
72 72
             add_action(
73 73
                 'AHEE__EE_System__load_core_configuration__complete',
74
-                function ()
74
+                function()
75 75
                 {
76 76
                     EE_Registry::instance()->NET_CFG->core->do_messages_on_same_request = true;
77 77
                     EE_Registry::instance()->NET_CFG->update_config(true, false);
@@ -123,8 +123,8 @@  discard block
 block discarded – undo
123 123
             'AHEE__EE_Cron_Tasks__finalize_abandoned_transactions',
124 124
             'AHEE__EE_Cron_Tasks__clean_up_junk_transactions',
125 125
         );
126
-        $crons    = (array)get_option('cron');
127
-        if (! is_array($crons)) {
126
+        $crons = (array) get_option('cron');
127
+        if ( ! is_array($crons)) {
128 128
             return;
129 129
         }
130 130
         foreach ($crons as $timestamp => $cron) {
@@ -132,7 +132,7 @@  discard block
 block discarded – undo
132 132
                 if (isset($cron[$ee_cron]) && is_array($cron[$ee_cron])) {
133 133
                     do_action('AHEE_log', __CLASS__, __FUNCTION__, $ee_cron, 'scheduled EE cron');
134 134
                     foreach ($cron[$ee_cron] as $ee_cron_details) {
135
-                        if (! empty($ee_cron_details['args'])) {
135
+                        if ( ! empty($ee_cron_details['args'])) {
136 136
                             do_action(
137 137
                                 'AHEE_log',
138 138
                                 __CLASS__,
@@ -160,7 +160,7 @@  discard block
 block discarded – undo
160 160
      */
161 161
     public static function reschedule_cron_for_transactions_if_maintenance_mode($cron_task, array $TXN_IDs)
162 162
     {
163
-        if (! method_exists('EE_Cron_Tasks', $cron_task)) {
163
+        if ( ! method_exists('EE_Cron_Tasks', $cron_task)) {
164 164
             throw new \DomainException(
165 165
                 sprintf(
166 166
                     __('"%1$s" is not valid method on EE_Cron_Tasks.', 'event_espresso'),
@@ -169,7 +169,7 @@  discard block
 block discarded – undo
169 169
             );
170 170
         }
171 171
         // reschedule the cron if we can't hit the db right now
172
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
172
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
173 173
             foreach ($TXN_IDs as $TXN_ID => $additional_vars) {
174 174
                 // ensure $additional_vars is an array
175 175
                 $additional_vars = is_array($additional_vars) ? $additional_vars : array($additional_vars);
@@ -294,7 +294,7 @@  discard block
 block discarded – undo
294 294
         EE_Registry::instance()->load_model('Transaction');
295 295
         foreach (self::$_update_transactions_with_payment as $TXN_ID => $PAY_ID) {
296 296
             // reschedule the cron if we can't hit the db right now
297
-            if (! EE_Maintenance_Mode::instance()->models_can_query()) {
297
+            if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
298 298
                 // reset cron job for updating the TXN
299 299
                 EE_Cron_Tasks::schedule_update_transaction_with_payment(
300 300
                     time() + EE_Cron_Tasks::reschedule_timeout,
Please login to merge, or discard this patch.
reg_steps/payment_options/EE_SPCO_Reg_Step_Payment_Options.class.php 1 patch
Indentation   +2866 added lines, -2866 removed lines patch added patch discarded remove patch
@@ -15,2870 +15,2870 @@
 block discarded – undo
15 15
 class EE_SPCO_Reg_Step_Payment_Options extends EE_SPCO_Reg_Step
16 16
 {
17 17
 
18
-    /**
19
-     * @access protected
20
-     * @var EE_Line_Item_Display $Line_Item_Display
21
-     */
22
-    protected $line_item_display;
23
-
24
-    /**
25
-     * @access protected
26
-     * @var boolean $handle_IPN_in_this_request
27
-     */
28
-    protected $handle_IPN_in_this_request = false;
29
-
30
-
31
-    /**
32
-     *    set_hooks - for hooking into EE Core, other modules, etc
33
-     *
34
-     * @access    public
35
-     * @return    void
36
-     */
37
-    public static function set_hooks()
38
-    {
39
-        add_filter(
40
-            'FHEE__SPCO__EE_Line_Item_Filter_Collection',
41
-            array('EE_SPCO_Reg_Step_Payment_Options', 'add_spco_line_item_filters')
42
-        );
43
-        add_action(
44
-            'wp_ajax_switch_spco_billing_form',
45
-            array('EE_SPCO_Reg_Step_Payment_Options', 'switch_spco_billing_form')
46
-        );
47
-        add_action(
48
-            'wp_ajax_nopriv_switch_spco_billing_form',
49
-            array('EE_SPCO_Reg_Step_Payment_Options', 'switch_spco_billing_form')
50
-        );
51
-        add_action('wp_ajax_save_payer_details', array('EE_SPCO_Reg_Step_Payment_Options', 'save_payer_details'));
52
-        add_action(
53
-            'wp_ajax_nopriv_save_payer_details',
54
-            array('EE_SPCO_Reg_Step_Payment_Options', 'save_payer_details')
55
-        );
56
-        add_action(
57
-            'wp_ajax_get_transaction_details_for_gateways',
58
-            array('EE_SPCO_Reg_Step_Payment_Options', 'get_transaction_details')
59
-        );
60
-        add_action(
61
-            'wp_ajax_nopriv_get_transaction_details_for_gateways',
62
-            array('EE_SPCO_Reg_Step_Payment_Options', 'get_transaction_details')
63
-        );
64
-        add_filter(
65
-            'FHEE__EED_Recaptcha___bypass_recaptcha__bypass_request_params_array',
66
-            array('EE_SPCO_Reg_Step_Payment_Options', 'bypass_recaptcha_for_load_payment_method'),
67
-            10,
68
-            1
69
-        );
70
-    }
71
-
72
-
73
-    /**
74
-     *    ajax switch_spco_billing_form
75
-     *
76
-     * @throws \EE_Error
77
-     */
78
-    public static function switch_spco_billing_form()
79
-    {
80
-        EED_Single_Page_Checkout::process_ajax_request('switch_payment_method');
81
-    }
82
-
83
-
84
-    /**
85
-     *    ajax save_payer_details
86
-     *
87
-     * @throws \EE_Error
88
-     */
89
-    public static function save_payer_details()
90
-    {
91
-        EED_Single_Page_Checkout::process_ajax_request('save_payer_details_via_ajax');
92
-    }
93
-
94
-
95
-    /**
96
-     *    ajax get_transaction_details
97
-     *
98
-     * @throws \EE_Error
99
-     */
100
-    public static function get_transaction_details()
101
-    {
102
-        EED_Single_Page_Checkout::process_ajax_request('get_transaction_details_for_gateways');
103
-    }
104
-
105
-
106
-    /**
107
-     * bypass_recaptcha_for_load_payment_method
108
-     *
109
-     * @access public
110
-     * @return array
111
-     * @throws InvalidArgumentException
112
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
113
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
114
-     */
115
-    public static function bypass_recaptcha_for_load_payment_method()
116
-    {
117
-        return array(
118
-            'EESID'  => EE_Registry::instance()->SSN->id(),
119
-            'step'   => 'payment_options',
120
-            'action' => 'spco_billing_form',
121
-        );
122
-    }
123
-
124
-
125
-    /**
126
-     *    class constructor
127
-     *
128
-     * @access    public
129
-     * @param    EE_Checkout $checkout
130
-     */
131
-    public function __construct(EE_Checkout $checkout)
132
-    {
133
-        $this->_slug     = 'payment_options';
134
-        $this->_name     = esc_html__('Payment Options', 'event_espresso');
135
-        $this->_template = SPCO_REG_STEPS_PATH . $this->_slug . DS . 'payment_options_main.template.php';
136
-        $this->checkout  = $checkout;
137
-        $this->_reset_success_message();
138
-        $this->set_instructions(
139
-            esc_html__(
140
-                'Please select a method of payment and provide any necessary billing information before proceeding.',
141
-                'event_espresso'
142
-            )
143
-        );
144
-    }
145
-
146
-
147
-    /**
148
-     * @return null
149
-     */
150
-    public function line_item_display()
151
-    {
152
-        return $this->line_item_display;
153
-    }
154
-
155
-
156
-    /**
157
-     * @param null $line_item_display
158
-     */
159
-    public function set_line_item_display($line_item_display)
160
-    {
161
-        $this->line_item_display = $line_item_display;
162
-    }
163
-
164
-
165
-    /**
166
-     * @return boolean
167
-     */
168
-    public function handle_IPN_in_this_request()
169
-    {
170
-        return $this->handle_IPN_in_this_request;
171
-    }
172
-
173
-
174
-    /**
175
-     * @param boolean $handle_IPN_in_this_request
176
-     */
177
-    public function set_handle_IPN_in_this_request($handle_IPN_in_this_request)
178
-    {
179
-        $this->handle_IPN_in_this_request = filter_var($handle_IPN_in_this_request, FILTER_VALIDATE_BOOLEAN);
180
-    }
181
-
182
-
183
-    /**
184
-     * translate_js_strings
185
-     *
186
-     * @return void
187
-     */
188
-    public function translate_js_strings()
189
-    {
190
-        EE_Registry::$i18n_js_strings['no_payment_method']      = esc_html__(
191
-            'Please select a method of payment in order to continue.',
192
-            'event_espresso'
193
-        );
194
-        EE_Registry::$i18n_js_strings['invalid_payment_method'] = esc_html__(
195
-            'A valid method of payment could not be determined. Please refresh the page and try again.',
196
-            'event_espresso'
197
-        );
198
-        EE_Registry::$i18n_js_strings['forwarding_to_offsite']  = esc_html__(
199
-            'Forwarding to Secure Payment Provider.',
200
-            'event_espresso'
201
-        );
202
-    }
203
-
204
-
205
-    /**
206
-     * enqueue_styles_and_scripts
207
-     *
208
-     * @return void
209
-     * @throws EE_Error
210
-     * @throws InvalidArgumentException
211
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
212
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
213
-     */
214
-    public function enqueue_styles_and_scripts()
215
-    {
216
-        $transaction = $this->checkout->transaction;
217
-        //if the transaction isn't set or nothing is owed on it, don't enqueue any JS
218
-        if (! $transaction instanceof EE_Transaction || EEH_Money::compare_floats($transaction->remaining(), 0)) {
219
-            return;
220
-        }
221
-        foreach (EEM_Payment_Method::instance()->get_all_for_transaction($transaction, EEM_Payment_Method::scope_cart) as $payment_method) {
222
-            $type_obj = $payment_method->type_obj();
223
-            if ($type_obj instanceof EE_PMT_Base) {
224
-                $billing_form = $type_obj->generate_new_billing_form($transaction);
225
-                if ($billing_form instanceof EE_Form_Section_Proper) {
226
-                    $billing_form->enqueue_js();
227
-                }
228
-            }
229
-        }
230
-    }
231
-
232
-
233
-    /**
234
-     * initialize_reg_step
235
-     *
236
-     * @return bool
237
-     * @throws EE_Error
238
-     * @throws InvalidArgumentException
239
-     * @throws ReflectionException
240
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
241
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
242
-     */
243
-    public function initialize_reg_step()
244
-    {
245
-        // TODO: if /when we implement donations, then this will need overriding
246
-        if (// don't need payment options for:
247
-            // 	registrations made via the admin
248
-            // 	completed transactions
249
-            // 	overpaid transactions
250
-            // 	$ 0.00 transactions (no payment required)
251
-            ! $this->checkout->payment_required()
252
-            // but do NOT remove if current action being called belongs to this reg step
253
-            && ! is_callable(array($this, $this->checkout->action))
254
-            && ! $this->completed()
255
-        ) {
256
-            // and if so, then we no longer need the Payment Options step
257
-            if ($this->is_current_step()) {
258
-                $this->checkout->generate_reg_form = false;
259
-            }
260
-            $this->checkout->remove_reg_step($this->_slug);
261
-            // DEBUG LOG
262
-            //$this->checkout->log( __CLASS__, __FUNCTION__, __LINE__ );
263
-            return false;
264
-        }
265
-        // load EEM_Payment_Method
266
-        EE_Registry::instance()->load_model('Payment_Method');
267
-        // get all active payment methods
268
-        $this->checkout->available_payment_methods = EEM_Payment_Method::instance()->get_all_for_transaction(
269
-            $this->checkout->transaction,
270
-            EEM_Payment_Method::scope_cart
271
-        );
272
-        return true;
273
-    }
274
-
275
-
276
-    /**
277
-     * @return EE_Form_Section_Proper
278
-     * @throws EE_Error
279
-     * @throws InvalidArgumentException
280
-     * @throws ReflectionException
281
-     * @throws \EventEspresso\core\exceptions\EntityNotFoundException
282
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
283
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
284
-     * @throws \EventEspresso\core\exceptions\InvalidStatusException
285
-     */
286
-    public function generate_reg_form()
287
-    {
288
-        // reset in case someone changes their mind
289
-        $this->_reset_selected_method_of_payment();
290
-        // set some defaults
291
-        $this->checkout->selected_method_of_payment = 'payments_closed';
292
-        $registrations_requiring_payment            = array();
293
-        $registrations_for_free_events              = array();
294
-        $registrations_requiring_pre_approval       = array();
295
-        $sold_out_events                            = array();
296
-        $insufficient_spaces_available              = array();
297
-        $no_payment_required                        = true;
298
-        // loop thru registrations to gather info
299
-        $registrations         = $this->checkout->transaction->registrations($this->checkout->reg_cache_where_params);
300
-        $ejected_registrations = EE_SPCO_Reg_Step_Payment_Options::find_registrations_that_lost_their_space(
301
-            $registrations,
302
-            $this->checkout->revisit
303
-        );
304
-        foreach ($registrations as $REG_ID => $registration) {
305
-            /** @var $registration EE_Registration */
306
-            // has this registration lost it's space ?
307
-            if (isset($ejected_registrations[$REG_ID])) {
308
-                $insufficient_spaces_available[$registration->event()->ID()] = $registration->event();
309
-                continue;
310
-            }
311
-            // event requires admin approval
312
-            if ($registration->status_ID() === EEM_Registration::status_id_not_approved) {
313
-                // add event to list of events with pre-approval reg status
314
-                $registrations_requiring_pre_approval[$REG_ID] = $registration;
315
-                do_action(
316
-                    'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__event_requires_pre_approval',
317
-                    $registration->event(),
318
-                    $this
319
-                );
320
-                continue;
321
-            }
322
-            if ($this->checkout->revisit
323
-                && $registration->status_ID() !== EEM_Registration::status_id_approved
324
-                && (
325
-                    $registration->event()->is_sold_out()
326
-                    || $registration->event()->is_sold_out(true)
327
-                )
328
-            ) {
329
-                // add event to list of events that are sold out
330
-                $sold_out_events[$registration->event()->ID()] = $registration->event();
331
-                do_action(
332
-                    'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__sold_out_event',
333
-                    $registration->event(),
334
-                    $this
335
-                );
336
-                continue;
337
-            }
338
-            // are they allowed to pay now and is there monies owing?
339
-            if ($registration->owes_monies_and_can_pay()) {
340
-                $registrations_requiring_payment[$REG_ID] = $registration;
341
-                do_action(
342
-                    'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__event_requires_payment',
343
-                    $registration->event(),
344
-                    $this
345
-                );
346
-            } elseif (! $this->checkout->revisit
347
-                && $registration->status_ID() !== EEM_Registration::status_id_not_approved
348
-                && $registration->ticket()->is_free()
349
-            ) {
350
-                $registrations_for_free_events[$registration->event()->ID()] = $registration;
351
-            }
352
-        }
353
-        $subsections = array();
354
-        // now decide which template to load
355
-        if (! empty($sold_out_events)) {
356
-            $subsections['sold_out_events'] = $this->_sold_out_events($sold_out_events);
357
-        }
358
-        if (! empty($insufficient_spaces_available)) {
359
-            $subsections['insufficient_space'] = $this->_insufficient_spaces_available(
360
-                $insufficient_spaces_available
361
-            );
362
-        }
363
-        if (! empty($registrations_requiring_pre_approval)) {
364
-            $subsections['registrations_requiring_pre_approval'] = $this->_registrations_requiring_pre_approval(
365
-                $registrations_requiring_pre_approval
366
-            );
367
-        }
368
-        if (! empty($registrations_for_free_events)) {
369
-            $subsections['no_payment_required'] = $this->_no_payment_required($registrations_for_free_events);
370
-        }
371
-        if (! empty($registrations_requiring_payment)) {
372
-            if ($this->checkout->amount_owing > 0) {
373
-                // autoload Line_Item_Display classes
374
-                EEH_Autoloader::register_line_item_filter_autoloaders();
375
-                $line_item_filter_processor = new EE_Line_Item_Filter_Processor(
376
-                    apply_filters(
377
-                        'FHEE__SPCO__EE_Line_Item_Filter_Collection',
378
-                        new EE_Line_Item_Filter_Collection()
379
-                    ),
380
-                    $this->checkout->cart->get_grand_total()
381
-                );
382
-                /** @var EE_Line_Item $filtered_line_item_tree */
383
-                $filtered_line_item_tree = $line_item_filter_processor->process();
384
-                EEH_Autoloader::register_line_item_display_autoloaders();
385
-                $this->set_line_item_display(new EE_Line_Item_Display('spco'));
386
-                $subsections['payment_options'] = $this->_display_payment_options(
387
-                    $this->line_item_display->display_line_item(
388
-                        $filtered_line_item_tree,
389
-                        array('registrations' => $registrations)
390
-                    )
391
-                );
392
-                $this->checkout->amount_owing   = $filtered_line_item_tree->total();
393
-                $this->_apply_registration_payments_to_amount_owing($registrations);
394
-            }
395
-            $no_payment_required = false;
396
-        } else {
397
-            $this->_hide_reg_step_submit_button_if_revisit();
398
-        }
399
-        $this->_save_selected_method_of_payment();
400
-
401
-        $subsections['default_hidden_inputs'] = $this->reg_step_hidden_inputs();
402
-        $subsections['extra_hidden_inputs']   = $this->_extra_hidden_inputs($no_payment_required);
403
-
404
-        return new EE_Form_Section_Proper(
405
-            array(
406
-                'name'            => $this->reg_form_name(),
407
-                'html_id'         => $this->reg_form_name(),
408
-                'subsections'     => $subsections,
409
-                'layout_strategy' => new EE_No_Layout(),
410
-            )
411
-        );
412
-    }
413
-
414
-
415
-    /**
416
-     * add line item filters required for this reg step
417
-     * these filters are applied via this line in EE_SPCO_Reg_Step_Payment_Options::set_hooks():
418
-     *        add_filter( 'FHEE__SPCO__EE_Line_Item_Filter_Collection', array( 'EE_SPCO_Reg_Step_Payment_Options',
419
-     *        'add_spco_line_item_filters' ) ); so any code that wants to use the same set of filters during the
420
-     *        payment options reg step, can apply these filters via the following: apply_filters(
421
-     *        'FHEE__SPCO__EE_Line_Item_Filter_Collection', new EE_Line_Item_Filter_Collection() ) or to an existing
422
-     *        filter collection by passing that instead of instantiating a new collection
423
-     *
424
-     * @param \EE_Line_Item_Filter_Collection $line_item_filter_collection
425
-     * @return EE_Line_Item_Filter_Collection
426
-     * @throws EE_Error
427
-     * @throws InvalidArgumentException
428
-     * @throws ReflectionException
429
-     * @throws \EventEspresso\core\exceptions\EntityNotFoundException
430
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
431
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
432
-     * @throws \EventEspresso\core\exceptions\InvalidStatusException
433
-     */
434
-    public static function add_spco_line_item_filters(EE_Line_Item_Filter_Collection $line_item_filter_collection)
435
-    {
436
-        if (! EE_Registry::instance()->SSN instanceof EE_Session) {
437
-            return $line_item_filter_collection;
438
-        }
439
-        if (! EE_Registry::instance()->SSN->checkout() instanceof EE_Checkout) {
440
-            return $line_item_filter_collection;
441
-        }
442
-        if (! EE_Registry::instance()->SSN->checkout()->transaction instanceof EE_Transaction) {
443
-            return $line_item_filter_collection;
444
-        }
445
-        $line_item_filter_collection->add(
446
-            new EE_Billable_Line_Item_Filter(
447
-                EE_SPCO_Reg_Step_Payment_Options::remove_ejected_registrations(
448
-                    EE_Registry::instance()->SSN->checkout()->transaction->registrations(
449
-                        EE_Registry::instance()->SSN->checkout()->reg_cache_where_params
450
-                    )
451
-                )
452
-            )
453
-        );
454
-        $line_item_filter_collection->add(new EE_Non_Zero_Line_Item_Filter());
455
-        return $line_item_filter_collection;
456
-    }
457
-
458
-
459
-    /**
460
-     * remove_ejected_registrations
461
-     * if a registrant has lost their potential space at an event due to lack of payment,
462
-     * then this method removes them from the list of registrations being paid for during this request
463
-     *
464
-     * @param \EE_Registration[] $registrations
465
-     * @return EE_Registration[]
466
-     * @throws EE_Error
467
-     * @throws InvalidArgumentException
468
-     * @throws ReflectionException
469
-     * @throws \EventEspresso\core\exceptions\EntityNotFoundException
470
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
471
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
472
-     * @throws \EventEspresso\core\exceptions\InvalidStatusException
473
-     */
474
-    public static function remove_ejected_registrations(array $registrations)
475
-    {
476
-        $ejected_registrations = EE_SPCO_Reg_Step_Payment_Options::find_registrations_that_lost_their_space(
477
-            $registrations,
478
-            EE_Registry::instance()->SSN->checkout()->revisit
479
-        );
480
-        foreach ($registrations as $REG_ID => $registration) {
481
-            // has this registration lost it's space ?
482
-            if (isset($ejected_registrations[$REG_ID])) {
483
-                unset($registrations[$REG_ID]);
484
-                continue;
485
-            }
486
-        }
487
-        return $registrations;
488
-    }
489
-
490
-
491
-    /**
492
-     * find_registrations_that_lost_their_space
493
-     * If a registrant chooses an offline payment method like Invoice,
494
-     * then no space is reserved for them at the event until they fully pay fo that site
495
-     * (unless the event's default reg status is set to APPROVED)
496
-     * if a registrant then later returns to pay, but the number of spaces available has been reduced due to sales,
497
-     * then this method will determine which registrations have lost the ability to complete the reg process.
498
-     *
499
-     * @param \EE_Registration[] $registrations
500
-     * @param bool               $revisit
501
-     * @return array
502
-     * @throws EE_Error
503
-     * @throws InvalidArgumentException
504
-     * @throws ReflectionException
505
-     * @throws \EventEspresso\core\exceptions\EntityNotFoundException
506
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
507
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
508
-     * @throws \EventEspresso\core\exceptions\InvalidStatusException
509
-     */
510
-    public static function find_registrations_that_lost_their_space(array $registrations, $revisit = false)
511
-    {
512
-        // registrations per event
513
-        $event_reg_count = array();
514
-        // spaces left per event
515
-        $event_spaces_remaining = array();
516
-        // tickets left sorted by ID
517
-        $tickets_remaining = array();
518
-        // registrations that have lost their space
519
-        $ejected_registrations = array();
520
-        foreach ($registrations as $REG_ID => $registration) {
521
-            if ($registration->status_ID() === EEM_Registration::status_id_approved
522
-                || apply_filters(
523
-                    'FHEE__EE_SPCO_Reg_Step_Payment_Options__find_registrations_that_lost_their_space__allow_reg_payment',
524
-                    false,
525
-                    $registration,
526
-                    $revisit
527
-                )
528
-            ) {
529
-                continue;
530
-            }
531
-            $EVT_ID = $registration->event_ID();
532
-            $ticket = $registration->ticket();
533
-            if (! isset($tickets_remaining[$ticket->ID()])) {
534
-                $tickets_remaining[$ticket->ID()] = $ticket->remaining();
535
-            }
536
-            if ($tickets_remaining[$ticket->ID()] > 0) {
537
-                if (! isset($event_reg_count[$EVT_ID])) {
538
-                    $event_reg_count[$EVT_ID] = 0;
539
-                }
540
-                $event_reg_count[$EVT_ID]++;
541
-                if (! isset($event_spaces_remaining[$EVT_ID])) {
542
-                    $event_spaces_remaining[$EVT_ID] = $registration->event()->spaces_remaining_for_sale();
543
-                }
544
-            }
545
-            if ($revisit
546
-                && ($tickets_remaining[$ticket->ID()] === 0
547
-                    || $event_reg_count[$EVT_ID] > $event_spaces_remaining[$EVT_ID]
548
-                )
549
-            ) {
550
-                $ejected_registrations[$REG_ID] = $registration->event();
551
-                if ($registration->status_ID() !== EEM_Registration::status_id_wait_list) {
552
-                    /** @type EE_Registration_Processor $registration_processor */
553
-                    $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
554
-                    // at this point, we should have enough details about the registrant to consider the registration
555
-                    // NOT incomplete
556
-                    $registration_processor->manually_update_registration_status(
557
-                        $registration,
558
-                        EEM_Registration::status_id_wait_list
559
-                    );
560
-                }
561
-            }
562
-        }
563
-        return $ejected_registrations;
564
-    }
565
-
566
-
567
-    /**
568
-     * _hide_reg_step_submit_button
569
-     * removes the html for the reg step submit button
570
-     * by replacing it with an empty string via filter callback
571
-     *
572
-     * @return void
573
-     */
574
-    protected function _adjust_registration_status_if_event_old_sold()
575
-    {
576
-    }
577
-
578
-
579
-    /**
580
-     * _hide_reg_step_submit_button
581
-     * removes the html for the reg step submit button
582
-     * by replacing it with an empty string via filter callback
583
-     *
584
-     * @return void
585
-     */
586
-    protected function _hide_reg_step_submit_button_if_revisit()
587
-    {
588
-        if ($this->checkout->revisit) {
589
-            add_filter('FHEE__EE_SPCO_Reg_Step__reg_step_submit_button__sbmt_btn_html', '__return_empty_string');
590
-        }
591
-    }
592
-
593
-
594
-    /**
595
-     * sold_out_events
596
-     * displays notices regarding events that have sold out since hte registrant first signed up
597
-     *
598
-     * @param \EE_Event[] $sold_out_events_array
599
-     * @return \EE_Form_Section_Proper
600
-     * @throws \EE_Error
601
-     */
602
-    private function _sold_out_events($sold_out_events_array = array())
603
-    {
604
-        // set some defaults
605
-        $this->checkout->selected_method_of_payment = 'events_sold_out';
606
-        $sold_out_events                            = '';
607
-        foreach ($sold_out_events_array as $sold_out_event) {
608
-            $sold_out_events .= EEH_HTML::li(
609
-                EEH_HTML::span(
610
-                    '  ' . $sold_out_event->name(),
611
-                    '',
612
-                    'dashicons dashicons-marker ee-icon-size-16 pink-text'
613
-                )
614
-            );
615
-        }
616
-        return new EE_Form_Section_Proper(
617
-            array(
618
-                'layout_strategy' => new EE_Template_Layout(
619
-                    array(
620
-                        'layout_template_file' => SPCO_REG_STEPS_PATH
621
-                                                  . $this->_slug
622
-                                                  . DS
623
-                                                  . 'sold_out_events.template.php',
624
-                        'template_args'        => apply_filters(
625
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___sold_out_events__template_args',
626
-                            array(
627
-                                'sold_out_events'     => $sold_out_events,
628
-                                'sold_out_events_msg' => apply_filters(
629
-                                    'FHEE__EE_SPCO_Reg_Step_Payment_Options___sold_out_events__sold_out_events_msg',
630
-                                    sprintf(
631
-                                        esc_html__(
632
-                                            'It appears that the event you were about to make a payment for has sold out since you first registered. If you have already made a partial payment towards this event, please contact the event administrator for a refund.%3$s%3$s%1$sPlease note that availability can change at any time due to cancellations, so please check back again later if registration for this event(s) is important to you.%2$s',
633
-                                            'event_espresso'
634
-                                        ),
635
-                                        '<strong>',
636
-                                        '</strong>',
637
-                                        '<br />'
638
-                                    )
639
-                                ),
640
-                            )
641
-                        ),
642
-                    )
643
-                ),
644
-            )
645
-        );
646
-    }
647
-
648
-
649
-    /**
650
-     * _insufficient_spaces_available
651
-     * displays notices regarding events that do not have enough remaining spaces
652
-     * to satisfy the current number of registrations looking to pay
653
-     *
654
-     * @param \EE_Event[] $insufficient_spaces_events_array
655
-     * @return \EE_Form_Section_Proper
656
-     * @throws \EE_Error
657
-     */
658
-    private function _insufficient_spaces_available($insufficient_spaces_events_array = array())
659
-    {
660
-        // set some defaults
661
-        $this->checkout->selected_method_of_payment = 'invoice';
662
-        $insufficient_space_events                  = '';
663
-        foreach ($insufficient_spaces_events_array as $event) {
664
-            if ($event instanceof EE_Event) {
665
-                $insufficient_space_events .= EEH_HTML::li(
666
-                    EEH_HTML::span(' ' . $event->name(), '', 'dashicons dashicons-marker ee-icon-size-16 pink-text')
667
-                );
668
-            }
669
-        }
670
-        return new EE_Form_Section_Proper(
671
-            array(
672
-                'subsections'     => array(
673
-                    'default_hidden_inputs' => $this->reg_step_hidden_inputs(),
674
-                    'extra_hidden_inputs'   => $this->_extra_hidden_inputs(),
675
-                ),
676
-                'layout_strategy' => new EE_Template_Layout(
677
-                    array(
678
-                        'layout_template_file' => SPCO_REG_STEPS_PATH
679
-                                                  . $this->_slug
680
-                                                  . DS
681
-                                                  . 'sold_out_events.template.php',
682
-                        'template_args'        => apply_filters(
683
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___insufficient_spaces_available__template_args',
684
-                            array(
685
-                                'sold_out_events'     => $insufficient_space_events,
686
-                                'sold_out_events_msg' => apply_filters(
687
-                                    'FHEE__EE_SPCO_Reg_Step_Payment_Options___insufficient_spaces_available__insufficient_space_msg',
688
-                                    esc_html__(
689
-                                        'It appears that the event you were about to make a payment for has sold additional tickets since you first registered, and there are no longer enough spaces left to accommodate your selections. You may continue to pay and secure the available space(s) remaining, or simply cancel if you no longer wish to purchase. If you have already made a partial payment towards this event, please contact the event administrator for a refund.',
690
-                                        'event_espresso'
691
-                                    )
692
-                                ),
693
-                            )
694
-                        ),
695
-                    )
696
-                ),
697
-            )
698
-        );
699
-    }
700
-
701
-
702
-    /**
703
-     * registrations_requiring_pre_approval
704
-     *
705
-     * @param array $registrations_requiring_pre_approval
706
-     * @return EE_Form_Section_Proper
707
-     * @throws EE_Error
708
-     * @throws \EventEspresso\core\exceptions\EntityNotFoundException
709
-     */
710
-    private function _registrations_requiring_pre_approval($registrations_requiring_pre_approval = array())
711
-    {
712
-        $events_requiring_pre_approval = '';
713
-        foreach ($registrations_requiring_pre_approval as $registration) {
714
-            if ($registration instanceof EE_Registration && $registration->event() instanceof EE_Event) {
715
-                $events_requiring_pre_approval[$registration->event()->ID()] = EEH_HTML::li(
716
-                    EEH_HTML::span(
717
-                        '',
718
-                        '',
719
-                        'dashicons dashicons-marker ee-icon-size-16 orange-text'
720
-                    )
721
-                    . EEH_HTML::span($registration->event()->name(), '', 'orange-text')
722
-                );
723
-            }
724
-        }
725
-        return new EE_Form_Section_Proper(
726
-            array(
727
-                'layout_strategy' => new EE_Template_Layout(
728
-                    array(
729
-                        'layout_template_file' => SPCO_REG_STEPS_PATH
730
-                                                  . $this->_slug
731
-                                                  . DS
732
-                                                  . 'events_requiring_pre_approval.template.php', // layout_template
733
-                        'template_args'        => apply_filters(
734
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___sold_out_events__template_args',
735
-                            array(
736
-                                'events_requiring_pre_approval'     => implode('', $events_requiring_pre_approval),
737
-                                'events_requiring_pre_approval_msg' => apply_filters(
738
-                                    'FHEE__EE_SPCO_Reg_Step_Payment_Options___events_requiring_pre_approval__events_requiring_pre_approval_msg',
739
-                                    esc_html__(
740
-                                        'The following events do not require payment at this time and will not be billed during this transaction. Billing will only occur after the attendee has been approved by the event organizer. You will be notified when your registration has been processed. If this is a free event, then no billing will occur.',
741
-                                        'event_espresso'
742
-                                    )
743
-                                ),
744
-                            )
745
-                        ),
746
-                    )
747
-                ),
748
-            )
749
-        );
750
-    }
751
-
752
-
753
-    /**
754
-     * _no_payment_required
755
-     *
756
-     * @param \EE_Event[] $registrations_for_free_events
757
-     * @return \EE_Form_Section_Proper
758
-     * @throws \EE_Error
759
-     */
760
-    private function _no_payment_required($registrations_for_free_events = array())
761
-    {
762
-        // set some defaults
763
-        $this->checkout->selected_method_of_payment = 'no_payment_required';
764
-        // generate no_payment_required form
765
-        return new EE_Form_Section_Proper(
766
-            array(
767
-                'layout_strategy' => new EE_Template_Layout(
768
-                    array(
769
-                        'layout_template_file' => SPCO_REG_STEPS_PATH
770
-                                                  . $this->_slug
771
-                                                  . DS
772
-                                                  . 'no_payment_required.template.php', // layout_template
773
-                        'template_args'        => apply_filters(
774
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___no_payment_required__template_args',
775
-                            array(
776
-                                'revisit'                       => $this->checkout->revisit,
777
-                                'registrations'                 => array(),
778
-                                'ticket_count'                  => array(),
779
-                                'registrations_for_free_events' => $registrations_for_free_events,
780
-                                'no_payment_required_msg'       => EEH_HTML::p(
781
-                                    esc_html__('This is a free event, so no billing will occur.', 'event_espresso')
782
-                                ),
783
-                            )
784
-                        ),
785
-                    )
786
-                ),
787
-            )
788
-        );
789
-    }
790
-
791
-
792
-    /**
793
-     * _display_payment_options
794
-     *
795
-     * @param string $transaction_details
796
-     * @return EE_Form_Section_Proper
797
-     * @throws EE_Error
798
-     * @throws InvalidArgumentException
799
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
800
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
801
-     */
802
-    private function _display_payment_options($transaction_details = '')
803
-    {
804
-        // has method_of_payment been set by no-js user?
805
-        $this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment();
806
-        // build payment options form
807
-        return apply_filters(
808
-            'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__payment_options_form',
809
-            new EE_Form_Section_Proper(
810
-                array(
811
-                    'subsections'     => array(
812
-                        'before_payment_options' => apply_filters(
813
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__before_payment_options',
814
-                            new EE_Form_Section_Proper(
815
-                                array('layout_strategy' => new EE_Div_Per_Section_Layout())
816
-                            )
817
-                        ),
818
-                        'payment_options'        => $this->_setup_payment_options(),
819
-                        'after_payment_options'  => apply_filters(
820
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__after_payment_options',
821
-                            new EE_Form_Section_Proper(
822
-                                array('layout_strategy' => new EE_Div_Per_Section_Layout())
823
-                            )
824
-                        ),
825
-                    ),
826
-                    'layout_strategy' => new EE_Template_Layout(
827
-                        array(
828
-                            'layout_template_file' => $this->_template,
829
-                            'template_args'        => apply_filters(
830
-                                'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__template_args',
831
-                                array(
832
-                                    'reg_count'                 => $this->line_item_display->total_items(),
833
-                                    'transaction_details'       => $transaction_details,
834
-                                    'available_payment_methods' => array(),
835
-                                )
836
-                            ),
837
-                        )
838
-                    ),
839
-                )
840
-            )
841
-        );
842
-    }
843
-
844
-
845
-    /**
846
-     * _extra_hidden_inputs
847
-     *
848
-     * @param bool $no_payment_required
849
-     * @return \EE_Form_Section_Proper
850
-     * @throws \EE_Error
851
-     */
852
-    private function _extra_hidden_inputs($no_payment_required = true)
853
-    {
854
-        return new EE_Form_Section_Proper(
855
-            array(
856
-                'html_id'         => 'ee-' . $this->slug() . '-extra-hidden-inputs',
857
-                'layout_strategy' => new EE_Div_Per_Section_Layout(),
858
-                'subsections'     => array(
859
-                    'spco_no_payment_required' => new EE_Hidden_Input(
860
-                        array(
861
-                            'normalization_strategy' => new EE_Boolean_Normalization(),
862
-                            'html_name'              => 'spco_no_payment_required',
863
-                            'html_id'                => 'spco-no-payment-required-payment_options',
864
-                            'default'                => $no_payment_required,
865
-                        )
866
-                    ),
867
-                    'spco_transaction_id'      => new EE_Fixed_Hidden_Input(
868
-                        array(
869
-                            'normalization_strategy' => new EE_Int_Normalization(),
870
-                            'html_name'              => 'spco_transaction_id',
871
-                            'html_id'                => 'spco-transaction-id',
872
-                            'default'                => $this->checkout->transaction->ID(),
873
-                        )
874
-                    ),
875
-                ),
876
-            )
877
-        );
878
-    }
879
-
880
-
881
-    /**
882
-     *    _apply_registration_payments_to_amount_owing
883
-     *
884
-     * @access protected
885
-     * @param array $registrations
886
-     * @throws EE_Error
887
-     */
888
-    protected function _apply_registration_payments_to_amount_owing(array $registrations)
889
-    {
890
-        $payments = array();
891
-        foreach ($registrations as $registration) {
892
-            if ($registration instanceof EE_Registration && $registration->owes_monies_and_can_pay()) {
893
-                $payments += $registration->registration_payments();
894
-            }
895
-        }
896
-        if (! empty($payments)) {
897
-            foreach ($payments as $payment) {
898
-                if ($payment instanceof EE_Registration_Payment) {
899
-                    $this->checkout->amount_owing -= $payment->amount();
900
-                }
901
-            }
902
-        }
903
-    }
904
-
905
-
906
-    /**
907
-     *    _reset_selected_method_of_payment
908
-     *
909
-     * @access    private
910
-     * @param    bool $force_reset
911
-     * @return void
912
-     * @throws InvalidArgumentException
913
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
914
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
915
-     */
916
-    private function _reset_selected_method_of_payment($force_reset = false)
917
-    {
918
-        $reset_payment_method = $force_reset
919
-            ? true
920
-            : sanitize_text_field(EE_Registry::instance()->REQ->get('reset_payment_method', false));
921
-        if ($reset_payment_method) {
922
-            $this->checkout->selected_method_of_payment = null;
923
-            $this->checkout->payment_method             = null;
924
-            $this->checkout->billing_form               = null;
925
-            $this->_save_selected_method_of_payment();
926
-        }
927
-    }
928
-
929
-
930
-    /**
931
-     * _save_selected_method_of_payment
932
-     * stores the selected_method_of_payment in the session
933
-     * so that it's available for all subsequent requests including AJAX
934
-     *
935
-     * @access        private
936
-     * @param string $selected_method_of_payment
937
-     * @return void
938
-     * @throws InvalidArgumentException
939
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
940
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
941
-     */
942
-    private function _save_selected_method_of_payment($selected_method_of_payment = '')
943
-    {
944
-        $selected_method_of_payment = ! empty($selected_method_of_payment)
945
-            ? $selected_method_of_payment
946
-            : $this->checkout->selected_method_of_payment;
947
-        EE_Registry::instance()->SSN->set_session_data(
948
-            array('selected_method_of_payment' => $selected_method_of_payment)
949
-        );
950
-    }
951
-
952
-
953
-    /**
954
-     * _setup_payment_options
955
-     *
956
-     * @return EE_Form_Section_Proper
957
-     * @throws EE_Error
958
-     * @throws InvalidArgumentException
959
-     * @throws ReflectionException
960
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
961
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
962
-     */
963
-    public function _setup_payment_options()
964
-    {
965
-        // load payment method classes
966
-        $this->checkout->available_payment_methods = $this->_get_available_payment_methods();
967
-        if (empty($this->checkout->available_payment_methods)) {
968
-            EE_Error::add_error(
969
-                apply_filters(
970
-                    'FHEE__EE_SPCO_Reg_Step_Payment_Options___setup_payment_options__error_message_no_payment_methods',
971
-                    sprintf(
972
-                        esc_html__(
973
-                            'Sorry, you cannot complete your purchase because a payment method is not active.%1$s Please contact %2$s for assistance and provide a description of the problem.',
974
-                            'event_espresso'
975
-                        ),
976
-                        '<br>',
977
-                        EE_Registry::instance()->CFG->organization->get_pretty('email')
978
-                    )
979
-                ),
980
-                __FILE__,
981
-                __FUNCTION__,
982
-                __LINE__
983
-            );
984
-        }
985
-        // switch up header depending on number of available payment methods
986
-        $payment_method_header     = count($this->checkout->available_payment_methods) > 1
987
-            ? apply_filters(
988
-                'FHEE__registration_page_payment_options__method_of_payment_hdr',
989
-                esc_html__('Please Select Your Method of Payment', 'event_espresso')
990
-            )
991
-            : apply_filters(
992
-                'FHEE__registration_page_payment_options__method_of_payment_hdr',
993
-                esc_html__('Method of Payment', 'event_espresso')
994
-            );
995
-        $available_payment_methods = array(
996
-            // display the "Payment Method" header
997
-            'payment_method_header' => new EE_Form_Section_HTML(
998
-                EEH_HTML::h4($payment_method_header, 'method-of-payment-hdr')
999
-            ),
1000
-        );
1001
-        // the list of actual payment methods ( invoice, paypal, etc ) in a  ( slug => HTML )  format
1002
-        $available_payment_method_options = array();
1003
-        $default_payment_method_option    = array();
1004
-        // additional instructions to be displayed and hidden below payment methods (adding a clearing div to start)
1005
-        $payment_methods_billing_info = array(
1006
-            new EE_Form_Section_HTML(
1007
-                EEH_HTML::div('<br />', '', '', 'clear:both;')
1008
-            ),
1009
-        );
1010
-        // loop through payment methods
1011
-        foreach ($this->checkout->available_payment_methods as $payment_method) {
1012
-            if ($payment_method instanceof EE_Payment_Method) {
1013
-                $payment_method_button = EEH_HTML::img(
1014
-                    $payment_method->button_url(),
1015
-                    $payment_method->name(),
1016
-                    'spco-payment-method-' . $payment_method->slug() . '-btn-img',
1017
-                    'spco-payment-method-btn-img'
1018
-                );
1019
-                // check if any payment methods are set as default
1020
-                // if payment method is already selected OR nothing is selected and this payment method should be
1021
-                // open_by_default
1022
-                if (($this->checkout->selected_method_of_payment === $payment_method->slug())
1023
-                    || (! $this->checkout->selected_method_of_payment && $payment_method->open_by_default())
1024
-                ) {
1025
-                    $this->checkout->selected_method_of_payment = $payment_method->slug();
1026
-                    $this->_save_selected_method_of_payment();
1027
-                    $default_payment_method_option[$payment_method->slug()] = $payment_method_button;
1028
-                } else {
1029
-                    $available_payment_method_options[$payment_method->slug()] = $payment_method_button;
1030
-                }
1031
-                $payment_methods_billing_info[$payment_method->slug() . '-info'] = $this->_payment_method_billing_info(
1032
-                    $payment_method
1033
-                );
1034
-            }
1035
-        }
1036
-        // prepend available_payment_method_options with default_payment_method_option so that it appears first in list
1037
-        // of PMs
1038
-        $available_payment_method_options = $default_payment_method_option + $available_payment_method_options;
1039
-        // now generate the actual form  inputs
1040
-        $available_payment_methods['available_payment_methods'] = $this->_available_payment_method_inputs(
1041
-            $available_payment_method_options
1042
-        );
1043
-        $available_payment_methods                              += $payment_methods_billing_info;
1044
-        // build the available payment methods form
1045
-        return new EE_Form_Section_Proper(
1046
-            array(
1047
-                'html_id'         => 'spco-available-methods-of-payment-dv',
1048
-                'subsections'     => $available_payment_methods,
1049
-                'layout_strategy' => new EE_Div_Per_Section_Layout(),
1050
-            )
1051
-        );
1052
-    }
1053
-
1054
-
1055
-    /**
1056
-     * _get_available_payment_methods
1057
-     *
1058
-     * @return EE_Payment_Method[]
1059
-     * @throws EE_Error
1060
-     * @throws InvalidArgumentException
1061
-     * @throws ReflectionException
1062
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1063
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1064
-     */
1065
-    protected function _get_available_payment_methods()
1066
-    {
1067
-        if (! empty($this->checkout->available_payment_methods)) {
1068
-            return $this->checkout->available_payment_methods;
1069
-        }
1070
-        $available_payment_methods = array();
1071
-        // load EEM_Payment_Method
1072
-        EE_Registry::instance()->load_model('Payment_Method');
1073
-        /** @type EEM_Payment_Method $EEM_Payment_Method */
1074
-        $EEM_Payment_Method = EE_Registry::instance()->LIB->EEM_Payment_Method;
1075
-        // get all active payment methods
1076
-        $payment_methods = $EEM_Payment_Method->get_all_for_transaction(
1077
-            $this->checkout->transaction,
1078
-            EEM_Payment_Method::scope_cart
1079
-        );
1080
-        foreach ($payment_methods as $payment_method) {
1081
-            if ($payment_method instanceof EE_Payment_Method) {
1082
-                $available_payment_methods[$payment_method->slug()] = $payment_method;
1083
-            }
1084
-        }
1085
-        return $available_payment_methods;
1086
-    }
1087
-
1088
-
1089
-    /**
1090
-     *    _available_payment_method_inputs
1091
-     *
1092
-     * @access    private
1093
-     * @param    array $available_payment_method_options
1094
-     * @return    \EE_Form_Section_Proper
1095
-     */
1096
-    private function _available_payment_method_inputs($available_payment_method_options = array())
1097
-    {
1098
-        // generate inputs
1099
-        return new EE_Form_Section_Proper(
1100
-            array(
1101
-                'html_id'         => 'ee-available-payment-method-inputs',
1102
-                'layout_strategy' => new EE_Div_Per_Section_Layout(),
1103
-                'subsections'     => array(
1104
-                    '' => new EE_Radio_Button_Input(
1105
-                        $available_payment_method_options,
1106
-                        array(
1107
-                            'html_name'          => 'selected_method_of_payment',
1108
-                            'html_class'         => 'spco-payment-method',
1109
-                            'default'            => $this->checkout->selected_method_of_payment,
1110
-                            'label_size'         => 11,
1111
-                            'enforce_label_size' => true,
1112
-                        )
1113
-                    ),
1114
-                ),
1115
-            )
1116
-        );
1117
-    }
1118
-
1119
-
1120
-    /**
1121
-     *    _payment_method_billing_info
1122
-     *
1123
-     * @access    private
1124
-     * @param    EE_Payment_Method $payment_method
1125
-     * @return EE_Form_Section_Proper
1126
-     * @throws EE_Error
1127
-     * @throws InvalidArgumentException
1128
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1129
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1130
-     */
1131
-    private function _payment_method_billing_info(EE_Payment_Method $payment_method)
1132
-    {
1133
-        $currently_selected = $this->checkout->selected_method_of_payment === $payment_method->slug()
1134
-            ? true
1135
-            : false;
1136
-        // generate the billing form for payment method
1137
-        $billing_form                 = $currently_selected
1138
-            ? $this->_get_billing_form_for_payment_method($payment_method)
1139
-            : new EE_Form_Section_HTML();
1140
-        $this->checkout->billing_form = $currently_selected
1141
-            ? $billing_form
1142
-            : $this->checkout->billing_form;
1143
-        // it's all in the details
1144
-        $info_html = EEH_HTML::h3(
1145
-            esc_html__('Important information regarding your payment', 'event_espresso'),
1146
-            '',
1147
-            'spco-payment-method-hdr'
1148
-        );
1149
-        // add some info regarding the step, either from what's saved in the admin,
1150
-        // or a default string depending on whether the PM has a billing form or not
1151
-        if ($payment_method->description()) {
1152
-            $payment_method_info = $payment_method->description();
1153
-        } elseif ($billing_form instanceof EE_Billing_Info_Form) {
1154
-            $payment_method_info = sprintf(
1155
-                esc_html__(
1156
-                    'Please provide the following billing information, then click the "%1$s" button below in order to proceed.',
1157
-                    'event_espresso'
1158
-                ),
1159
-                $this->submit_button_text()
1160
-            );
1161
-        } else {
1162
-            $payment_method_info = sprintf(
1163
-                esc_html__('Please click the "%1$s" button below in order to proceed.', 'event_espresso'),
1164
-                $this->submit_button_text()
1165
-            );
1166
-        }
1167
-        $info_html .= EEH_HTML::p(
1168
-            apply_filters(
1169
-                'FHEE__EE_SPCO_Reg_Step_Payment_Options___payment_method_billing_info__payment_method_info',
1170
-                $payment_method_info
1171
-            ),
1172
-            '',
1173
-            'spco-payment-method-desc ee-attention'
1174
-        );
1175
-        return new EE_Form_Section_Proper(
1176
-            array(
1177
-                'html_id'         => 'spco-payment-method-info-' . $payment_method->slug(),
1178
-                'html_class'      => 'spco-payment-method-info-dv',
1179
-                // only display the selected or default PM
1180
-                'html_style'      => $currently_selected ? '' : 'display:none;',
1181
-                'layout_strategy' => new EE_Div_Per_Section_Layout(),
1182
-                'subsections'     => array(
1183
-                    'info'         => new EE_Form_Section_HTML($info_html),
1184
-                    'billing_form' => $currently_selected ? $billing_form : new EE_Form_Section_HTML(),
1185
-                ),
1186
-            )
1187
-        );
1188
-    }
1189
-
1190
-
1191
-    /**
1192
-     * get_billing_form_html_for_payment_method
1193
-     *
1194
-     * @access public
1195
-     * @return string
1196
-     * @throws EE_Error
1197
-     * @throws InvalidArgumentException
1198
-     * @throws ReflectionException
1199
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1200
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1201
-     */
1202
-    public function get_billing_form_html_for_payment_method()
1203
-    {
1204
-        // how have they chosen to pay?
1205
-        $this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
1206
-        $this->checkout->payment_method             = $this->_get_payment_method_for_selected_method_of_payment();
1207
-        if (! $this->checkout->payment_method instanceof EE_Payment_Method) {
1208
-            return false;
1209
-        }
1210
-        if (apply_filters(
1211
-            'FHEE__EE_SPCO_Reg_Step_Payment_Options__registration_checkout__selected_payment_method__display_success',
1212
-            false
1213
-        )) {
1214
-            EE_Error::add_success(
1215
-                apply_filters(
1216
-                    'FHEE__Single_Page_Checkout__registration_checkout__selected_payment_method',
1217
-                    sprintf(
1218
-                        esc_html__(
1219
-                            'You have selected "%s" as your method of payment. Please note the important payment information below.',
1220
-                            'event_espresso'
1221
-                        ),
1222
-                        $this->checkout->payment_method->name()
1223
-                    )
1224
-                )
1225
-            );
1226
-        }
1227
-        // now generate billing form for selected method of payment
1228
-        $payment_method_billing_form = $this->_get_billing_form_for_payment_method($this->checkout->payment_method);
1229
-        // fill form with attendee info if applicable
1230
-        if ($payment_method_billing_form instanceof EE_Billing_Attendee_Info_Form
1231
-            && $this->checkout->transaction_has_primary_registrant()
1232
-        ) {
1233
-            $payment_method_billing_form->populate_from_attendee(
1234
-                $this->checkout->transaction->primary_registration()->attendee()
1235
-            );
1236
-        }
1237
-        // and debug content
1238
-        if ($payment_method_billing_form instanceof EE_Billing_Info_Form
1239
-            && $this->checkout->payment_method->type_obj() instanceof EE_PMT_Base
1240
-        ) {
1241
-            $payment_method_billing_form =
1242
-                $this->checkout->payment_method->type_obj()->apply_billing_form_debug_settings(
1243
-                    $payment_method_billing_form
1244
-                );
1245
-        }
1246
-        $billing_info = $payment_method_billing_form instanceof EE_Form_Section_Proper
1247
-            ? $payment_method_billing_form->get_html()
1248
-            : '';
1249
-        $this->checkout->json_response->set_return_data(array('payment_method_info' => $billing_info));
1250
-        // localize validation rules for main form
1251
-        $this->checkout->current_step->reg_form->localize_validation_rules();
1252
-        $this->checkout->json_response->add_validation_rules(EE_Form_Section_Proper::js_localization());
1253
-        return true;
1254
-    }
1255
-
1256
-
1257
-    /**
1258
-     * _get_billing_form_for_payment_method
1259
-     *
1260
-     * @access private
1261
-     * @param EE_Payment_Method $payment_method
1262
-     * @return EE_Billing_Info_Form|EE_Form_Section_HTML
1263
-     * @throws EE_Error
1264
-     * @throws InvalidArgumentException
1265
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1266
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1267
-     */
1268
-    private function _get_billing_form_for_payment_method(EE_Payment_Method $payment_method)
1269
-    {
1270
-        $billing_form = $payment_method->type_obj()->billing_form(
1271
-            $this->checkout->transaction,
1272
-            array('amount_owing' => $this->checkout->amount_owing)
1273
-        );
1274
-        if ($billing_form instanceof EE_Billing_Info_Form) {
1275
-            if (apply_filters(
1276
-                'FHEE__EE_SPCO_Reg_Step_Payment_Options__registration_checkout__selected_payment_method__display_success',
1277
-                false
1278
-            )
1279
-                && EE_Registry::instance()->REQ->is_set('payment_method')
1280
-            ) {
1281
-                EE_Error::add_success(
1282
-                    apply_filters(
1283
-                        'FHEE__Single_Page_Checkout__registration_checkout__selected_payment_method',
1284
-                        sprintf(
1285
-                            esc_html__(
1286
-                                'You have selected "%s" as your method of payment. Please note the important payment information below.',
1287
-                                'event_espresso'
1288
-                            ),
1289
-                            $payment_method->name()
1290
-                        )
1291
-                    )
1292
-                );
1293
-            }
1294
-            return apply_filters(
1295
-                'FHEE__EE_SPCO_Reg_Step_Payment_Options___get_billing_form_for_payment_method__billing_form',
1296
-                $billing_form,
1297
-                $payment_method
1298
-            );
1299
-        }
1300
-        // no actual billing form, so return empty HTML form section
1301
-        return new EE_Form_Section_HTML();
1302
-    }
1303
-
1304
-
1305
-    /**
1306
-     * _get_selected_method_of_payment
1307
-     *
1308
-     * @access private
1309
-     * @param boolean $required whether to throw an error if the "selected_method_of_payment"
1310
-     *                          is not found in the incoming request
1311
-     * @param string  $request_param
1312
-     * @return NULL|string
1313
-     * @throws EE_Error
1314
-     * @throws InvalidArgumentException
1315
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1316
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1317
-     */
1318
-    private function _get_selected_method_of_payment(
1319
-        $required = false,
1320
-        $request_param = 'selected_method_of_payment'
1321
-    ) {
1322
-        // is selected_method_of_payment set in the request ?
1323
-        $selected_method_of_payment = EE_Registry::instance()->REQ->get($request_param, false);
1324
-        if ($selected_method_of_payment) {
1325
-            // sanitize it
1326
-            $selected_method_of_payment = is_array($selected_method_of_payment)
1327
-                ? array_shift($selected_method_of_payment)
1328
-                : $selected_method_of_payment;
1329
-            $selected_method_of_payment = sanitize_text_field($selected_method_of_payment);
1330
-            // store it in the session so that it's available for all subsequent requests including AJAX
1331
-            $this->_save_selected_method_of_payment($selected_method_of_payment);
1332
-        } else {
1333
-            // or is is set in the session ?
1334
-            $selected_method_of_payment = EE_Registry::instance()->SSN->get_session_data(
1335
-                'selected_method_of_payment'
1336
-            );
1337
-        }
1338
-        // do ya really really gotta have it?
1339
-        if (empty($selected_method_of_payment) && $required) {
1340
-            EE_Error::add_error(
1341
-                sprintf(
1342
-                    esc_html__(
1343
-                        'The selected method of payment could not be determined.%sPlease ensure that you have selected one before proceeding.%sIf you continue to experience difficulties, then refresh your browser and try again, or contact %s for assistance.',
1344
-                        'event_espresso'
1345
-                    ),
1346
-                    '<br/>',
1347
-                    '<br/>',
1348
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
1349
-                ),
1350
-                __FILE__,
1351
-                __FUNCTION__,
1352
-                __LINE__
1353
-            );
1354
-            return null;
1355
-        }
1356
-        return $selected_method_of_payment;
1357
-    }
1358
-
1359
-
1360
-
1361
-
1362
-
1363
-
1364
-    /********************************************************************************************************/
1365
-    /***********************************  SWITCH PAYMENT METHOD  ************************************/
1366
-    /********************************************************************************************************/
1367
-    /**
1368
-     * switch_payment_method
1369
-     *
1370
-     * @access public
1371
-     * @return string
1372
-     * @throws EE_Error
1373
-     * @throws InvalidArgumentException
1374
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1375
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1376
-     */
1377
-    public function switch_payment_method()
1378
-    {
1379
-        if (! $this->_verify_payment_method_is_set()) {
1380
-            return false;
1381
-        }
1382
-        if (apply_filters(
1383
-            'FHEE__EE_SPCO_Reg_Step_Payment_Options__registration_checkout__selected_payment_method__display_success',
1384
-            false
1385
-        )) {
1386
-            EE_Error::add_success(
1387
-                apply_filters(
1388
-                    'FHEE__Single_Page_Checkout__registration_checkout__selected_payment_method',
1389
-                    sprintf(
1390
-                        esc_html__(
1391
-                            'You have selected "%s" as your method of payment. Please note the important payment information below.',
1392
-                            'event_espresso'
1393
-                        ),
1394
-                        $this->checkout->payment_method->name()
1395
-                    )
1396
-                )
1397
-            );
1398
-        }
1399
-        // generate billing form for selected method of payment if it hasn't been done already
1400
-        if ($this->checkout->payment_method->type_obj()->has_billing_form()) {
1401
-            $this->checkout->billing_form = $this->_get_billing_form_for_payment_method(
1402
-                $this->checkout->payment_method
1403
-            );
1404
-        }
1405
-        // fill form with attendee info if applicable
1406
-        if (apply_filters(
1407
-            'FHEE__populate_billing_form_fields_from_attendee',
1408
-            (
1409
-                $this->checkout->billing_form instanceof EE_Billing_Attendee_Info_Form
1410
-                && $this->checkout->transaction_has_primary_registrant()
1411
-            ),
1412
-            $this->checkout->billing_form,
1413
-            $this->checkout->transaction
1414
-        )
1415
-        ) {
1416
-            $this->checkout->billing_form->populate_from_attendee(
1417
-                $this->checkout->transaction->primary_registration()->attendee()
1418
-            );
1419
-        }
1420
-        // and debug content
1421
-        if ($this->checkout->billing_form instanceof EE_Billing_Info_Form
1422
-            && $this->checkout->payment_method->type_obj() instanceof EE_PMT_Base
1423
-        ) {
1424
-            $this->checkout->billing_form =
1425
-                $this->checkout->payment_method->type_obj()->apply_billing_form_debug_settings(
1426
-                    $this->checkout->billing_form
1427
-                );
1428
-        }
1429
-        // get html and validation rules for form
1430
-        if ($this->checkout->billing_form instanceof EE_Form_Section_Proper) {
1431
-            $this->checkout->json_response->set_return_data(
1432
-                array('payment_method_info' => $this->checkout->billing_form->get_html())
1433
-            );
1434
-            // localize validation rules for main form
1435
-            $this->checkout->billing_form->localize_validation_rules(true);
1436
-            $this->checkout->json_response->add_validation_rules(EE_Form_Section_Proper::js_localization());
1437
-        } else {
1438
-            $this->checkout->json_response->set_return_data(array('payment_method_info' => ''));
1439
-        }
1440
-        //prevents advancement to next step
1441
-        $this->checkout->continue_reg = false;
1442
-        return true;
1443
-    }
1444
-
1445
-
1446
-    /**
1447
-     * _verify_payment_method_is_set
1448
-     *
1449
-     * @return bool
1450
-     * @throws EE_Error
1451
-     * @throws InvalidArgumentException
1452
-     * @throws ReflectionException
1453
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1454
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1455
-     */
1456
-    protected function _verify_payment_method_is_set()
1457
-    {
1458
-        // generate billing form for selected method of payment if it hasn't been done already
1459
-        if (empty($this->checkout->selected_method_of_payment)) {
1460
-            // how have they chosen to pay?
1461
-            $this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
1462
-        } else {
1463
-            // choose your own adventure based on method_of_payment
1464
-            switch ($this->checkout->selected_method_of_payment) {
1465
-                case 'events_sold_out' :
1466
-                    EE_Error::add_attention(
1467
-                        apply_filters(
1468
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___verify_payment_method_is_set__sold_out_events_msg',
1469
-                            esc_html__(
1470
-                                'It appears that the event you were about to make a payment for has sold out since this form first loaded. Please contact the event administrator if you believe this is an error.',
1471
-                                'event_espresso'
1472
-                            )
1473
-                        ),
1474
-                        __FILE__, __FUNCTION__, __LINE__
1475
-                    );
1476
-                    return false;
1477
-                    break;
1478
-                case 'payments_closed' :
1479
-                    EE_Error::add_attention(
1480
-                        apply_filters(
1481
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___verify_payment_method_is_set__payments_closed_msg',
1482
-                            esc_html__(
1483
-                                'It appears that the event you were about to make a payment for is not accepting payments at this time. Please contact the event administrator if you believe this is an error.',
1484
-                                'event_espresso'
1485
-                            )
1486
-                        ),
1487
-                        __FILE__, __FUNCTION__, __LINE__
1488
-                    );
1489
-                    return false;
1490
-                    break;
1491
-                case 'no_payment_required' :
1492
-                    EE_Error::add_attention(
1493
-                        apply_filters(
1494
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___verify_payment_method_is_set__no_payment_required_msg',
1495
-                            esc_html__(
1496
-                                'It appears that the event you were about to make a payment for does not require payment. Please contact the event administrator if you believe this is an error.',
1497
-                                'event_espresso'
1498
-                            )
1499
-                        ),
1500
-                        __FILE__, __FUNCTION__, __LINE__
1501
-                    );
1502
-                    return false;
1503
-                    break;
1504
-                default:
1505
-            }
1506
-        }
1507
-        // verify payment method
1508
-        if (! $this->checkout->payment_method instanceof EE_Payment_Method) {
1509
-            // get payment method for selected method of payment
1510
-            $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment();
1511
-        }
1512
-        return $this->checkout->payment_method instanceof EE_Payment_Method ? true : false;
1513
-    }
1514
-
1515
-
1516
-
1517
-    /********************************************************************************************************/
1518
-    /***************************************  SAVE PAYER DETAILS  ****************************************/
1519
-    /********************************************************************************************************/
1520
-    /**
1521
-     * save_payer_details_via_ajax
1522
-     *
1523
-     * @return void
1524
-     * @throws EE_Error
1525
-     * @throws InvalidArgumentException
1526
-     * @throws ReflectionException
1527
-     * @throws RuntimeException
1528
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1529
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1530
-     */
1531
-    public function save_payer_details_via_ajax()
1532
-    {
1533
-        if (! $this->_verify_payment_method_is_set()) {
1534
-            return;
1535
-        }
1536
-        // generate billing form for selected method of payment if it hasn't been done already
1537
-        if ($this->checkout->payment_method->type_obj()->has_billing_form()) {
1538
-            $this->checkout->billing_form = $this->_get_billing_form_for_payment_method(
1539
-                $this->checkout->payment_method
1540
-            );
1541
-        }
1542
-        // generate primary attendee from payer info if applicable
1543
-        if (! $this->checkout->transaction_has_primary_registrant()) {
1544
-            $attendee = $this->_create_attendee_from_request_data();
1545
-            if ($attendee instanceof EE_Attendee) {
1546
-                foreach ($this->checkout->transaction->registrations() as $registration) {
1547
-                    if ($registration->is_primary_registrant()) {
1548
-                        $this->checkout->primary_attendee_obj = $attendee;
1549
-                        $registration->_add_relation_to($attendee, 'Attendee');
1550
-                        $registration->set_attendee_id($attendee->ID());
1551
-                        $registration->update_cache_after_object_save('Attendee', $attendee);
1552
-                    }
1553
-                }
1554
-            }
1555
-        }
1556
-    }
1557
-
1558
-
1559
-    /**
1560
-     * create_attendee_from_request_data
1561
-     * uses info from alternate GET or POST data (such as AJAX) to create a new attendee
1562
-     *
1563
-     * @return EE_Attendee
1564
-     * @throws EE_Error
1565
-     * @throws InvalidArgumentException
1566
-     * @throws ReflectionException
1567
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1568
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1569
-     */
1570
-    protected function _create_attendee_from_request_data()
1571
-    {
1572
-        // get State ID
1573
-        $STA_ID = ! empty($_REQUEST['state']) ? sanitize_text_field($_REQUEST['state']) : '';
1574
-        if (! empty($STA_ID)) {
1575
-            // can we get state object from name ?
1576
-            EE_Registry::instance()->load_model('State');
1577
-            $state  = EEM_State::instance()->get_col(array(array('STA_name' => $STA_ID), 'limit' => 1), 'STA_ID');
1578
-            $STA_ID = is_array($state) && ! empty($state) ? reset($state) : $STA_ID;
1579
-        }
1580
-        // get Country ISO
1581
-        $CNT_ISO = ! empty($_REQUEST['country']) ? sanitize_text_field($_REQUEST['country']) : '';
1582
-        if (! empty($CNT_ISO)) {
1583
-            // can we get country object from name ?
1584
-            EE_Registry::instance()->load_model('Country');
1585
-            $country = EEM_Country::instance()->get_col(
1586
-                array(array('CNT_name' => $CNT_ISO), 'limit' => 1),
1587
-                'CNT_ISO'
1588
-            );
1589
-            $CNT_ISO = is_array($country) && ! empty($country) ? reset($country) : $CNT_ISO;
1590
-        }
1591
-        // grab attendee data
1592
-        $attendee_data = array(
1593
-            'ATT_fname'    => ! empty($_REQUEST['first_name']) ? sanitize_text_field($_REQUEST['first_name']) : '',
1594
-            'ATT_lname'    => ! empty($_REQUEST['last_name']) ? sanitize_text_field($_REQUEST['last_name']) : '',
1595
-            'ATT_email'    => ! empty($_REQUEST['email']) ? sanitize_email($_REQUEST['email']) : '',
1596
-            'ATT_address'  => ! empty($_REQUEST['address']) ? sanitize_text_field($_REQUEST['address']) : '',
1597
-            'ATT_address2' => ! empty($_REQUEST['address2']) ? sanitize_text_field($_REQUEST['address2']) : '',
1598
-            'ATT_city'     => ! empty($_REQUEST['city']) ? sanitize_text_field($_REQUEST['city']) : '',
1599
-            'STA_ID'       => $STA_ID,
1600
-            'CNT_ISO'      => $CNT_ISO,
1601
-            'ATT_zip'      => ! empty($_REQUEST['zip']) ? sanitize_text_field($_REQUEST['zip']) : '',
1602
-            'ATT_phone'    => ! empty($_REQUEST['phone']) ? sanitize_text_field($_REQUEST['phone']) : '',
1603
-        );
1604
-        // validate the email address since it is the most important piece of info
1605
-        if (empty($attendee_data['ATT_email']) || $attendee_data['ATT_email'] !== $_REQUEST['email']) {
1606
-            EE_Error::add_error(
1607
-                esc_html__('An invalid email address was submitted.', 'event_espresso'),
1608
-                __FILE__,
1609
-                __FUNCTION__,
1610
-                __LINE__
1611
-            );
1612
-        }
1613
-        // does this attendee already exist in the db ? we're searching using a combination of first name, last name,
1614
-        // AND email address
1615
-        if (! empty($attendee_data['ATT_fname'])
1616
-            && ! empty($attendee_data['ATT_lname'])
1617
-            && ! empty($attendee_data['ATT_email'])
1618
-        ) {
1619
-            $existing_attendee = EE_Registry::instance()->LIB->EEM_Attendee->find_existing_attendee(
1620
-                array(
1621
-                    'ATT_fname' => $attendee_data['ATT_fname'],
1622
-                    'ATT_lname' => $attendee_data['ATT_lname'],
1623
-                    'ATT_email' => $attendee_data['ATT_email'],
1624
-                )
1625
-            );
1626
-            if ($existing_attendee instanceof EE_Attendee) {
1627
-                return $existing_attendee;
1628
-            }
1629
-        }
1630
-        // no existing attendee? kk let's create a new one
1631
-        // kinda lame, but we need a first and last name to create an attendee, so use the email address if those
1632
-        // don't exist
1633
-        $attendee_data['ATT_fname'] = ! empty($attendee_data['ATT_fname'])
1634
-            ? $attendee_data['ATT_fname']
1635
-            : $attendee_data['ATT_email'];
1636
-        $attendee_data['ATT_lname'] = ! empty($attendee_data['ATT_lname'])
1637
-            ? $attendee_data['ATT_lname']
1638
-            : $attendee_data['ATT_email'];
1639
-        return EE_Attendee::new_instance($attendee_data);
1640
-    }
1641
-
1642
-
1643
-
1644
-    /********************************************************************************************************/
1645
-    /****************************************  PROCESS REG STEP  *****************************************/
1646
-    /********************************************************************************************************/
1647
-    /**
1648
-     * process_reg_step
1649
-     *
1650
-     * @return bool
1651
-     * @throws EE_Error
1652
-     * @throws InvalidArgumentException
1653
-     * @throws ReflectionException
1654
-     * @throws \EventEspresso\core\exceptions\EntityNotFoundException
1655
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1656
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1657
-     * @throws \EventEspresso\core\exceptions\InvalidStatusException
1658
-     */
1659
-    public function process_reg_step()
1660
-    {
1661
-        // how have they chosen to pay?
1662
-        $this->checkout->selected_method_of_payment = $this->checkout->transaction->is_free()
1663
-            ? 'no_payment_required'
1664
-            : $this->_get_selected_method_of_payment(true);
1665
-        // choose your own adventure based on method_of_payment
1666
-        switch ($this->checkout->selected_method_of_payment) {
1667
-
1668
-            case 'events_sold_out' :
1669
-                $this->checkout->redirect     = true;
1670
-                $this->checkout->redirect_url = $this->checkout->cancel_page_url;
1671
-                $this->checkout->json_response->set_redirect_url($this->checkout->redirect_url);
1672
-                // mark this reg step as completed
1673
-                $this->set_completed();
1674
-                return false;
1675
-                break;
1676
-
1677
-            case 'payments_closed' :
1678
-                if (apply_filters(
1679
-                    'FHEE__EE_SPCO_Reg_Step_Payment_Options__process_reg_step__payments_closed__display_success',
1680
-                    false
1681
-                )) {
1682
-                    EE_Error::add_success(
1683
-                        esc_html__('no payment required at this time.', 'event_espresso'),
1684
-                        __FILE__,
1685
-                        __FUNCTION__,
1686
-                        __LINE__
1687
-                    );
1688
-                }
1689
-                // mark this reg step as completed
1690
-                $this->set_completed();
1691
-                return true;
1692
-                break;
1693
-
1694
-            case 'no_payment_required' :
1695
-                if (apply_filters(
1696
-                    'FHEE__EE_SPCO_Reg_Step_Payment_Options__process_reg_step__no_payment_required__display_success',
1697
-                    false
1698
-                )) {
1699
-                    EE_Error::add_success(
1700
-                        esc_html__('no payment required.', 'event_espresso'),
1701
-                        __FILE__,
1702
-                        __FUNCTION__,
1703
-                        __LINE__
1704
-                    );
1705
-                }
1706
-                // mark this reg step as completed
1707
-                $this->set_completed();
1708
-                return true;
1709
-                break;
1710
-
1711
-            default:
1712
-                $registrations         = EE_Registry::instance()->SSN->checkout()->transaction->registrations(
1713
-                    EE_Registry::instance()->SSN->checkout()->reg_cache_where_params
1714
-                );
1715
-                $ejected_registrations = EE_SPCO_Reg_Step_Payment_Options::find_registrations_that_lost_their_space(
1716
-                    $registrations,
1717
-                    EE_Registry::instance()->SSN->checkout()->revisit
1718
-                );
1719
-                // calculate difference between the two arrays
1720
-                $registrations = array_diff($registrations, $ejected_registrations);
1721
-                if (empty($registrations)) {
1722
-                    $this->_redirect_because_event_sold_out();
1723
-                    return false;
1724
-                }
1725
-                $payment_successful = $this->_process_payment();
1726
-                if ($payment_successful) {
1727
-                    $this->checkout->continue_reg = true;
1728
-                    $this->_maybe_set_completed($this->checkout->payment_method);
1729
-                } else {
1730
-                    $this->checkout->continue_reg = false;
1731
-                }
1732
-                return $payment_successful;
1733
-        }
1734
-    }
1735
-
1736
-
1737
-    /**
1738
-     * _redirect_because_event_sold_out
1739
-     *
1740
-     * @access protected
1741
-     * @return void
1742
-     */
1743
-    protected function _redirect_because_event_sold_out()
1744
-    {
1745
-        $this->checkout->continue_reg = false;
1746
-        // set redirect URL
1747
-        $this->checkout->redirect_url = add_query_arg(
1748
-            array('e_reg_url_link' => $this->checkout->reg_url_link),
1749
-            $this->checkout->current_step->reg_step_url()
1750
-        );
1751
-        $this->checkout->json_response->set_redirect_url($this->checkout->redirect_url);
1752
-    }
1753
-
1754
-
1755
-    /**
1756
-     * _maybe_set_completed
1757
-     *
1758
-     * @access protected
1759
-     * @param \EE_Payment_Method $payment_method
1760
-     * @return void
1761
-     * @throws \EE_Error
1762
-     */
1763
-    protected function _maybe_set_completed(EE_Payment_Method $payment_method)
1764
-    {
1765
-        switch ($payment_method->type_obj()->payment_occurs()) {
1766
-            case EE_PMT_Base::offsite :
1767
-                break;
1768
-            case EE_PMT_Base::onsite :
1769
-            case EE_PMT_Base::offline :
1770
-                // mark this reg step as completed
1771
-                $this->set_completed();
1772
-                break;
1773
-        }
1774
-    }
1775
-
1776
-
1777
-    /**
1778
-     *    update_reg_step
1779
-     *    this is the final step after a user  revisits the site to retry a payment
1780
-     *
1781
-     * @return bool
1782
-     * @throws EE_Error
1783
-     * @throws InvalidArgumentException
1784
-     * @throws ReflectionException
1785
-     * @throws \EventEspresso\core\exceptions\EntityNotFoundException
1786
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1787
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1788
-     * @throws \EventEspresso\core\exceptions\InvalidStatusException
1789
-     */
1790
-    public function update_reg_step()
1791
-    {
1792
-        $success = true;
1793
-        // if payment required
1794
-        if ($this->checkout->transaction->total() > 0) {
1795
-            do_action(
1796
-                'AHEE__EE_Single_Page_Checkout__process_finalize_registration__before_gateway',
1797
-                $this->checkout->transaction
1798
-            );
1799
-            // attempt payment via payment method
1800
-            $success = $this->process_reg_step();
1801
-        }
1802
-        if ($success && ! $this->checkout->redirect) {
1803
-            $this->checkout->cart->get_grand_total()->save_this_and_descendants_to_txn(
1804
-                $this->checkout->transaction->ID()
1805
-            );
1806
-            // set return URL
1807
-            $this->checkout->redirect_url = add_query_arg(
1808
-                array('e_reg_url_link' => $this->checkout->reg_url_link),
1809
-                $this->checkout->thank_you_page_url
1810
-            );
1811
-        }
1812
-        return $success;
1813
-    }
1814
-
1815
-
1816
-    /**
1817
-     *    _process_payment
1818
-     *
1819
-     * @access private
1820
-     * @return bool
1821
-     * @throws EE_Error
1822
-     * @throws InvalidArgumentException
1823
-     * @throws ReflectionException
1824
-     * @throws RuntimeException
1825
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1826
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1827
-     */
1828
-    private function _process_payment()
1829
-    {
1830
-        // basically confirm that the event hasn't sold out since they hit the page
1831
-        if (! $this->_last_second_ticket_verifications()) {
1832
-            return false;
1833
-        }
1834
-        // ya gotta make a choice man
1835
-        if (empty($this->checkout->selected_method_of_payment)) {
1836
-            $this->checkout->json_response->set_plz_select_method_of_payment(
1837
-                esc_html__('Please select a method of payment before proceeding.', 'event_espresso')
1838
-            );
1839
-            return false;
1840
-        }
1841
-        // get EE_Payment_Method object
1842
-        if (! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()) {
1843
-            return false;
1844
-        }
1845
-        // setup billing form
1846
-        if ($this->checkout->payment_method->is_on_site()) {
1847
-            $this->checkout->billing_form = $this->_get_billing_form_for_payment_method(
1848
-                $this->checkout->payment_method
1849
-            );
1850
-            // bad billing form ?
1851
-            if (! $this->_billing_form_is_valid()) {
1852
-                return false;
1853
-            }
1854
-        }
1855
-        // ensure primary registrant has been fully processed
1856
-        if (! $this->_setup_primary_registrant_prior_to_payment()) {
1857
-            return false;
1858
-        }
1859
-        // if session is close to expiring (under 10 minutes by default)
1860
-        if ((time() - EE_Registry::instance()->SSN->expiration()) < EE_Registry::instance()->SSN->extension()) {
1861
-            // add some time to session expiration so that payment can be completed
1862
-            EE_Registry::instance()->SSN->extend_expiration();
1863
-        }
1864
-        /** @type EE_Transaction_Processor $transaction_processor */
1865
-        //$transaction_processor = EE_Registry::instance()->load_class( 'Transaction_Processor' );
1866
-        // in case a registrant leaves to an Off-Site Gateway and never returns, we want to approve any registrations
1867
-        // for events with a default reg status of Approved
1868
-        // $transaction_processor->toggle_registration_statuses_for_default_approved_events(
1869
-        //      $this->checkout->transaction, $this->checkout->reg_cache_where_params
1870
-        // );
1871
-        // attempt payment
1872
-        $payment = $this->_attempt_payment($this->checkout->payment_method);
1873
-        // process results
1874
-        $payment = $this->_validate_payment($payment);
1875
-        $payment = $this->_post_payment_processing($payment);
1876
-        // verify payment
1877
-        if ($payment instanceof EE_Payment) {
1878
-            // store that for later
1879
-            $this->checkout->payment = $payment;
1880
-            // we can also consider the TXN to not have been failed, so temporarily upgrade it's status to abandoned
1881
-            $this->checkout->transaction->toggle_failed_transaction_status();
1882
-            $payment_status = $payment->status();
1883
-            if (
1884
-                $payment_status === EEM_Payment::status_id_approved
1885
-                || $payment_status === EEM_Payment::status_id_pending
1886
-            ) {
1887
-                return true;
1888
-            } else {
1889
-                return false;
1890
-            }
1891
-        } else if ($payment === true) {
1892
-            // please note that offline payment methods will NOT make a payment,
1893
-            // but instead just mark themselves as the PMD_ID on the transaction, and return true
1894
-            $this->checkout->payment = $payment;
1895
-            return true;
1896
-        }
1897
-        // where's my money?
1898
-        return false;
1899
-    }
1900
-
1901
-
1902
-    /**
1903
-     * _last_second_ticket_verifications
1904
-     *
1905
-     * @access public
1906
-     * @return bool
1907
-     * @throws EE_Error
1908
-     */
1909
-    protected function _last_second_ticket_verifications()
1910
-    {
1911
-        // don't bother re-validating if not a return visit
1912
-        if (! $this->checkout->revisit) {
1913
-            return true;
1914
-        }
1915
-        $registrations = $this->checkout->transaction->registrations();
1916
-        if (empty($registrations)) {
1917
-            return false;
1918
-        }
1919
-        foreach ($registrations as $registration) {
1920
-            if ($registration instanceof EE_Registration) {
1921
-                $event = $registration->event_obj();
1922
-                if ($event instanceof EE_Event && $event->is_sold_out(true)) {
1923
-                    EE_Error::add_error(
1924
-                        apply_filters(
1925
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___last_second_ticket_verifications__sold_out_events_msg',
1926
-                            sprintf(
1927
-                                esc_html__(
1928
-                                    'It appears that the %1$s event that you were about to make a payment for has sold out since you first registered and/or arrived at this page. Please refresh the page and try again. If you have already made a partial payment towards this event, please contact the event administrator for a refund.',
1929
-                                    'event_espresso'
1930
-                                ),
1931
-                                $event->name()
1932
-                            )
1933
-                        ),
1934
-                        __FILE__,
1935
-                        __FUNCTION__,
1936
-                        __LINE__
1937
-                    );
1938
-                    return false;
1939
-                }
1940
-            }
1941
-        }
1942
-        return true;
1943
-    }
1944
-
1945
-
1946
-    /**
1947
-     * redirect_form
1948
-     *
1949
-     * @access public
1950
-     * @return bool
1951
-     * @throws EE_Error
1952
-     * @throws InvalidArgumentException
1953
-     * @throws ReflectionException
1954
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1955
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1956
-     */
1957
-    public function redirect_form()
1958
-    {
1959
-        $payment_method_billing_info = $this->_payment_method_billing_info(
1960
-            $this->_get_payment_method_for_selected_method_of_payment()
1961
-        );
1962
-        $html                        = $payment_method_billing_info->get_html();
1963
-        $html                        .= $this->checkout->redirect_form;
1964
-        EE_Registry::instance()->REQ->add_output($html);
1965
-        return true;
1966
-    }
1967
-
1968
-
1969
-    /**
1970
-     * _billing_form_is_valid
1971
-     *
1972
-     * @access private
1973
-     * @return bool
1974
-     * @throws \EE_Error
1975
-     */
1976
-    private function _billing_form_is_valid()
1977
-    {
1978
-        if (! $this->checkout->payment_method->type_obj()->has_billing_form()) {
1979
-            return true;
1980
-        }
1981
-        if ($this->checkout->billing_form instanceof EE_Billing_Info_Form) {
1982
-            if ($this->checkout->billing_form->was_submitted()) {
1983
-                $this->checkout->billing_form->receive_form_submission();
1984
-                if ($this->checkout->billing_form->is_valid()) {
1985
-                    return true;
1986
-                }
1987
-                $validation_errors = $this->checkout->billing_form->get_validation_errors_accumulated();
1988
-                $error_strings     = array();
1989
-                foreach ($validation_errors as $validation_error) {
1990
-                    if ($validation_error instanceof EE_Validation_Error) {
1991
-                        $form_section = $validation_error->get_form_section();
1992
-                        if ($form_section instanceof EE_Form_Input_Base) {
1993
-                            $label = $form_section->html_label_text();
1994
-                        } elseif ($form_section instanceof EE_Form_Section_Base) {
1995
-                            $label = $form_section->name();
1996
-                        } else {
1997
-                            $label = esc_html__('Validation Error', 'event_espresso');
1998
-                        }
1999
-                        $error_strings[] = sprintf('%1$s: %2$s', $label, $validation_error->getMessage());
2000
-                    }
2001
-                }
2002
-                EE_Error::add_error(
2003
-                    sprintf(
2004
-                        esc_html__(
2005
-                            'One or more billing form inputs are invalid and require correction before proceeding. %1$s %2$s',
2006
-                            'event_espresso'
2007
-                        ),
2008
-                        '<br/>',
2009
-                        implode('<br/>', $error_strings)
2010
-                    ),
2011
-                    __FILE__,
2012
-                    __FUNCTION__,
2013
-                    __LINE__
2014
-                );
2015
-            } else {
2016
-                EE_Error::add_error(
2017
-                    esc_html__(
2018
-                        'The billing form was not submitted or something prevented it\'s submission.',
2019
-                        'event_espresso'
2020
-                    ),
2021
-                    __FILE__,
2022
-                    __FUNCTION__,
2023
-                    __LINE__
2024
-                );
2025
-            }
2026
-        } else {
2027
-            EE_Error::add_error(
2028
-                esc_html__('The submitted billing form is invalid possibly due to a technical reason.', 'event_espresso'),
2029
-                __FILE__,
2030
-                __FUNCTION__,
2031
-                __LINE__
2032
-            );
2033
-        }
2034
-        return false;
2035
-    }
2036
-
2037
-
2038
-    /**
2039
-     * _setup_primary_registrant_prior_to_payment
2040
-     * ensures that the primary registrant has a valid attendee object created with the critical details populated
2041
-     * (first & last name & email) and that both the transaction object and primary registration object have been saved
2042
-     * plz note that any other registrations will NOT be saved at this point (because they may not have any details
2043
-     * yet)
2044
-     *
2045
-     * @access private
2046
-     * @return bool
2047
-     * @throws EE_Error
2048
-     * @throws InvalidArgumentException
2049
-     * @throws ReflectionException
2050
-     * @throws RuntimeException
2051
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2052
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2053
-     */
2054
-    private function _setup_primary_registrant_prior_to_payment()
2055
-    {
2056
-        // check if transaction has a primary registrant and that it has a related Attendee object
2057
-        // if not, then we need to at least gather some primary registrant data before attempting payment
2058
-        if (
2059
-            $this->checkout->billing_form instanceof EE_Billing_Attendee_Info_Form
2060
-            && ! $this->checkout->transaction_has_primary_registrant()
2061
-            && ! $this->_capture_primary_registration_data_from_billing_form()
2062
-        ) {
2063
-            return false;
2064
-        }
2065
-        // because saving an object clears it's cache, we need to do the chevy shuffle
2066
-        // grab the primary_registration object
2067
-        $primary_registration = $this->checkout->transaction->primary_registration();
2068
-        // at this point we'll consider a TXN to not have been failed
2069
-        $this->checkout->transaction->toggle_failed_transaction_status();
2070
-        // save the TXN ( which clears cached copy of primary_registration)
2071
-        $this->checkout->transaction->save();
2072
-        // grab TXN ID and save it to the primary_registration
2073
-        $primary_registration->set_transaction_id($this->checkout->transaction->ID());
2074
-        // save what we have so far
2075
-        $primary_registration->save();
2076
-        return true;
2077
-    }
2078
-
2079
-
2080
-    /**
2081
-     * _capture_primary_registration_data_from_billing_form
2082
-     *
2083
-     * @access private
2084
-     * @return bool
2085
-     * @throws EE_Error
2086
-     * @throws InvalidArgumentException
2087
-     * @throws ReflectionException
2088
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2089
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2090
-     */
2091
-    private function _capture_primary_registration_data_from_billing_form()
2092
-    {
2093
-        // convert billing form data into an attendee
2094
-        $this->checkout->primary_attendee_obj = $this->checkout->billing_form->create_attendee_from_billing_form_data();
2095
-        if (! $this->checkout->primary_attendee_obj instanceof EE_Attendee) {
2096
-            EE_Error::add_error(
2097
-                sprintf(
2098
-                    esc_html__(
2099
-                        'The billing form details could not be used for attendee details due to a technical issue.%sPlease try again or contact %s for assistance.',
2100
-                        'event_espresso'
2101
-                    ),
2102
-                    '<br/>',
2103
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
2104
-                ),
2105
-                __FILE__,
2106
-                __FUNCTION__,
2107
-                __LINE__
2108
-            );
2109
-            return false;
2110
-        }
2111
-        $primary_registration = $this->checkout->transaction->primary_registration();
2112
-        if (! $primary_registration instanceof EE_Registration) {
2113
-            EE_Error::add_error(
2114
-                sprintf(
2115
-                    esc_html__(
2116
-                        'The primary registrant for this transaction could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.',
2117
-                        'event_espresso'
2118
-                    ),
2119
-                    '<br/>',
2120
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
2121
-                ),
2122
-                __FILE__,
2123
-                __FUNCTION__,
2124
-                __LINE__
2125
-            );
2126
-            return false;
2127
-        }
2128
-        if (! $primary_registration->_add_relation_to($this->checkout->primary_attendee_obj, 'Attendee')
2129
-              instanceof
2130
-              EE_Attendee
2131
-        ) {
2132
-            EE_Error::add_error(
2133
-                sprintf(
2134
-                    esc_html__(
2135
-                        'The primary registrant could not be associated with this transaction due to a technical issue.%sPlease try again or contact %s for assistance.',
2136
-                        'event_espresso'
2137
-                    ),
2138
-                    '<br/>',
2139
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
2140
-                ),
2141
-                __FILE__,
2142
-                __FUNCTION__,
2143
-                __LINE__
2144
-            );
2145
-            return false;
2146
-        }
2147
-        /** @type EE_Registration_Processor $registration_processor */
2148
-        $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
2149
-        // at this point, we should have enough details about the registrant to consider the registration NOT incomplete
2150
-        $registration_processor->toggle_incomplete_registration_status_to_default($primary_registration);
2151
-        return true;
2152
-    }
2153
-
2154
-
2155
-    /**
2156
-     * _get_payment_method_for_selected_method_of_payment
2157
-     * retrieves a valid payment method
2158
-     *
2159
-     * @access public
2160
-     * @return EE_Payment_Method
2161
-     * @throws EE_Error
2162
-     * @throws InvalidArgumentException
2163
-     * @throws ReflectionException
2164
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2165
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2166
-     */
2167
-    private function _get_payment_method_for_selected_method_of_payment()
2168
-    {
2169
-        if ($this->checkout->selected_method_of_payment === 'events_sold_out') {
2170
-            $this->_redirect_because_event_sold_out();
2171
-            return null;
2172
-        }
2173
-        // get EE_Payment_Method object
2174
-        if (isset($this->checkout->available_payment_methods[$this->checkout->selected_method_of_payment])) {
2175
-            $payment_method = $this->checkout->available_payment_methods[$this->checkout->selected_method_of_payment];
2176
-        } else {
2177
-            // load EEM_Payment_Method
2178
-            EE_Registry::instance()->load_model('Payment_Method');
2179
-            /** @type EEM_Payment_Method $EEM_Payment_Method */
2180
-            $EEM_Payment_Method = EE_Registry::instance()->LIB->EEM_Payment_Method;
2181
-            $payment_method     = $EEM_Payment_Method->get_one_by_slug($this->checkout->selected_method_of_payment);
2182
-        }
2183
-        // verify $payment_method
2184
-        if (! $payment_method instanceof EE_Payment_Method) {
2185
-            // not a payment
2186
-            EE_Error::add_error(
2187
-                sprintf(
2188
-                    esc_html__(
2189
-                        'The selected method of payment could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.',
2190
-                        'event_espresso'
2191
-                    ),
2192
-                    '<br/>',
2193
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
2194
-                ),
2195
-                __FILE__,
2196
-                __FUNCTION__,
2197
-                __LINE__
2198
-            );
2199
-            return null;
2200
-        }
2201
-        // and verify it has a valid Payment_Method Type object
2202
-        if (! $payment_method->type_obj() instanceof EE_PMT_Base) {
2203
-            // not a payment
2204
-            EE_Error::add_error(
2205
-                sprintf(
2206
-                    esc_html__(
2207
-                        'A valid payment method could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.',
2208
-                        'event_espresso'
2209
-                    ),
2210
-                    '<br/>',
2211
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
2212
-                ),
2213
-                __FILE__,
2214
-                __FUNCTION__,
2215
-                __LINE__
2216
-            );
2217
-            return null;
2218
-        }
2219
-        return $payment_method;
2220
-    }
2221
-
2222
-
2223
-    /**
2224
-     *    _attempt_payment
2225
-     *
2226
-     * @access    private
2227
-     * @type    EE_Payment_Method $payment_method
2228
-     * @return mixed EE_Payment | boolean
2229
-     * @throws EE_Error
2230
-     * @throws InvalidArgumentException
2231
-     * @throws ReflectionException
2232
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2233
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2234
-     */
2235
-    private function _attempt_payment(EE_Payment_Method $payment_method)
2236
-    {
2237
-        $payment = null;
2238
-        $this->checkout->transaction->save();
2239
-        $payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2240
-        if (! $payment_processor instanceof EE_Payment_Processor) {
2241
-            return false;
2242
-        }
2243
-        try {
2244
-            $payment_processor->set_revisit($this->checkout->revisit);
2245
-            // generate payment object
2246
-            $payment = $payment_processor->process_payment(
2247
-                $payment_method,
2248
-                $this->checkout->transaction,
2249
-                $this->checkout->amount_owing,
2250
-                $this->checkout->billing_form,
2251
-                $this->_get_return_url($payment_method),
2252
-                'CART',
2253
-                $this->checkout->admin_request,
2254
-                true,
2255
-                $this->reg_step_url()
2256
-            );
2257
-        } catch (Exception $e) {
2258
-            $this->_handle_payment_processor_exception($e);
2259
-        }
2260
-        return $payment;
2261
-    }
2262
-
2263
-
2264
-    /**
2265
-     * _handle_payment_processor_exception
2266
-     *
2267
-     * @access protected
2268
-     * @param \Exception $e
2269
-     * @return void
2270
-     * @throws EE_Error
2271
-     * @throws InvalidArgumentException
2272
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2273
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2274
-     */
2275
-    protected function _handle_payment_processor_exception(Exception $e)
2276
-    {
2277
-        EE_Error::add_error(
2278
-            sprintf(
2279
-                esc_html__(
2280
-                    'The payment could not br processed due to a technical issue.%1$sPlease try again or contact %2$s for assistance.||The following Exception was thrown in %4$s on line %5$s:%1$s%3$s',
2281
-                    'event_espresso'
2282
-                ),
2283
-                '<br/>',
2284
-                EE_Registry::instance()->CFG->organization->get_pretty('email'),
2285
-                $e->getMessage(),
2286
-                $e->getFile(),
2287
-                $e->getLine()
2288
-            ),
2289
-            __FILE__,
2290
-            __FUNCTION__,
2291
-            __LINE__
2292
-        );
2293
-    }
2294
-
2295
-
2296
-    /**
2297
-     * _get_return_url
2298
-     *
2299
-     * @access protected
2300
-     * @param \EE_Payment_Method $payment_method
2301
-     * @return string
2302
-     * @throws \EE_Error
2303
-     */
2304
-    protected function _get_return_url(EE_Payment_Method $payment_method)
2305
-    {
2306
-        $return_url = '';
2307
-        switch ($payment_method->type_obj()->payment_occurs()) {
2308
-            case EE_PMT_Base::offsite :
2309
-                $return_url = add_query_arg(
2310
-                    array(
2311
-                        'action'                     => 'process_gateway_response',
2312
-                        'selected_method_of_payment' => $this->checkout->selected_method_of_payment,
2313
-                        'spco_txn'                   => $this->checkout->transaction->ID(),
2314
-                    ),
2315
-                    $this->reg_step_url()
2316
-                );
2317
-                break;
2318
-            case EE_PMT_Base::onsite :
2319
-            case EE_PMT_Base::offline :
2320
-                $return_url = $this->checkout->next_step->reg_step_url();
2321
-                break;
2322
-        }
2323
-        return $return_url;
2324
-    }
2325
-
2326
-
2327
-    /**
2328
-     * _validate_payment
2329
-     *
2330
-     * @access private
2331
-     * @param EE_Payment $payment
2332
-     * @return EE_Payment|FALSE
2333
-     * @throws EE_Error
2334
-     * @throws InvalidArgumentException
2335
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2336
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2337
-     */
2338
-    private function _validate_payment($payment = null)
2339
-    {
2340
-        if ($this->checkout->payment_method->is_off_line()) {
2341
-            return true;
2342
-        }
2343
-        // verify payment object
2344
-        if (! $payment instanceof EE_Payment) {
2345
-            // not a payment
2346
-            EE_Error::add_error(
2347
-                sprintf(
2348
-                    esc_html__(
2349
-                        'A valid payment was not generated due to a technical issue.%1$sPlease try again or contact %2$s for assistance.',
2350
-                        'event_espresso'
2351
-                    ),
2352
-                    '<br/>',
2353
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
2354
-                ),
2355
-                __FILE__,
2356
-                __FUNCTION__,
2357
-                __LINE__
2358
-            );
2359
-            return false;
2360
-        }
2361
-        return $payment;
2362
-    }
2363
-
2364
-
2365
-    /**
2366
-     * _post_payment_processing
2367
-     *
2368
-     * @access private
2369
-     * @param EE_Payment|bool $payment
2370
-     * @return bool
2371
-     * @throws EE_Error
2372
-     * @throws InvalidArgumentException
2373
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2374
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2375
-     */
2376
-    private function _post_payment_processing($payment = null)
2377
-    {
2378
-        // Off-Line payment?
2379
-        if ($payment === true) {
2380
-            //$this->_setup_redirect_for_next_step();
2381
-            return true;
2382
-            // On-Site payment?
2383
-        } else if ($this->checkout->payment_method->is_on_site()) {
2384
-            if (! $this->_process_payment_status($payment, EE_PMT_Base::onsite)) {
2385
-                //$this->_setup_redirect_for_next_step();
2386
-                $this->checkout->continue_reg = false;
2387
-            }
2388
-            // Off-Site payment?
2389
-        } else if ($this->checkout->payment_method->is_off_site()) {
2390
-            // if a payment object was made and it specifies a redirect url, then we'll setup that redirect info
2391
-            if ($payment instanceof EE_Payment && $payment->redirect_url()) {
2392
-                do_action('AHEE_log', __CLASS__, __FUNCTION__, $payment->redirect_url(), '$payment->redirect_url()');
2393
-                $this->checkout->redirect      = true;
2394
-                $this->checkout->redirect_form = $payment->redirect_form();
2395
-                $this->checkout->redirect_url  = $this->reg_step_url('redirect_form');
2396
-                // set JSON response
2397
-                $this->checkout->json_response->set_redirect_form($this->checkout->redirect_form);
2398
-                // and lastly, let's bump the payment status to pending
2399
-                $payment->set_status(EEM_Payment::status_id_pending);
2400
-                $payment->save();
2401
-            } else {
2402
-                // not a payment
2403
-                $this->checkout->continue_reg = false;
2404
-                EE_Error::add_error(
2405
-                    sprintf(
2406
-                        esc_html__(
2407
-                            'It appears the Off Site Payment Method was not configured properly.%sPlease try again or contact %s for assistance.',
2408
-                            'event_espresso'
2409
-                        ),
2410
-                        '<br/>',
2411
-                        EE_Registry::instance()->CFG->organization->get_pretty('email')
2412
-                    ),
2413
-                    __FILE__,
2414
-                    __FUNCTION__,
2415
-                    __LINE__
2416
-                );
2417
-            }
2418
-        } else {
2419
-            // ummm ya... not Off-Line, not On-Site, not off-Site ????
2420
-            $this->checkout->continue_reg = false;
2421
-            return false;
2422
-        }
2423
-        return $payment;
2424
-    }
2425
-
2426
-
2427
-    /**
2428
-     *    _process_payment_status
2429
-     *
2430
-     * @access private
2431
-     * @type    EE_Payment $payment
2432
-     * @param string       $payment_occurs
2433
-     * @return bool
2434
-     * @throws EE_Error
2435
-     * @throws InvalidArgumentException
2436
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2437
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2438
-     */
2439
-    private function _process_payment_status($payment, $payment_occurs = EE_PMT_Base::offline)
2440
-    {
2441
-        // off-line payment? carry on
2442
-        if ($payment_occurs === EE_PMT_Base::offline) {
2443
-            return true;
2444
-        }
2445
-        // verify payment validity
2446
-        if ($payment instanceof EE_Payment) {
2447
-            do_action('AHEE_log', __CLASS__, __FUNCTION__, $payment->status(), '$payment->status()');
2448
-            $msg = $payment->gateway_response();
2449
-            // check results
2450
-            switch ($payment->status()) {
2451
-                // good payment
2452
-                case EEM_Payment::status_id_approved :
2453
-                    EE_Error::add_success(
2454
-                        esc_html__('Your payment was processed successfully.', 'event_espresso'),
2455
-                        __FILE__,
2456
-                        __FUNCTION__,
2457
-                        __LINE__
2458
-                    );
2459
-                    return true;
2460
-                    break;
2461
-                // slow payment
2462
-                case EEM_Payment::status_id_pending :
2463
-                    if (empty($msg)) {
2464
-                        $msg = esc_html__(
2465
-                            'Your payment appears to have been processed successfully, but the Instant Payment Notification has not yet been received. It should arrive shortly.',
2466
-                            'event_espresso'
2467
-                        );
2468
-                    }
2469
-                    EE_Error::add_success($msg, __FILE__, __FUNCTION__, __LINE__);
2470
-                    return true;
2471
-                    break;
2472
-                // don't wanna payment
2473
-                case EEM_Payment::status_id_cancelled :
2474
-                    if (empty($msg)) {
2475
-                        $msg = _n(
2476
-                            'Payment cancelled. Please try again.',
2477
-                            'Payment cancelled. Please try again or select another method of payment.',
2478
-                            count($this->checkout->available_payment_methods),
2479
-                            'event_espresso'
2480
-                        );
2481
-                    }
2482
-                    EE_Error::add_attention($msg, __FILE__, __FUNCTION__, __LINE__);
2483
-                    return false;
2484
-                    break;
2485
-                // not enough payment
2486
-                case EEM_Payment::status_id_declined :
2487
-                    if (empty($msg)) {
2488
-                        $msg = _n(
2489
-                            'We\'re sorry but your payment was declined. Please try again.',
2490
-                            'We\'re sorry but your payment was declined. Please try again or select another method of payment.',
2491
-                            count($this->checkout->available_payment_methods),
2492
-                            'event_espresso'
2493
-                        );
2494
-                    }
2495
-                    EE_Error::add_attention($msg, __FILE__, __FUNCTION__, __LINE__);
2496
-                    return false;
2497
-                    break;
2498
-                // bad payment
2499
-                case EEM_Payment::status_id_failed :
2500
-                    if (! empty($msg)) {
2501
-                        EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2502
-                        return false;
2503
-                    }
2504
-                    // default to error below
2505
-                    break;
2506
-            }
2507
-        }
2508
-        // off-site payment gateway responses are too unreliable, so let's just assume that
2509
-        // the payment processing is just running slower than the registrant's request
2510
-        if ($payment_occurs === EE_PMT_Base::offsite) {
2511
-            return true;
2512
-        }
2513
-        EE_Error::add_error(
2514
-            sprintf(
2515
-                esc_html__(
2516
-                    'Your payment could not be processed successfully due to a technical issue.%sPlease try again or contact %s for assistance.',
2517
-                    'event_espresso'
2518
-                ),
2519
-                '<br/>',
2520
-                EE_Registry::instance()->CFG->organization->get_pretty('email')
2521
-            ),
2522
-            __FILE__,
2523
-            __FUNCTION__,
2524
-            __LINE__
2525
-        );
2526
-        return false;
2527
-    }
2528
-
2529
-
2530
-
2531
-
2532
-
2533
-
2534
-    /********************************************************************************************************/
2535
-    /**********************************  PROCESS GATEWAY RESPONSE  **********************************/
2536
-    /********************************************************************************************************/
2537
-    /**
2538
-     * process_gateway_response
2539
-     * this is the return point for Off-Site Payment Methods
2540
-     * It will attempt to "handle the IPN" if it appears that this has not already occurred,
2541
-     * otherwise, it will load up the last payment made for the TXN.
2542
-     * If the payment retrieved looks good, it will then either:
2543
-     *    complete the current step and allow advancement to the next reg step
2544
-     *        or present the payment options again
2545
-     *
2546
-     * @access private
2547
-     * @return EE_Payment|FALSE
2548
-     * @throws EE_Error
2549
-     * @throws InvalidArgumentException
2550
-     * @throws ReflectionException
2551
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2552
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2553
-     * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
2554
-     */
2555
-    public function process_gateway_response()
2556
-    {
2557
-        $payment = null;
2558
-        // how have they chosen to pay?
2559
-        $this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
2560
-        // get EE_Payment_Method object
2561
-        if (! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()) {
2562
-            $this->checkout->continue_reg = false;
2563
-            return false;
2564
-        }
2565
-        if (! $this->checkout->payment_method->is_off_site()) {
2566
-            return false;
2567
-        }
2568
-        $this->_validate_offsite_return();
2569
-        // DEBUG LOG
2570
-        //$this->checkout->log(
2571
-        //	__CLASS__, __FUNCTION__, __LINE__,
2572
-        //	array(
2573
-        //		'selected_method_of_payment' => $this->checkout->selected_method_of_payment,
2574
-        //		'payment_method' => $this->checkout->payment_method,
2575
-        //	),
2576
-        //	true
2577
-        //);
2578
-        // verify TXN
2579
-        if ($this->checkout->transaction instanceof EE_Transaction) {
2580
-            $gateway = $this->checkout->payment_method->type_obj()->get_gateway();
2581
-            if (! $gateway instanceof EE_Offsite_Gateway) {
2582
-                $this->checkout->continue_reg = false;
2583
-                return false;
2584
-            }
2585
-            $payment = $this->_process_off_site_payment($gateway);
2586
-            $payment = $this->_process_cancelled_payments($payment);
2587
-            $payment = $this->_validate_payment($payment);
2588
-            // if payment was not declined by the payment gateway or cancelled by the registrant
2589
-            if ($this->_process_payment_status($payment, EE_PMT_Base::offsite)) {
2590
-                //$this->_setup_redirect_for_next_step();
2591
-                // store that for later
2592
-                $this->checkout->payment = $payment;
2593
-                // mark this reg step as completed, as long as gateway doesn't use a separate IPN request,
2594
-                // because we will complete this step during the IPN processing then
2595
-                if ($gateway instanceof EE_Offsite_Gateway && ! $this->handle_IPN_in_this_request()) {
2596
-                    $this->set_completed();
2597
-                }
2598
-                return true;
2599
-            }
2600
-        }
2601
-        // DEBUG LOG
2602
-        //$this->checkout->log( __CLASS__, __FUNCTION__, __LINE__,
2603
-        //	array( 'payment' => $payment )
2604
-        //);
2605
-        $this->checkout->continue_reg = false;
2606
-        return false;
2607
-    }
2608
-
2609
-
2610
-    /**
2611
-     * _validate_return
2612
-     *
2613
-     * @access private
2614
-     * @return void
2615
-     * @throws EE_Error
2616
-     * @throws InvalidArgumentException
2617
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2618
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2619
-     * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
2620
-     */
2621
-    private function _validate_offsite_return()
2622
-    {
2623
-        $TXN_ID = (int)EE_Registry::instance()->REQ->get('spco_txn', 0);
2624
-        if ($TXN_ID !== $this->checkout->transaction->ID()) {
2625
-            // Houston... we might have a problem
2626
-            $invalid_TXN = false;
2627
-            // first gather some info
2628
-            $valid_TXN          = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
2629
-            $primary_registrant = $valid_TXN instanceof EE_Transaction
2630
-                ? $valid_TXN->primary_registration()
2631
-                : null;
2632
-            // let's start by retrieving the cart for this TXN
2633
-            $cart = $this->checkout->get_cart_for_transaction($this->checkout->transaction);
2634
-            if ($cart instanceof EE_Cart) {
2635
-                // verify that the current cart has tickets
2636
-                $tickets = $cart->get_tickets();
2637
-                if (empty($tickets)) {
2638
-                    $invalid_TXN = true;
2639
-                }
2640
-            } else {
2641
-                $invalid_TXN = true;
2642
-            }
2643
-            $valid_TXN_SID = $primary_registrant instanceof EE_Registration
2644
-                ? $primary_registrant->session_ID()
2645
-                : null;
2646
-            // validate current Session ID and compare against valid TXN session ID
2647
-            if (
2648
-                $invalid_TXN // if this is already true, then skip other checks
2649
-                || EE_Session::instance()->id() === null
2650
-                || (
2651
-                    // WARNING !!!
2652
-                    // this could be PayPal sending back duplicate requests (ya they do that)
2653
-                    // or it **could** mean someone is simply registering AGAIN after having just done so
2654
-                    // so now we need to determine if this current TXN looks valid or not
2655
-                    // and whether this reg step has even been started ?
2656
-                    EE_Session::instance()->id() === $valid_TXN_SID
2657
-                    // really? you're half way through this reg step, but you never started it ?
2658
-                    && $this->checkout->transaction->reg_step_completed($this->slug()) === false
2659
-                )
2660
-            ) {
2661
-                $invalid_TXN = true;
2662
-            }
2663
-            if ($invalid_TXN) {
2664
-                // is the valid TXN completed ?
2665
-                if ($valid_TXN instanceof EE_Transaction) {
2666
-                    // has this step even been started ?
2667
-                    $reg_step_completed = $valid_TXN->reg_step_completed($this->slug());
2668
-                    if ($reg_step_completed !== false && $reg_step_completed !== true) {
2669
-                        // so it **looks** like this is a double request from PayPal
2670
-                        // so let's try to pick up where we left off
2671
-                        $this->checkout->transaction = $valid_TXN;
2672
-                        $this->checkout->refresh_all_entities(true);
2673
-                        return;
2674
-                    }
2675
-                }
2676
-                // you appear to be lost?
2677
-                $this->_redirect_wayward_request($primary_registrant);
2678
-            }
2679
-        }
2680
-    }
2681
-
2682
-
2683
-    /**
2684
-     * _redirect_wayward_request
2685
-     *
2686
-     * @access private
2687
-     * @param \EE_Registration|null $primary_registrant
2688
-     * @return bool
2689
-     * @throws EE_Error
2690
-     * @throws InvalidArgumentException
2691
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2692
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2693
-     */
2694
-    private function _redirect_wayward_request(EE_Registration $primary_registrant)
2695
-    {
2696
-        if (! $primary_registrant instanceof EE_Registration) {
2697
-            // try redirecting based on the current TXN
2698
-            $primary_registrant = $this->checkout->transaction instanceof EE_Transaction
2699
-                ? $this->checkout->transaction->primary_registration()
2700
-                : null;
2701
-        }
2702
-        if (! $primary_registrant instanceof EE_Registration) {
2703
-            EE_Error::add_error(
2704
-                sprintf(
2705
-                    esc_html__(
2706
-                        'Invalid information was received from the Off-Site Payment Processor and your Transaction details could not be retrieved from the database.%1$sPlease try again or contact %2$s for assistance.',
2707
-                        'event_espresso'
2708
-                    ),
2709
-                    '<br/>',
2710
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
2711
-                ),
2712
-                __FILE__,
2713
-                __FUNCTION__,
2714
-                __LINE__
2715
-            );
2716
-            return false;
2717
-        }
2718
-        // make sure transaction is not locked
2719
-        $this->checkout->transaction->unlock();
2720
-        wp_safe_redirect(
2721
-            add_query_arg(
2722
-                array(
2723
-                    'e_reg_url_link' => $primary_registrant->reg_url_link(),
2724
-                ),
2725
-                $this->checkout->thank_you_page_url
2726
-            )
2727
-        );
2728
-        exit();
2729
-    }
2730
-
2731
-
2732
-    /**
2733
-     * _process_off_site_payment
2734
-     *
2735
-     * @access private
2736
-     * @param \EE_Offsite_Gateway $gateway
2737
-     * @return EE_Payment
2738
-     * @throws EE_Error
2739
-     * @throws InvalidArgumentException
2740
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2741
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2742
-     */
2743
-    private function _process_off_site_payment(EE_Offsite_Gateway $gateway)
2744
-    {
2745
-        try {
2746
-            $request_data = \EE_Registry::instance()->REQ->params();
2747
-            // if gateway uses_separate_IPN_request, then we don't have to process the IPN manually
2748
-            $this->set_handle_IPN_in_this_request(
2749
-                $gateway->handle_IPN_in_this_request($request_data, false)
2750
-            );
2751
-            if ($this->handle_IPN_in_this_request()) {
2752
-                // get payment details and process results
2753
-                /** @type EE_Payment_Processor $payment_processor */
2754
-                $payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2755
-                $payment           = $payment_processor->process_ipn(
2756
-                    $request_data,
2757
-                    $this->checkout->transaction,
2758
-                    $this->checkout->payment_method,
2759
-                    true,
2760
-                    false
2761
-                );
2762
-                //$payment_source = 'process_ipn';
2763
-            } else {
2764
-                $payment = $this->checkout->transaction->last_payment();
2765
-                //$payment_source = 'last_payment';
2766
-            }
2767
-        } catch (Exception $e) {
2768
-            // let's just eat the exception and try to move on using any previously set payment info
2769
-            $payment = $this->checkout->transaction->last_payment();
2770
-            //$payment_source = 'last_payment after Exception';
2771
-            // but if we STILL don't have a payment object
2772
-            if (! $payment instanceof EE_Payment) {
2773
-                // then we'll object ! ( not object like a thing... but object like what a lawyer says ! )
2774
-                $this->_handle_payment_processor_exception($e);
2775
-            }
2776
-        }
2777
-        // DEBUG LOG
2778
-        //$this->checkout->log( __CLASS__, __FUNCTION__, __LINE__,
2779
-        //	array(
2780
-        //		'process_ipn_payment' => $payment,
2781
-        //		'payment_source'      => $payment_source,
2782
-        //	)
2783
-        //);
2784
-        return $payment;
2785
-    }
2786
-
2787
-
2788
-    /**
2789
-     * _process_cancelled_payments
2790
-     * just makes sure that the payment status gets updated correctly
2791
-     * so tha tan error isn't generated during payment validation
2792
-     *
2793
-     * @access private
2794
-     * @param EE_Payment $payment
2795
-     * @return EE_Payment | FALSE
2796
-     * @throws \EE_Error
2797
-     */
2798
-    private function _process_cancelled_payments($payment = null)
2799
-    {
2800
-        if (
2801
-            $payment instanceof EE_Payment
2802
-            && isset($_REQUEST['ee_cancel_payment'])
2803
-            && $payment->status() === EEM_Payment::status_id_failed
2804
-        ) {
2805
-            $payment->set_status(EEM_Payment::status_id_cancelled);
2806
-        }
2807
-        return $payment;
2808
-    }
2809
-
2810
-
2811
-    /**
2812
-     *    get_transaction_details_for_gateways
2813
-     *
2814
-     * @access    public
2815
-     * @return int
2816
-     * @throws EE_Error
2817
-     * @throws InvalidArgumentException
2818
-     * @throws ReflectionException
2819
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2820
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2821
-     */
2822
-    public function get_transaction_details_for_gateways()
2823
-    {
2824
-        $txn_details = array();
2825
-        // ya gotta make a choice man
2826
-        if (empty($this->checkout->selected_method_of_payment)) {
2827
-            $txn_details = array(
2828
-                'error' => esc_html__('Please select a method of payment before proceeding.', 'event_espresso'),
2829
-            );
2830
-        }
2831
-        // get EE_Payment_Method object
2832
-        if (
2833
-            empty($txn_details)
2834
-            &&
2835
-            ! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()
2836
-        ) {
2837
-            $txn_details = array(
2838
-                'selected_method_of_payment' => $this->checkout->selected_method_of_payment,
2839
-                'error'                      => esc_html__(
2840
-                    'A valid Payment Method could not be determined.',
2841
-                    'event_espresso'
2842
-                ),
2843
-            );
2844
-        }
2845
-        if (empty($txn_details) && $this->checkout->transaction instanceof EE_Transaction) {
2846
-            $return_url  = $this->_get_return_url($this->checkout->payment_method);
2847
-            $txn_details = array(
2848
-                'TXN_ID'         => $this->checkout->transaction->ID(),
2849
-                'TXN_timestamp'  => $this->checkout->transaction->datetime(),
2850
-                'TXN_total'      => $this->checkout->transaction->total(),
2851
-                'TXN_paid'       => $this->checkout->transaction->paid(),
2852
-                'TXN_reg_steps'  => $this->checkout->transaction->reg_steps(),
2853
-                'STS_ID'         => $this->checkout->transaction->status_ID(),
2854
-                'PMD_ID'         => $this->checkout->transaction->payment_method_ID(),
2855
-                'payment_amount' => $this->checkout->amount_owing,
2856
-                'return_url'     => $return_url,
2857
-                'cancel_url'     => add_query_arg(array('ee_cancel_payment' => true), $return_url),
2858
-                'notify_url'     => EE_Config::instance()->core->txn_page_url(
2859
-                    array(
2860
-                        'e_reg_url_link'    => $this->checkout->transaction->primary_registration()->reg_url_link(),
2861
-                        'ee_payment_method' => $this->checkout->payment_method->slug(),
2862
-                    )
2863
-                ),
2864
-            );
2865
-        }
2866
-        echo wp_json_encode($txn_details);
2867
-        exit();
2868
-    }
2869
-
2870
-
2871
-    /**
2872
-     *    __sleep
2873
-     * to conserve db space, let's remove the reg_form and the EE_Checkout object from EE_SPCO_Reg_Step objects upon
2874
-     * serialization EE_Checkout will handle the reimplementation of itself upon waking, but we won't bother with the
2875
-     * reg form, because if needed, it will be regenerated anyways
2876
-     *
2877
-     * @return array
2878
-     */
2879
-    public function __sleep()
2880
-    {
2881
-        // remove the reg form and the checkout
2882
-        return array_diff(array_keys(get_object_vars($this)), array('reg_form', 'checkout', 'line_item_display'));
2883
-    }
18
+	/**
19
+	 * @access protected
20
+	 * @var EE_Line_Item_Display $Line_Item_Display
21
+	 */
22
+	protected $line_item_display;
23
+
24
+	/**
25
+	 * @access protected
26
+	 * @var boolean $handle_IPN_in_this_request
27
+	 */
28
+	protected $handle_IPN_in_this_request = false;
29
+
30
+
31
+	/**
32
+	 *    set_hooks - for hooking into EE Core, other modules, etc
33
+	 *
34
+	 * @access    public
35
+	 * @return    void
36
+	 */
37
+	public static function set_hooks()
38
+	{
39
+		add_filter(
40
+			'FHEE__SPCO__EE_Line_Item_Filter_Collection',
41
+			array('EE_SPCO_Reg_Step_Payment_Options', 'add_spco_line_item_filters')
42
+		);
43
+		add_action(
44
+			'wp_ajax_switch_spco_billing_form',
45
+			array('EE_SPCO_Reg_Step_Payment_Options', 'switch_spco_billing_form')
46
+		);
47
+		add_action(
48
+			'wp_ajax_nopriv_switch_spco_billing_form',
49
+			array('EE_SPCO_Reg_Step_Payment_Options', 'switch_spco_billing_form')
50
+		);
51
+		add_action('wp_ajax_save_payer_details', array('EE_SPCO_Reg_Step_Payment_Options', 'save_payer_details'));
52
+		add_action(
53
+			'wp_ajax_nopriv_save_payer_details',
54
+			array('EE_SPCO_Reg_Step_Payment_Options', 'save_payer_details')
55
+		);
56
+		add_action(
57
+			'wp_ajax_get_transaction_details_for_gateways',
58
+			array('EE_SPCO_Reg_Step_Payment_Options', 'get_transaction_details')
59
+		);
60
+		add_action(
61
+			'wp_ajax_nopriv_get_transaction_details_for_gateways',
62
+			array('EE_SPCO_Reg_Step_Payment_Options', 'get_transaction_details')
63
+		);
64
+		add_filter(
65
+			'FHEE__EED_Recaptcha___bypass_recaptcha__bypass_request_params_array',
66
+			array('EE_SPCO_Reg_Step_Payment_Options', 'bypass_recaptcha_for_load_payment_method'),
67
+			10,
68
+			1
69
+		);
70
+	}
71
+
72
+
73
+	/**
74
+	 *    ajax switch_spco_billing_form
75
+	 *
76
+	 * @throws \EE_Error
77
+	 */
78
+	public static function switch_spco_billing_form()
79
+	{
80
+		EED_Single_Page_Checkout::process_ajax_request('switch_payment_method');
81
+	}
82
+
83
+
84
+	/**
85
+	 *    ajax save_payer_details
86
+	 *
87
+	 * @throws \EE_Error
88
+	 */
89
+	public static function save_payer_details()
90
+	{
91
+		EED_Single_Page_Checkout::process_ajax_request('save_payer_details_via_ajax');
92
+	}
93
+
94
+
95
+	/**
96
+	 *    ajax get_transaction_details
97
+	 *
98
+	 * @throws \EE_Error
99
+	 */
100
+	public static function get_transaction_details()
101
+	{
102
+		EED_Single_Page_Checkout::process_ajax_request('get_transaction_details_for_gateways');
103
+	}
104
+
105
+
106
+	/**
107
+	 * bypass_recaptcha_for_load_payment_method
108
+	 *
109
+	 * @access public
110
+	 * @return array
111
+	 * @throws InvalidArgumentException
112
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
113
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
114
+	 */
115
+	public static function bypass_recaptcha_for_load_payment_method()
116
+	{
117
+		return array(
118
+			'EESID'  => EE_Registry::instance()->SSN->id(),
119
+			'step'   => 'payment_options',
120
+			'action' => 'spco_billing_form',
121
+		);
122
+	}
123
+
124
+
125
+	/**
126
+	 *    class constructor
127
+	 *
128
+	 * @access    public
129
+	 * @param    EE_Checkout $checkout
130
+	 */
131
+	public function __construct(EE_Checkout $checkout)
132
+	{
133
+		$this->_slug     = 'payment_options';
134
+		$this->_name     = esc_html__('Payment Options', 'event_espresso');
135
+		$this->_template = SPCO_REG_STEPS_PATH . $this->_slug . DS . 'payment_options_main.template.php';
136
+		$this->checkout  = $checkout;
137
+		$this->_reset_success_message();
138
+		$this->set_instructions(
139
+			esc_html__(
140
+				'Please select a method of payment and provide any necessary billing information before proceeding.',
141
+				'event_espresso'
142
+			)
143
+		);
144
+	}
145
+
146
+
147
+	/**
148
+	 * @return null
149
+	 */
150
+	public function line_item_display()
151
+	{
152
+		return $this->line_item_display;
153
+	}
154
+
155
+
156
+	/**
157
+	 * @param null $line_item_display
158
+	 */
159
+	public function set_line_item_display($line_item_display)
160
+	{
161
+		$this->line_item_display = $line_item_display;
162
+	}
163
+
164
+
165
+	/**
166
+	 * @return boolean
167
+	 */
168
+	public function handle_IPN_in_this_request()
169
+	{
170
+		return $this->handle_IPN_in_this_request;
171
+	}
172
+
173
+
174
+	/**
175
+	 * @param boolean $handle_IPN_in_this_request
176
+	 */
177
+	public function set_handle_IPN_in_this_request($handle_IPN_in_this_request)
178
+	{
179
+		$this->handle_IPN_in_this_request = filter_var($handle_IPN_in_this_request, FILTER_VALIDATE_BOOLEAN);
180
+	}
181
+
182
+
183
+	/**
184
+	 * translate_js_strings
185
+	 *
186
+	 * @return void
187
+	 */
188
+	public function translate_js_strings()
189
+	{
190
+		EE_Registry::$i18n_js_strings['no_payment_method']      = esc_html__(
191
+			'Please select a method of payment in order to continue.',
192
+			'event_espresso'
193
+		);
194
+		EE_Registry::$i18n_js_strings['invalid_payment_method'] = esc_html__(
195
+			'A valid method of payment could not be determined. Please refresh the page and try again.',
196
+			'event_espresso'
197
+		);
198
+		EE_Registry::$i18n_js_strings['forwarding_to_offsite']  = esc_html__(
199
+			'Forwarding to Secure Payment Provider.',
200
+			'event_espresso'
201
+		);
202
+	}
203
+
204
+
205
+	/**
206
+	 * enqueue_styles_and_scripts
207
+	 *
208
+	 * @return void
209
+	 * @throws EE_Error
210
+	 * @throws InvalidArgumentException
211
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
212
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
213
+	 */
214
+	public function enqueue_styles_and_scripts()
215
+	{
216
+		$transaction = $this->checkout->transaction;
217
+		//if the transaction isn't set or nothing is owed on it, don't enqueue any JS
218
+		if (! $transaction instanceof EE_Transaction || EEH_Money::compare_floats($transaction->remaining(), 0)) {
219
+			return;
220
+		}
221
+		foreach (EEM_Payment_Method::instance()->get_all_for_transaction($transaction, EEM_Payment_Method::scope_cart) as $payment_method) {
222
+			$type_obj = $payment_method->type_obj();
223
+			if ($type_obj instanceof EE_PMT_Base) {
224
+				$billing_form = $type_obj->generate_new_billing_form($transaction);
225
+				if ($billing_form instanceof EE_Form_Section_Proper) {
226
+					$billing_form->enqueue_js();
227
+				}
228
+			}
229
+		}
230
+	}
231
+
232
+
233
+	/**
234
+	 * initialize_reg_step
235
+	 *
236
+	 * @return bool
237
+	 * @throws EE_Error
238
+	 * @throws InvalidArgumentException
239
+	 * @throws ReflectionException
240
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
241
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
242
+	 */
243
+	public function initialize_reg_step()
244
+	{
245
+		// TODO: if /when we implement donations, then this will need overriding
246
+		if (// don't need payment options for:
247
+			// 	registrations made via the admin
248
+			// 	completed transactions
249
+			// 	overpaid transactions
250
+			// 	$ 0.00 transactions (no payment required)
251
+			! $this->checkout->payment_required()
252
+			// but do NOT remove if current action being called belongs to this reg step
253
+			&& ! is_callable(array($this, $this->checkout->action))
254
+			&& ! $this->completed()
255
+		) {
256
+			// and if so, then we no longer need the Payment Options step
257
+			if ($this->is_current_step()) {
258
+				$this->checkout->generate_reg_form = false;
259
+			}
260
+			$this->checkout->remove_reg_step($this->_slug);
261
+			// DEBUG LOG
262
+			//$this->checkout->log( __CLASS__, __FUNCTION__, __LINE__ );
263
+			return false;
264
+		}
265
+		// load EEM_Payment_Method
266
+		EE_Registry::instance()->load_model('Payment_Method');
267
+		// get all active payment methods
268
+		$this->checkout->available_payment_methods = EEM_Payment_Method::instance()->get_all_for_transaction(
269
+			$this->checkout->transaction,
270
+			EEM_Payment_Method::scope_cart
271
+		);
272
+		return true;
273
+	}
274
+
275
+
276
+	/**
277
+	 * @return EE_Form_Section_Proper
278
+	 * @throws EE_Error
279
+	 * @throws InvalidArgumentException
280
+	 * @throws ReflectionException
281
+	 * @throws \EventEspresso\core\exceptions\EntityNotFoundException
282
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
283
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
284
+	 * @throws \EventEspresso\core\exceptions\InvalidStatusException
285
+	 */
286
+	public function generate_reg_form()
287
+	{
288
+		// reset in case someone changes their mind
289
+		$this->_reset_selected_method_of_payment();
290
+		// set some defaults
291
+		$this->checkout->selected_method_of_payment = 'payments_closed';
292
+		$registrations_requiring_payment            = array();
293
+		$registrations_for_free_events              = array();
294
+		$registrations_requiring_pre_approval       = array();
295
+		$sold_out_events                            = array();
296
+		$insufficient_spaces_available              = array();
297
+		$no_payment_required                        = true;
298
+		// loop thru registrations to gather info
299
+		$registrations         = $this->checkout->transaction->registrations($this->checkout->reg_cache_where_params);
300
+		$ejected_registrations = EE_SPCO_Reg_Step_Payment_Options::find_registrations_that_lost_their_space(
301
+			$registrations,
302
+			$this->checkout->revisit
303
+		);
304
+		foreach ($registrations as $REG_ID => $registration) {
305
+			/** @var $registration EE_Registration */
306
+			// has this registration lost it's space ?
307
+			if (isset($ejected_registrations[$REG_ID])) {
308
+				$insufficient_spaces_available[$registration->event()->ID()] = $registration->event();
309
+				continue;
310
+			}
311
+			// event requires admin approval
312
+			if ($registration->status_ID() === EEM_Registration::status_id_not_approved) {
313
+				// add event to list of events with pre-approval reg status
314
+				$registrations_requiring_pre_approval[$REG_ID] = $registration;
315
+				do_action(
316
+					'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__event_requires_pre_approval',
317
+					$registration->event(),
318
+					$this
319
+				);
320
+				continue;
321
+			}
322
+			if ($this->checkout->revisit
323
+				&& $registration->status_ID() !== EEM_Registration::status_id_approved
324
+				&& (
325
+					$registration->event()->is_sold_out()
326
+					|| $registration->event()->is_sold_out(true)
327
+				)
328
+			) {
329
+				// add event to list of events that are sold out
330
+				$sold_out_events[$registration->event()->ID()] = $registration->event();
331
+				do_action(
332
+					'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__sold_out_event',
333
+					$registration->event(),
334
+					$this
335
+				);
336
+				continue;
337
+			}
338
+			// are they allowed to pay now and is there monies owing?
339
+			if ($registration->owes_monies_and_can_pay()) {
340
+				$registrations_requiring_payment[$REG_ID] = $registration;
341
+				do_action(
342
+					'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__event_requires_payment',
343
+					$registration->event(),
344
+					$this
345
+				);
346
+			} elseif (! $this->checkout->revisit
347
+				&& $registration->status_ID() !== EEM_Registration::status_id_not_approved
348
+				&& $registration->ticket()->is_free()
349
+			) {
350
+				$registrations_for_free_events[$registration->event()->ID()] = $registration;
351
+			}
352
+		}
353
+		$subsections = array();
354
+		// now decide which template to load
355
+		if (! empty($sold_out_events)) {
356
+			$subsections['sold_out_events'] = $this->_sold_out_events($sold_out_events);
357
+		}
358
+		if (! empty($insufficient_spaces_available)) {
359
+			$subsections['insufficient_space'] = $this->_insufficient_spaces_available(
360
+				$insufficient_spaces_available
361
+			);
362
+		}
363
+		if (! empty($registrations_requiring_pre_approval)) {
364
+			$subsections['registrations_requiring_pre_approval'] = $this->_registrations_requiring_pre_approval(
365
+				$registrations_requiring_pre_approval
366
+			);
367
+		}
368
+		if (! empty($registrations_for_free_events)) {
369
+			$subsections['no_payment_required'] = $this->_no_payment_required($registrations_for_free_events);
370
+		}
371
+		if (! empty($registrations_requiring_payment)) {
372
+			if ($this->checkout->amount_owing > 0) {
373
+				// autoload Line_Item_Display classes
374
+				EEH_Autoloader::register_line_item_filter_autoloaders();
375
+				$line_item_filter_processor = new EE_Line_Item_Filter_Processor(
376
+					apply_filters(
377
+						'FHEE__SPCO__EE_Line_Item_Filter_Collection',
378
+						new EE_Line_Item_Filter_Collection()
379
+					),
380
+					$this->checkout->cart->get_grand_total()
381
+				);
382
+				/** @var EE_Line_Item $filtered_line_item_tree */
383
+				$filtered_line_item_tree = $line_item_filter_processor->process();
384
+				EEH_Autoloader::register_line_item_display_autoloaders();
385
+				$this->set_line_item_display(new EE_Line_Item_Display('spco'));
386
+				$subsections['payment_options'] = $this->_display_payment_options(
387
+					$this->line_item_display->display_line_item(
388
+						$filtered_line_item_tree,
389
+						array('registrations' => $registrations)
390
+					)
391
+				);
392
+				$this->checkout->amount_owing   = $filtered_line_item_tree->total();
393
+				$this->_apply_registration_payments_to_amount_owing($registrations);
394
+			}
395
+			$no_payment_required = false;
396
+		} else {
397
+			$this->_hide_reg_step_submit_button_if_revisit();
398
+		}
399
+		$this->_save_selected_method_of_payment();
400
+
401
+		$subsections['default_hidden_inputs'] = $this->reg_step_hidden_inputs();
402
+		$subsections['extra_hidden_inputs']   = $this->_extra_hidden_inputs($no_payment_required);
403
+
404
+		return new EE_Form_Section_Proper(
405
+			array(
406
+				'name'            => $this->reg_form_name(),
407
+				'html_id'         => $this->reg_form_name(),
408
+				'subsections'     => $subsections,
409
+				'layout_strategy' => new EE_No_Layout(),
410
+			)
411
+		);
412
+	}
413
+
414
+
415
+	/**
416
+	 * add line item filters required for this reg step
417
+	 * these filters are applied via this line in EE_SPCO_Reg_Step_Payment_Options::set_hooks():
418
+	 *        add_filter( 'FHEE__SPCO__EE_Line_Item_Filter_Collection', array( 'EE_SPCO_Reg_Step_Payment_Options',
419
+	 *        'add_spco_line_item_filters' ) ); so any code that wants to use the same set of filters during the
420
+	 *        payment options reg step, can apply these filters via the following: apply_filters(
421
+	 *        'FHEE__SPCO__EE_Line_Item_Filter_Collection', new EE_Line_Item_Filter_Collection() ) or to an existing
422
+	 *        filter collection by passing that instead of instantiating a new collection
423
+	 *
424
+	 * @param \EE_Line_Item_Filter_Collection $line_item_filter_collection
425
+	 * @return EE_Line_Item_Filter_Collection
426
+	 * @throws EE_Error
427
+	 * @throws InvalidArgumentException
428
+	 * @throws ReflectionException
429
+	 * @throws \EventEspresso\core\exceptions\EntityNotFoundException
430
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
431
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
432
+	 * @throws \EventEspresso\core\exceptions\InvalidStatusException
433
+	 */
434
+	public static function add_spco_line_item_filters(EE_Line_Item_Filter_Collection $line_item_filter_collection)
435
+	{
436
+		if (! EE_Registry::instance()->SSN instanceof EE_Session) {
437
+			return $line_item_filter_collection;
438
+		}
439
+		if (! EE_Registry::instance()->SSN->checkout() instanceof EE_Checkout) {
440
+			return $line_item_filter_collection;
441
+		}
442
+		if (! EE_Registry::instance()->SSN->checkout()->transaction instanceof EE_Transaction) {
443
+			return $line_item_filter_collection;
444
+		}
445
+		$line_item_filter_collection->add(
446
+			new EE_Billable_Line_Item_Filter(
447
+				EE_SPCO_Reg_Step_Payment_Options::remove_ejected_registrations(
448
+					EE_Registry::instance()->SSN->checkout()->transaction->registrations(
449
+						EE_Registry::instance()->SSN->checkout()->reg_cache_where_params
450
+					)
451
+				)
452
+			)
453
+		);
454
+		$line_item_filter_collection->add(new EE_Non_Zero_Line_Item_Filter());
455
+		return $line_item_filter_collection;
456
+	}
457
+
458
+
459
+	/**
460
+	 * remove_ejected_registrations
461
+	 * if a registrant has lost their potential space at an event due to lack of payment,
462
+	 * then this method removes them from the list of registrations being paid for during this request
463
+	 *
464
+	 * @param \EE_Registration[] $registrations
465
+	 * @return EE_Registration[]
466
+	 * @throws EE_Error
467
+	 * @throws InvalidArgumentException
468
+	 * @throws ReflectionException
469
+	 * @throws \EventEspresso\core\exceptions\EntityNotFoundException
470
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
471
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
472
+	 * @throws \EventEspresso\core\exceptions\InvalidStatusException
473
+	 */
474
+	public static function remove_ejected_registrations(array $registrations)
475
+	{
476
+		$ejected_registrations = EE_SPCO_Reg_Step_Payment_Options::find_registrations_that_lost_their_space(
477
+			$registrations,
478
+			EE_Registry::instance()->SSN->checkout()->revisit
479
+		);
480
+		foreach ($registrations as $REG_ID => $registration) {
481
+			// has this registration lost it's space ?
482
+			if (isset($ejected_registrations[$REG_ID])) {
483
+				unset($registrations[$REG_ID]);
484
+				continue;
485
+			}
486
+		}
487
+		return $registrations;
488
+	}
489
+
490
+
491
+	/**
492
+	 * find_registrations_that_lost_their_space
493
+	 * If a registrant chooses an offline payment method like Invoice,
494
+	 * then no space is reserved for them at the event until they fully pay fo that site
495
+	 * (unless the event's default reg status is set to APPROVED)
496
+	 * if a registrant then later returns to pay, but the number of spaces available has been reduced due to sales,
497
+	 * then this method will determine which registrations have lost the ability to complete the reg process.
498
+	 *
499
+	 * @param \EE_Registration[] $registrations
500
+	 * @param bool               $revisit
501
+	 * @return array
502
+	 * @throws EE_Error
503
+	 * @throws InvalidArgumentException
504
+	 * @throws ReflectionException
505
+	 * @throws \EventEspresso\core\exceptions\EntityNotFoundException
506
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
507
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
508
+	 * @throws \EventEspresso\core\exceptions\InvalidStatusException
509
+	 */
510
+	public static function find_registrations_that_lost_their_space(array $registrations, $revisit = false)
511
+	{
512
+		// registrations per event
513
+		$event_reg_count = array();
514
+		// spaces left per event
515
+		$event_spaces_remaining = array();
516
+		// tickets left sorted by ID
517
+		$tickets_remaining = array();
518
+		// registrations that have lost their space
519
+		$ejected_registrations = array();
520
+		foreach ($registrations as $REG_ID => $registration) {
521
+			if ($registration->status_ID() === EEM_Registration::status_id_approved
522
+				|| apply_filters(
523
+					'FHEE__EE_SPCO_Reg_Step_Payment_Options__find_registrations_that_lost_their_space__allow_reg_payment',
524
+					false,
525
+					$registration,
526
+					$revisit
527
+				)
528
+			) {
529
+				continue;
530
+			}
531
+			$EVT_ID = $registration->event_ID();
532
+			$ticket = $registration->ticket();
533
+			if (! isset($tickets_remaining[$ticket->ID()])) {
534
+				$tickets_remaining[$ticket->ID()] = $ticket->remaining();
535
+			}
536
+			if ($tickets_remaining[$ticket->ID()] > 0) {
537
+				if (! isset($event_reg_count[$EVT_ID])) {
538
+					$event_reg_count[$EVT_ID] = 0;
539
+				}
540
+				$event_reg_count[$EVT_ID]++;
541
+				if (! isset($event_spaces_remaining[$EVT_ID])) {
542
+					$event_spaces_remaining[$EVT_ID] = $registration->event()->spaces_remaining_for_sale();
543
+				}
544
+			}
545
+			if ($revisit
546
+				&& ($tickets_remaining[$ticket->ID()] === 0
547
+					|| $event_reg_count[$EVT_ID] > $event_spaces_remaining[$EVT_ID]
548
+				)
549
+			) {
550
+				$ejected_registrations[$REG_ID] = $registration->event();
551
+				if ($registration->status_ID() !== EEM_Registration::status_id_wait_list) {
552
+					/** @type EE_Registration_Processor $registration_processor */
553
+					$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
554
+					// at this point, we should have enough details about the registrant to consider the registration
555
+					// NOT incomplete
556
+					$registration_processor->manually_update_registration_status(
557
+						$registration,
558
+						EEM_Registration::status_id_wait_list
559
+					);
560
+				}
561
+			}
562
+		}
563
+		return $ejected_registrations;
564
+	}
565
+
566
+
567
+	/**
568
+	 * _hide_reg_step_submit_button
569
+	 * removes the html for the reg step submit button
570
+	 * by replacing it with an empty string via filter callback
571
+	 *
572
+	 * @return void
573
+	 */
574
+	protected function _adjust_registration_status_if_event_old_sold()
575
+	{
576
+	}
577
+
578
+
579
+	/**
580
+	 * _hide_reg_step_submit_button
581
+	 * removes the html for the reg step submit button
582
+	 * by replacing it with an empty string via filter callback
583
+	 *
584
+	 * @return void
585
+	 */
586
+	protected function _hide_reg_step_submit_button_if_revisit()
587
+	{
588
+		if ($this->checkout->revisit) {
589
+			add_filter('FHEE__EE_SPCO_Reg_Step__reg_step_submit_button__sbmt_btn_html', '__return_empty_string');
590
+		}
591
+	}
592
+
593
+
594
+	/**
595
+	 * sold_out_events
596
+	 * displays notices regarding events that have sold out since hte registrant first signed up
597
+	 *
598
+	 * @param \EE_Event[] $sold_out_events_array
599
+	 * @return \EE_Form_Section_Proper
600
+	 * @throws \EE_Error
601
+	 */
602
+	private function _sold_out_events($sold_out_events_array = array())
603
+	{
604
+		// set some defaults
605
+		$this->checkout->selected_method_of_payment = 'events_sold_out';
606
+		$sold_out_events                            = '';
607
+		foreach ($sold_out_events_array as $sold_out_event) {
608
+			$sold_out_events .= EEH_HTML::li(
609
+				EEH_HTML::span(
610
+					'  ' . $sold_out_event->name(),
611
+					'',
612
+					'dashicons dashicons-marker ee-icon-size-16 pink-text'
613
+				)
614
+			);
615
+		}
616
+		return new EE_Form_Section_Proper(
617
+			array(
618
+				'layout_strategy' => new EE_Template_Layout(
619
+					array(
620
+						'layout_template_file' => SPCO_REG_STEPS_PATH
621
+												  . $this->_slug
622
+												  . DS
623
+												  . 'sold_out_events.template.php',
624
+						'template_args'        => apply_filters(
625
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___sold_out_events__template_args',
626
+							array(
627
+								'sold_out_events'     => $sold_out_events,
628
+								'sold_out_events_msg' => apply_filters(
629
+									'FHEE__EE_SPCO_Reg_Step_Payment_Options___sold_out_events__sold_out_events_msg',
630
+									sprintf(
631
+										esc_html__(
632
+											'It appears that the event you were about to make a payment for has sold out since you first registered. If you have already made a partial payment towards this event, please contact the event administrator for a refund.%3$s%3$s%1$sPlease note that availability can change at any time due to cancellations, so please check back again later if registration for this event(s) is important to you.%2$s',
633
+											'event_espresso'
634
+										),
635
+										'<strong>',
636
+										'</strong>',
637
+										'<br />'
638
+									)
639
+								),
640
+							)
641
+						),
642
+					)
643
+				),
644
+			)
645
+		);
646
+	}
647
+
648
+
649
+	/**
650
+	 * _insufficient_spaces_available
651
+	 * displays notices regarding events that do not have enough remaining spaces
652
+	 * to satisfy the current number of registrations looking to pay
653
+	 *
654
+	 * @param \EE_Event[] $insufficient_spaces_events_array
655
+	 * @return \EE_Form_Section_Proper
656
+	 * @throws \EE_Error
657
+	 */
658
+	private function _insufficient_spaces_available($insufficient_spaces_events_array = array())
659
+	{
660
+		// set some defaults
661
+		$this->checkout->selected_method_of_payment = 'invoice';
662
+		$insufficient_space_events                  = '';
663
+		foreach ($insufficient_spaces_events_array as $event) {
664
+			if ($event instanceof EE_Event) {
665
+				$insufficient_space_events .= EEH_HTML::li(
666
+					EEH_HTML::span(' ' . $event->name(), '', 'dashicons dashicons-marker ee-icon-size-16 pink-text')
667
+				);
668
+			}
669
+		}
670
+		return new EE_Form_Section_Proper(
671
+			array(
672
+				'subsections'     => array(
673
+					'default_hidden_inputs' => $this->reg_step_hidden_inputs(),
674
+					'extra_hidden_inputs'   => $this->_extra_hidden_inputs(),
675
+				),
676
+				'layout_strategy' => new EE_Template_Layout(
677
+					array(
678
+						'layout_template_file' => SPCO_REG_STEPS_PATH
679
+												  . $this->_slug
680
+												  . DS
681
+												  . 'sold_out_events.template.php',
682
+						'template_args'        => apply_filters(
683
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___insufficient_spaces_available__template_args',
684
+							array(
685
+								'sold_out_events'     => $insufficient_space_events,
686
+								'sold_out_events_msg' => apply_filters(
687
+									'FHEE__EE_SPCO_Reg_Step_Payment_Options___insufficient_spaces_available__insufficient_space_msg',
688
+									esc_html__(
689
+										'It appears that the event you were about to make a payment for has sold additional tickets since you first registered, and there are no longer enough spaces left to accommodate your selections. You may continue to pay and secure the available space(s) remaining, or simply cancel if you no longer wish to purchase. If you have already made a partial payment towards this event, please contact the event administrator for a refund.',
690
+										'event_espresso'
691
+									)
692
+								),
693
+							)
694
+						),
695
+					)
696
+				),
697
+			)
698
+		);
699
+	}
700
+
701
+
702
+	/**
703
+	 * registrations_requiring_pre_approval
704
+	 *
705
+	 * @param array $registrations_requiring_pre_approval
706
+	 * @return EE_Form_Section_Proper
707
+	 * @throws EE_Error
708
+	 * @throws \EventEspresso\core\exceptions\EntityNotFoundException
709
+	 */
710
+	private function _registrations_requiring_pre_approval($registrations_requiring_pre_approval = array())
711
+	{
712
+		$events_requiring_pre_approval = '';
713
+		foreach ($registrations_requiring_pre_approval as $registration) {
714
+			if ($registration instanceof EE_Registration && $registration->event() instanceof EE_Event) {
715
+				$events_requiring_pre_approval[$registration->event()->ID()] = EEH_HTML::li(
716
+					EEH_HTML::span(
717
+						'',
718
+						'',
719
+						'dashicons dashicons-marker ee-icon-size-16 orange-text'
720
+					)
721
+					. EEH_HTML::span($registration->event()->name(), '', 'orange-text')
722
+				);
723
+			}
724
+		}
725
+		return new EE_Form_Section_Proper(
726
+			array(
727
+				'layout_strategy' => new EE_Template_Layout(
728
+					array(
729
+						'layout_template_file' => SPCO_REG_STEPS_PATH
730
+												  . $this->_slug
731
+												  . DS
732
+												  . 'events_requiring_pre_approval.template.php', // layout_template
733
+						'template_args'        => apply_filters(
734
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___sold_out_events__template_args',
735
+							array(
736
+								'events_requiring_pre_approval'     => implode('', $events_requiring_pre_approval),
737
+								'events_requiring_pre_approval_msg' => apply_filters(
738
+									'FHEE__EE_SPCO_Reg_Step_Payment_Options___events_requiring_pre_approval__events_requiring_pre_approval_msg',
739
+									esc_html__(
740
+										'The following events do not require payment at this time and will not be billed during this transaction. Billing will only occur after the attendee has been approved by the event organizer. You will be notified when your registration has been processed. If this is a free event, then no billing will occur.',
741
+										'event_espresso'
742
+									)
743
+								),
744
+							)
745
+						),
746
+					)
747
+				),
748
+			)
749
+		);
750
+	}
751
+
752
+
753
+	/**
754
+	 * _no_payment_required
755
+	 *
756
+	 * @param \EE_Event[] $registrations_for_free_events
757
+	 * @return \EE_Form_Section_Proper
758
+	 * @throws \EE_Error
759
+	 */
760
+	private function _no_payment_required($registrations_for_free_events = array())
761
+	{
762
+		// set some defaults
763
+		$this->checkout->selected_method_of_payment = 'no_payment_required';
764
+		// generate no_payment_required form
765
+		return new EE_Form_Section_Proper(
766
+			array(
767
+				'layout_strategy' => new EE_Template_Layout(
768
+					array(
769
+						'layout_template_file' => SPCO_REG_STEPS_PATH
770
+												  . $this->_slug
771
+												  . DS
772
+												  . 'no_payment_required.template.php', // layout_template
773
+						'template_args'        => apply_filters(
774
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___no_payment_required__template_args',
775
+							array(
776
+								'revisit'                       => $this->checkout->revisit,
777
+								'registrations'                 => array(),
778
+								'ticket_count'                  => array(),
779
+								'registrations_for_free_events' => $registrations_for_free_events,
780
+								'no_payment_required_msg'       => EEH_HTML::p(
781
+									esc_html__('This is a free event, so no billing will occur.', 'event_espresso')
782
+								),
783
+							)
784
+						),
785
+					)
786
+				),
787
+			)
788
+		);
789
+	}
790
+
791
+
792
+	/**
793
+	 * _display_payment_options
794
+	 *
795
+	 * @param string $transaction_details
796
+	 * @return EE_Form_Section_Proper
797
+	 * @throws EE_Error
798
+	 * @throws InvalidArgumentException
799
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
800
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
801
+	 */
802
+	private function _display_payment_options($transaction_details = '')
803
+	{
804
+		// has method_of_payment been set by no-js user?
805
+		$this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment();
806
+		// build payment options form
807
+		return apply_filters(
808
+			'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__payment_options_form',
809
+			new EE_Form_Section_Proper(
810
+				array(
811
+					'subsections'     => array(
812
+						'before_payment_options' => apply_filters(
813
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__before_payment_options',
814
+							new EE_Form_Section_Proper(
815
+								array('layout_strategy' => new EE_Div_Per_Section_Layout())
816
+							)
817
+						),
818
+						'payment_options'        => $this->_setup_payment_options(),
819
+						'after_payment_options'  => apply_filters(
820
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__after_payment_options',
821
+							new EE_Form_Section_Proper(
822
+								array('layout_strategy' => new EE_Div_Per_Section_Layout())
823
+							)
824
+						),
825
+					),
826
+					'layout_strategy' => new EE_Template_Layout(
827
+						array(
828
+							'layout_template_file' => $this->_template,
829
+							'template_args'        => apply_filters(
830
+								'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__template_args',
831
+								array(
832
+									'reg_count'                 => $this->line_item_display->total_items(),
833
+									'transaction_details'       => $transaction_details,
834
+									'available_payment_methods' => array(),
835
+								)
836
+							),
837
+						)
838
+					),
839
+				)
840
+			)
841
+		);
842
+	}
843
+
844
+
845
+	/**
846
+	 * _extra_hidden_inputs
847
+	 *
848
+	 * @param bool $no_payment_required
849
+	 * @return \EE_Form_Section_Proper
850
+	 * @throws \EE_Error
851
+	 */
852
+	private function _extra_hidden_inputs($no_payment_required = true)
853
+	{
854
+		return new EE_Form_Section_Proper(
855
+			array(
856
+				'html_id'         => 'ee-' . $this->slug() . '-extra-hidden-inputs',
857
+				'layout_strategy' => new EE_Div_Per_Section_Layout(),
858
+				'subsections'     => array(
859
+					'spco_no_payment_required' => new EE_Hidden_Input(
860
+						array(
861
+							'normalization_strategy' => new EE_Boolean_Normalization(),
862
+							'html_name'              => 'spco_no_payment_required',
863
+							'html_id'                => 'spco-no-payment-required-payment_options',
864
+							'default'                => $no_payment_required,
865
+						)
866
+					),
867
+					'spco_transaction_id'      => new EE_Fixed_Hidden_Input(
868
+						array(
869
+							'normalization_strategy' => new EE_Int_Normalization(),
870
+							'html_name'              => 'spco_transaction_id',
871
+							'html_id'                => 'spco-transaction-id',
872
+							'default'                => $this->checkout->transaction->ID(),
873
+						)
874
+					),
875
+				),
876
+			)
877
+		);
878
+	}
879
+
880
+
881
+	/**
882
+	 *    _apply_registration_payments_to_amount_owing
883
+	 *
884
+	 * @access protected
885
+	 * @param array $registrations
886
+	 * @throws EE_Error
887
+	 */
888
+	protected function _apply_registration_payments_to_amount_owing(array $registrations)
889
+	{
890
+		$payments = array();
891
+		foreach ($registrations as $registration) {
892
+			if ($registration instanceof EE_Registration && $registration->owes_monies_and_can_pay()) {
893
+				$payments += $registration->registration_payments();
894
+			}
895
+		}
896
+		if (! empty($payments)) {
897
+			foreach ($payments as $payment) {
898
+				if ($payment instanceof EE_Registration_Payment) {
899
+					$this->checkout->amount_owing -= $payment->amount();
900
+				}
901
+			}
902
+		}
903
+	}
904
+
905
+
906
+	/**
907
+	 *    _reset_selected_method_of_payment
908
+	 *
909
+	 * @access    private
910
+	 * @param    bool $force_reset
911
+	 * @return void
912
+	 * @throws InvalidArgumentException
913
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
914
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
915
+	 */
916
+	private function _reset_selected_method_of_payment($force_reset = false)
917
+	{
918
+		$reset_payment_method = $force_reset
919
+			? true
920
+			: sanitize_text_field(EE_Registry::instance()->REQ->get('reset_payment_method', false));
921
+		if ($reset_payment_method) {
922
+			$this->checkout->selected_method_of_payment = null;
923
+			$this->checkout->payment_method             = null;
924
+			$this->checkout->billing_form               = null;
925
+			$this->_save_selected_method_of_payment();
926
+		}
927
+	}
928
+
929
+
930
+	/**
931
+	 * _save_selected_method_of_payment
932
+	 * stores the selected_method_of_payment in the session
933
+	 * so that it's available for all subsequent requests including AJAX
934
+	 *
935
+	 * @access        private
936
+	 * @param string $selected_method_of_payment
937
+	 * @return void
938
+	 * @throws InvalidArgumentException
939
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
940
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
941
+	 */
942
+	private function _save_selected_method_of_payment($selected_method_of_payment = '')
943
+	{
944
+		$selected_method_of_payment = ! empty($selected_method_of_payment)
945
+			? $selected_method_of_payment
946
+			: $this->checkout->selected_method_of_payment;
947
+		EE_Registry::instance()->SSN->set_session_data(
948
+			array('selected_method_of_payment' => $selected_method_of_payment)
949
+		);
950
+	}
951
+
952
+
953
+	/**
954
+	 * _setup_payment_options
955
+	 *
956
+	 * @return EE_Form_Section_Proper
957
+	 * @throws EE_Error
958
+	 * @throws InvalidArgumentException
959
+	 * @throws ReflectionException
960
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
961
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
962
+	 */
963
+	public function _setup_payment_options()
964
+	{
965
+		// load payment method classes
966
+		$this->checkout->available_payment_methods = $this->_get_available_payment_methods();
967
+		if (empty($this->checkout->available_payment_methods)) {
968
+			EE_Error::add_error(
969
+				apply_filters(
970
+					'FHEE__EE_SPCO_Reg_Step_Payment_Options___setup_payment_options__error_message_no_payment_methods',
971
+					sprintf(
972
+						esc_html__(
973
+							'Sorry, you cannot complete your purchase because a payment method is not active.%1$s Please contact %2$s for assistance and provide a description of the problem.',
974
+							'event_espresso'
975
+						),
976
+						'<br>',
977
+						EE_Registry::instance()->CFG->organization->get_pretty('email')
978
+					)
979
+				),
980
+				__FILE__,
981
+				__FUNCTION__,
982
+				__LINE__
983
+			);
984
+		}
985
+		// switch up header depending on number of available payment methods
986
+		$payment_method_header     = count($this->checkout->available_payment_methods) > 1
987
+			? apply_filters(
988
+				'FHEE__registration_page_payment_options__method_of_payment_hdr',
989
+				esc_html__('Please Select Your Method of Payment', 'event_espresso')
990
+			)
991
+			: apply_filters(
992
+				'FHEE__registration_page_payment_options__method_of_payment_hdr',
993
+				esc_html__('Method of Payment', 'event_espresso')
994
+			);
995
+		$available_payment_methods = array(
996
+			// display the "Payment Method" header
997
+			'payment_method_header' => new EE_Form_Section_HTML(
998
+				EEH_HTML::h4($payment_method_header, 'method-of-payment-hdr')
999
+			),
1000
+		);
1001
+		// the list of actual payment methods ( invoice, paypal, etc ) in a  ( slug => HTML )  format
1002
+		$available_payment_method_options = array();
1003
+		$default_payment_method_option    = array();
1004
+		// additional instructions to be displayed and hidden below payment methods (adding a clearing div to start)
1005
+		$payment_methods_billing_info = array(
1006
+			new EE_Form_Section_HTML(
1007
+				EEH_HTML::div('<br />', '', '', 'clear:both;')
1008
+			),
1009
+		);
1010
+		// loop through payment methods
1011
+		foreach ($this->checkout->available_payment_methods as $payment_method) {
1012
+			if ($payment_method instanceof EE_Payment_Method) {
1013
+				$payment_method_button = EEH_HTML::img(
1014
+					$payment_method->button_url(),
1015
+					$payment_method->name(),
1016
+					'spco-payment-method-' . $payment_method->slug() . '-btn-img',
1017
+					'spco-payment-method-btn-img'
1018
+				);
1019
+				// check if any payment methods are set as default
1020
+				// if payment method is already selected OR nothing is selected and this payment method should be
1021
+				// open_by_default
1022
+				if (($this->checkout->selected_method_of_payment === $payment_method->slug())
1023
+					|| (! $this->checkout->selected_method_of_payment && $payment_method->open_by_default())
1024
+				) {
1025
+					$this->checkout->selected_method_of_payment = $payment_method->slug();
1026
+					$this->_save_selected_method_of_payment();
1027
+					$default_payment_method_option[$payment_method->slug()] = $payment_method_button;
1028
+				} else {
1029
+					$available_payment_method_options[$payment_method->slug()] = $payment_method_button;
1030
+				}
1031
+				$payment_methods_billing_info[$payment_method->slug() . '-info'] = $this->_payment_method_billing_info(
1032
+					$payment_method
1033
+				);
1034
+			}
1035
+		}
1036
+		// prepend available_payment_method_options with default_payment_method_option so that it appears first in list
1037
+		// of PMs
1038
+		$available_payment_method_options = $default_payment_method_option + $available_payment_method_options;
1039
+		// now generate the actual form  inputs
1040
+		$available_payment_methods['available_payment_methods'] = $this->_available_payment_method_inputs(
1041
+			$available_payment_method_options
1042
+		);
1043
+		$available_payment_methods                              += $payment_methods_billing_info;
1044
+		// build the available payment methods form
1045
+		return new EE_Form_Section_Proper(
1046
+			array(
1047
+				'html_id'         => 'spco-available-methods-of-payment-dv',
1048
+				'subsections'     => $available_payment_methods,
1049
+				'layout_strategy' => new EE_Div_Per_Section_Layout(),
1050
+			)
1051
+		);
1052
+	}
1053
+
1054
+
1055
+	/**
1056
+	 * _get_available_payment_methods
1057
+	 *
1058
+	 * @return EE_Payment_Method[]
1059
+	 * @throws EE_Error
1060
+	 * @throws InvalidArgumentException
1061
+	 * @throws ReflectionException
1062
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1063
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1064
+	 */
1065
+	protected function _get_available_payment_methods()
1066
+	{
1067
+		if (! empty($this->checkout->available_payment_methods)) {
1068
+			return $this->checkout->available_payment_methods;
1069
+		}
1070
+		$available_payment_methods = array();
1071
+		// load EEM_Payment_Method
1072
+		EE_Registry::instance()->load_model('Payment_Method');
1073
+		/** @type EEM_Payment_Method $EEM_Payment_Method */
1074
+		$EEM_Payment_Method = EE_Registry::instance()->LIB->EEM_Payment_Method;
1075
+		// get all active payment methods
1076
+		$payment_methods = $EEM_Payment_Method->get_all_for_transaction(
1077
+			$this->checkout->transaction,
1078
+			EEM_Payment_Method::scope_cart
1079
+		);
1080
+		foreach ($payment_methods as $payment_method) {
1081
+			if ($payment_method instanceof EE_Payment_Method) {
1082
+				$available_payment_methods[$payment_method->slug()] = $payment_method;
1083
+			}
1084
+		}
1085
+		return $available_payment_methods;
1086
+	}
1087
+
1088
+
1089
+	/**
1090
+	 *    _available_payment_method_inputs
1091
+	 *
1092
+	 * @access    private
1093
+	 * @param    array $available_payment_method_options
1094
+	 * @return    \EE_Form_Section_Proper
1095
+	 */
1096
+	private function _available_payment_method_inputs($available_payment_method_options = array())
1097
+	{
1098
+		// generate inputs
1099
+		return new EE_Form_Section_Proper(
1100
+			array(
1101
+				'html_id'         => 'ee-available-payment-method-inputs',
1102
+				'layout_strategy' => new EE_Div_Per_Section_Layout(),
1103
+				'subsections'     => array(
1104
+					'' => new EE_Radio_Button_Input(
1105
+						$available_payment_method_options,
1106
+						array(
1107
+							'html_name'          => 'selected_method_of_payment',
1108
+							'html_class'         => 'spco-payment-method',
1109
+							'default'            => $this->checkout->selected_method_of_payment,
1110
+							'label_size'         => 11,
1111
+							'enforce_label_size' => true,
1112
+						)
1113
+					),
1114
+				),
1115
+			)
1116
+		);
1117
+	}
1118
+
1119
+
1120
+	/**
1121
+	 *    _payment_method_billing_info
1122
+	 *
1123
+	 * @access    private
1124
+	 * @param    EE_Payment_Method $payment_method
1125
+	 * @return EE_Form_Section_Proper
1126
+	 * @throws EE_Error
1127
+	 * @throws InvalidArgumentException
1128
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1129
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1130
+	 */
1131
+	private function _payment_method_billing_info(EE_Payment_Method $payment_method)
1132
+	{
1133
+		$currently_selected = $this->checkout->selected_method_of_payment === $payment_method->slug()
1134
+			? true
1135
+			: false;
1136
+		// generate the billing form for payment method
1137
+		$billing_form                 = $currently_selected
1138
+			? $this->_get_billing_form_for_payment_method($payment_method)
1139
+			: new EE_Form_Section_HTML();
1140
+		$this->checkout->billing_form = $currently_selected
1141
+			? $billing_form
1142
+			: $this->checkout->billing_form;
1143
+		// it's all in the details
1144
+		$info_html = EEH_HTML::h3(
1145
+			esc_html__('Important information regarding your payment', 'event_espresso'),
1146
+			'',
1147
+			'spco-payment-method-hdr'
1148
+		);
1149
+		// add some info regarding the step, either from what's saved in the admin,
1150
+		// or a default string depending on whether the PM has a billing form or not
1151
+		if ($payment_method->description()) {
1152
+			$payment_method_info = $payment_method->description();
1153
+		} elseif ($billing_form instanceof EE_Billing_Info_Form) {
1154
+			$payment_method_info = sprintf(
1155
+				esc_html__(
1156
+					'Please provide the following billing information, then click the "%1$s" button below in order to proceed.',
1157
+					'event_espresso'
1158
+				),
1159
+				$this->submit_button_text()
1160
+			);
1161
+		} else {
1162
+			$payment_method_info = sprintf(
1163
+				esc_html__('Please click the "%1$s" button below in order to proceed.', 'event_espresso'),
1164
+				$this->submit_button_text()
1165
+			);
1166
+		}
1167
+		$info_html .= EEH_HTML::p(
1168
+			apply_filters(
1169
+				'FHEE__EE_SPCO_Reg_Step_Payment_Options___payment_method_billing_info__payment_method_info',
1170
+				$payment_method_info
1171
+			),
1172
+			'',
1173
+			'spco-payment-method-desc ee-attention'
1174
+		);
1175
+		return new EE_Form_Section_Proper(
1176
+			array(
1177
+				'html_id'         => 'spco-payment-method-info-' . $payment_method->slug(),
1178
+				'html_class'      => 'spco-payment-method-info-dv',
1179
+				// only display the selected or default PM
1180
+				'html_style'      => $currently_selected ? '' : 'display:none;',
1181
+				'layout_strategy' => new EE_Div_Per_Section_Layout(),
1182
+				'subsections'     => array(
1183
+					'info'         => new EE_Form_Section_HTML($info_html),
1184
+					'billing_form' => $currently_selected ? $billing_form : new EE_Form_Section_HTML(),
1185
+				),
1186
+			)
1187
+		);
1188
+	}
1189
+
1190
+
1191
+	/**
1192
+	 * get_billing_form_html_for_payment_method
1193
+	 *
1194
+	 * @access public
1195
+	 * @return string
1196
+	 * @throws EE_Error
1197
+	 * @throws InvalidArgumentException
1198
+	 * @throws ReflectionException
1199
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1200
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1201
+	 */
1202
+	public function get_billing_form_html_for_payment_method()
1203
+	{
1204
+		// how have they chosen to pay?
1205
+		$this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
1206
+		$this->checkout->payment_method             = $this->_get_payment_method_for_selected_method_of_payment();
1207
+		if (! $this->checkout->payment_method instanceof EE_Payment_Method) {
1208
+			return false;
1209
+		}
1210
+		if (apply_filters(
1211
+			'FHEE__EE_SPCO_Reg_Step_Payment_Options__registration_checkout__selected_payment_method__display_success',
1212
+			false
1213
+		)) {
1214
+			EE_Error::add_success(
1215
+				apply_filters(
1216
+					'FHEE__Single_Page_Checkout__registration_checkout__selected_payment_method',
1217
+					sprintf(
1218
+						esc_html__(
1219
+							'You have selected "%s" as your method of payment. Please note the important payment information below.',
1220
+							'event_espresso'
1221
+						),
1222
+						$this->checkout->payment_method->name()
1223
+					)
1224
+				)
1225
+			);
1226
+		}
1227
+		// now generate billing form for selected method of payment
1228
+		$payment_method_billing_form = $this->_get_billing_form_for_payment_method($this->checkout->payment_method);
1229
+		// fill form with attendee info if applicable
1230
+		if ($payment_method_billing_form instanceof EE_Billing_Attendee_Info_Form
1231
+			&& $this->checkout->transaction_has_primary_registrant()
1232
+		) {
1233
+			$payment_method_billing_form->populate_from_attendee(
1234
+				$this->checkout->transaction->primary_registration()->attendee()
1235
+			);
1236
+		}
1237
+		// and debug content
1238
+		if ($payment_method_billing_form instanceof EE_Billing_Info_Form
1239
+			&& $this->checkout->payment_method->type_obj() instanceof EE_PMT_Base
1240
+		) {
1241
+			$payment_method_billing_form =
1242
+				$this->checkout->payment_method->type_obj()->apply_billing_form_debug_settings(
1243
+					$payment_method_billing_form
1244
+				);
1245
+		}
1246
+		$billing_info = $payment_method_billing_form instanceof EE_Form_Section_Proper
1247
+			? $payment_method_billing_form->get_html()
1248
+			: '';
1249
+		$this->checkout->json_response->set_return_data(array('payment_method_info' => $billing_info));
1250
+		// localize validation rules for main form
1251
+		$this->checkout->current_step->reg_form->localize_validation_rules();
1252
+		$this->checkout->json_response->add_validation_rules(EE_Form_Section_Proper::js_localization());
1253
+		return true;
1254
+	}
1255
+
1256
+
1257
+	/**
1258
+	 * _get_billing_form_for_payment_method
1259
+	 *
1260
+	 * @access private
1261
+	 * @param EE_Payment_Method $payment_method
1262
+	 * @return EE_Billing_Info_Form|EE_Form_Section_HTML
1263
+	 * @throws EE_Error
1264
+	 * @throws InvalidArgumentException
1265
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1266
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1267
+	 */
1268
+	private function _get_billing_form_for_payment_method(EE_Payment_Method $payment_method)
1269
+	{
1270
+		$billing_form = $payment_method->type_obj()->billing_form(
1271
+			$this->checkout->transaction,
1272
+			array('amount_owing' => $this->checkout->amount_owing)
1273
+		);
1274
+		if ($billing_form instanceof EE_Billing_Info_Form) {
1275
+			if (apply_filters(
1276
+				'FHEE__EE_SPCO_Reg_Step_Payment_Options__registration_checkout__selected_payment_method__display_success',
1277
+				false
1278
+			)
1279
+				&& EE_Registry::instance()->REQ->is_set('payment_method')
1280
+			) {
1281
+				EE_Error::add_success(
1282
+					apply_filters(
1283
+						'FHEE__Single_Page_Checkout__registration_checkout__selected_payment_method',
1284
+						sprintf(
1285
+							esc_html__(
1286
+								'You have selected "%s" as your method of payment. Please note the important payment information below.',
1287
+								'event_espresso'
1288
+							),
1289
+							$payment_method->name()
1290
+						)
1291
+					)
1292
+				);
1293
+			}
1294
+			return apply_filters(
1295
+				'FHEE__EE_SPCO_Reg_Step_Payment_Options___get_billing_form_for_payment_method__billing_form',
1296
+				$billing_form,
1297
+				$payment_method
1298
+			);
1299
+		}
1300
+		// no actual billing form, so return empty HTML form section
1301
+		return new EE_Form_Section_HTML();
1302
+	}
1303
+
1304
+
1305
+	/**
1306
+	 * _get_selected_method_of_payment
1307
+	 *
1308
+	 * @access private
1309
+	 * @param boolean $required whether to throw an error if the "selected_method_of_payment"
1310
+	 *                          is not found in the incoming request
1311
+	 * @param string  $request_param
1312
+	 * @return NULL|string
1313
+	 * @throws EE_Error
1314
+	 * @throws InvalidArgumentException
1315
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1316
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1317
+	 */
1318
+	private function _get_selected_method_of_payment(
1319
+		$required = false,
1320
+		$request_param = 'selected_method_of_payment'
1321
+	) {
1322
+		// is selected_method_of_payment set in the request ?
1323
+		$selected_method_of_payment = EE_Registry::instance()->REQ->get($request_param, false);
1324
+		if ($selected_method_of_payment) {
1325
+			// sanitize it
1326
+			$selected_method_of_payment = is_array($selected_method_of_payment)
1327
+				? array_shift($selected_method_of_payment)
1328
+				: $selected_method_of_payment;
1329
+			$selected_method_of_payment = sanitize_text_field($selected_method_of_payment);
1330
+			// store it in the session so that it's available for all subsequent requests including AJAX
1331
+			$this->_save_selected_method_of_payment($selected_method_of_payment);
1332
+		} else {
1333
+			// or is is set in the session ?
1334
+			$selected_method_of_payment = EE_Registry::instance()->SSN->get_session_data(
1335
+				'selected_method_of_payment'
1336
+			);
1337
+		}
1338
+		// do ya really really gotta have it?
1339
+		if (empty($selected_method_of_payment) && $required) {
1340
+			EE_Error::add_error(
1341
+				sprintf(
1342
+					esc_html__(
1343
+						'The selected method of payment could not be determined.%sPlease ensure that you have selected one before proceeding.%sIf you continue to experience difficulties, then refresh your browser and try again, or contact %s for assistance.',
1344
+						'event_espresso'
1345
+					),
1346
+					'<br/>',
1347
+					'<br/>',
1348
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
1349
+				),
1350
+				__FILE__,
1351
+				__FUNCTION__,
1352
+				__LINE__
1353
+			);
1354
+			return null;
1355
+		}
1356
+		return $selected_method_of_payment;
1357
+	}
1358
+
1359
+
1360
+
1361
+
1362
+
1363
+
1364
+	/********************************************************************************************************/
1365
+	/***********************************  SWITCH PAYMENT METHOD  ************************************/
1366
+	/********************************************************************************************************/
1367
+	/**
1368
+	 * switch_payment_method
1369
+	 *
1370
+	 * @access public
1371
+	 * @return string
1372
+	 * @throws EE_Error
1373
+	 * @throws InvalidArgumentException
1374
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1375
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1376
+	 */
1377
+	public function switch_payment_method()
1378
+	{
1379
+		if (! $this->_verify_payment_method_is_set()) {
1380
+			return false;
1381
+		}
1382
+		if (apply_filters(
1383
+			'FHEE__EE_SPCO_Reg_Step_Payment_Options__registration_checkout__selected_payment_method__display_success',
1384
+			false
1385
+		)) {
1386
+			EE_Error::add_success(
1387
+				apply_filters(
1388
+					'FHEE__Single_Page_Checkout__registration_checkout__selected_payment_method',
1389
+					sprintf(
1390
+						esc_html__(
1391
+							'You have selected "%s" as your method of payment. Please note the important payment information below.',
1392
+							'event_espresso'
1393
+						),
1394
+						$this->checkout->payment_method->name()
1395
+					)
1396
+				)
1397
+			);
1398
+		}
1399
+		// generate billing form for selected method of payment if it hasn't been done already
1400
+		if ($this->checkout->payment_method->type_obj()->has_billing_form()) {
1401
+			$this->checkout->billing_form = $this->_get_billing_form_for_payment_method(
1402
+				$this->checkout->payment_method
1403
+			);
1404
+		}
1405
+		// fill form with attendee info if applicable
1406
+		if (apply_filters(
1407
+			'FHEE__populate_billing_form_fields_from_attendee',
1408
+			(
1409
+				$this->checkout->billing_form instanceof EE_Billing_Attendee_Info_Form
1410
+				&& $this->checkout->transaction_has_primary_registrant()
1411
+			),
1412
+			$this->checkout->billing_form,
1413
+			$this->checkout->transaction
1414
+		)
1415
+		) {
1416
+			$this->checkout->billing_form->populate_from_attendee(
1417
+				$this->checkout->transaction->primary_registration()->attendee()
1418
+			);
1419
+		}
1420
+		// and debug content
1421
+		if ($this->checkout->billing_form instanceof EE_Billing_Info_Form
1422
+			&& $this->checkout->payment_method->type_obj() instanceof EE_PMT_Base
1423
+		) {
1424
+			$this->checkout->billing_form =
1425
+				$this->checkout->payment_method->type_obj()->apply_billing_form_debug_settings(
1426
+					$this->checkout->billing_form
1427
+				);
1428
+		}
1429
+		// get html and validation rules for form
1430
+		if ($this->checkout->billing_form instanceof EE_Form_Section_Proper) {
1431
+			$this->checkout->json_response->set_return_data(
1432
+				array('payment_method_info' => $this->checkout->billing_form->get_html())
1433
+			);
1434
+			// localize validation rules for main form
1435
+			$this->checkout->billing_form->localize_validation_rules(true);
1436
+			$this->checkout->json_response->add_validation_rules(EE_Form_Section_Proper::js_localization());
1437
+		} else {
1438
+			$this->checkout->json_response->set_return_data(array('payment_method_info' => ''));
1439
+		}
1440
+		//prevents advancement to next step
1441
+		$this->checkout->continue_reg = false;
1442
+		return true;
1443
+	}
1444
+
1445
+
1446
+	/**
1447
+	 * _verify_payment_method_is_set
1448
+	 *
1449
+	 * @return bool
1450
+	 * @throws EE_Error
1451
+	 * @throws InvalidArgumentException
1452
+	 * @throws ReflectionException
1453
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1454
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1455
+	 */
1456
+	protected function _verify_payment_method_is_set()
1457
+	{
1458
+		// generate billing form for selected method of payment if it hasn't been done already
1459
+		if (empty($this->checkout->selected_method_of_payment)) {
1460
+			// how have they chosen to pay?
1461
+			$this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
1462
+		} else {
1463
+			// choose your own adventure based on method_of_payment
1464
+			switch ($this->checkout->selected_method_of_payment) {
1465
+				case 'events_sold_out' :
1466
+					EE_Error::add_attention(
1467
+						apply_filters(
1468
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___verify_payment_method_is_set__sold_out_events_msg',
1469
+							esc_html__(
1470
+								'It appears that the event you were about to make a payment for has sold out since this form first loaded. Please contact the event administrator if you believe this is an error.',
1471
+								'event_espresso'
1472
+							)
1473
+						),
1474
+						__FILE__, __FUNCTION__, __LINE__
1475
+					);
1476
+					return false;
1477
+					break;
1478
+				case 'payments_closed' :
1479
+					EE_Error::add_attention(
1480
+						apply_filters(
1481
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___verify_payment_method_is_set__payments_closed_msg',
1482
+							esc_html__(
1483
+								'It appears that the event you were about to make a payment for is not accepting payments at this time. Please contact the event administrator if you believe this is an error.',
1484
+								'event_espresso'
1485
+							)
1486
+						),
1487
+						__FILE__, __FUNCTION__, __LINE__
1488
+					);
1489
+					return false;
1490
+					break;
1491
+				case 'no_payment_required' :
1492
+					EE_Error::add_attention(
1493
+						apply_filters(
1494
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___verify_payment_method_is_set__no_payment_required_msg',
1495
+							esc_html__(
1496
+								'It appears that the event you were about to make a payment for does not require payment. Please contact the event administrator if you believe this is an error.',
1497
+								'event_espresso'
1498
+							)
1499
+						),
1500
+						__FILE__, __FUNCTION__, __LINE__
1501
+					);
1502
+					return false;
1503
+					break;
1504
+				default:
1505
+			}
1506
+		}
1507
+		// verify payment method
1508
+		if (! $this->checkout->payment_method instanceof EE_Payment_Method) {
1509
+			// get payment method for selected method of payment
1510
+			$this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment();
1511
+		}
1512
+		return $this->checkout->payment_method instanceof EE_Payment_Method ? true : false;
1513
+	}
1514
+
1515
+
1516
+
1517
+	/********************************************************************************************************/
1518
+	/***************************************  SAVE PAYER DETAILS  ****************************************/
1519
+	/********************************************************************************************************/
1520
+	/**
1521
+	 * save_payer_details_via_ajax
1522
+	 *
1523
+	 * @return void
1524
+	 * @throws EE_Error
1525
+	 * @throws InvalidArgumentException
1526
+	 * @throws ReflectionException
1527
+	 * @throws RuntimeException
1528
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1529
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1530
+	 */
1531
+	public function save_payer_details_via_ajax()
1532
+	{
1533
+		if (! $this->_verify_payment_method_is_set()) {
1534
+			return;
1535
+		}
1536
+		// generate billing form for selected method of payment if it hasn't been done already
1537
+		if ($this->checkout->payment_method->type_obj()->has_billing_form()) {
1538
+			$this->checkout->billing_form = $this->_get_billing_form_for_payment_method(
1539
+				$this->checkout->payment_method
1540
+			);
1541
+		}
1542
+		// generate primary attendee from payer info if applicable
1543
+		if (! $this->checkout->transaction_has_primary_registrant()) {
1544
+			$attendee = $this->_create_attendee_from_request_data();
1545
+			if ($attendee instanceof EE_Attendee) {
1546
+				foreach ($this->checkout->transaction->registrations() as $registration) {
1547
+					if ($registration->is_primary_registrant()) {
1548
+						$this->checkout->primary_attendee_obj = $attendee;
1549
+						$registration->_add_relation_to($attendee, 'Attendee');
1550
+						$registration->set_attendee_id($attendee->ID());
1551
+						$registration->update_cache_after_object_save('Attendee', $attendee);
1552
+					}
1553
+				}
1554
+			}
1555
+		}
1556
+	}
1557
+
1558
+
1559
+	/**
1560
+	 * create_attendee_from_request_data
1561
+	 * uses info from alternate GET or POST data (such as AJAX) to create a new attendee
1562
+	 *
1563
+	 * @return EE_Attendee
1564
+	 * @throws EE_Error
1565
+	 * @throws InvalidArgumentException
1566
+	 * @throws ReflectionException
1567
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1568
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1569
+	 */
1570
+	protected function _create_attendee_from_request_data()
1571
+	{
1572
+		// get State ID
1573
+		$STA_ID = ! empty($_REQUEST['state']) ? sanitize_text_field($_REQUEST['state']) : '';
1574
+		if (! empty($STA_ID)) {
1575
+			// can we get state object from name ?
1576
+			EE_Registry::instance()->load_model('State');
1577
+			$state  = EEM_State::instance()->get_col(array(array('STA_name' => $STA_ID), 'limit' => 1), 'STA_ID');
1578
+			$STA_ID = is_array($state) && ! empty($state) ? reset($state) : $STA_ID;
1579
+		}
1580
+		// get Country ISO
1581
+		$CNT_ISO = ! empty($_REQUEST['country']) ? sanitize_text_field($_REQUEST['country']) : '';
1582
+		if (! empty($CNT_ISO)) {
1583
+			// can we get country object from name ?
1584
+			EE_Registry::instance()->load_model('Country');
1585
+			$country = EEM_Country::instance()->get_col(
1586
+				array(array('CNT_name' => $CNT_ISO), 'limit' => 1),
1587
+				'CNT_ISO'
1588
+			);
1589
+			$CNT_ISO = is_array($country) && ! empty($country) ? reset($country) : $CNT_ISO;
1590
+		}
1591
+		// grab attendee data
1592
+		$attendee_data = array(
1593
+			'ATT_fname'    => ! empty($_REQUEST['first_name']) ? sanitize_text_field($_REQUEST['first_name']) : '',
1594
+			'ATT_lname'    => ! empty($_REQUEST['last_name']) ? sanitize_text_field($_REQUEST['last_name']) : '',
1595
+			'ATT_email'    => ! empty($_REQUEST['email']) ? sanitize_email($_REQUEST['email']) : '',
1596
+			'ATT_address'  => ! empty($_REQUEST['address']) ? sanitize_text_field($_REQUEST['address']) : '',
1597
+			'ATT_address2' => ! empty($_REQUEST['address2']) ? sanitize_text_field($_REQUEST['address2']) : '',
1598
+			'ATT_city'     => ! empty($_REQUEST['city']) ? sanitize_text_field($_REQUEST['city']) : '',
1599
+			'STA_ID'       => $STA_ID,
1600
+			'CNT_ISO'      => $CNT_ISO,
1601
+			'ATT_zip'      => ! empty($_REQUEST['zip']) ? sanitize_text_field($_REQUEST['zip']) : '',
1602
+			'ATT_phone'    => ! empty($_REQUEST['phone']) ? sanitize_text_field($_REQUEST['phone']) : '',
1603
+		);
1604
+		// validate the email address since it is the most important piece of info
1605
+		if (empty($attendee_data['ATT_email']) || $attendee_data['ATT_email'] !== $_REQUEST['email']) {
1606
+			EE_Error::add_error(
1607
+				esc_html__('An invalid email address was submitted.', 'event_espresso'),
1608
+				__FILE__,
1609
+				__FUNCTION__,
1610
+				__LINE__
1611
+			);
1612
+		}
1613
+		// does this attendee already exist in the db ? we're searching using a combination of first name, last name,
1614
+		// AND email address
1615
+		if (! empty($attendee_data['ATT_fname'])
1616
+			&& ! empty($attendee_data['ATT_lname'])
1617
+			&& ! empty($attendee_data['ATT_email'])
1618
+		) {
1619
+			$existing_attendee = EE_Registry::instance()->LIB->EEM_Attendee->find_existing_attendee(
1620
+				array(
1621
+					'ATT_fname' => $attendee_data['ATT_fname'],
1622
+					'ATT_lname' => $attendee_data['ATT_lname'],
1623
+					'ATT_email' => $attendee_data['ATT_email'],
1624
+				)
1625
+			);
1626
+			if ($existing_attendee instanceof EE_Attendee) {
1627
+				return $existing_attendee;
1628
+			}
1629
+		}
1630
+		// no existing attendee? kk let's create a new one
1631
+		// kinda lame, but we need a first and last name to create an attendee, so use the email address if those
1632
+		// don't exist
1633
+		$attendee_data['ATT_fname'] = ! empty($attendee_data['ATT_fname'])
1634
+			? $attendee_data['ATT_fname']
1635
+			: $attendee_data['ATT_email'];
1636
+		$attendee_data['ATT_lname'] = ! empty($attendee_data['ATT_lname'])
1637
+			? $attendee_data['ATT_lname']
1638
+			: $attendee_data['ATT_email'];
1639
+		return EE_Attendee::new_instance($attendee_data);
1640
+	}
1641
+
1642
+
1643
+
1644
+	/********************************************************************************************************/
1645
+	/****************************************  PROCESS REG STEP  *****************************************/
1646
+	/********************************************************************************************************/
1647
+	/**
1648
+	 * process_reg_step
1649
+	 *
1650
+	 * @return bool
1651
+	 * @throws EE_Error
1652
+	 * @throws InvalidArgumentException
1653
+	 * @throws ReflectionException
1654
+	 * @throws \EventEspresso\core\exceptions\EntityNotFoundException
1655
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1656
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1657
+	 * @throws \EventEspresso\core\exceptions\InvalidStatusException
1658
+	 */
1659
+	public function process_reg_step()
1660
+	{
1661
+		// how have they chosen to pay?
1662
+		$this->checkout->selected_method_of_payment = $this->checkout->transaction->is_free()
1663
+			? 'no_payment_required'
1664
+			: $this->_get_selected_method_of_payment(true);
1665
+		// choose your own adventure based on method_of_payment
1666
+		switch ($this->checkout->selected_method_of_payment) {
1667
+
1668
+			case 'events_sold_out' :
1669
+				$this->checkout->redirect     = true;
1670
+				$this->checkout->redirect_url = $this->checkout->cancel_page_url;
1671
+				$this->checkout->json_response->set_redirect_url($this->checkout->redirect_url);
1672
+				// mark this reg step as completed
1673
+				$this->set_completed();
1674
+				return false;
1675
+				break;
1676
+
1677
+			case 'payments_closed' :
1678
+				if (apply_filters(
1679
+					'FHEE__EE_SPCO_Reg_Step_Payment_Options__process_reg_step__payments_closed__display_success',
1680
+					false
1681
+				)) {
1682
+					EE_Error::add_success(
1683
+						esc_html__('no payment required at this time.', 'event_espresso'),
1684
+						__FILE__,
1685
+						__FUNCTION__,
1686
+						__LINE__
1687
+					);
1688
+				}
1689
+				// mark this reg step as completed
1690
+				$this->set_completed();
1691
+				return true;
1692
+				break;
1693
+
1694
+			case 'no_payment_required' :
1695
+				if (apply_filters(
1696
+					'FHEE__EE_SPCO_Reg_Step_Payment_Options__process_reg_step__no_payment_required__display_success',
1697
+					false
1698
+				)) {
1699
+					EE_Error::add_success(
1700
+						esc_html__('no payment required.', 'event_espresso'),
1701
+						__FILE__,
1702
+						__FUNCTION__,
1703
+						__LINE__
1704
+					);
1705
+				}
1706
+				// mark this reg step as completed
1707
+				$this->set_completed();
1708
+				return true;
1709
+				break;
1710
+
1711
+			default:
1712
+				$registrations         = EE_Registry::instance()->SSN->checkout()->transaction->registrations(
1713
+					EE_Registry::instance()->SSN->checkout()->reg_cache_where_params
1714
+				);
1715
+				$ejected_registrations = EE_SPCO_Reg_Step_Payment_Options::find_registrations_that_lost_their_space(
1716
+					$registrations,
1717
+					EE_Registry::instance()->SSN->checkout()->revisit
1718
+				);
1719
+				// calculate difference between the two arrays
1720
+				$registrations = array_diff($registrations, $ejected_registrations);
1721
+				if (empty($registrations)) {
1722
+					$this->_redirect_because_event_sold_out();
1723
+					return false;
1724
+				}
1725
+				$payment_successful = $this->_process_payment();
1726
+				if ($payment_successful) {
1727
+					$this->checkout->continue_reg = true;
1728
+					$this->_maybe_set_completed($this->checkout->payment_method);
1729
+				} else {
1730
+					$this->checkout->continue_reg = false;
1731
+				}
1732
+				return $payment_successful;
1733
+		}
1734
+	}
1735
+
1736
+
1737
+	/**
1738
+	 * _redirect_because_event_sold_out
1739
+	 *
1740
+	 * @access protected
1741
+	 * @return void
1742
+	 */
1743
+	protected function _redirect_because_event_sold_out()
1744
+	{
1745
+		$this->checkout->continue_reg = false;
1746
+		// set redirect URL
1747
+		$this->checkout->redirect_url = add_query_arg(
1748
+			array('e_reg_url_link' => $this->checkout->reg_url_link),
1749
+			$this->checkout->current_step->reg_step_url()
1750
+		);
1751
+		$this->checkout->json_response->set_redirect_url($this->checkout->redirect_url);
1752
+	}
1753
+
1754
+
1755
+	/**
1756
+	 * _maybe_set_completed
1757
+	 *
1758
+	 * @access protected
1759
+	 * @param \EE_Payment_Method $payment_method
1760
+	 * @return void
1761
+	 * @throws \EE_Error
1762
+	 */
1763
+	protected function _maybe_set_completed(EE_Payment_Method $payment_method)
1764
+	{
1765
+		switch ($payment_method->type_obj()->payment_occurs()) {
1766
+			case EE_PMT_Base::offsite :
1767
+				break;
1768
+			case EE_PMT_Base::onsite :
1769
+			case EE_PMT_Base::offline :
1770
+				// mark this reg step as completed
1771
+				$this->set_completed();
1772
+				break;
1773
+		}
1774
+	}
1775
+
1776
+
1777
+	/**
1778
+	 *    update_reg_step
1779
+	 *    this is the final step after a user  revisits the site to retry a payment
1780
+	 *
1781
+	 * @return bool
1782
+	 * @throws EE_Error
1783
+	 * @throws InvalidArgumentException
1784
+	 * @throws ReflectionException
1785
+	 * @throws \EventEspresso\core\exceptions\EntityNotFoundException
1786
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1787
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1788
+	 * @throws \EventEspresso\core\exceptions\InvalidStatusException
1789
+	 */
1790
+	public function update_reg_step()
1791
+	{
1792
+		$success = true;
1793
+		// if payment required
1794
+		if ($this->checkout->transaction->total() > 0) {
1795
+			do_action(
1796
+				'AHEE__EE_Single_Page_Checkout__process_finalize_registration__before_gateway',
1797
+				$this->checkout->transaction
1798
+			);
1799
+			// attempt payment via payment method
1800
+			$success = $this->process_reg_step();
1801
+		}
1802
+		if ($success && ! $this->checkout->redirect) {
1803
+			$this->checkout->cart->get_grand_total()->save_this_and_descendants_to_txn(
1804
+				$this->checkout->transaction->ID()
1805
+			);
1806
+			// set return URL
1807
+			$this->checkout->redirect_url = add_query_arg(
1808
+				array('e_reg_url_link' => $this->checkout->reg_url_link),
1809
+				$this->checkout->thank_you_page_url
1810
+			);
1811
+		}
1812
+		return $success;
1813
+	}
1814
+
1815
+
1816
+	/**
1817
+	 *    _process_payment
1818
+	 *
1819
+	 * @access private
1820
+	 * @return bool
1821
+	 * @throws EE_Error
1822
+	 * @throws InvalidArgumentException
1823
+	 * @throws ReflectionException
1824
+	 * @throws RuntimeException
1825
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1826
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1827
+	 */
1828
+	private function _process_payment()
1829
+	{
1830
+		// basically confirm that the event hasn't sold out since they hit the page
1831
+		if (! $this->_last_second_ticket_verifications()) {
1832
+			return false;
1833
+		}
1834
+		// ya gotta make a choice man
1835
+		if (empty($this->checkout->selected_method_of_payment)) {
1836
+			$this->checkout->json_response->set_plz_select_method_of_payment(
1837
+				esc_html__('Please select a method of payment before proceeding.', 'event_espresso')
1838
+			);
1839
+			return false;
1840
+		}
1841
+		// get EE_Payment_Method object
1842
+		if (! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()) {
1843
+			return false;
1844
+		}
1845
+		// setup billing form
1846
+		if ($this->checkout->payment_method->is_on_site()) {
1847
+			$this->checkout->billing_form = $this->_get_billing_form_for_payment_method(
1848
+				$this->checkout->payment_method
1849
+			);
1850
+			// bad billing form ?
1851
+			if (! $this->_billing_form_is_valid()) {
1852
+				return false;
1853
+			}
1854
+		}
1855
+		// ensure primary registrant has been fully processed
1856
+		if (! $this->_setup_primary_registrant_prior_to_payment()) {
1857
+			return false;
1858
+		}
1859
+		// if session is close to expiring (under 10 minutes by default)
1860
+		if ((time() - EE_Registry::instance()->SSN->expiration()) < EE_Registry::instance()->SSN->extension()) {
1861
+			// add some time to session expiration so that payment can be completed
1862
+			EE_Registry::instance()->SSN->extend_expiration();
1863
+		}
1864
+		/** @type EE_Transaction_Processor $transaction_processor */
1865
+		//$transaction_processor = EE_Registry::instance()->load_class( 'Transaction_Processor' );
1866
+		// in case a registrant leaves to an Off-Site Gateway and never returns, we want to approve any registrations
1867
+		// for events with a default reg status of Approved
1868
+		// $transaction_processor->toggle_registration_statuses_for_default_approved_events(
1869
+		//      $this->checkout->transaction, $this->checkout->reg_cache_where_params
1870
+		// );
1871
+		// attempt payment
1872
+		$payment = $this->_attempt_payment($this->checkout->payment_method);
1873
+		// process results
1874
+		$payment = $this->_validate_payment($payment);
1875
+		$payment = $this->_post_payment_processing($payment);
1876
+		// verify payment
1877
+		if ($payment instanceof EE_Payment) {
1878
+			// store that for later
1879
+			$this->checkout->payment = $payment;
1880
+			// we can also consider the TXN to not have been failed, so temporarily upgrade it's status to abandoned
1881
+			$this->checkout->transaction->toggle_failed_transaction_status();
1882
+			$payment_status = $payment->status();
1883
+			if (
1884
+				$payment_status === EEM_Payment::status_id_approved
1885
+				|| $payment_status === EEM_Payment::status_id_pending
1886
+			) {
1887
+				return true;
1888
+			} else {
1889
+				return false;
1890
+			}
1891
+		} else if ($payment === true) {
1892
+			// please note that offline payment methods will NOT make a payment,
1893
+			// but instead just mark themselves as the PMD_ID on the transaction, and return true
1894
+			$this->checkout->payment = $payment;
1895
+			return true;
1896
+		}
1897
+		// where's my money?
1898
+		return false;
1899
+	}
1900
+
1901
+
1902
+	/**
1903
+	 * _last_second_ticket_verifications
1904
+	 *
1905
+	 * @access public
1906
+	 * @return bool
1907
+	 * @throws EE_Error
1908
+	 */
1909
+	protected function _last_second_ticket_verifications()
1910
+	{
1911
+		// don't bother re-validating if not a return visit
1912
+		if (! $this->checkout->revisit) {
1913
+			return true;
1914
+		}
1915
+		$registrations = $this->checkout->transaction->registrations();
1916
+		if (empty($registrations)) {
1917
+			return false;
1918
+		}
1919
+		foreach ($registrations as $registration) {
1920
+			if ($registration instanceof EE_Registration) {
1921
+				$event = $registration->event_obj();
1922
+				if ($event instanceof EE_Event && $event->is_sold_out(true)) {
1923
+					EE_Error::add_error(
1924
+						apply_filters(
1925
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___last_second_ticket_verifications__sold_out_events_msg',
1926
+							sprintf(
1927
+								esc_html__(
1928
+									'It appears that the %1$s event that you were about to make a payment for has sold out since you first registered and/or arrived at this page. Please refresh the page and try again. If you have already made a partial payment towards this event, please contact the event administrator for a refund.',
1929
+									'event_espresso'
1930
+								),
1931
+								$event->name()
1932
+							)
1933
+						),
1934
+						__FILE__,
1935
+						__FUNCTION__,
1936
+						__LINE__
1937
+					);
1938
+					return false;
1939
+				}
1940
+			}
1941
+		}
1942
+		return true;
1943
+	}
1944
+
1945
+
1946
+	/**
1947
+	 * redirect_form
1948
+	 *
1949
+	 * @access public
1950
+	 * @return bool
1951
+	 * @throws EE_Error
1952
+	 * @throws InvalidArgumentException
1953
+	 * @throws ReflectionException
1954
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1955
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1956
+	 */
1957
+	public function redirect_form()
1958
+	{
1959
+		$payment_method_billing_info = $this->_payment_method_billing_info(
1960
+			$this->_get_payment_method_for_selected_method_of_payment()
1961
+		);
1962
+		$html                        = $payment_method_billing_info->get_html();
1963
+		$html                        .= $this->checkout->redirect_form;
1964
+		EE_Registry::instance()->REQ->add_output($html);
1965
+		return true;
1966
+	}
1967
+
1968
+
1969
+	/**
1970
+	 * _billing_form_is_valid
1971
+	 *
1972
+	 * @access private
1973
+	 * @return bool
1974
+	 * @throws \EE_Error
1975
+	 */
1976
+	private function _billing_form_is_valid()
1977
+	{
1978
+		if (! $this->checkout->payment_method->type_obj()->has_billing_form()) {
1979
+			return true;
1980
+		}
1981
+		if ($this->checkout->billing_form instanceof EE_Billing_Info_Form) {
1982
+			if ($this->checkout->billing_form->was_submitted()) {
1983
+				$this->checkout->billing_form->receive_form_submission();
1984
+				if ($this->checkout->billing_form->is_valid()) {
1985
+					return true;
1986
+				}
1987
+				$validation_errors = $this->checkout->billing_form->get_validation_errors_accumulated();
1988
+				$error_strings     = array();
1989
+				foreach ($validation_errors as $validation_error) {
1990
+					if ($validation_error instanceof EE_Validation_Error) {
1991
+						$form_section = $validation_error->get_form_section();
1992
+						if ($form_section instanceof EE_Form_Input_Base) {
1993
+							$label = $form_section->html_label_text();
1994
+						} elseif ($form_section instanceof EE_Form_Section_Base) {
1995
+							$label = $form_section->name();
1996
+						} else {
1997
+							$label = esc_html__('Validation Error', 'event_espresso');
1998
+						}
1999
+						$error_strings[] = sprintf('%1$s: %2$s', $label, $validation_error->getMessage());
2000
+					}
2001
+				}
2002
+				EE_Error::add_error(
2003
+					sprintf(
2004
+						esc_html__(
2005
+							'One or more billing form inputs are invalid and require correction before proceeding. %1$s %2$s',
2006
+							'event_espresso'
2007
+						),
2008
+						'<br/>',
2009
+						implode('<br/>', $error_strings)
2010
+					),
2011
+					__FILE__,
2012
+					__FUNCTION__,
2013
+					__LINE__
2014
+				);
2015
+			} else {
2016
+				EE_Error::add_error(
2017
+					esc_html__(
2018
+						'The billing form was not submitted or something prevented it\'s submission.',
2019
+						'event_espresso'
2020
+					),
2021
+					__FILE__,
2022
+					__FUNCTION__,
2023
+					__LINE__
2024
+				);
2025
+			}
2026
+		} else {
2027
+			EE_Error::add_error(
2028
+				esc_html__('The submitted billing form is invalid possibly due to a technical reason.', 'event_espresso'),
2029
+				__FILE__,
2030
+				__FUNCTION__,
2031
+				__LINE__
2032
+			);
2033
+		}
2034
+		return false;
2035
+	}
2036
+
2037
+
2038
+	/**
2039
+	 * _setup_primary_registrant_prior_to_payment
2040
+	 * ensures that the primary registrant has a valid attendee object created with the critical details populated
2041
+	 * (first & last name & email) and that both the transaction object and primary registration object have been saved
2042
+	 * plz note that any other registrations will NOT be saved at this point (because they may not have any details
2043
+	 * yet)
2044
+	 *
2045
+	 * @access private
2046
+	 * @return bool
2047
+	 * @throws EE_Error
2048
+	 * @throws InvalidArgumentException
2049
+	 * @throws ReflectionException
2050
+	 * @throws RuntimeException
2051
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2052
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2053
+	 */
2054
+	private function _setup_primary_registrant_prior_to_payment()
2055
+	{
2056
+		// check if transaction has a primary registrant and that it has a related Attendee object
2057
+		// if not, then we need to at least gather some primary registrant data before attempting payment
2058
+		if (
2059
+			$this->checkout->billing_form instanceof EE_Billing_Attendee_Info_Form
2060
+			&& ! $this->checkout->transaction_has_primary_registrant()
2061
+			&& ! $this->_capture_primary_registration_data_from_billing_form()
2062
+		) {
2063
+			return false;
2064
+		}
2065
+		// because saving an object clears it's cache, we need to do the chevy shuffle
2066
+		// grab the primary_registration object
2067
+		$primary_registration = $this->checkout->transaction->primary_registration();
2068
+		// at this point we'll consider a TXN to not have been failed
2069
+		$this->checkout->transaction->toggle_failed_transaction_status();
2070
+		// save the TXN ( which clears cached copy of primary_registration)
2071
+		$this->checkout->transaction->save();
2072
+		// grab TXN ID and save it to the primary_registration
2073
+		$primary_registration->set_transaction_id($this->checkout->transaction->ID());
2074
+		// save what we have so far
2075
+		$primary_registration->save();
2076
+		return true;
2077
+	}
2078
+
2079
+
2080
+	/**
2081
+	 * _capture_primary_registration_data_from_billing_form
2082
+	 *
2083
+	 * @access private
2084
+	 * @return bool
2085
+	 * @throws EE_Error
2086
+	 * @throws InvalidArgumentException
2087
+	 * @throws ReflectionException
2088
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2089
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2090
+	 */
2091
+	private function _capture_primary_registration_data_from_billing_form()
2092
+	{
2093
+		// convert billing form data into an attendee
2094
+		$this->checkout->primary_attendee_obj = $this->checkout->billing_form->create_attendee_from_billing_form_data();
2095
+		if (! $this->checkout->primary_attendee_obj instanceof EE_Attendee) {
2096
+			EE_Error::add_error(
2097
+				sprintf(
2098
+					esc_html__(
2099
+						'The billing form details could not be used for attendee details due to a technical issue.%sPlease try again or contact %s for assistance.',
2100
+						'event_espresso'
2101
+					),
2102
+					'<br/>',
2103
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
2104
+				),
2105
+				__FILE__,
2106
+				__FUNCTION__,
2107
+				__LINE__
2108
+			);
2109
+			return false;
2110
+		}
2111
+		$primary_registration = $this->checkout->transaction->primary_registration();
2112
+		if (! $primary_registration instanceof EE_Registration) {
2113
+			EE_Error::add_error(
2114
+				sprintf(
2115
+					esc_html__(
2116
+						'The primary registrant for this transaction could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.',
2117
+						'event_espresso'
2118
+					),
2119
+					'<br/>',
2120
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
2121
+				),
2122
+				__FILE__,
2123
+				__FUNCTION__,
2124
+				__LINE__
2125
+			);
2126
+			return false;
2127
+		}
2128
+		if (! $primary_registration->_add_relation_to($this->checkout->primary_attendee_obj, 'Attendee')
2129
+			  instanceof
2130
+			  EE_Attendee
2131
+		) {
2132
+			EE_Error::add_error(
2133
+				sprintf(
2134
+					esc_html__(
2135
+						'The primary registrant could not be associated with this transaction due to a technical issue.%sPlease try again or contact %s for assistance.',
2136
+						'event_espresso'
2137
+					),
2138
+					'<br/>',
2139
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
2140
+				),
2141
+				__FILE__,
2142
+				__FUNCTION__,
2143
+				__LINE__
2144
+			);
2145
+			return false;
2146
+		}
2147
+		/** @type EE_Registration_Processor $registration_processor */
2148
+		$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
2149
+		// at this point, we should have enough details about the registrant to consider the registration NOT incomplete
2150
+		$registration_processor->toggle_incomplete_registration_status_to_default($primary_registration);
2151
+		return true;
2152
+	}
2153
+
2154
+
2155
+	/**
2156
+	 * _get_payment_method_for_selected_method_of_payment
2157
+	 * retrieves a valid payment method
2158
+	 *
2159
+	 * @access public
2160
+	 * @return EE_Payment_Method
2161
+	 * @throws EE_Error
2162
+	 * @throws InvalidArgumentException
2163
+	 * @throws ReflectionException
2164
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2165
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2166
+	 */
2167
+	private function _get_payment_method_for_selected_method_of_payment()
2168
+	{
2169
+		if ($this->checkout->selected_method_of_payment === 'events_sold_out') {
2170
+			$this->_redirect_because_event_sold_out();
2171
+			return null;
2172
+		}
2173
+		// get EE_Payment_Method object
2174
+		if (isset($this->checkout->available_payment_methods[$this->checkout->selected_method_of_payment])) {
2175
+			$payment_method = $this->checkout->available_payment_methods[$this->checkout->selected_method_of_payment];
2176
+		} else {
2177
+			// load EEM_Payment_Method
2178
+			EE_Registry::instance()->load_model('Payment_Method');
2179
+			/** @type EEM_Payment_Method $EEM_Payment_Method */
2180
+			$EEM_Payment_Method = EE_Registry::instance()->LIB->EEM_Payment_Method;
2181
+			$payment_method     = $EEM_Payment_Method->get_one_by_slug($this->checkout->selected_method_of_payment);
2182
+		}
2183
+		// verify $payment_method
2184
+		if (! $payment_method instanceof EE_Payment_Method) {
2185
+			// not a payment
2186
+			EE_Error::add_error(
2187
+				sprintf(
2188
+					esc_html__(
2189
+						'The selected method of payment could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.',
2190
+						'event_espresso'
2191
+					),
2192
+					'<br/>',
2193
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
2194
+				),
2195
+				__FILE__,
2196
+				__FUNCTION__,
2197
+				__LINE__
2198
+			);
2199
+			return null;
2200
+		}
2201
+		// and verify it has a valid Payment_Method Type object
2202
+		if (! $payment_method->type_obj() instanceof EE_PMT_Base) {
2203
+			// not a payment
2204
+			EE_Error::add_error(
2205
+				sprintf(
2206
+					esc_html__(
2207
+						'A valid payment method could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.',
2208
+						'event_espresso'
2209
+					),
2210
+					'<br/>',
2211
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
2212
+				),
2213
+				__FILE__,
2214
+				__FUNCTION__,
2215
+				__LINE__
2216
+			);
2217
+			return null;
2218
+		}
2219
+		return $payment_method;
2220
+	}
2221
+
2222
+
2223
+	/**
2224
+	 *    _attempt_payment
2225
+	 *
2226
+	 * @access    private
2227
+	 * @type    EE_Payment_Method $payment_method
2228
+	 * @return mixed EE_Payment | boolean
2229
+	 * @throws EE_Error
2230
+	 * @throws InvalidArgumentException
2231
+	 * @throws ReflectionException
2232
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2233
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2234
+	 */
2235
+	private function _attempt_payment(EE_Payment_Method $payment_method)
2236
+	{
2237
+		$payment = null;
2238
+		$this->checkout->transaction->save();
2239
+		$payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2240
+		if (! $payment_processor instanceof EE_Payment_Processor) {
2241
+			return false;
2242
+		}
2243
+		try {
2244
+			$payment_processor->set_revisit($this->checkout->revisit);
2245
+			// generate payment object
2246
+			$payment = $payment_processor->process_payment(
2247
+				$payment_method,
2248
+				$this->checkout->transaction,
2249
+				$this->checkout->amount_owing,
2250
+				$this->checkout->billing_form,
2251
+				$this->_get_return_url($payment_method),
2252
+				'CART',
2253
+				$this->checkout->admin_request,
2254
+				true,
2255
+				$this->reg_step_url()
2256
+			);
2257
+		} catch (Exception $e) {
2258
+			$this->_handle_payment_processor_exception($e);
2259
+		}
2260
+		return $payment;
2261
+	}
2262
+
2263
+
2264
+	/**
2265
+	 * _handle_payment_processor_exception
2266
+	 *
2267
+	 * @access protected
2268
+	 * @param \Exception $e
2269
+	 * @return void
2270
+	 * @throws EE_Error
2271
+	 * @throws InvalidArgumentException
2272
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2273
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2274
+	 */
2275
+	protected function _handle_payment_processor_exception(Exception $e)
2276
+	{
2277
+		EE_Error::add_error(
2278
+			sprintf(
2279
+				esc_html__(
2280
+					'The payment could not br processed due to a technical issue.%1$sPlease try again or contact %2$s for assistance.||The following Exception was thrown in %4$s on line %5$s:%1$s%3$s',
2281
+					'event_espresso'
2282
+				),
2283
+				'<br/>',
2284
+				EE_Registry::instance()->CFG->organization->get_pretty('email'),
2285
+				$e->getMessage(),
2286
+				$e->getFile(),
2287
+				$e->getLine()
2288
+			),
2289
+			__FILE__,
2290
+			__FUNCTION__,
2291
+			__LINE__
2292
+		);
2293
+	}
2294
+
2295
+
2296
+	/**
2297
+	 * _get_return_url
2298
+	 *
2299
+	 * @access protected
2300
+	 * @param \EE_Payment_Method $payment_method
2301
+	 * @return string
2302
+	 * @throws \EE_Error
2303
+	 */
2304
+	protected function _get_return_url(EE_Payment_Method $payment_method)
2305
+	{
2306
+		$return_url = '';
2307
+		switch ($payment_method->type_obj()->payment_occurs()) {
2308
+			case EE_PMT_Base::offsite :
2309
+				$return_url = add_query_arg(
2310
+					array(
2311
+						'action'                     => 'process_gateway_response',
2312
+						'selected_method_of_payment' => $this->checkout->selected_method_of_payment,
2313
+						'spco_txn'                   => $this->checkout->transaction->ID(),
2314
+					),
2315
+					$this->reg_step_url()
2316
+				);
2317
+				break;
2318
+			case EE_PMT_Base::onsite :
2319
+			case EE_PMT_Base::offline :
2320
+				$return_url = $this->checkout->next_step->reg_step_url();
2321
+				break;
2322
+		}
2323
+		return $return_url;
2324
+	}
2325
+
2326
+
2327
+	/**
2328
+	 * _validate_payment
2329
+	 *
2330
+	 * @access private
2331
+	 * @param EE_Payment $payment
2332
+	 * @return EE_Payment|FALSE
2333
+	 * @throws EE_Error
2334
+	 * @throws InvalidArgumentException
2335
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2336
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2337
+	 */
2338
+	private function _validate_payment($payment = null)
2339
+	{
2340
+		if ($this->checkout->payment_method->is_off_line()) {
2341
+			return true;
2342
+		}
2343
+		// verify payment object
2344
+		if (! $payment instanceof EE_Payment) {
2345
+			// not a payment
2346
+			EE_Error::add_error(
2347
+				sprintf(
2348
+					esc_html__(
2349
+						'A valid payment was not generated due to a technical issue.%1$sPlease try again or contact %2$s for assistance.',
2350
+						'event_espresso'
2351
+					),
2352
+					'<br/>',
2353
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
2354
+				),
2355
+				__FILE__,
2356
+				__FUNCTION__,
2357
+				__LINE__
2358
+			);
2359
+			return false;
2360
+		}
2361
+		return $payment;
2362
+	}
2363
+
2364
+
2365
+	/**
2366
+	 * _post_payment_processing
2367
+	 *
2368
+	 * @access private
2369
+	 * @param EE_Payment|bool $payment
2370
+	 * @return bool
2371
+	 * @throws EE_Error
2372
+	 * @throws InvalidArgumentException
2373
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2374
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2375
+	 */
2376
+	private function _post_payment_processing($payment = null)
2377
+	{
2378
+		// Off-Line payment?
2379
+		if ($payment === true) {
2380
+			//$this->_setup_redirect_for_next_step();
2381
+			return true;
2382
+			// On-Site payment?
2383
+		} else if ($this->checkout->payment_method->is_on_site()) {
2384
+			if (! $this->_process_payment_status($payment, EE_PMT_Base::onsite)) {
2385
+				//$this->_setup_redirect_for_next_step();
2386
+				$this->checkout->continue_reg = false;
2387
+			}
2388
+			// Off-Site payment?
2389
+		} else if ($this->checkout->payment_method->is_off_site()) {
2390
+			// if a payment object was made and it specifies a redirect url, then we'll setup that redirect info
2391
+			if ($payment instanceof EE_Payment && $payment->redirect_url()) {
2392
+				do_action('AHEE_log', __CLASS__, __FUNCTION__, $payment->redirect_url(), '$payment->redirect_url()');
2393
+				$this->checkout->redirect      = true;
2394
+				$this->checkout->redirect_form = $payment->redirect_form();
2395
+				$this->checkout->redirect_url  = $this->reg_step_url('redirect_form');
2396
+				// set JSON response
2397
+				$this->checkout->json_response->set_redirect_form($this->checkout->redirect_form);
2398
+				// and lastly, let's bump the payment status to pending
2399
+				$payment->set_status(EEM_Payment::status_id_pending);
2400
+				$payment->save();
2401
+			} else {
2402
+				// not a payment
2403
+				$this->checkout->continue_reg = false;
2404
+				EE_Error::add_error(
2405
+					sprintf(
2406
+						esc_html__(
2407
+							'It appears the Off Site Payment Method was not configured properly.%sPlease try again or contact %s for assistance.',
2408
+							'event_espresso'
2409
+						),
2410
+						'<br/>',
2411
+						EE_Registry::instance()->CFG->organization->get_pretty('email')
2412
+					),
2413
+					__FILE__,
2414
+					__FUNCTION__,
2415
+					__LINE__
2416
+				);
2417
+			}
2418
+		} else {
2419
+			// ummm ya... not Off-Line, not On-Site, not off-Site ????
2420
+			$this->checkout->continue_reg = false;
2421
+			return false;
2422
+		}
2423
+		return $payment;
2424
+	}
2425
+
2426
+
2427
+	/**
2428
+	 *    _process_payment_status
2429
+	 *
2430
+	 * @access private
2431
+	 * @type    EE_Payment $payment
2432
+	 * @param string       $payment_occurs
2433
+	 * @return bool
2434
+	 * @throws EE_Error
2435
+	 * @throws InvalidArgumentException
2436
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2437
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2438
+	 */
2439
+	private function _process_payment_status($payment, $payment_occurs = EE_PMT_Base::offline)
2440
+	{
2441
+		// off-line payment? carry on
2442
+		if ($payment_occurs === EE_PMT_Base::offline) {
2443
+			return true;
2444
+		}
2445
+		// verify payment validity
2446
+		if ($payment instanceof EE_Payment) {
2447
+			do_action('AHEE_log', __CLASS__, __FUNCTION__, $payment->status(), '$payment->status()');
2448
+			$msg = $payment->gateway_response();
2449
+			// check results
2450
+			switch ($payment->status()) {
2451
+				// good payment
2452
+				case EEM_Payment::status_id_approved :
2453
+					EE_Error::add_success(
2454
+						esc_html__('Your payment was processed successfully.', 'event_espresso'),
2455
+						__FILE__,
2456
+						__FUNCTION__,
2457
+						__LINE__
2458
+					);
2459
+					return true;
2460
+					break;
2461
+				// slow payment
2462
+				case EEM_Payment::status_id_pending :
2463
+					if (empty($msg)) {
2464
+						$msg = esc_html__(
2465
+							'Your payment appears to have been processed successfully, but the Instant Payment Notification has not yet been received. It should arrive shortly.',
2466
+							'event_espresso'
2467
+						);
2468
+					}
2469
+					EE_Error::add_success($msg, __FILE__, __FUNCTION__, __LINE__);
2470
+					return true;
2471
+					break;
2472
+				// don't wanna payment
2473
+				case EEM_Payment::status_id_cancelled :
2474
+					if (empty($msg)) {
2475
+						$msg = _n(
2476
+							'Payment cancelled. Please try again.',
2477
+							'Payment cancelled. Please try again or select another method of payment.',
2478
+							count($this->checkout->available_payment_methods),
2479
+							'event_espresso'
2480
+						);
2481
+					}
2482
+					EE_Error::add_attention($msg, __FILE__, __FUNCTION__, __LINE__);
2483
+					return false;
2484
+					break;
2485
+				// not enough payment
2486
+				case EEM_Payment::status_id_declined :
2487
+					if (empty($msg)) {
2488
+						$msg = _n(
2489
+							'We\'re sorry but your payment was declined. Please try again.',
2490
+							'We\'re sorry but your payment was declined. Please try again or select another method of payment.',
2491
+							count($this->checkout->available_payment_methods),
2492
+							'event_espresso'
2493
+						);
2494
+					}
2495
+					EE_Error::add_attention($msg, __FILE__, __FUNCTION__, __LINE__);
2496
+					return false;
2497
+					break;
2498
+				// bad payment
2499
+				case EEM_Payment::status_id_failed :
2500
+					if (! empty($msg)) {
2501
+						EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2502
+						return false;
2503
+					}
2504
+					// default to error below
2505
+					break;
2506
+			}
2507
+		}
2508
+		// off-site payment gateway responses are too unreliable, so let's just assume that
2509
+		// the payment processing is just running slower than the registrant's request
2510
+		if ($payment_occurs === EE_PMT_Base::offsite) {
2511
+			return true;
2512
+		}
2513
+		EE_Error::add_error(
2514
+			sprintf(
2515
+				esc_html__(
2516
+					'Your payment could not be processed successfully due to a technical issue.%sPlease try again or contact %s for assistance.',
2517
+					'event_espresso'
2518
+				),
2519
+				'<br/>',
2520
+				EE_Registry::instance()->CFG->organization->get_pretty('email')
2521
+			),
2522
+			__FILE__,
2523
+			__FUNCTION__,
2524
+			__LINE__
2525
+		);
2526
+		return false;
2527
+	}
2528
+
2529
+
2530
+
2531
+
2532
+
2533
+
2534
+	/********************************************************************************************************/
2535
+	/**********************************  PROCESS GATEWAY RESPONSE  **********************************/
2536
+	/********************************************************************************************************/
2537
+	/**
2538
+	 * process_gateway_response
2539
+	 * this is the return point for Off-Site Payment Methods
2540
+	 * It will attempt to "handle the IPN" if it appears that this has not already occurred,
2541
+	 * otherwise, it will load up the last payment made for the TXN.
2542
+	 * If the payment retrieved looks good, it will then either:
2543
+	 *    complete the current step and allow advancement to the next reg step
2544
+	 *        or present the payment options again
2545
+	 *
2546
+	 * @access private
2547
+	 * @return EE_Payment|FALSE
2548
+	 * @throws EE_Error
2549
+	 * @throws InvalidArgumentException
2550
+	 * @throws ReflectionException
2551
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2552
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2553
+	 * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
2554
+	 */
2555
+	public function process_gateway_response()
2556
+	{
2557
+		$payment = null;
2558
+		// how have they chosen to pay?
2559
+		$this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
2560
+		// get EE_Payment_Method object
2561
+		if (! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()) {
2562
+			$this->checkout->continue_reg = false;
2563
+			return false;
2564
+		}
2565
+		if (! $this->checkout->payment_method->is_off_site()) {
2566
+			return false;
2567
+		}
2568
+		$this->_validate_offsite_return();
2569
+		// DEBUG LOG
2570
+		//$this->checkout->log(
2571
+		//	__CLASS__, __FUNCTION__, __LINE__,
2572
+		//	array(
2573
+		//		'selected_method_of_payment' => $this->checkout->selected_method_of_payment,
2574
+		//		'payment_method' => $this->checkout->payment_method,
2575
+		//	),
2576
+		//	true
2577
+		//);
2578
+		// verify TXN
2579
+		if ($this->checkout->transaction instanceof EE_Transaction) {
2580
+			$gateway = $this->checkout->payment_method->type_obj()->get_gateway();
2581
+			if (! $gateway instanceof EE_Offsite_Gateway) {
2582
+				$this->checkout->continue_reg = false;
2583
+				return false;
2584
+			}
2585
+			$payment = $this->_process_off_site_payment($gateway);
2586
+			$payment = $this->_process_cancelled_payments($payment);
2587
+			$payment = $this->_validate_payment($payment);
2588
+			// if payment was not declined by the payment gateway or cancelled by the registrant
2589
+			if ($this->_process_payment_status($payment, EE_PMT_Base::offsite)) {
2590
+				//$this->_setup_redirect_for_next_step();
2591
+				// store that for later
2592
+				$this->checkout->payment = $payment;
2593
+				// mark this reg step as completed, as long as gateway doesn't use a separate IPN request,
2594
+				// because we will complete this step during the IPN processing then
2595
+				if ($gateway instanceof EE_Offsite_Gateway && ! $this->handle_IPN_in_this_request()) {
2596
+					$this->set_completed();
2597
+				}
2598
+				return true;
2599
+			}
2600
+		}
2601
+		// DEBUG LOG
2602
+		//$this->checkout->log( __CLASS__, __FUNCTION__, __LINE__,
2603
+		//	array( 'payment' => $payment )
2604
+		//);
2605
+		$this->checkout->continue_reg = false;
2606
+		return false;
2607
+	}
2608
+
2609
+
2610
+	/**
2611
+	 * _validate_return
2612
+	 *
2613
+	 * @access private
2614
+	 * @return void
2615
+	 * @throws EE_Error
2616
+	 * @throws InvalidArgumentException
2617
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2618
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2619
+	 * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
2620
+	 */
2621
+	private function _validate_offsite_return()
2622
+	{
2623
+		$TXN_ID = (int)EE_Registry::instance()->REQ->get('spco_txn', 0);
2624
+		if ($TXN_ID !== $this->checkout->transaction->ID()) {
2625
+			// Houston... we might have a problem
2626
+			$invalid_TXN = false;
2627
+			// first gather some info
2628
+			$valid_TXN          = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
2629
+			$primary_registrant = $valid_TXN instanceof EE_Transaction
2630
+				? $valid_TXN->primary_registration()
2631
+				: null;
2632
+			// let's start by retrieving the cart for this TXN
2633
+			$cart = $this->checkout->get_cart_for_transaction($this->checkout->transaction);
2634
+			if ($cart instanceof EE_Cart) {
2635
+				// verify that the current cart has tickets
2636
+				$tickets = $cart->get_tickets();
2637
+				if (empty($tickets)) {
2638
+					$invalid_TXN = true;
2639
+				}
2640
+			} else {
2641
+				$invalid_TXN = true;
2642
+			}
2643
+			$valid_TXN_SID = $primary_registrant instanceof EE_Registration
2644
+				? $primary_registrant->session_ID()
2645
+				: null;
2646
+			// validate current Session ID and compare against valid TXN session ID
2647
+			if (
2648
+				$invalid_TXN // if this is already true, then skip other checks
2649
+				|| EE_Session::instance()->id() === null
2650
+				|| (
2651
+					// WARNING !!!
2652
+					// this could be PayPal sending back duplicate requests (ya they do that)
2653
+					// or it **could** mean someone is simply registering AGAIN after having just done so
2654
+					// so now we need to determine if this current TXN looks valid or not
2655
+					// and whether this reg step has even been started ?
2656
+					EE_Session::instance()->id() === $valid_TXN_SID
2657
+					// really? you're half way through this reg step, but you never started it ?
2658
+					&& $this->checkout->transaction->reg_step_completed($this->slug()) === false
2659
+				)
2660
+			) {
2661
+				$invalid_TXN = true;
2662
+			}
2663
+			if ($invalid_TXN) {
2664
+				// is the valid TXN completed ?
2665
+				if ($valid_TXN instanceof EE_Transaction) {
2666
+					// has this step even been started ?
2667
+					$reg_step_completed = $valid_TXN->reg_step_completed($this->slug());
2668
+					if ($reg_step_completed !== false && $reg_step_completed !== true) {
2669
+						// so it **looks** like this is a double request from PayPal
2670
+						// so let's try to pick up where we left off
2671
+						$this->checkout->transaction = $valid_TXN;
2672
+						$this->checkout->refresh_all_entities(true);
2673
+						return;
2674
+					}
2675
+				}
2676
+				// you appear to be lost?
2677
+				$this->_redirect_wayward_request($primary_registrant);
2678
+			}
2679
+		}
2680
+	}
2681
+
2682
+
2683
+	/**
2684
+	 * _redirect_wayward_request
2685
+	 *
2686
+	 * @access private
2687
+	 * @param \EE_Registration|null $primary_registrant
2688
+	 * @return bool
2689
+	 * @throws EE_Error
2690
+	 * @throws InvalidArgumentException
2691
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2692
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2693
+	 */
2694
+	private function _redirect_wayward_request(EE_Registration $primary_registrant)
2695
+	{
2696
+		if (! $primary_registrant instanceof EE_Registration) {
2697
+			// try redirecting based on the current TXN
2698
+			$primary_registrant = $this->checkout->transaction instanceof EE_Transaction
2699
+				? $this->checkout->transaction->primary_registration()
2700
+				: null;
2701
+		}
2702
+		if (! $primary_registrant instanceof EE_Registration) {
2703
+			EE_Error::add_error(
2704
+				sprintf(
2705
+					esc_html__(
2706
+						'Invalid information was received from the Off-Site Payment Processor and your Transaction details could not be retrieved from the database.%1$sPlease try again or contact %2$s for assistance.',
2707
+						'event_espresso'
2708
+					),
2709
+					'<br/>',
2710
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
2711
+				),
2712
+				__FILE__,
2713
+				__FUNCTION__,
2714
+				__LINE__
2715
+			);
2716
+			return false;
2717
+		}
2718
+		// make sure transaction is not locked
2719
+		$this->checkout->transaction->unlock();
2720
+		wp_safe_redirect(
2721
+			add_query_arg(
2722
+				array(
2723
+					'e_reg_url_link' => $primary_registrant->reg_url_link(),
2724
+				),
2725
+				$this->checkout->thank_you_page_url
2726
+			)
2727
+		);
2728
+		exit();
2729
+	}
2730
+
2731
+
2732
+	/**
2733
+	 * _process_off_site_payment
2734
+	 *
2735
+	 * @access private
2736
+	 * @param \EE_Offsite_Gateway $gateway
2737
+	 * @return EE_Payment
2738
+	 * @throws EE_Error
2739
+	 * @throws InvalidArgumentException
2740
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2741
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2742
+	 */
2743
+	private function _process_off_site_payment(EE_Offsite_Gateway $gateway)
2744
+	{
2745
+		try {
2746
+			$request_data = \EE_Registry::instance()->REQ->params();
2747
+			// if gateway uses_separate_IPN_request, then we don't have to process the IPN manually
2748
+			$this->set_handle_IPN_in_this_request(
2749
+				$gateway->handle_IPN_in_this_request($request_data, false)
2750
+			);
2751
+			if ($this->handle_IPN_in_this_request()) {
2752
+				// get payment details and process results
2753
+				/** @type EE_Payment_Processor $payment_processor */
2754
+				$payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2755
+				$payment           = $payment_processor->process_ipn(
2756
+					$request_data,
2757
+					$this->checkout->transaction,
2758
+					$this->checkout->payment_method,
2759
+					true,
2760
+					false
2761
+				);
2762
+				//$payment_source = 'process_ipn';
2763
+			} else {
2764
+				$payment = $this->checkout->transaction->last_payment();
2765
+				//$payment_source = 'last_payment';
2766
+			}
2767
+		} catch (Exception $e) {
2768
+			// let's just eat the exception and try to move on using any previously set payment info
2769
+			$payment = $this->checkout->transaction->last_payment();
2770
+			//$payment_source = 'last_payment after Exception';
2771
+			// but if we STILL don't have a payment object
2772
+			if (! $payment instanceof EE_Payment) {
2773
+				// then we'll object ! ( not object like a thing... but object like what a lawyer says ! )
2774
+				$this->_handle_payment_processor_exception($e);
2775
+			}
2776
+		}
2777
+		// DEBUG LOG
2778
+		//$this->checkout->log( __CLASS__, __FUNCTION__, __LINE__,
2779
+		//	array(
2780
+		//		'process_ipn_payment' => $payment,
2781
+		//		'payment_source'      => $payment_source,
2782
+		//	)
2783
+		//);
2784
+		return $payment;
2785
+	}
2786
+
2787
+
2788
+	/**
2789
+	 * _process_cancelled_payments
2790
+	 * just makes sure that the payment status gets updated correctly
2791
+	 * so tha tan error isn't generated during payment validation
2792
+	 *
2793
+	 * @access private
2794
+	 * @param EE_Payment $payment
2795
+	 * @return EE_Payment | FALSE
2796
+	 * @throws \EE_Error
2797
+	 */
2798
+	private function _process_cancelled_payments($payment = null)
2799
+	{
2800
+		if (
2801
+			$payment instanceof EE_Payment
2802
+			&& isset($_REQUEST['ee_cancel_payment'])
2803
+			&& $payment->status() === EEM_Payment::status_id_failed
2804
+		) {
2805
+			$payment->set_status(EEM_Payment::status_id_cancelled);
2806
+		}
2807
+		return $payment;
2808
+	}
2809
+
2810
+
2811
+	/**
2812
+	 *    get_transaction_details_for_gateways
2813
+	 *
2814
+	 * @access    public
2815
+	 * @return int
2816
+	 * @throws EE_Error
2817
+	 * @throws InvalidArgumentException
2818
+	 * @throws ReflectionException
2819
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2820
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2821
+	 */
2822
+	public function get_transaction_details_for_gateways()
2823
+	{
2824
+		$txn_details = array();
2825
+		// ya gotta make a choice man
2826
+		if (empty($this->checkout->selected_method_of_payment)) {
2827
+			$txn_details = array(
2828
+				'error' => esc_html__('Please select a method of payment before proceeding.', 'event_espresso'),
2829
+			);
2830
+		}
2831
+		// get EE_Payment_Method object
2832
+		if (
2833
+			empty($txn_details)
2834
+			&&
2835
+			! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()
2836
+		) {
2837
+			$txn_details = array(
2838
+				'selected_method_of_payment' => $this->checkout->selected_method_of_payment,
2839
+				'error'                      => esc_html__(
2840
+					'A valid Payment Method could not be determined.',
2841
+					'event_espresso'
2842
+				),
2843
+			);
2844
+		}
2845
+		if (empty($txn_details) && $this->checkout->transaction instanceof EE_Transaction) {
2846
+			$return_url  = $this->_get_return_url($this->checkout->payment_method);
2847
+			$txn_details = array(
2848
+				'TXN_ID'         => $this->checkout->transaction->ID(),
2849
+				'TXN_timestamp'  => $this->checkout->transaction->datetime(),
2850
+				'TXN_total'      => $this->checkout->transaction->total(),
2851
+				'TXN_paid'       => $this->checkout->transaction->paid(),
2852
+				'TXN_reg_steps'  => $this->checkout->transaction->reg_steps(),
2853
+				'STS_ID'         => $this->checkout->transaction->status_ID(),
2854
+				'PMD_ID'         => $this->checkout->transaction->payment_method_ID(),
2855
+				'payment_amount' => $this->checkout->amount_owing,
2856
+				'return_url'     => $return_url,
2857
+				'cancel_url'     => add_query_arg(array('ee_cancel_payment' => true), $return_url),
2858
+				'notify_url'     => EE_Config::instance()->core->txn_page_url(
2859
+					array(
2860
+						'e_reg_url_link'    => $this->checkout->transaction->primary_registration()->reg_url_link(),
2861
+						'ee_payment_method' => $this->checkout->payment_method->slug(),
2862
+					)
2863
+				),
2864
+			);
2865
+		}
2866
+		echo wp_json_encode($txn_details);
2867
+		exit();
2868
+	}
2869
+
2870
+
2871
+	/**
2872
+	 *    __sleep
2873
+	 * to conserve db space, let's remove the reg_form and the EE_Checkout object from EE_SPCO_Reg_Step objects upon
2874
+	 * serialization EE_Checkout will handle the reimplementation of itself upon waking, but we won't bother with the
2875
+	 * reg form, because if needed, it will be regenerated anyways
2876
+	 *
2877
+	 * @return array
2878
+	 */
2879
+	public function __sleep()
2880
+	{
2881
+		// remove the reg form and the checkout
2882
+		return array_diff(array_keys(get_object_vars($this)), array('reg_form', 'checkout', 'line_item_display'));
2883
+	}
2884 2884
 }
Please login to merge, or discard this patch.
core/business/EE_Registration_Processor.class.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -734,7 +734,7 @@
 block discarded – undo
734 734
      * @since 4.9.1
735 735
      * @param int                   $att_nmbr
736 736
      * @param EE_Line_Item | string $item
737
-     * @return string
737
+     * @return RegUrlLink
738 738
      * @throws InvalidArgumentException
739 739
      */
740 740
     public function generate_reg_url_link($att_nmbr, $item)
Please login to merge, or discard this patch.
Spacing   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -74,7 +74,7 @@  discard block
 block discarded – undo
74 74
     public static function instance()
75 75
     {
76 76
         // check if class object is instantiated
77
-        if (! self::$_instance instanceof EE_Registration_Processor) {
77
+        if ( ! self::$_instance instanceof EE_Registration_Processor) {
78 78
             self::$_instance = new self();
79 79
         }
80 80
         return self::$_instance;
@@ -109,7 +109,7 @@  discard block
 block discarded – undo
109 109
     public function set_old_reg_status($REG_ID, $old_reg_status)
110 110
     {
111 111
         // only set the first time
112
-        if (! isset($this->_old_reg_status[$REG_ID])) {
112
+        if ( ! isset($this->_old_reg_status[$REG_ID])) {
113 113
             $this->_old_reg_status[$REG_ID] = $old_reg_status;
114 114
         }
115 115
     }
@@ -264,7 +264,7 @@  discard block
 block discarded – undo
264 264
                 $registration->save();
265 265
             }
266 266
             // don't trigger notifications during IPNs because they will get triggered by EE_Payment_Processor
267
-            if (! EE_Processor_Base::$IPN) {
267
+            if ( ! EE_Processor_Base::$IPN) {
268 268
                 // otherwise, send out notifications
269 269
                 add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true', 10);
270 270
             }
@@ -320,7 +320,7 @@  discard block
 block discarded – undo
320 320
                 $registration->save();
321 321
             }
322 322
             // don't trigger notifications during IPNs because they will get triggered by EE_Payment_Processor
323
-            if (! EE_Processor_Base::$IPN) {
323
+            if ( ! EE_Processor_Base::$IPN) {
324 324
                 // otherwise, send out notifications
325 325
                 add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true', 10);
326 326
             }
@@ -365,7 +365,7 @@  discard block
 block discarded – undo
365 365
         // set initial REG_Status
366 366
         $this->set_old_reg_status($registration->ID(), $registration->status_ID());
367 367
         // was a payment just made ?
368
-        $payment    = isset($additional_details['payment_updates'], $additional_details['last_payment'])
368
+        $payment = isset($additional_details['payment_updates'], $additional_details['last_payment'])
369 369
                       && $additional_details['payment_updates']
370 370
                       && $additional_details['last_payment'] instanceof EE_Payment
371 371
             ? $additional_details['last_payment']
@@ -406,7 +406,7 @@  discard block
 block discarded – undo
406 406
                 $registration->save();
407 407
             }
408 408
             // don't trigger notifications during IPNs because they will get triggered by EE_Payment_Processor
409
-            if (! EE_Processor_Base::$IPN) {
409
+            if ( ! EE_Processor_Base::$IPN) {
410 410
                 // otherwise, send out notifications
411 411
                 add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true', 10);
412 412
             }
@@ -437,7 +437,7 @@  discard block
 block discarded – undo
437 437
     public function trigger_registration_update_notifications($registration, array $additional_details = array())
438 438
     {
439 439
         try {
440
-            if (! $registration instanceof EE_Registration) {
440
+            if ( ! $registration instanceof EE_Registration) {
441 441
                 throw new EE_Error(
442 442
                     esc_html__('An invalid registration was received.', 'event_espresso')
443 443
                 );
@@ -451,7 +451,7 @@  discard block
 block discarded – undo
451 451
             // 	false,
452 452
             // 	'EE_Transaction: ' . $registration->transaction()->ID()
453 453
             // );
454
-            if (! $registration->is_primary_registrant()) {
454
+            if ( ! $registration->is_primary_registrant()) {
455 455
                 return;
456 456
             }
457 457
             do_action(
@@ -570,7 +570,7 @@  discard block
 block discarded – undo
570 570
         $diff = $transaction->total() - $reg_final_price_sum;
571 571
         //ok then, just grab one of the registrations
572 572
         if ($diff !== 0) {
573
-            $a_reg   = EEM_Registration::instance()->get_one(
573
+            $a_reg = EEM_Registration::instance()->get_one(
574 574
                 array(
575 575
                     array(
576 576
                         'TXN_ID' => $transaction->ID(),
@@ -605,7 +605,7 @@  discard block
 block discarded – undo
605 605
         $closed_reg_statuses = ! empty($closed_reg_statuses)
606 606
             ? $closed_reg_statuses
607 607
             : EEM_Registration::closed_reg_statuses();
608
-        if (! in_array($registration->status_ID(), $closed_reg_statuses, true)) {
608
+        if ( ! in_array($registration->status_ID(), $closed_reg_statuses, true)) {
609 609
             return false;
610 610
         }
611 611
         // release a reserved ticket by decrementing ticket and datetime reserved values
@@ -641,7 +641,7 @@  discard block
 block discarded – undo
641 641
             return false;
642 642
         }
643 643
         $ticket = $registration->ticket();
644
-        if (! $ticket instanceof EE_Ticket) {
644
+        if ( ! $ticket instanceof EE_Ticket) {
645 645
             throw new EE_Error(
646 646
                 sprintf(
647 647
                     esc_html__(
@@ -691,7 +691,7 @@  discard block
 block discarded – undo
691 691
         $total_ticket_count = 1
692 692
     ) {
693 693
         EE_Error::doing_it_wrong(
694
-            __CLASS__ . '::' . __FUNCTION__,
694
+            __CLASS__.'::'.__FUNCTION__,
695 695
             sprintf(
696 696
                 esc_html__('This method is deprecated. Please use "%s" instead', 'event_espresso'),
697 697
                 '\EventEspresso\core\domain\services\registration\CreateRegistrationService::create()'
@@ -701,7 +701,7 @@  discard block
 block discarded – undo
701 701
         );
702 702
         // grab the related ticket object for this line_item
703 703
         $ticket = $line_item->ticket();
704
-        if (! $ticket instanceof EE_Ticket) {
704
+        if ( ! $ticket instanceof EE_Ticket) {
705 705
             EE_Error::add_error(
706 706
                 sprintf(
707 707
                     esc_html__('Line item %s did not contain a valid ticket', 'event_espresso'),
@@ -740,7 +740,7 @@  discard block
 block discarded – undo
740 740
     public function generate_reg_url_link($att_nmbr, $item)
741 741
     {
742 742
         EE_Error::doing_it_wrong(
743
-            __CLASS__ . '::' . __FUNCTION__,
743
+            __CLASS__.'::'.__FUNCTION__,
744 744
             sprintf(
745 745
                 esc_html__('This method is deprecated. Please use "%s" instead', 'event_espresso'),
746 746
                 'EventEspresso\core\domain\entities\RegUrlLink'
@@ -767,7 +767,7 @@  discard block
 block discarded – undo
767 767
     public function generate_reg_code(EE_Registration $registration)
768 768
     {
769 769
         EE_Error::doing_it_wrong(
770
-            __CLASS__ . '::' . __FUNCTION__,
770
+            __CLASS__.'::'.__FUNCTION__,
771 771
             sprintf(
772 772
                 esc_html__('This method is deprecated. Please use "%s" instead', 'event_espresso'),
773 773
                 'EventEspresso\core\domain\entities\RegCode'
Please login to merge, or discard this patch.
Indentation   +759 added lines, -759 removed lines patch added patch discarded remove patch
@@ -26,765 +26,765 @@
 block discarded – undo
26 26
 class EE_Registration_Processor extends EE_Processor_Base
27 27
 {
28 28
 
29
-    /**
30
-     * @var EE_Registration_Processor $_instance
31
-     * @access    private
32
-     */
33
-    private static $_instance;
34
-
35
-    /**
36
-     * initial reg status at the beginning of this request.
37
-     * indexed by registration ID
38
-     *
39
-     * @var array
40
-     */
41
-    protected $_old_reg_status = array();
42
-
43
-    /**
44
-     * reg status at the end of the request after all processing.
45
-     * indexed by registration ID
46
-     *
47
-     * @var array
48
-     */
49
-    protected $_new_reg_status = array();
50
-
51
-    /**
52
-     * amounts paid at the end of the request after all processing.
53
-     * indexed by registration ID
54
-     *
55
-     * @var array
56
-     */
57
-    protected static $_amount_paid = array();
58
-
59
-    /**
60
-     * Cache of the reg final price for registrations corresponding to a ticket line item
61
-     *
62
-     * @deprecated
63
-     * @var array @see EEH_Line_Item::calculate_reg_final_prices_per_line_item()'s return value
64
-     */
65
-    protected $_reg_final_price_per_tkt_line_item;
66
-
67
-
68
-
69
-    /**
70
-     * @singleton method used to instantiate class object
71
-     * @access    public
72
-     * @return EE_Registration_Processor instance
73
-     */
74
-    public static function instance()
75
-    {
76
-        // check if class object is instantiated
77
-        if (! self::$_instance instanceof EE_Registration_Processor) {
78
-            self::$_instance = new self();
79
-        }
80
-        return self::$_instance;
81
-    }
82
-
83
-
84
-
85
-    /**
86
-     * EE_Registration_Processor constructor
87
-     */
88
-    private function __construct()
89
-    {
90
-    }
91
-
92
-
93
-
94
-    /**
95
-     * @param int $REG_ID
96
-     * @return string
97
-     */
98
-    public function old_reg_status($REG_ID)
99
-    {
100
-        return isset($this->_old_reg_status[$REG_ID]) ? $this->_old_reg_status[$REG_ID] : null;
101
-    }
102
-
103
-
104
-
105
-    /**
106
-     * @param int    $REG_ID
107
-     * @param string $old_reg_status
108
-     */
109
-    public function set_old_reg_status($REG_ID, $old_reg_status)
110
-    {
111
-        // only set the first time
112
-        if (! isset($this->_old_reg_status[$REG_ID])) {
113
-            $this->_old_reg_status[$REG_ID] = $old_reg_status;
114
-        }
115
-    }
116
-
117
-
118
-
119
-    /**
120
-     * @param int $REG_ID
121
-     * @return string
122
-     */
123
-    public function new_reg_status($REG_ID)
124
-    {
125
-        return isset($this->_new_reg_status[$REG_ID]) ? $this->_new_reg_status[$REG_ID] : null;
126
-    }
127
-
128
-
129
-
130
-    /**
131
-     * @param int    $REG_ID
132
-     * @param string $new_reg_status
133
-     */
134
-    public function set_new_reg_status($REG_ID, $new_reg_status)
135
-    {
136
-        $this->_new_reg_status[$REG_ID] = $new_reg_status;
137
-    }
138
-
139
-
140
-
141
-    /**
142
-     * reg_status_updated
143
-     *
144
-     * @param int $REG_ID
145
-     * @return bool
146
-     */
147
-    public function reg_status_updated($REG_ID)
148
-    {
149
-        return $this->new_reg_status($REG_ID) !== $this->old_reg_status($REG_ID);
150
-    }
151
-
152
-
153
-
154
-    /**
155
-     * @param EE_Registration $registration
156
-     * @throws EE_Error
157
-     * @throws EntityNotFoundException
158
-     * @throws InvalidArgumentException
159
-     * @throws InvalidDataTypeException
160
-     * @throws InvalidInterfaceException
161
-     * @throws ReflectionException
162
-     * @throws RuntimeException
163
-     */
164
-    public function update_registration_status_and_trigger_notifications(EE_Registration $registration)
165
-    {
166
-        $this->toggle_incomplete_registration_status_to_default($registration, false);
167
-        $this->toggle_registration_status_for_default_approved_events($registration, false);
168
-        $this->toggle_registration_status_if_no_monies_owing($registration, false);
169
-        $registration->save();
170
-        // trigger notifications
171
-        $this->trigger_registration_update_notifications($registration);
172
-    }
173
-
174
-
175
-
176
-    /**
177
-     *    manually_update_registration_status
178
-     *
179
-     * @access public
180
-     * @param EE_Registration $registration
181
-     * @param string          $new_reg_status
182
-     * @param bool            $save TRUE will save the registration if the status is updated, FALSE will leave that up
183
-     *                              to client code
184
-     * @return bool
185
-     * @throws EE_Error
186
-     * @throws EntityNotFoundException
187
-     * @throws InvalidArgumentException
188
-     * @throws InvalidDataTypeException
189
-     * @throws InvalidInterfaceException
190
-     * @throws ReflectionException
191
-     * @throws RuntimeException
192
-     */
193
-    public function manually_update_registration_status(
194
-        EE_Registration $registration,
195
-        $new_reg_status = '',
196
-        $save = true
197
-    ) {
198
-        // set initial REG_Status
199
-        $this->set_old_reg_status($registration->ID(), $registration->status_ID());
200
-        // set incoming REG_Status
201
-        $this->set_new_reg_status($registration->ID(), $new_reg_status);
202
-        // toggle reg status but only if it has changed and the user can do so
203
-        if (
204
-            $this->reg_status_updated($registration->ID())
205
-            && EE_Registry::instance()->CAP->current_user_can(
206
-                'ee_edit_registration',
207
-                'toggle_registration_status',
208
-                $registration->ID()
209
-            )
210
-        ) {
211
-            // change status to new value
212
-            $updated = $registration->set_status($this->new_reg_status($registration->ID()));
213
-            if ($updated && $save) {
214
-                $registration->save();
215
-            }
216
-            return true;
217
-        }
218
-        return false;
219
-    }
220
-
221
-
222
-
223
-    /**
224
-     *    toggle_incomplete_registration_status_to_default
225
-     *        changes any incomplete registrations to either the event or global default registration status
226
-     *
227
-     * @access public
228
-     * @param EE_Registration $registration
229
-     * @param bool            $save TRUE will save the registration if the status is updated, FALSE will leave that up
230
-     *                              to client code
231
-     * @param Context|null    $context
232
-     * @return void
233
-     * @throws EE_Error
234
-     * @throws InvalidArgumentException
235
-     * @throws ReflectionException
236
-     * @throws RuntimeException
237
-     * @throws EntityNotFoundException
238
-     * @throws InvalidDataTypeException
239
-     * @throws InvalidInterfaceException
240
-     */
241
-    public function toggle_incomplete_registration_status_to_default(
242
-        EE_Registration $registration,
243
-        $save = true,
244
-        Context $context = null
245
-    ) {
246
-        $existing_reg_status = $registration->status_ID();
247
-        // set initial REG_Status
248
-        $this->set_old_reg_status($registration->ID(), $existing_reg_status);
249
-        // is the registration currently incomplete ?
250
-        if ($registration->status_ID() === EEM_Registration::status_id_incomplete) {
251
-            // grab default reg status for the event, if set
252
-            $event_default_registration_status = $registration->event()->default_registration_status();
253
-            // if no default reg status is set for the event, then use the global value
254
-            $STS_ID = ! empty($event_default_registration_status)
255
-                ? $event_default_registration_status
256
-                : EE_Registry::instance()->CFG->registration->default_STS_ID;
257
-            // if the event default reg status is approved, then downgrade temporarily to payment pending to ensure that payments are triggered
258
-            $STS_ID = $STS_ID === EEM_Registration::status_id_approved ? EEM_Registration::status_id_pending_payment
259
-                : $STS_ID;
260
-            // set incoming REG_Status
261
-            $this->set_new_reg_status($registration->ID(), $STS_ID);
262
-            $registration->set_status($STS_ID, false, $context);
263
-            if ($save) {
264
-                $registration->save();
265
-            }
266
-            // don't trigger notifications during IPNs because they will get triggered by EE_Payment_Processor
267
-            if (! EE_Processor_Base::$IPN) {
268
-                // otherwise, send out notifications
269
-                add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true', 10);
270
-            }
271
-            // DEBUG LOG
272
-            //$this->log(
273
-            //	__CLASS__, __FUNCTION__, __LINE__,
274
-            //	$registration->transaction(),
275
-            //	array(
276
-            //		'IPN'                   => EE_Processor_Base::$IPN,
277
-            //		'deliver_notifications' => has_filter( 'FHEE__EED_Messages___maybe_registration__deliver_notifications' ),
278
-            //	)
279
-            //);
280
-        }
281
-    }
282
-
283
-
284
-
285
-    /**
286
-     *    toggle_registration_status_for_default_approved_events
287
-     *
288
-     * @access public
289
-     * @param EE_Registration $registration
290
-     * @param bool            $save TRUE will save the registration if the status is updated, FALSE will leave that up
291
-     *                              to client code
292
-     * @return bool
293
-     * @throws EE_Error
294
-     * @throws EntityNotFoundException
295
-     * @throws InvalidArgumentException
296
-     * @throws InvalidDataTypeException
297
-     * @throws InvalidInterfaceException
298
-     * @throws ReflectionException
299
-     * @throws RuntimeException
300
-     */
301
-    public function toggle_registration_status_for_default_approved_events(EE_Registration $registration, $save = true)
302
-    {
303
-        $reg_status = $registration->status_ID();
304
-        // set initial REG_Status
305
-        $this->set_old_reg_status($registration->ID(), $reg_status);
306
-        // if not already, toggle reg status to approved IF the event default reg status is approved
307
-        // ( as long as the registration wasn't cancelled or declined at some point )
308
-        if (
309
-            $reg_status !== EEM_Registration::status_id_cancelled
310
-            && $reg_status
311
-               !== EEM_Registration::status_id_declined
312
-            && $reg_status !== EEM_Registration::status_id_approved
313
-            && $registration->event()->default_registration_status() === EEM_Registration::status_id_approved
314
-        ) {
315
-            // set incoming REG_Status
316
-            $this->set_new_reg_status($registration->ID(), EEM_Registration::status_id_approved);
317
-            // toggle status to approved
318
-            $registration->set_status(EEM_Registration::status_id_approved);
319
-            if ($save) {
320
-                $registration->save();
321
-            }
322
-            // don't trigger notifications during IPNs because they will get triggered by EE_Payment_Processor
323
-            if (! EE_Processor_Base::$IPN) {
324
-                // otherwise, send out notifications
325
-                add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true', 10);
326
-            }
327
-            // DEBUG LOG
328
-            //$this->log(
329
-            //	__CLASS__, __FUNCTION__, __LINE__,
330
-            //	$registration->transaction(),
331
-            //	array(
332
-            //		'IPN'                   => EE_Processor_Base::$IPN,
333
-            //		'deliver_notifications' => has_filter( 'FHEE__EED_Messages___maybe_registration__deliver_notifications' ),
334
-            //	)
335
-            //);
336
-            return true;
337
-        }
338
-        return false;
339
-    }
340
-
341
-
342
-
343
-    /**
344
-     *    toggle_registration_statuses_if_no_monies_owing
345
-     *
346
-     * @access public
347
-     * @param EE_Registration $registration
348
-     * @param bool            $save TRUE will save the registration if the status is updated, FALSE will leave that up
349
-     *                              to client code
350
-     * @param array           $additional_details
351
-     * @return bool
352
-     * @throws EE_Error
353
-     * @throws EntityNotFoundException
354
-     * @throws InvalidArgumentException
355
-     * @throws InvalidDataTypeException
356
-     * @throws InvalidInterfaceException
357
-     * @throws ReflectionException
358
-     * @throws RuntimeException
359
-     */
360
-    public function toggle_registration_status_if_no_monies_owing(
361
-        EE_Registration $registration,
362
-        $save = true,
363
-        array $additional_details = array()
364
-    ) {
365
-        // set initial REG_Status
366
-        $this->set_old_reg_status($registration->ID(), $registration->status_ID());
367
-        // was a payment just made ?
368
-        $payment    = isset($additional_details['payment_updates'], $additional_details['last_payment'])
369
-                      && $additional_details['payment_updates']
370
-                      && $additional_details['last_payment'] instanceof EE_Payment
371
-            ? $additional_details['last_payment']
372
-            : null;
373
-        $total_paid = array_sum(self::$_amount_paid);
374
-        // toggle reg status to approved IF
375
-        if (
376
-            // REG status is pending payment
377
-            $registration->status_ID() === EEM_Registration::status_id_pending_payment
378
-            // AND no monies are owing
379
-            && (
380
-                (
381
-                    $registration->transaction()->is_completed()
382
-                    || $registration->transaction()->is_overpaid()
383
-                    || $registration->transaction()->is_free()
384
-                    || apply_filters(
385
-                        'FHEE__EE_Registration_Processor__toggle_registration_status_if_no_monies_owing',
386
-                        false,
387
-                        $registration
388
-                    )
389
-                )
390
-                || (
391
-                    $payment instanceof EE_Payment && $payment->is_approved()
392
-                    && // this specific registration has not yet been paid for
393
-                    ! isset(self::$_amount_paid[$registration->ID()])
394
-                    && // payment amount, less what we have already attributed to other registrations, is greater than this reg's final price
395
-                    $payment->amount() - $total_paid >= $registration->final_price()
396
-                )
397
-            )
398
-        ) {
399
-            // mark as paid
400
-            self::$_amount_paid[$registration->ID()] = $registration->final_price();
401
-            // track new REG_Status
402
-            $this->set_new_reg_status($registration->ID(), EEM_Registration::status_id_approved);
403
-            // toggle status to approved
404
-            $registration->set_status(EEM_Registration::status_id_approved);
405
-            if ($save) {
406
-                $registration->save();
407
-            }
408
-            // don't trigger notifications during IPNs because they will get triggered by EE_Payment_Processor
409
-            if (! EE_Processor_Base::$IPN) {
410
-                // otherwise, send out notifications
411
-                add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true', 10);
412
-            }
413
-            // DEBUG LOG
414
-            //$this->log(
415
-            //	__CLASS__, __FUNCTION__, __LINE__,
416
-            //	$registration->transaction(),
417
-            //	array(
418
-            //		'IPN'                   => EE_Processor_Base::$IPN,
419
-            //		'deliver_notifications' => has_filter( 'FHEE__EED_Messages___maybe_registration__deliver_notifications' ),
420
-            //	)
421
-            //);
422
-            return true;
423
-        }
424
-        return false;
425
-    }
426
-
427
-
428
-
429
-    /**
430
-     *    registration_status_changed
431
-     *
432
-     * @access public
433
-     * @param EE_Registration $registration
434
-     * @param array           $additional_details
435
-     * @return void
436
-     */
437
-    public function trigger_registration_update_notifications($registration, array $additional_details = array())
438
-    {
439
-        try {
440
-            if (! $registration instanceof EE_Registration) {
441
-                throw new EE_Error(
442
-                    esc_html__('An invalid registration was received.', 'event_espresso')
443
-                );
444
-            }
445
-            // EE_Registry::instance()->load_helper( 'Debug_Tools' );
446
-            // EEH_Debug_Tools::log(
447
-            // 	__CLASS__,
448
-            // 	__FUNCTION__,
449
-            // 	__LINE__,
450
-            // 	array( $registration->transaction(), $additional_details ),
451
-            // 	false,
452
-            // 	'EE_Transaction: ' . $registration->transaction()->ID()
453
-            // );
454
-            if (! $registration->is_primary_registrant()) {
455
-                return;
456
-            }
457
-            do_action(
458
-                'AHEE__EE_Registration_Processor__trigger_registration_update_notifications',
459
-                $registration,
460
-                $additional_details
461
-            );
462
-        } catch (Exception $e) {
463
-            EE_Error::add_error($e->getMessage(), $e->getFile(), 'unknown_function_from_exception', $e->getLine());
464
-        }
465
-    }
466
-
467
-
468
-
469
-    /**
470
-     * sets reg status based either on passed param or on transaction status and event pre-approval setting
471
-     *
472
-     * @param EE_Registration $registration
473
-     * @param array           $additional_details
474
-     * @return bool
475
-     * @throws EE_Error
476
-     * @throws EntityNotFoundException
477
-     * @throws InvalidArgumentException
478
-     * @throws InvalidDataTypeException
479
-     * @throws InvalidInterfaceException
480
-     * @throws ReflectionException
481
-     * @throws RuntimeException
482
-     */
483
-    public function update_registration_after_checkout_or_payment(
484
-        EE_Registration $registration,
485
-        array $additional_details = array()
486
-    ) {
487
-        // set initial REG_Status
488
-        $this->set_old_reg_status($registration->ID(), $registration->status_ID());
489
-        // if the registration status gets updated, then save the registration
490
-        if (
491
-            $this->toggle_registration_status_for_default_approved_events($registration, false)
492
-            || $this->toggle_registration_status_if_no_monies_owing(
493
-                $registration,
494
-                false,
495
-                $additional_details
496
-            )
497
-        ) {
498
-            $registration->save();
499
-        }
500
-        // set new  REG_Status
501
-        $this->set_new_reg_status($registration->ID(), $registration->status_ID());
502
-        return $this->reg_status_updated($registration->ID())
503
-               && $this->new_reg_status($registration->ID()) === EEM_Registration::status_id_approved;
504
-    }
505
-
506
-
507
-
508
-    /**
509
-     * Updates the registration' final prices based on the current line item tree (taking into account
510
-     * discounts, taxes, and other line items unrelated to tickets.)
511
-     *
512
-     * @param EE_Transaction $transaction
513
-     * @param boolean        $save_regs whether to immediately save registrations in this function or not
514
-     * @return void
515
-     * @throws EE_Error
516
-     * @throws InvalidArgumentException
517
-     * @throws InvalidDataTypeException
518
-     * @throws InvalidInterfaceException
519
-     * @throws RuntimeException
520
-     */
521
-    public function update_registration_final_prices($transaction, $save_regs = true)
522
-    {
523
-        $reg_final_price_per_ticket_line_item = EEH_Line_Item::calculate_reg_final_prices_per_line_item(
524
-            $transaction->total_line_item()
525
-        );
526
-        foreach ($transaction->registrations() as $registration) {
527
-            /** @var EE_Line_Item $line_item */
528
-            $line_item = EEM_Line_Item::instance()->get_line_item_for_registration($registration);
529
-            if (isset($reg_final_price_per_ticket_line_item[$line_item->ID()])) {
530
-                $registration->set_final_price($reg_final_price_per_ticket_line_item[$line_item->ID()]);
531
-                if ($save_regs) {
532
-                    $registration->save();
533
-                }
534
-            }
535
-        }
536
-        //and make sure there's no rounding problem
537
-        $this->fix_reg_final_price_rounding_issue($transaction);
538
-    }
539
-
540
-
541
-
542
-    /**
543
-     * Makes sure there is no rounding errors for the REG_final_prices.
544
-     * Eg, if we have 3 registrations for $1, and there is a $0.01 discount between the three of them,
545
-     * they will each be for $0.99333333, which gets rounded to $1 again.
546
-     * So the transaction total will be $2.99, but each registration will be for $1,
547
-     * so if each registrant paid individually they will have overpaid by $0.01.
548
-     * So in order to overcome this, we check for any difference, and if there is a difference
549
-     * we just grab one registrant at random and make them responsible for it.
550
-     * This should be used after setting REG_final_prices (it's done automatically as part of
551
-     * EE_Registration_Processor::update_registration_final_prices())
552
-     *
553
-     * @param EE_Transaction $transaction
554
-     * @return bool success verifying that there is NO difference after this method is done
555
-     * @throws EE_Error
556
-     * @throws InvalidArgumentException
557
-     * @throws InvalidDataTypeException
558
-     * @throws InvalidInterfaceException
559
-     */
560
-    public function fix_reg_final_price_rounding_issue($transaction)
561
-    {
562
-        $reg_final_price_sum = EEM_Registration::instance()->sum(
563
-            array(
564
-                array(
565
-                    'TXN_ID' => $transaction->ID(),
566
-                ),
567
-            ),
568
-            'REG_final_price'
569
-        );
570
-        $diff = $transaction->total() - $reg_final_price_sum;
571
-        //ok then, just grab one of the registrations
572
-        if ($diff !== 0) {
573
-            $a_reg   = EEM_Registration::instance()->get_one(
574
-                array(
575
-                    array(
576
-                        'TXN_ID' => $transaction->ID(),
577
-                    ),
578
-                )
579
-            );
580
-            return $a_reg instanceof EE_Registration
581
-                ? (bool) $a_reg->save(array('REG_final_price' => $a_reg->final_price() + $diff))
582
-                : false;
583
-        }
584
-        return true;
585
-    }
586
-
587
-
588
-
589
-    /**
590
-     * update_registration_after_being_canceled_or_declined
591
-     *
592
-     * @param EE_Registration $registration
593
-     * @param array           $closed_reg_statuses
594
-     * @param bool            $update_reg
595
-     * @return bool
596
-     * @throws EE_Error
597
-     * @throws RuntimeException
598
-     */
599
-    public function update_registration_after_being_canceled_or_declined(
600
-        EE_Registration $registration,
601
-        array $closed_reg_statuses = array(),
602
-        $update_reg = true
603
-    ) {
604
-        // these reg statuses should not be considered in any calculations involving monies owing
605
-        $closed_reg_statuses = ! empty($closed_reg_statuses)
606
-            ? $closed_reg_statuses
607
-            : EEM_Registration::closed_reg_statuses();
608
-        if (! in_array($registration->status_ID(), $closed_reg_statuses, true)) {
609
-            return false;
610
-        }
611
-        // release a reserved ticket by decrementing ticket and datetime reserved values
612
-        $registration->release_reserved_ticket(true);
613
-        $registration->set_final_price(0);
614
-        if ($update_reg) {
615
-            $registration->save();
616
-        }
617
-        return true;
618
-    }
619
-
620
-
621
-
622
-    /**
623
-     * update_canceled_or_declined_registration_after_being_reinstated
624
-     *
625
-     * @param EE_Registration $registration
626
-     * @param array           $closed_reg_statuses
627
-     * @param bool            $update_reg
628
-     * @return bool
629
-     * @throws EE_Error
630
-     * @throws RuntimeException
631
-     */
632
-    public function update_canceled_or_declined_registration_after_being_reinstated(
633
-        EE_Registration $registration,
634
-        array $closed_reg_statuses = array(),
635
-        $update_reg = true
636
-    ) {
637
-        // these reg statuses should not be considered in any calculations involving monies owing
638
-        $closed_reg_statuses = ! empty($closed_reg_statuses) ? $closed_reg_statuses
639
-            : EEM_Registration::closed_reg_statuses();
640
-        if (in_array($registration->status_ID(), $closed_reg_statuses, true)) {
641
-            return false;
642
-        }
643
-        $ticket = $registration->ticket();
644
-        if (! $ticket instanceof EE_Ticket) {
645
-            throw new EE_Error(
646
-                sprintf(
647
-                    esc_html__(
648
-                        'The Ticket for Registration %1$d was not found or is invalid.',
649
-                        'event_espresso'
650
-                    ),
651
-                    $registration->ticket_ID()
652
-                )
653
-            );
654
-        }
655
-        $registration->set_final_price($ticket->price());
656
-        if ($update_reg) {
657
-            $registration->save();
658
-        }
659
-        return true;
660
-    }
661
-
662
-
663
-
664
-    /**
665
-     * generate_ONE_registration_from_line_item
666
-     * Although a ticket line item may have a quantity greater than 1,
667
-     * this method will ONLY CREATE ONE REGISTRATION !!!
668
-     * Regardless of the ticket line item quantity.
669
-     * This means that any code calling this method is responsible for ensuring
670
-     * that the final registration count matches the ticket line item quantity.
671
-     * This was done to make it easier to match the number of registrations
672
-     * to the number of tickets in the cart, when the cart has been edited
673
-     * after SPCO has already been initialized. So if an additional ticket was added to the cart, you can simply pass
674
-     * the line item to this method to add a second ticket, and in this case, you would not want to add 2 tickets.
675
-     *
676
-     * @deprecated
677
-     * @since 4.9.1
678
-     * @param EE_Line_Item    $line_item
679
-     * @param \EE_Transaction $transaction
680
-     * @param int             $att_nmbr
681
-     * @param int             $total_ticket_count
682
-     * @return EE_Registration | null
683
-     * @throws \OutOfRangeException
684
-     * @throws \EventEspresso\core\exceptions\UnexpectedEntityException
685
-     * @throws \EE_Error
686
-     */
687
-    public function generate_ONE_registration_from_line_item(
688
-        EE_Line_Item $line_item,
689
-        EE_Transaction $transaction,
690
-        $att_nmbr = 1,
691
-        $total_ticket_count = 1
692
-    ) {
693
-        EE_Error::doing_it_wrong(
694
-            __CLASS__ . '::' . __FUNCTION__,
695
-            sprintf(
696
-                esc_html__('This method is deprecated. Please use "%s" instead', 'event_espresso'),
697
-                '\EventEspresso\core\domain\services\registration\CreateRegistrationService::create()'
698
-            ),
699
-            '4.9.1',
700
-            '5.0.0'
701
-        );
702
-        // grab the related ticket object for this line_item
703
-        $ticket = $line_item->ticket();
704
-        if (! $ticket instanceof EE_Ticket) {
705
-            EE_Error::add_error(
706
-                sprintf(
707
-                    esc_html__('Line item %s did not contain a valid ticket', 'event_espresso'),
708
-                    $line_item->ID()
709
-                ),
710
-                __FILE__,
711
-                __FUNCTION__,
712
-                __LINE__
713
-            );
714
-            return null;
715
-        }
716
-        $registration_service = new CreateRegistrationService();
717
-        // then generate a new registration from that
718
-        return $registration_service->create(
719
-            $ticket->get_related_event(),
720
-            $transaction,
721
-            $ticket,
722
-            $line_item,
723
-            $att_nmbr,
724
-            $total_ticket_count
725
-        );
726
-    }
727
-
728
-
729
-
730
-    /**
731
-     * generates reg_url_link
732
-     *
733
-     * @deprecated
734
-     * @since 4.9.1
735
-     * @param int                   $att_nmbr
736
-     * @param EE_Line_Item | string $item
737
-     * @return string
738
-     * @throws InvalidArgumentException
739
-     */
740
-    public function generate_reg_url_link($att_nmbr, $item)
741
-    {
742
-        EE_Error::doing_it_wrong(
743
-            __CLASS__ . '::' . __FUNCTION__,
744
-            sprintf(
745
-                esc_html__('This method is deprecated. Please use "%s" instead', 'event_espresso'),
746
-                'EventEspresso\core\domain\entities\RegUrlLink'
747
-            ),
748
-            '4.9.1',
749
-            '5.0.0'
750
-        );
751
-        return new RegUrlLink($att_nmbr, $item);
752
-    }
753
-
754
-
755
-
756
-    /**
757
-     * generates reg code
758
-     *
759
-     * @deprecated
760
-     * @since 4.9.1
761
-     * @param EE_Registration $registration
762
-     * @return string
763
-     * @throws EE_Error
764
-     * @throws EntityNotFoundException
765
-     * @throws InvalidArgumentException
766
-     */
767
-    public function generate_reg_code(EE_Registration $registration)
768
-    {
769
-        EE_Error::doing_it_wrong(
770
-            __CLASS__ . '::' . __FUNCTION__,
771
-            sprintf(
772
-                esc_html__('This method is deprecated. Please use "%s" instead', 'event_espresso'),
773
-                'EventEspresso\core\domain\entities\RegCode'
774
-            ),
775
-            '4.9.1',
776
-            '5.0.0'
777
-        );
778
-        return apply_filters(
779
-            'FHEE__EE_Registration_Processor___generate_reg_code__new_reg_code',
780
-            new RegCode(
781
-                RegUrlLink::fromRegistration($registration),
782
-                $registration->transaction(),
783
-                $registration->ticket()
784
-            ),
785
-            $registration
786
-        );
787
-    }
29
+	/**
30
+	 * @var EE_Registration_Processor $_instance
31
+	 * @access    private
32
+	 */
33
+	private static $_instance;
34
+
35
+	/**
36
+	 * initial reg status at the beginning of this request.
37
+	 * indexed by registration ID
38
+	 *
39
+	 * @var array
40
+	 */
41
+	protected $_old_reg_status = array();
42
+
43
+	/**
44
+	 * reg status at the end of the request after all processing.
45
+	 * indexed by registration ID
46
+	 *
47
+	 * @var array
48
+	 */
49
+	protected $_new_reg_status = array();
50
+
51
+	/**
52
+	 * amounts paid at the end of the request after all processing.
53
+	 * indexed by registration ID
54
+	 *
55
+	 * @var array
56
+	 */
57
+	protected static $_amount_paid = array();
58
+
59
+	/**
60
+	 * Cache of the reg final price for registrations corresponding to a ticket line item
61
+	 *
62
+	 * @deprecated
63
+	 * @var array @see EEH_Line_Item::calculate_reg_final_prices_per_line_item()'s return value
64
+	 */
65
+	protected $_reg_final_price_per_tkt_line_item;
66
+
67
+
68
+
69
+	/**
70
+	 * @singleton method used to instantiate class object
71
+	 * @access    public
72
+	 * @return EE_Registration_Processor instance
73
+	 */
74
+	public static function instance()
75
+	{
76
+		// check if class object is instantiated
77
+		if (! self::$_instance instanceof EE_Registration_Processor) {
78
+			self::$_instance = new self();
79
+		}
80
+		return self::$_instance;
81
+	}
82
+
83
+
84
+
85
+	/**
86
+	 * EE_Registration_Processor constructor
87
+	 */
88
+	private function __construct()
89
+	{
90
+	}
91
+
92
+
93
+
94
+	/**
95
+	 * @param int $REG_ID
96
+	 * @return string
97
+	 */
98
+	public function old_reg_status($REG_ID)
99
+	{
100
+		return isset($this->_old_reg_status[$REG_ID]) ? $this->_old_reg_status[$REG_ID] : null;
101
+	}
102
+
103
+
104
+
105
+	/**
106
+	 * @param int    $REG_ID
107
+	 * @param string $old_reg_status
108
+	 */
109
+	public function set_old_reg_status($REG_ID, $old_reg_status)
110
+	{
111
+		// only set the first time
112
+		if (! isset($this->_old_reg_status[$REG_ID])) {
113
+			$this->_old_reg_status[$REG_ID] = $old_reg_status;
114
+		}
115
+	}
116
+
117
+
118
+
119
+	/**
120
+	 * @param int $REG_ID
121
+	 * @return string
122
+	 */
123
+	public function new_reg_status($REG_ID)
124
+	{
125
+		return isset($this->_new_reg_status[$REG_ID]) ? $this->_new_reg_status[$REG_ID] : null;
126
+	}
127
+
128
+
129
+
130
+	/**
131
+	 * @param int    $REG_ID
132
+	 * @param string $new_reg_status
133
+	 */
134
+	public function set_new_reg_status($REG_ID, $new_reg_status)
135
+	{
136
+		$this->_new_reg_status[$REG_ID] = $new_reg_status;
137
+	}
138
+
139
+
140
+
141
+	/**
142
+	 * reg_status_updated
143
+	 *
144
+	 * @param int $REG_ID
145
+	 * @return bool
146
+	 */
147
+	public function reg_status_updated($REG_ID)
148
+	{
149
+		return $this->new_reg_status($REG_ID) !== $this->old_reg_status($REG_ID);
150
+	}
151
+
152
+
153
+
154
+	/**
155
+	 * @param EE_Registration $registration
156
+	 * @throws EE_Error
157
+	 * @throws EntityNotFoundException
158
+	 * @throws InvalidArgumentException
159
+	 * @throws InvalidDataTypeException
160
+	 * @throws InvalidInterfaceException
161
+	 * @throws ReflectionException
162
+	 * @throws RuntimeException
163
+	 */
164
+	public function update_registration_status_and_trigger_notifications(EE_Registration $registration)
165
+	{
166
+		$this->toggle_incomplete_registration_status_to_default($registration, false);
167
+		$this->toggle_registration_status_for_default_approved_events($registration, false);
168
+		$this->toggle_registration_status_if_no_monies_owing($registration, false);
169
+		$registration->save();
170
+		// trigger notifications
171
+		$this->trigger_registration_update_notifications($registration);
172
+	}
173
+
174
+
175
+
176
+	/**
177
+	 *    manually_update_registration_status
178
+	 *
179
+	 * @access public
180
+	 * @param EE_Registration $registration
181
+	 * @param string          $new_reg_status
182
+	 * @param bool            $save TRUE will save the registration if the status is updated, FALSE will leave that up
183
+	 *                              to client code
184
+	 * @return bool
185
+	 * @throws EE_Error
186
+	 * @throws EntityNotFoundException
187
+	 * @throws InvalidArgumentException
188
+	 * @throws InvalidDataTypeException
189
+	 * @throws InvalidInterfaceException
190
+	 * @throws ReflectionException
191
+	 * @throws RuntimeException
192
+	 */
193
+	public function manually_update_registration_status(
194
+		EE_Registration $registration,
195
+		$new_reg_status = '',
196
+		$save = true
197
+	) {
198
+		// set initial REG_Status
199
+		$this->set_old_reg_status($registration->ID(), $registration->status_ID());
200
+		// set incoming REG_Status
201
+		$this->set_new_reg_status($registration->ID(), $new_reg_status);
202
+		// toggle reg status but only if it has changed and the user can do so
203
+		if (
204
+			$this->reg_status_updated($registration->ID())
205
+			&& EE_Registry::instance()->CAP->current_user_can(
206
+				'ee_edit_registration',
207
+				'toggle_registration_status',
208
+				$registration->ID()
209
+			)
210
+		) {
211
+			// change status to new value
212
+			$updated = $registration->set_status($this->new_reg_status($registration->ID()));
213
+			if ($updated && $save) {
214
+				$registration->save();
215
+			}
216
+			return true;
217
+		}
218
+		return false;
219
+	}
220
+
221
+
222
+
223
+	/**
224
+	 *    toggle_incomplete_registration_status_to_default
225
+	 *        changes any incomplete registrations to either the event or global default registration status
226
+	 *
227
+	 * @access public
228
+	 * @param EE_Registration $registration
229
+	 * @param bool            $save TRUE will save the registration if the status is updated, FALSE will leave that up
230
+	 *                              to client code
231
+	 * @param Context|null    $context
232
+	 * @return void
233
+	 * @throws EE_Error
234
+	 * @throws InvalidArgumentException
235
+	 * @throws ReflectionException
236
+	 * @throws RuntimeException
237
+	 * @throws EntityNotFoundException
238
+	 * @throws InvalidDataTypeException
239
+	 * @throws InvalidInterfaceException
240
+	 */
241
+	public function toggle_incomplete_registration_status_to_default(
242
+		EE_Registration $registration,
243
+		$save = true,
244
+		Context $context = null
245
+	) {
246
+		$existing_reg_status = $registration->status_ID();
247
+		// set initial REG_Status
248
+		$this->set_old_reg_status($registration->ID(), $existing_reg_status);
249
+		// is the registration currently incomplete ?
250
+		if ($registration->status_ID() === EEM_Registration::status_id_incomplete) {
251
+			// grab default reg status for the event, if set
252
+			$event_default_registration_status = $registration->event()->default_registration_status();
253
+			// if no default reg status is set for the event, then use the global value
254
+			$STS_ID = ! empty($event_default_registration_status)
255
+				? $event_default_registration_status
256
+				: EE_Registry::instance()->CFG->registration->default_STS_ID;
257
+			// if the event default reg status is approved, then downgrade temporarily to payment pending to ensure that payments are triggered
258
+			$STS_ID = $STS_ID === EEM_Registration::status_id_approved ? EEM_Registration::status_id_pending_payment
259
+				: $STS_ID;
260
+			// set incoming REG_Status
261
+			$this->set_new_reg_status($registration->ID(), $STS_ID);
262
+			$registration->set_status($STS_ID, false, $context);
263
+			if ($save) {
264
+				$registration->save();
265
+			}
266
+			// don't trigger notifications during IPNs because they will get triggered by EE_Payment_Processor
267
+			if (! EE_Processor_Base::$IPN) {
268
+				// otherwise, send out notifications
269
+				add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true', 10);
270
+			}
271
+			// DEBUG LOG
272
+			//$this->log(
273
+			//	__CLASS__, __FUNCTION__, __LINE__,
274
+			//	$registration->transaction(),
275
+			//	array(
276
+			//		'IPN'                   => EE_Processor_Base::$IPN,
277
+			//		'deliver_notifications' => has_filter( 'FHEE__EED_Messages___maybe_registration__deliver_notifications' ),
278
+			//	)
279
+			//);
280
+		}
281
+	}
282
+
283
+
284
+
285
+	/**
286
+	 *    toggle_registration_status_for_default_approved_events
287
+	 *
288
+	 * @access public
289
+	 * @param EE_Registration $registration
290
+	 * @param bool            $save TRUE will save the registration if the status is updated, FALSE will leave that up
291
+	 *                              to client code
292
+	 * @return bool
293
+	 * @throws EE_Error
294
+	 * @throws EntityNotFoundException
295
+	 * @throws InvalidArgumentException
296
+	 * @throws InvalidDataTypeException
297
+	 * @throws InvalidInterfaceException
298
+	 * @throws ReflectionException
299
+	 * @throws RuntimeException
300
+	 */
301
+	public function toggle_registration_status_for_default_approved_events(EE_Registration $registration, $save = true)
302
+	{
303
+		$reg_status = $registration->status_ID();
304
+		// set initial REG_Status
305
+		$this->set_old_reg_status($registration->ID(), $reg_status);
306
+		// if not already, toggle reg status to approved IF the event default reg status is approved
307
+		// ( as long as the registration wasn't cancelled or declined at some point )
308
+		if (
309
+			$reg_status !== EEM_Registration::status_id_cancelled
310
+			&& $reg_status
311
+			   !== EEM_Registration::status_id_declined
312
+			&& $reg_status !== EEM_Registration::status_id_approved
313
+			&& $registration->event()->default_registration_status() === EEM_Registration::status_id_approved
314
+		) {
315
+			// set incoming REG_Status
316
+			$this->set_new_reg_status($registration->ID(), EEM_Registration::status_id_approved);
317
+			// toggle status to approved
318
+			$registration->set_status(EEM_Registration::status_id_approved);
319
+			if ($save) {
320
+				$registration->save();
321
+			}
322
+			// don't trigger notifications during IPNs because they will get triggered by EE_Payment_Processor
323
+			if (! EE_Processor_Base::$IPN) {
324
+				// otherwise, send out notifications
325
+				add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true', 10);
326
+			}
327
+			// DEBUG LOG
328
+			//$this->log(
329
+			//	__CLASS__, __FUNCTION__, __LINE__,
330
+			//	$registration->transaction(),
331
+			//	array(
332
+			//		'IPN'                   => EE_Processor_Base::$IPN,
333
+			//		'deliver_notifications' => has_filter( 'FHEE__EED_Messages___maybe_registration__deliver_notifications' ),
334
+			//	)
335
+			//);
336
+			return true;
337
+		}
338
+		return false;
339
+	}
340
+
341
+
342
+
343
+	/**
344
+	 *    toggle_registration_statuses_if_no_monies_owing
345
+	 *
346
+	 * @access public
347
+	 * @param EE_Registration $registration
348
+	 * @param bool            $save TRUE will save the registration if the status is updated, FALSE will leave that up
349
+	 *                              to client code
350
+	 * @param array           $additional_details
351
+	 * @return bool
352
+	 * @throws EE_Error
353
+	 * @throws EntityNotFoundException
354
+	 * @throws InvalidArgumentException
355
+	 * @throws InvalidDataTypeException
356
+	 * @throws InvalidInterfaceException
357
+	 * @throws ReflectionException
358
+	 * @throws RuntimeException
359
+	 */
360
+	public function toggle_registration_status_if_no_monies_owing(
361
+		EE_Registration $registration,
362
+		$save = true,
363
+		array $additional_details = array()
364
+	) {
365
+		// set initial REG_Status
366
+		$this->set_old_reg_status($registration->ID(), $registration->status_ID());
367
+		// was a payment just made ?
368
+		$payment    = isset($additional_details['payment_updates'], $additional_details['last_payment'])
369
+					  && $additional_details['payment_updates']
370
+					  && $additional_details['last_payment'] instanceof EE_Payment
371
+			? $additional_details['last_payment']
372
+			: null;
373
+		$total_paid = array_sum(self::$_amount_paid);
374
+		// toggle reg status to approved IF
375
+		if (
376
+			// REG status is pending payment
377
+			$registration->status_ID() === EEM_Registration::status_id_pending_payment
378
+			// AND no monies are owing
379
+			&& (
380
+				(
381
+					$registration->transaction()->is_completed()
382
+					|| $registration->transaction()->is_overpaid()
383
+					|| $registration->transaction()->is_free()
384
+					|| apply_filters(
385
+						'FHEE__EE_Registration_Processor__toggle_registration_status_if_no_monies_owing',
386
+						false,
387
+						$registration
388
+					)
389
+				)
390
+				|| (
391
+					$payment instanceof EE_Payment && $payment->is_approved()
392
+					&& // this specific registration has not yet been paid for
393
+					! isset(self::$_amount_paid[$registration->ID()])
394
+					&& // payment amount, less what we have already attributed to other registrations, is greater than this reg's final price
395
+					$payment->amount() - $total_paid >= $registration->final_price()
396
+				)
397
+			)
398
+		) {
399
+			// mark as paid
400
+			self::$_amount_paid[$registration->ID()] = $registration->final_price();
401
+			// track new REG_Status
402
+			$this->set_new_reg_status($registration->ID(), EEM_Registration::status_id_approved);
403
+			// toggle status to approved
404
+			$registration->set_status(EEM_Registration::status_id_approved);
405
+			if ($save) {
406
+				$registration->save();
407
+			}
408
+			// don't trigger notifications during IPNs because they will get triggered by EE_Payment_Processor
409
+			if (! EE_Processor_Base::$IPN) {
410
+				// otherwise, send out notifications
411
+				add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true', 10);
412
+			}
413
+			// DEBUG LOG
414
+			//$this->log(
415
+			//	__CLASS__, __FUNCTION__, __LINE__,
416
+			//	$registration->transaction(),
417
+			//	array(
418
+			//		'IPN'                   => EE_Processor_Base::$IPN,
419
+			//		'deliver_notifications' => has_filter( 'FHEE__EED_Messages___maybe_registration__deliver_notifications' ),
420
+			//	)
421
+			//);
422
+			return true;
423
+		}
424
+		return false;
425
+	}
426
+
427
+
428
+
429
+	/**
430
+	 *    registration_status_changed
431
+	 *
432
+	 * @access public
433
+	 * @param EE_Registration $registration
434
+	 * @param array           $additional_details
435
+	 * @return void
436
+	 */
437
+	public function trigger_registration_update_notifications($registration, array $additional_details = array())
438
+	{
439
+		try {
440
+			if (! $registration instanceof EE_Registration) {
441
+				throw new EE_Error(
442
+					esc_html__('An invalid registration was received.', 'event_espresso')
443
+				);
444
+			}
445
+			// EE_Registry::instance()->load_helper( 'Debug_Tools' );
446
+			// EEH_Debug_Tools::log(
447
+			// 	__CLASS__,
448
+			// 	__FUNCTION__,
449
+			// 	__LINE__,
450
+			// 	array( $registration->transaction(), $additional_details ),
451
+			// 	false,
452
+			// 	'EE_Transaction: ' . $registration->transaction()->ID()
453
+			// );
454
+			if (! $registration->is_primary_registrant()) {
455
+				return;
456
+			}
457
+			do_action(
458
+				'AHEE__EE_Registration_Processor__trigger_registration_update_notifications',
459
+				$registration,
460
+				$additional_details
461
+			);
462
+		} catch (Exception $e) {
463
+			EE_Error::add_error($e->getMessage(), $e->getFile(), 'unknown_function_from_exception', $e->getLine());
464
+		}
465
+	}
466
+
467
+
468
+
469
+	/**
470
+	 * sets reg status based either on passed param or on transaction status and event pre-approval setting
471
+	 *
472
+	 * @param EE_Registration $registration
473
+	 * @param array           $additional_details
474
+	 * @return bool
475
+	 * @throws EE_Error
476
+	 * @throws EntityNotFoundException
477
+	 * @throws InvalidArgumentException
478
+	 * @throws InvalidDataTypeException
479
+	 * @throws InvalidInterfaceException
480
+	 * @throws ReflectionException
481
+	 * @throws RuntimeException
482
+	 */
483
+	public function update_registration_after_checkout_or_payment(
484
+		EE_Registration $registration,
485
+		array $additional_details = array()
486
+	) {
487
+		// set initial REG_Status
488
+		$this->set_old_reg_status($registration->ID(), $registration->status_ID());
489
+		// if the registration status gets updated, then save the registration
490
+		if (
491
+			$this->toggle_registration_status_for_default_approved_events($registration, false)
492
+			|| $this->toggle_registration_status_if_no_monies_owing(
493
+				$registration,
494
+				false,
495
+				$additional_details
496
+			)
497
+		) {
498
+			$registration->save();
499
+		}
500
+		// set new  REG_Status
501
+		$this->set_new_reg_status($registration->ID(), $registration->status_ID());
502
+		return $this->reg_status_updated($registration->ID())
503
+			   && $this->new_reg_status($registration->ID()) === EEM_Registration::status_id_approved;
504
+	}
505
+
506
+
507
+
508
+	/**
509
+	 * Updates the registration' final prices based on the current line item tree (taking into account
510
+	 * discounts, taxes, and other line items unrelated to tickets.)
511
+	 *
512
+	 * @param EE_Transaction $transaction
513
+	 * @param boolean        $save_regs whether to immediately save registrations in this function or not
514
+	 * @return void
515
+	 * @throws EE_Error
516
+	 * @throws InvalidArgumentException
517
+	 * @throws InvalidDataTypeException
518
+	 * @throws InvalidInterfaceException
519
+	 * @throws RuntimeException
520
+	 */
521
+	public function update_registration_final_prices($transaction, $save_regs = true)
522
+	{
523
+		$reg_final_price_per_ticket_line_item = EEH_Line_Item::calculate_reg_final_prices_per_line_item(
524
+			$transaction->total_line_item()
525
+		);
526
+		foreach ($transaction->registrations() as $registration) {
527
+			/** @var EE_Line_Item $line_item */
528
+			$line_item = EEM_Line_Item::instance()->get_line_item_for_registration($registration);
529
+			if (isset($reg_final_price_per_ticket_line_item[$line_item->ID()])) {
530
+				$registration->set_final_price($reg_final_price_per_ticket_line_item[$line_item->ID()]);
531
+				if ($save_regs) {
532
+					$registration->save();
533
+				}
534
+			}
535
+		}
536
+		//and make sure there's no rounding problem
537
+		$this->fix_reg_final_price_rounding_issue($transaction);
538
+	}
539
+
540
+
541
+
542
+	/**
543
+	 * Makes sure there is no rounding errors for the REG_final_prices.
544
+	 * Eg, if we have 3 registrations for $1, and there is a $0.01 discount between the three of them,
545
+	 * they will each be for $0.99333333, which gets rounded to $1 again.
546
+	 * So the transaction total will be $2.99, but each registration will be for $1,
547
+	 * so if each registrant paid individually they will have overpaid by $0.01.
548
+	 * So in order to overcome this, we check for any difference, and if there is a difference
549
+	 * we just grab one registrant at random and make them responsible for it.
550
+	 * This should be used after setting REG_final_prices (it's done automatically as part of
551
+	 * EE_Registration_Processor::update_registration_final_prices())
552
+	 *
553
+	 * @param EE_Transaction $transaction
554
+	 * @return bool success verifying that there is NO difference after this method is done
555
+	 * @throws EE_Error
556
+	 * @throws InvalidArgumentException
557
+	 * @throws InvalidDataTypeException
558
+	 * @throws InvalidInterfaceException
559
+	 */
560
+	public function fix_reg_final_price_rounding_issue($transaction)
561
+	{
562
+		$reg_final_price_sum = EEM_Registration::instance()->sum(
563
+			array(
564
+				array(
565
+					'TXN_ID' => $transaction->ID(),
566
+				),
567
+			),
568
+			'REG_final_price'
569
+		);
570
+		$diff = $transaction->total() - $reg_final_price_sum;
571
+		//ok then, just grab one of the registrations
572
+		if ($diff !== 0) {
573
+			$a_reg   = EEM_Registration::instance()->get_one(
574
+				array(
575
+					array(
576
+						'TXN_ID' => $transaction->ID(),
577
+					),
578
+				)
579
+			);
580
+			return $a_reg instanceof EE_Registration
581
+				? (bool) $a_reg->save(array('REG_final_price' => $a_reg->final_price() + $diff))
582
+				: false;
583
+		}
584
+		return true;
585
+	}
586
+
587
+
588
+
589
+	/**
590
+	 * update_registration_after_being_canceled_or_declined
591
+	 *
592
+	 * @param EE_Registration $registration
593
+	 * @param array           $closed_reg_statuses
594
+	 * @param bool            $update_reg
595
+	 * @return bool
596
+	 * @throws EE_Error
597
+	 * @throws RuntimeException
598
+	 */
599
+	public function update_registration_after_being_canceled_or_declined(
600
+		EE_Registration $registration,
601
+		array $closed_reg_statuses = array(),
602
+		$update_reg = true
603
+	) {
604
+		// these reg statuses should not be considered in any calculations involving monies owing
605
+		$closed_reg_statuses = ! empty($closed_reg_statuses)
606
+			? $closed_reg_statuses
607
+			: EEM_Registration::closed_reg_statuses();
608
+		if (! in_array($registration->status_ID(), $closed_reg_statuses, true)) {
609
+			return false;
610
+		}
611
+		// release a reserved ticket by decrementing ticket and datetime reserved values
612
+		$registration->release_reserved_ticket(true);
613
+		$registration->set_final_price(0);
614
+		if ($update_reg) {
615
+			$registration->save();
616
+		}
617
+		return true;
618
+	}
619
+
620
+
621
+
622
+	/**
623
+	 * update_canceled_or_declined_registration_after_being_reinstated
624
+	 *
625
+	 * @param EE_Registration $registration
626
+	 * @param array           $closed_reg_statuses
627
+	 * @param bool            $update_reg
628
+	 * @return bool
629
+	 * @throws EE_Error
630
+	 * @throws RuntimeException
631
+	 */
632
+	public function update_canceled_or_declined_registration_after_being_reinstated(
633
+		EE_Registration $registration,
634
+		array $closed_reg_statuses = array(),
635
+		$update_reg = true
636
+	) {
637
+		// these reg statuses should not be considered in any calculations involving monies owing
638
+		$closed_reg_statuses = ! empty($closed_reg_statuses) ? $closed_reg_statuses
639
+			: EEM_Registration::closed_reg_statuses();
640
+		if (in_array($registration->status_ID(), $closed_reg_statuses, true)) {
641
+			return false;
642
+		}
643
+		$ticket = $registration->ticket();
644
+		if (! $ticket instanceof EE_Ticket) {
645
+			throw new EE_Error(
646
+				sprintf(
647
+					esc_html__(
648
+						'The Ticket for Registration %1$d was not found or is invalid.',
649
+						'event_espresso'
650
+					),
651
+					$registration->ticket_ID()
652
+				)
653
+			);
654
+		}
655
+		$registration->set_final_price($ticket->price());
656
+		if ($update_reg) {
657
+			$registration->save();
658
+		}
659
+		return true;
660
+	}
661
+
662
+
663
+
664
+	/**
665
+	 * generate_ONE_registration_from_line_item
666
+	 * Although a ticket line item may have a quantity greater than 1,
667
+	 * this method will ONLY CREATE ONE REGISTRATION !!!
668
+	 * Regardless of the ticket line item quantity.
669
+	 * This means that any code calling this method is responsible for ensuring
670
+	 * that the final registration count matches the ticket line item quantity.
671
+	 * This was done to make it easier to match the number of registrations
672
+	 * to the number of tickets in the cart, when the cart has been edited
673
+	 * after SPCO has already been initialized. So if an additional ticket was added to the cart, you can simply pass
674
+	 * the line item to this method to add a second ticket, and in this case, you would not want to add 2 tickets.
675
+	 *
676
+	 * @deprecated
677
+	 * @since 4.9.1
678
+	 * @param EE_Line_Item    $line_item
679
+	 * @param \EE_Transaction $transaction
680
+	 * @param int             $att_nmbr
681
+	 * @param int             $total_ticket_count
682
+	 * @return EE_Registration | null
683
+	 * @throws \OutOfRangeException
684
+	 * @throws \EventEspresso\core\exceptions\UnexpectedEntityException
685
+	 * @throws \EE_Error
686
+	 */
687
+	public function generate_ONE_registration_from_line_item(
688
+		EE_Line_Item $line_item,
689
+		EE_Transaction $transaction,
690
+		$att_nmbr = 1,
691
+		$total_ticket_count = 1
692
+	) {
693
+		EE_Error::doing_it_wrong(
694
+			__CLASS__ . '::' . __FUNCTION__,
695
+			sprintf(
696
+				esc_html__('This method is deprecated. Please use "%s" instead', 'event_espresso'),
697
+				'\EventEspresso\core\domain\services\registration\CreateRegistrationService::create()'
698
+			),
699
+			'4.9.1',
700
+			'5.0.0'
701
+		);
702
+		// grab the related ticket object for this line_item
703
+		$ticket = $line_item->ticket();
704
+		if (! $ticket instanceof EE_Ticket) {
705
+			EE_Error::add_error(
706
+				sprintf(
707
+					esc_html__('Line item %s did not contain a valid ticket', 'event_espresso'),
708
+					$line_item->ID()
709
+				),
710
+				__FILE__,
711
+				__FUNCTION__,
712
+				__LINE__
713
+			);
714
+			return null;
715
+		}
716
+		$registration_service = new CreateRegistrationService();
717
+		// then generate a new registration from that
718
+		return $registration_service->create(
719
+			$ticket->get_related_event(),
720
+			$transaction,
721
+			$ticket,
722
+			$line_item,
723
+			$att_nmbr,
724
+			$total_ticket_count
725
+		);
726
+	}
727
+
728
+
729
+
730
+	/**
731
+	 * generates reg_url_link
732
+	 *
733
+	 * @deprecated
734
+	 * @since 4.9.1
735
+	 * @param int                   $att_nmbr
736
+	 * @param EE_Line_Item | string $item
737
+	 * @return string
738
+	 * @throws InvalidArgumentException
739
+	 */
740
+	public function generate_reg_url_link($att_nmbr, $item)
741
+	{
742
+		EE_Error::doing_it_wrong(
743
+			__CLASS__ . '::' . __FUNCTION__,
744
+			sprintf(
745
+				esc_html__('This method is deprecated. Please use "%s" instead', 'event_espresso'),
746
+				'EventEspresso\core\domain\entities\RegUrlLink'
747
+			),
748
+			'4.9.1',
749
+			'5.0.0'
750
+		);
751
+		return new RegUrlLink($att_nmbr, $item);
752
+	}
753
+
754
+
755
+
756
+	/**
757
+	 * generates reg code
758
+	 *
759
+	 * @deprecated
760
+	 * @since 4.9.1
761
+	 * @param EE_Registration $registration
762
+	 * @return string
763
+	 * @throws EE_Error
764
+	 * @throws EntityNotFoundException
765
+	 * @throws InvalidArgumentException
766
+	 */
767
+	public function generate_reg_code(EE_Registration $registration)
768
+	{
769
+		EE_Error::doing_it_wrong(
770
+			__CLASS__ . '::' . __FUNCTION__,
771
+			sprintf(
772
+				esc_html__('This method is deprecated. Please use "%s" instead', 'event_espresso'),
773
+				'EventEspresso\core\domain\entities\RegCode'
774
+			),
775
+			'4.9.1',
776
+			'5.0.0'
777
+		);
778
+		return apply_filters(
779
+			'FHEE__EE_Registration_Processor___generate_reg_code__new_reg_code',
780
+			new RegCode(
781
+				RegUrlLink::fromRegistration($registration),
782
+				$registration->transaction(),
783
+				$registration->ticket()
784
+			),
785
+			$registration
786
+		);
787
+	}
788 788
 
789 789
 
790 790
 
Please login to merge, or discard this patch.
core/EE_Payment_Processor.core.php 2 patches
Indentation   +857 added lines, -857 removed lines patch added patch discarded remove patch
@@ -21,861 +21,861 @@
 block discarded – undo
21 21
 class EE_Payment_Processor extends EE_Processor_Base implements ResettableInterface
22 22
 {
23 23
 
24
-    /**
25
-     * @var EE_Payment_Processor $_instance
26
-     * @access    private
27
-     */
28
-    private static $_instance;
29
-
30
-
31
-
32
-    /**
33
-     * @singleton method used to instantiate class object
34
-     * @access    public
35
-     * @return EE_Payment_Processor instance
36
-     */
37
-    public static function instance()
38
-    {
39
-        // check if class object is instantiated
40
-        if (! self::$_instance instanceof EE_Payment_Processor) {
41
-            self::$_instance = new self();
42
-        }
43
-        return self::$_instance;
44
-    }
45
-
46
-
47
-
48
-    /**
49
-     * @return EE_Payment_Processor
50
-     */
51
-    public static function reset()
52
-    {
53
-        self::$_instance = null;
54
-        return self::instance();
55
-    }
56
-
57
-
58
-
59
-    /**
60
-     *private constructor to prevent direct creation
61
-     *
62
-     * @Constructor
63
-     * @access private
64
-     */
65
-    private function __construct()
66
-    {
67
-        do_action('AHEE__EE_Payment_Processor__construct');
68
-        add_action('http_api_curl', array($this, '_curl_requests_to_paypal_use_tls'), 10, 3);
69
-    }
70
-
71
-
72
-
73
-    /**
74
-     * Using the selected gateway, processes the payment for that transaction, and updates the transaction
75
-     * appropriately. Saves the payment that is generated
76
-     *
77
-     * @param EE_Payment_Method    $payment_method
78
-     * @param EE_Transaction       $transaction
79
-     * @param float                $amount       if only part of the transaction is to be paid for, how much.
80
-     *                                           Leave null if payment is for the full amount owing
81
-     * @param EE_Billing_Info_Form $billing_form (or probably null, if it's an offline or offsite payment method).
82
-     *                                           Receive_form_submission() should have
83
-     *                                           already been called on the billing form
84
-     *                                           (ie, its inputs should have their normalized values set).
85
-     * @param string               $return_url   string used mostly by offsite gateways to specify
86
-     *                                           where to go AFTER the offsite gateway
87
-     * @param string               $method       like 'CART', indicates who the client who called this was
88
-     * @param bool                 $by_admin     TRUE if payment is being attempted from the admin
89
-     * @param boolean              $update_txn   whether or not to call
90
-     *                                           EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
91
-     * @param string               $cancel_url   URL to return to if off-site payments are cancelled
92
-     * @return EE_Payment
93
-     * @throws EE_Error
94
-     * @throws InvalidArgumentException
95
-     * @throws ReflectionException
96
-     * @throws RuntimeException
97
-     * @throws InvalidDataTypeException
98
-     * @throws InvalidInterfaceException
99
-     */
100
-    public function process_payment(
101
-        EE_Payment_Method $payment_method,
102
-        EE_Transaction $transaction,
103
-        $amount = null,
104
-        $billing_form = null,
105
-        $return_url = null,
106
-        $method = 'CART',
107
-        $by_admin = false,
108
-        $update_txn = true,
109
-        $cancel_url = ''
110
-    ) {
111
-        if ((float)$amount < 0) {
112
-            throw new EE_Error(
113
-                sprintf(
114
-                    __(
115
-                        'Attempting to make a payment for a negative amount of %1$d for transaction %2$d. That should be a refund',
116
-                        'event_espresso'
117
-                    ),
118
-                    $amount,
119
-                    $transaction->ID()
120
-                )
121
-            );
122
-        }
123
-        // verify payment method
124
-        $payment_method = EEM_Payment_Method::instance()->ensure_is_obj(
125
-            $payment_method,
126
-            true
127
-        );
128
-        // verify transaction
129
-        EEM_Transaction::instance()->ensure_is_obj($transaction);
130
-        $transaction->set_payment_method_ID($payment_method->ID());
131
-        // verify payment method type
132
-        if ($payment_method->type_obj() instanceof EE_PMT_Base) {
133
-            $payment = $payment_method->type_obj()->process_payment(
134
-                $transaction,
135
-                min($amount, $transaction->remaining()),//make sure we don't overcharge
136
-                $billing_form,
137
-                $return_url,
138
-                add_query_arg(array('ee_cancel_payment' => true), $cancel_url),
139
-                $method,
140
-                $by_admin
141
-            );
142
-            // check if payment method uses an off-site gateway
143
-            if ($payment_method->type_obj()->payment_occurs() !== EE_PMT_Base::offsite) {
144
-                // don't process payments for off-site gateways yet because no payment has occurred yet
145
-                $this->update_txn_based_on_payment($transaction, $payment, $update_txn);
146
-            }
147
-            return $payment;
148
-        }
149
-        EE_Error::add_error(
150
-            sprintf(
151
-                __(
152
-                    'A valid payment method could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.',
153
-                    'event_espresso'
154
-                ),
155
-                '<br/>',
156
-                EE_Registry::instance()->CFG->organization->get_pretty('email')
157
-            ),
158
-            __FILE__,
159
-            __FUNCTION__,
160
-            __LINE__
161
-        );
162
-        return null;
163
-    }
164
-
165
-
166
-
167
-    /**
168
-     * @param EE_Transaction|int $transaction
169
-     * @param EE_Payment_Method  $payment_method
170
-     * @return string
171
-     * @throws EE_Error
172
-     * @throws InvalidArgumentException
173
-     * @throws InvalidDataTypeException
174
-     * @throws InvalidInterfaceException
175
-     */
176
-    public function get_ipn_url_for_payment_method($transaction, $payment_method)
177
-    {
178
-        /** @type \EE_Transaction $transaction */
179
-        $transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
180
-        $primary_reg = $transaction->primary_registration();
181
-        if (! $primary_reg instanceof EE_Registration) {
182
-            throw new EE_Error(
183
-                sprintf(
184
-                    __(
185
-                        'Cannot get IPN URL for transaction with ID %d because it has no primary registration',
186
-                        'event_espresso'
187
-                    ),
188
-                    $transaction->ID()
189
-                )
190
-            );
191
-        }
192
-        $payment_method = EEM_Payment_Method::instance()->ensure_is_obj(
193
-            $payment_method,
194
-            true
195
-        );
196
-        $url            = add_query_arg(
197
-            array(
198
-                'e_reg_url_link'    => $primary_reg->reg_url_link(),
199
-                'ee_payment_method' => $payment_method->slug(),
200
-            ),
201
-            EE_Registry::instance()->CFG->core->txn_page_url()
202
-        );
203
-        return $url;
204
-    }
205
-
206
-
207
-
208
-    /**
209
-     * Process the IPN. Firstly, we'll hope we put the standard args into the IPN URL so
210
-     * we can easily find what registration the IPN is for and what payment method.
211
-     * However, if not, we'll give all payment methods a chance to claim it and process it.
212
-     * If a payment is found for the IPN info, it is saved.
213
-     *
214
-     * @param array              $_req_data            eg $_REQUEST
215
-     * @param EE_Transaction|int $transaction          optional (or a transactions id)
216
-     * @param EE_Payment_Method  $payment_method       (or a slug or id of one)
217
-     * @param boolean            $update_txn           whether or not to call
218
-     *                                                 EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
219
-     * @param bool               $separate_IPN_request whether the IPN uses a separate request ( true like PayPal )
220
-     *                                                 or is processed manually ( false like Mijireh )
221
-     * @throws EE_Error
222
-     * @throws Exception
223
-     * @return EE_Payment
224
-     * @throws \RuntimeException
225
-     * @throws \ReflectionException
226
-     * @throws \InvalidArgumentException
227
-     * @throws InvalidInterfaceException
228
-     * @throws InvalidDataTypeException
229
-     */
230
-    public function process_ipn(
231
-        $_req_data,
232
-        $transaction = null,
233
-        $payment_method = null,
234
-        $update_txn = true,
235
-        $separate_IPN_request = true
236
-    ) {
237
-        EE_Registry::instance()->load_model('Change_Log');
238
-        $_req_data = $this->_remove_unusable_characters_from_array((array)$_req_data);
239
-        EE_Processor_Base::set_IPN($separate_IPN_request);
240
-        $obj_for_log = null;
241
-        if ($transaction instanceof EE_Transaction) {
242
-            $obj_for_log = $transaction;
243
-            if ($payment_method instanceof EE_Payment_Method) {
244
-                $obj_for_log = EEM_Payment::instance()->get_one(
245
-                    array(
246
-                        array('TXN_ID' => $transaction->ID(), 'PMD_ID' => $payment_method->ID()),
247
-                        'order_by' => array('PAY_timestamp' => 'desc'),
248
-                    )
249
-                );
250
-            }
251
-        } elseif ($payment_method instanceof EE_Payment) {
252
-            $obj_for_log = $payment_method;
253
-        }
254
-        $log = EEM_Change_Log::instance()->log(
255
-            EEM_Change_Log::type_gateway,
256
-            array('IPN data received' => $_req_data),
257
-            $obj_for_log
258
-        );
259
-        try {
260
-            /**
261
-             * @var EE_Payment $payment
262
-             */
263
-            $payment = null;
264
-            if ($transaction && $payment_method) {
265
-                /** @type EE_Transaction $transaction */
266
-                $transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
267
-                /** @type EE_Payment_Method $payment_method */
268
-                $payment_method = EEM_Payment_Method::instance()->ensure_is_obj($payment_method);
269
-                if ($payment_method->type_obj() instanceof EE_PMT_Base) {
270
-                    try {
271
-                        $payment = $payment_method->type_obj()->handle_ipn($_req_data, $transaction);
272
-                        $log->set_object($payment);
273
-                    } catch (EventEspresso\core\exceptions\IpnException $e) {
274
-                        EEM_Change_Log::instance()->log(
275
-                            EEM_Change_Log::type_gateway,
276
-                            array(
277
-                                'message'     => 'IPN Exception: ' . $e->getMessage(),
278
-                                'current_url' => EEH_URL::current_url(),
279
-                                'payment'     => $e->getPaymentProperties(),
280
-                                'IPN_data'    => $e->getIpnData(),
281
-                            ),
282
-                            $obj_for_log
283
-                        );
284
-                        return $e->getPayment();
285
-                    }
286
-                } else {
287
-                    // not a payment
288
-                    EE_Error::add_error(
289
-                        sprintf(
290
-                            __(
291
-                                'A valid payment method could not be determined due to a technical issue.%sPlease refresh your browser and try again or contact %s for assistance.',
292
-                                'event_espresso'
293
-                            ),
294
-                            '<br/>',
295
-                            EE_Registry::instance()->CFG->organization->get_pretty('email')
296
-                        ),
297
-                        __FILE__,
298
-                        __FUNCTION__,
299
-                        __LINE__
300
-                    );
301
-                }
302
-            } else {
303
-                //that's actually pretty ok. The IPN just wasn't able
304
-                //to identify which transaction or payment method this was for
305
-                // give all active payment methods a chance to claim it
306
-                $active_payment_methods = EEM_Payment_Method::instance()->get_all_active();
307
-                foreach ($active_payment_methods as $active_payment_method) {
308
-                    try {
309
-                        $payment        = $active_payment_method->type_obj()->handle_unclaimed_ipn($_req_data);
310
-                        $payment_method = $active_payment_method;
311
-                        EEM_Change_Log::instance()->log(
312
-                            EEM_Change_Log::type_gateway,
313
-                            array('IPN data' => $_req_data),
314
-                            $payment
315
-                        );
316
-                        break;
317
-                    } catch (EventEspresso\core\exceptions\IpnException $e) {
318
-                        EEM_Change_Log::instance()->log(
319
-                            EEM_Change_Log::type_gateway,
320
-                            array(
321
-                                'message'     => 'IPN Exception: ' . $e->getMessage(),
322
-                                'current_url' => EEH_URL::current_url(),
323
-                                'payment'     => $e->getPaymentProperties(),
324
-                                'IPN_data'    => $e->getIpnData(),
325
-                            ),
326
-                            $obj_for_log
327
-                        );
328
-                        return $e->getPayment();
329
-                    } catch (EE_Error $e) {
330
-                        // that's fine- it apparently couldn't handle the IPN
331
-                    }
332
-                }
333
-            }
334
-            // EEM_Payment_Log::instance()->log("got to 7",$transaction,$payment_method);
335
-            if ($payment instanceof EE_Payment) {
336
-                $payment->save();
337
-                //  update the TXN
338
-                $this->update_txn_based_on_payment(
339
-                    $transaction,
340
-                    $payment,
341
-                    $update_txn,
342
-                    $separate_IPN_request
343
-                );
344
-            } else {
345
-                //we couldn't find the payment for this IPN... let's try and log at least SOMETHING
346
-                if ($payment_method) {
347
-                    EEM_Change_Log::instance()->log(
348
-                        EEM_Change_Log::type_gateway,
349
-                        array('IPN data' => $_req_data),
350
-                        $payment_method
351
-                    );
352
-                } elseif ($transaction) {
353
-                    EEM_Change_Log::instance()->log(
354
-                        EEM_Change_Log::type_gateway,
355
-                        array('IPN data' => $_req_data),
356
-                        $transaction
357
-                    );
358
-                }
359
-            }
360
-            return $payment;
361
-        } catch (EE_Error $e) {
362
-            do_action(
363
-                'AHEE__log',
364
-                __FILE__,
365
-                __FUNCTION__,
366
-                sprintf(
367
-                    __(
368
-                        'Error occurred while receiving IPN. Transaction: %1$s, req data: %2$s. The error was "%3$s"',
369
-                        'event_espresso'
370
-                    ),
371
-                    print_r($transaction, true),
372
-                    print_r($_req_data, true),
373
-                    $e->getMessage()
374
-                )
375
-            );
376
-            throw $e;
377
-        }
378
-    }
379
-
380
-
381
-
382
-    /**
383
-     * Removes any non-printable illegal characters from the input,
384
-     * which might cause a raucous when trying to insert into the database
385
-     *
386
-     * @param  array $request_data
387
-     * @return array
388
-     */
389
-    protected function _remove_unusable_characters_from_array(array $request_data)
390
-    {
391
-        $return_data = array();
392
-        foreach ($request_data as $key => $value) {
393
-            $return_data[$this->_remove_unusable_characters($key)] = $this->_remove_unusable_characters(
394
-                $value
395
-            );
396
-        }
397
-        return $return_data;
398
-    }
399
-
400
-
401
-
402
-    /**
403
-     * Removes any non-printable illegal characters from the input,
404
-     * which might cause a raucous when trying to insert into the database
405
-     *
406
-     * @param string $request_data
407
-     * @return string
408
-     */
409
-    protected function _remove_unusable_characters($request_data)
410
-    {
411
-        return preg_replace('/[^[:print:]]/', '', $request_data);
412
-    }
413
-
414
-
415
-
416
-    /**
417
-     * Should be called just before displaying the payment attempt results to the user,
418
-     * when the payment attempt has finished. Some payment methods may have special
419
-     * logic to perform here. For example, if process_payment() happens on a special request
420
-     * and then the user is redirected to a page that displays the payment's status, this
421
-     * should be called while loading the page that displays the payment's status. If the user is
422
-     * sent to an offsite payment provider, this should be called upon returning from that offsite payment
423
-     * provider.
424
-     *
425
-     * @param EE_Transaction|int $transaction
426
-     * @param bool               $update_txn whether or not to call
427
-     *                                       EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
428
-     * @return EE_Payment
429
-     * @throws EE_Error
430
-     * @throws InvalidArgumentException
431
-     * @throws ReflectionException
432
-     * @throws RuntimeException
433
-     * @throws InvalidDataTypeException
434
-     * @throws InvalidInterfaceException
435
-     * @deprecated 4.6.24 method is no longer used. Instead it is up to client code, like SPCO,
436
-     *                                       to call handle_ipn() for offsite gateways that don't receive separate IPNs
437
-     */
438
-    public function finalize_payment_for($transaction, $update_txn = true)
439
-    {
440
-        /** @var $transaction EE_Transaction */
441
-        $transaction         = EEM_Transaction::instance()->ensure_is_obj($transaction);
442
-        $last_payment_method = $transaction->payment_method();
443
-        if ($last_payment_method instanceof EE_Payment_Method) {
444
-            $payment = $last_payment_method->type_obj()->finalize_payment_for($transaction);
445
-            $this->update_txn_based_on_payment($transaction, $payment, $update_txn);
446
-            return $payment;
447
-        }
448
-        return null;
449
-    }
450
-
451
-
452
-
453
-    /**
454
-     * Processes a direct refund request, saves the payment, and updates the transaction appropriately.
455
-     *
456
-     * @param EE_Payment_Method $payment_method
457
-     * @param EE_Payment        $payment_to_refund
458
-     * @param array             $refund_info
459
-     * @return EE_Payment
460
-     * @throws EE_Error
461
-     * @throws InvalidArgumentException
462
-     * @throws ReflectionException
463
-     * @throws RuntimeException
464
-     * @throws InvalidDataTypeException
465
-     * @throws InvalidInterfaceException
466
-     */
467
-    public function process_refund(
468
-        EE_Payment_Method $payment_method,
469
-        EE_Payment $payment_to_refund,
470
-        array $refund_info = array()
471
-    ) {
472
-        if ($payment_method instanceof EE_Payment_Method && $payment_method->type_obj()->supports_sending_refunds()) {
473
-            $payment_method->type_obj()->process_refund($payment_to_refund, $refund_info);
474
-            $this->update_txn_based_on_payment($payment_to_refund->transaction(), $payment_to_refund);
475
-        }
476
-        return $payment_to_refund;
477
-    }
478
-
479
-
480
-
481
-    /**
482
-     * This should be called each time there may have been an update to a
483
-     * payment on a transaction (ie, we asked for a payment to process a
484
-     * payment for a transaction, or we told a payment method about an IPN, or
485
-     * we told a payment method to
486
-     * "finalize_payment_for" (a transaction), or we told a payment method to
487
-     * process a refund. This should handle firing the correct hooks to
488
-     * indicate
489
-     * what exactly happened and updating the transaction appropriately). This
490
-     * could be integrated directly into EE_Transaction upon save, but we want
491
-     * this logic to be separate from 'normal' plain-jane saving and updating
492
-     * of transactions and payments, and to be tied to payment processing.
493
-     * Note: this method DOES NOT save the payment passed into it. It is the responsibility
494
-     * of previous code to decide whether or not to save (because the payment passed into
495
-     * this method might be a temporary, never-to-be-saved payment from an offline gateway,
496
-     * in which case we only want that payment object for some temporary usage during this request,
497
-     * but we don't want it to be saved).
498
-     *
499
-     * @param EE_Transaction|int $transaction
500
-     * @param EE_Payment         $payment
501
-     * @param boolean            $update_txn
502
-     *                        whether or not to call
503
-     *                        EE_Transaction_Processor::
504
-     *                        update_transaction_and_registrations_after_checkout_or_payment()
505
-     *                        (you can save 1 DB query if you know you're going
506
-     *                        to save it later instead)
507
-     * @param bool               $IPN
508
-     *                        if processing IPNs or other similar payment
509
-     *                        related activities that occur in alternate
510
-     *                        requests than the main one that is processing the
511
-     *                        TXN, then set this to true to check whether the
512
-     *                        TXN is locked before updating
513
-     * @throws EE_Error
514
-     * @throws InvalidArgumentException
515
-     * @throws ReflectionException
516
-     * @throws RuntimeException
517
-     * @throws InvalidDataTypeException
518
-     * @throws InvalidInterfaceException
519
-     */
520
-    public function update_txn_based_on_payment($transaction, $payment, $update_txn = true, $IPN = false)
521
-    {
522
-        $do_action = 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__not_successful';
523
-        /** @type EE_Transaction $transaction */
524
-        $transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
525
-        // can we freely update the TXN at this moment?
526
-        if ($IPN && $transaction->is_locked()) {
527
-            // don't update the transaction at this exact moment
528
-            // because the TXN is active in another request
529
-            EE_Cron_Tasks::schedule_update_transaction_with_payment(
530
-                time(),
531
-                $transaction->ID(),
532
-                $payment->ID()
533
-            );
534
-        } else {
535
-            // verify payment and that it has been saved
536
-            if ($payment instanceof EE_Payment && $payment->ID()) {
537
-                if (
538
-                    $payment->payment_method() instanceof EE_Payment_Method
539
-                    && $payment->payment_method()->type_obj() instanceof EE_PMT_Base
540
-                ) {
541
-                    $payment->payment_method()->type_obj()->update_txn_based_on_payment($payment);
542
-                    // update TXN registrations with payment info
543
-                    $this->process_registration_payments($transaction, $payment);
544
-                }
545
-                $do_action = $payment->just_approved()
546
-                    ? 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__successful'
547
-                    : $do_action;
548
-            } else {
549
-                // send out notifications
550
-                add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
551
-                $do_action = 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__no_payment_made';
552
-            }
553
-            if ($payment instanceof EE_Payment && $payment->status() !== EEM_Payment::status_id_failed) {
554
-                /** @type EE_Transaction_Payments $transaction_payments */
555
-                $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
556
-                // set new value for total paid
557
-                $transaction_payments->calculate_total_payments_and_update_status($transaction);
558
-                // call EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment() ???
559
-                if ($update_txn) {
560
-                    $this->_post_payment_processing($transaction, $payment, $IPN);
561
-                }
562
-            }
563
-            // granular hook for others to use.
564
-            do_action($do_action, $transaction, $payment);
565
-            do_action('AHEE_log', __CLASS__, __FUNCTION__, $do_action, '$do_action');
566
-            //global hook for others to use.
567
-            do_action('AHEE__EE_Payment_Processor__update_txn_based_on_payment', $transaction, $payment);
568
-        }
569
-    }
570
-
571
-
572
-
573
-    /**
574
-     * update registrations REG_paid field after successful payment and link registrations with payment
575
-     *
576
-     * @param EE_Transaction    $transaction
577
-     * @param EE_Payment        $payment
578
-     * @param EE_Registration[] $registrations
579
-     * @throws EE_Error
580
-     * @throws InvalidArgumentException
581
-     * @throws RuntimeException
582
-     * @throws InvalidDataTypeException
583
-     * @throws InvalidInterfaceException
584
-     */
585
-    public function process_registration_payments(
586
-        EE_Transaction $transaction,
587
-        EE_Payment $payment,
588
-        array $registrations = array()
589
-    ) {
590
-        // only process if payment was successful
591
-        if ($payment->status() !== EEM_Payment::status_id_approved) {
592
-            return;
593
-        }
594
-        //EEM_Registration::instance()->show_next_x_db_queries();
595
-        if (empty($registrations)) {
596
-            // find registrations with monies owing that can receive a payment
597
-            $registrations = $transaction->registrations(
598
-                array(
599
-                    array(
600
-                        // only these reg statuses can receive payments
601
-                        'STS_ID'           => array('IN', EEM_Registration::reg_statuses_that_allow_payment()),
602
-                        'REG_final_price'  => array('!=', 0),
603
-                        'REG_final_price*' => array('!=', 'REG_paid', true),
604
-                    ),
605
-                )
606
-            );
607
-        }
608
-        // still nothing ??!??
609
-        if (empty($registrations)) {
610
-            return;
611
-        }
612
-        // todo: break out the following logic into a separate strategy class
613
-        // todo: named something like "Sequential_Reg_Payment_Strategy"
614
-        // todo: which would apply payments using the capitalist "first come first paid" approach
615
-        // todo: then have another strategy class like "Distributed_Reg_Payment_Strategy"
616
-        // todo: which would be the socialist "everybody gets a piece of pie" approach,
617
-        // todo: which would be better for deposits, where you want a bit of the payment applied to each registration
618
-        $refund = $payment->is_a_refund();
619
-        // how much is available to apply to registrations?
620
-        $available_payment_amount = abs($payment->amount());
621
-        foreach ($registrations as $registration) {
622
-            if ($registration instanceof EE_Registration) {
623
-                // nothing left?
624
-                if ($available_payment_amount <= 0) {
625
-                    break;
626
-                }
627
-                if ($refund) {
628
-                    $available_payment_amount = $this->process_registration_refund(
629
-                        $registration,
630
-                        $payment,
631
-                        $available_payment_amount
632
-                    );
633
-                } else {
634
-                    $available_payment_amount = $this->process_registration_payment(
635
-                        $registration,
636
-                        $payment,
637
-                        $available_payment_amount
638
-                    );
639
-                }
640
-            }
641
-        }
642
-        if ($available_payment_amount > 0
643
-            && apply_filters(
644
-                'FHEE__EE_Payment_Processor__process_registration_payments__display_notifications',
645
-                false
646
-            )) {
647
-            EE_Error::add_attention(
648
-                sprintf(
649
-                    __(
650
-                        'A remainder of %1$s exists after applying this payment to Registration(s) %2$s.%3$sPlease verify that the original payment amount of %4$s is correct. If so, you should edit this payment and select at least one additional registration in the "Registrations to Apply Payment to" section, so that the remainder of this payment can be applied to the additional registration(s).',
651
-                        'event_espresso'
652
-                    ),
653
-                    EEH_Template::format_currency($available_payment_amount),
654
-                    implode(', ', array_keys($registrations)),
655
-                    '<br/>',
656
-                    EEH_Template::format_currency($payment->amount())
657
-                ),
658
-                __FILE__,
659
-                __FUNCTION__,
660
-                __LINE__
661
-            );
662
-        }
663
-    }
664
-
665
-
666
-
667
-    /**
668
-     * update registration REG_paid field after successful payment and link registration with payment
669
-     *
670
-     * @param EE_Registration $registration
671
-     * @param EE_Payment      $payment
672
-     * @param float           $available_payment_amount
673
-     * @return float
674
-     * @throws EE_Error
675
-     * @throws InvalidArgumentException
676
-     * @throws RuntimeException
677
-     * @throws InvalidDataTypeException
678
-     * @throws InvalidInterfaceException
679
-     */
680
-    public function process_registration_payment(
681
-        EE_Registration $registration,
682
-        EE_Payment $payment,
683
-        $available_payment_amount = 0.00
684
-    ) {
685
-        $owing = $registration->final_price() - $registration->paid();
686
-        if ($owing > 0) {
687
-            // don't allow payment amount to exceed the available payment amount, OR the amount owing
688
-            $payment_amount = min($available_payment_amount, $owing);
689
-            // update $available_payment_amount
690
-            $available_payment_amount -= $payment_amount;
691
-            //calculate and set new REG_paid
692
-            $registration->set_paid($registration->paid() + $payment_amount);
693
-            // now save it
694
-            $this->_apply_registration_payment($registration, $payment, $payment_amount);
695
-        }
696
-        return $available_payment_amount;
697
-    }
698
-
699
-
700
-
701
-    /**
702
-     * update registration REG_paid field after successful payment and link registration with payment
703
-     *
704
-     * @param EE_Registration $registration
705
-     * @param EE_Payment      $payment
706
-     * @param float           $payment_amount
707
-     * @return void
708
-     * @throws EE_Error
709
-     * @throws InvalidArgumentException
710
-     * @throws InvalidDataTypeException
711
-     * @throws InvalidInterfaceException
712
-     */
713
-    protected function _apply_registration_payment(
714
-        EE_Registration $registration,
715
-        EE_Payment $payment,
716
-        $payment_amount = 0.00
717
-    ) {
718
-        // find any existing reg payment records for this registration and payment
719
-        $existing_reg_payment = EEM_Registration_Payment::instance()->get_one(
720
-            array(array('REG_ID' => $registration->ID(), 'PAY_ID' => $payment->ID()))
721
-        );
722
-        // if existing registration payment exists
723
-        if ($existing_reg_payment instanceof EE_Registration_Payment) {
724
-            // then update that record
725
-            $existing_reg_payment->set_amount($payment_amount);
726
-            $existing_reg_payment->save();
727
-        } else {
728
-            // or add new relation between registration and payment and set amount
729
-            $registration->_add_relation_to(
730
-                $payment,
731
-                'Payment',
732
-                array('RPY_amount' => $payment_amount)
733
-            );
734
-            // make it stick
735
-            $registration->save();
736
-        }
737
-    }
738
-
739
-
740
-
741
-    /**
742
-     * update registration REG_paid field after refund and link registration with payment
743
-     *
744
-     * @param EE_Registration $registration
745
-     * @param EE_Payment      $payment
746
-     * @param float           $available_refund_amount - IMPORTANT !!! SEND AVAILABLE REFUND AMOUNT AS A POSITIVE NUMBER
747
-     * @return float
748
-     * @throws EE_Error
749
-     * @throws InvalidArgumentException
750
-     * @throws RuntimeException
751
-     * @throws InvalidDataTypeException
752
-     * @throws InvalidInterfaceException
753
-     */
754
-    public function process_registration_refund(
755
-        EE_Registration $registration,
756
-        EE_Payment $payment,
757
-        $available_refund_amount = 0.00
758
-    ) {
759
-        //EEH_Debug_Tools::printr( $payment->amount(), '$payment->amount()', __FILE__, __LINE__ );
760
-        if ($registration->paid() > 0) {
761
-            // ensure $available_refund_amount is NOT negative
762
-            $available_refund_amount = (float)abs($available_refund_amount);
763
-            // don't allow refund amount to exceed the available payment amount, OR the amount paid
764
-            $refund_amount = min($available_refund_amount, (float)$registration->paid());
765
-            // update $available_payment_amount
766
-            $available_refund_amount -= $refund_amount;
767
-            //calculate and set new REG_paid
768
-            $registration->set_paid($registration->paid() - $refund_amount);
769
-            // convert payment amount back to a negative value for storage in the db
770
-            $refund_amount = (float)abs($refund_amount) * -1;
771
-            // now save it
772
-            $this->_apply_registration_payment($registration, $payment, $refund_amount);
773
-        }
774
-        return $available_refund_amount;
775
-    }
776
-
777
-
778
-
779
-    /**
780
-     * Process payments and transaction after payment process completed.
781
-     * ultimately this will send the TXN and payment details off so that notifications can be sent out.
782
-     * if this request happens to be processing an IPN,
783
-     * then we will also set the Payment Options Reg Step to completed,
784
-     * and attempt to completely finalize the TXN if all of the other Reg Steps are completed as well.
785
-     *
786
-     * @param EE_Transaction $transaction
787
-     * @param EE_Payment     $payment
788
-     * @param bool           $IPN
789
-     * @throws EE_Error
790
-     * @throws InvalidArgumentException
791
-     * @throws ReflectionException
792
-     * @throws RuntimeException
793
-     * @throws InvalidDataTypeException
794
-     * @throws InvalidInterfaceException
795
-     */
796
-    protected function _post_payment_processing(EE_Transaction $transaction, EE_Payment $payment, $IPN = false)
797
-    {
798
-        /** @type EE_Transaction_Processor $transaction_processor */
799
-        $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
800
-        // is the Payment Options Reg Step completed ?
801
-        $payment_options_step_completed = $transaction->reg_step_completed('payment_options');
802
-        // if the Payment Options Reg Step is completed...
803
-        $revisit = $payment_options_step_completed === true;
804
-        // then this is kinda sorta a revisit with regards to payments at least
805
-        $transaction_processor->set_revisit($revisit);
806
-        // if this is an IPN, let's consider the Payment Options Reg Step completed if not already
807
-        if (
808
-            $IPN
809
-            && $payment_options_step_completed !== true
810
-            && ($payment->is_approved() || $payment->is_pending())
811
-        ) {
812
-            $payment_options_step_completed = $transaction->set_reg_step_completed(
813
-                'payment_options'
814
-            );
815
-        }
816
-        // maybe update status, but don't save transaction just yet
817
-        $transaction->update_status_based_on_total_paid(false);
818
-        // check if 'finalize_registration' step has been completed...
819
-        $finalized = $transaction->reg_step_completed('finalize_registration');
820
-        //  if this is an IPN and the final step has not been initiated
821
-        if ($IPN && $payment_options_step_completed && $finalized === false) {
822
-            // and if it hasn't already been set as being started...
823
-            $finalized = $transaction->set_reg_step_initiated('finalize_registration');
824
-        }
825
-        $transaction->save();
826
-        // because the above will return false if the final step was not fully completed, we need to check again...
827
-        if ($IPN && $finalized !== false) {
828
-            // and if we are all good to go, then send out notifications
829
-            add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
830
-            //ok, now process the transaction according to the payment
831
-            $transaction_processor->update_transaction_and_registrations_after_checkout_or_payment(
832
-                $transaction,
833
-                $payment
834
-            );
835
-        }
836
-        // DEBUG LOG
837
-        $payment_method = $payment->payment_method();
838
-        if ($payment_method instanceof EE_Payment_Method) {
839
-            $payment_method_type_obj = $payment_method->type_obj();
840
-            if ($payment_method_type_obj instanceof EE_PMT_Base) {
841
-                $gateway = $payment_method_type_obj->get_gateway();
842
-                if ($gateway instanceof EE_Gateway) {
843
-                    $gateway->log(
844
-                        array(
845
-                            'message'               => __('Post Payment Transaction Details', 'event_espresso'),
846
-                            'transaction'           => $transaction->model_field_array(),
847
-                            'finalized'             => $finalized,
848
-                            'IPN'                   => $IPN,
849
-                            'deliver_notifications' => has_filter(
850
-                                'FHEE__EED_Messages___maybe_registration__deliver_notifications'
851
-                            ),
852
-                        ),
853
-                        $payment
854
-                    );
855
-                }
856
-            }
857
-        }
858
-    }
859
-
860
-
861
-
862
-    /**
863
-     * Force posts to PayPal to use TLS v1.2. See:
864
-     * https://core.trac.wordpress.org/ticket/36320
865
-     * https://core.trac.wordpress.org/ticket/34924#comment:15
866
-     * https://www.paypal-knowledge.com/infocenter/index?page=content&widgetview=true&id=FAQ1914&viewlocale=en_US
867
-     * This will affect PayPal standard, pro, express, and Payflow.
868
-     *
869
-     * @param $handle
870
-     * @param $r
871
-     * @param $url
872
-     */
873
-    public static function _curl_requests_to_paypal_use_tls($handle, $r, $url)
874
-    {
875
-        if (strpos($url, 'https://') !== false && strpos($url, '.paypal.com') !== false) {
876
-            //Use the value of the constant CURL_SSLVERSION_TLSv1 = 1
877
-            //instead of the constant because it might not be defined
878
-            curl_setopt($handle, CURLOPT_SSLVERSION, 1);
879
-        }
880
-    }
24
+	/**
25
+	 * @var EE_Payment_Processor $_instance
26
+	 * @access    private
27
+	 */
28
+	private static $_instance;
29
+
30
+
31
+
32
+	/**
33
+	 * @singleton method used to instantiate class object
34
+	 * @access    public
35
+	 * @return EE_Payment_Processor instance
36
+	 */
37
+	public static function instance()
38
+	{
39
+		// check if class object is instantiated
40
+		if (! self::$_instance instanceof EE_Payment_Processor) {
41
+			self::$_instance = new self();
42
+		}
43
+		return self::$_instance;
44
+	}
45
+
46
+
47
+
48
+	/**
49
+	 * @return EE_Payment_Processor
50
+	 */
51
+	public static function reset()
52
+	{
53
+		self::$_instance = null;
54
+		return self::instance();
55
+	}
56
+
57
+
58
+
59
+	/**
60
+	 *private constructor to prevent direct creation
61
+	 *
62
+	 * @Constructor
63
+	 * @access private
64
+	 */
65
+	private function __construct()
66
+	{
67
+		do_action('AHEE__EE_Payment_Processor__construct');
68
+		add_action('http_api_curl', array($this, '_curl_requests_to_paypal_use_tls'), 10, 3);
69
+	}
70
+
71
+
72
+
73
+	/**
74
+	 * Using the selected gateway, processes the payment for that transaction, and updates the transaction
75
+	 * appropriately. Saves the payment that is generated
76
+	 *
77
+	 * @param EE_Payment_Method    $payment_method
78
+	 * @param EE_Transaction       $transaction
79
+	 * @param float                $amount       if only part of the transaction is to be paid for, how much.
80
+	 *                                           Leave null if payment is for the full amount owing
81
+	 * @param EE_Billing_Info_Form $billing_form (or probably null, if it's an offline or offsite payment method).
82
+	 *                                           Receive_form_submission() should have
83
+	 *                                           already been called on the billing form
84
+	 *                                           (ie, its inputs should have their normalized values set).
85
+	 * @param string               $return_url   string used mostly by offsite gateways to specify
86
+	 *                                           where to go AFTER the offsite gateway
87
+	 * @param string               $method       like 'CART', indicates who the client who called this was
88
+	 * @param bool                 $by_admin     TRUE if payment is being attempted from the admin
89
+	 * @param boolean              $update_txn   whether or not to call
90
+	 *                                           EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
91
+	 * @param string               $cancel_url   URL to return to if off-site payments are cancelled
92
+	 * @return EE_Payment
93
+	 * @throws EE_Error
94
+	 * @throws InvalidArgumentException
95
+	 * @throws ReflectionException
96
+	 * @throws RuntimeException
97
+	 * @throws InvalidDataTypeException
98
+	 * @throws InvalidInterfaceException
99
+	 */
100
+	public function process_payment(
101
+		EE_Payment_Method $payment_method,
102
+		EE_Transaction $transaction,
103
+		$amount = null,
104
+		$billing_form = null,
105
+		$return_url = null,
106
+		$method = 'CART',
107
+		$by_admin = false,
108
+		$update_txn = true,
109
+		$cancel_url = ''
110
+	) {
111
+		if ((float)$amount < 0) {
112
+			throw new EE_Error(
113
+				sprintf(
114
+					__(
115
+						'Attempting to make a payment for a negative amount of %1$d for transaction %2$d. That should be a refund',
116
+						'event_espresso'
117
+					),
118
+					$amount,
119
+					$transaction->ID()
120
+				)
121
+			);
122
+		}
123
+		// verify payment method
124
+		$payment_method = EEM_Payment_Method::instance()->ensure_is_obj(
125
+			$payment_method,
126
+			true
127
+		);
128
+		// verify transaction
129
+		EEM_Transaction::instance()->ensure_is_obj($transaction);
130
+		$transaction->set_payment_method_ID($payment_method->ID());
131
+		// verify payment method type
132
+		if ($payment_method->type_obj() instanceof EE_PMT_Base) {
133
+			$payment = $payment_method->type_obj()->process_payment(
134
+				$transaction,
135
+				min($amount, $transaction->remaining()),//make sure we don't overcharge
136
+				$billing_form,
137
+				$return_url,
138
+				add_query_arg(array('ee_cancel_payment' => true), $cancel_url),
139
+				$method,
140
+				$by_admin
141
+			);
142
+			// check if payment method uses an off-site gateway
143
+			if ($payment_method->type_obj()->payment_occurs() !== EE_PMT_Base::offsite) {
144
+				// don't process payments for off-site gateways yet because no payment has occurred yet
145
+				$this->update_txn_based_on_payment($transaction, $payment, $update_txn);
146
+			}
147
+			return $payment;
148
+		}
149
+		EE_Error::add_error(
150
+			sprintf(
151
+				__(
152
+					'A valid payment method could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.',
153
+					'event_espresso'
154
+				),
155
+				'<br/>',
156
+				EE_Registry::instance()->CFG->organization->get_pretty('email')
157
+			),
158
+			__FILE__,
159
+			__FUNCTION__,
160
+			__LINE__
161
+		);
162
+		return null;
163
+	}
164
+
165
+
166
+
167
+	/**
168
+	 * @param EE_Transaction|int $transaction
169
+	 * @param EE_Payment_Method  $payment_method
170
+	 * @return string
171
+	 * @throws EE_Error
172
+	 * @throws InvalidArgumentException
173
+	 * @throws InvalidDataTypeException
174
+	 * @throws InvalidInterfaceException
175
+	 */
176
+	public function get_ipn_url_for_payment_method($transaction, $payment_method)
177
+	{
178
+		/** @type \EE_Transaction $transaction */
179
+		$transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
180
+		$primary_reg = $transaction->primary_registration();
181
+		if (! $primary_reg instanceof EE_Registration) {
182
+			throw new EE_Error(
183
+				sprintf(
184
+					__(
185
+						'Cannot get IPN URL for transaction with ID %d because it has no primary registration',
186
+						'event_espresso'
187
+					),
188
+					$transaction->ID()
189
+				)
190
+			);
191
+		}
192
+		$payment_method = EEM_Payment_Method::instance()->ensure_is_obj(
193
+			$payment_method,
194
+			true
195
+		);
196
+		$url            = add_query_arg(
197
+			array(
198
+				'e_reg_url_link'    => $primary_reg->reg_url_link(),
199
+				'ee_payment_method' => $payment_method->slug(),
200
+			),
201
+			EE_Registry::instance()->CFG->core->txn_page_url()
202
+		);
203
+		return $url;
204
+	}
205
+
206
+
207
+
208
+	/**
209
+	 * Process the IPN. Firstly, we'll hope we put the standard args into the IPN URL so
210
+	 * we can easily find what registration the IPN is for and what payment method.
211
+	 * However, if not, we'll give all payment methods a chance to claim it and process it.
212
+	 * If a payment is found for the IPN info, it is saved.
213
+	 *
214
+	 * @param array              $_req_data            eg $_REQUEST
215
+	 * @param EE_Transaction|int $transaction          optional (or a transactions id)
216
+	 * @param EE_Payment_Method  $payment_method       (or a slug or id of one)
217
+	 * @param boolean            $update_txn           whether or not to call
218
+	 *                                                 EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
219
+	 * @param bool               $separate_IPN_request whether the IPN uses a separate request ( true like PayPal )
220
+	 *                                                 or is processed manually ( false like Mijireh )
221
+	 * @throws EE_Error
222
+	 * @throws Exception
223
+	 * @return EE_Payment
224
+	 * @throws \RuntimeException
225
+	 * @throws \ReflectionException
226
+	 * @throws \InvalidArgumentException
227
+	 * @throws InvalidInterfaceException
228
+	 * @throws InvalidDataTypeException
229
+	 */
230
+	public function process_ipn(
231
+		$_req_data,
232
+		$transaction = null,
233
+		$payment_method = null,
234
+		$update_txn = true,
235
+		$separate_IPN_request = true
236
+	) {
237
+		EE_Registry::instance()->load_model('Change_Log');
238
+		$_req_data = $this->_remove_unusable_characters_from_array((array)$_req_data);
239
+		EE_Processor_Base::set_IPN($separate_IPN_request);
240
+		$obj_for_log = null;
241
+		if ($transaction instanceof EE_Transaction) {
242
+			$obj_for_log = $transaction;
243
+			if ($payment_method instanceof EE_Payment_Method) {
244
+				$obj_for_log = EEM_Payment::instance()->get_one(
245
+					array(
246
+						array('TXN_ID' => $transaction->ID(), 'PMD_ID' => $payment_method->ID()),
247
+						'order_by' => array('PAY_timestamp' => 'desc'),
248
+					)
249
+				);
250
+			}
251
+		} elseif ($payment_method instanceof EE_Payment) {
252
+			$obj_for_log = $payment_method;
253
+		}
254
+		$log = EEM_Change_Log::instance()->log(
255
+			EEM_Change_Log::type_gateway,
256
+			array('IPN data received' => $_req_data),
257
+			$obj_for_log
258
+		);
259
+		try {
260
+			/**
261
+			 * @var EE_Payment $payment
262
+			 */
263
+			$payment = null;
264
+			if ($transaction && $payment_method) {
265
+				/** @type EE_Transaction $transaction */
266
+				$transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
267
+				/** @type EE_Payment_Method $payment_method */
268
+				$payment_method = EEM_Payment_Method::instance()->ensure_is_obj($payment_method);
269
+				if ($payment_method->type_obj() instanceof EE_PMT_Base) {
270
+					try {
271
+						$payment = $payment_method->type_obj()->handle_ipn($_req_data, $transaction);
272
+						$log->set_object($payment);
273
+					} catch (EventEspresso\core\exceptions\IpnException $e) {
274
+						EEM_Change_Log::instance()->log(
275
+							EEM_Change_Log::type_gateway,
276
+							array(
277
+								'message'     => 'IPN Exception: ' . $e->getMessage(),
278
+								'current_url' => EEH_URL::current_url(),
279
+								'payment'     => $e->getPaymentProperties(),
280
+								'IPN_data'    => $e->getIpnData(),
281
+							),
282
+							$obj_for_log
283
+						);
284
+						return $e->getPayment();
285
+					}
286
+				} else {
287
+					// not a payment
288
+					EE_Error::add_error(
289
+						sprintf(
290
+							__(
291
+								'A valid payment method could not be determined due to a technical issue.%sPlease refresh your browser and try again or contact %s for assistance.',
292
+								'event_espresso'
293
+							),
294
+							'<br/>',
295
+							EE_Registry::instance()->CFG->organization->get_pretty('email')
296
+						),
297
+						__FILE__,
298
+						__FUNCTION__,
299
+						__LINE__
300
+					);
301
+				}
302
+			} else {
303
+				//that's actually pretty ok. The IPN just wasn't able
304
+				//to identify which transaction or payment method this was for
305
+				// give all active payment methods a chance to claim it
306
+				$active_payment_methods = EEM_Payment_Method::instance()->get_all_active();
307
+				foreach ($active_payment_methods as $active_payment_method) {
308
+					try {
309
+						$payment        = $active_payment_method->type_obj()->handle_unclaimed_ipn($_req_data);
310
+						$payment_method = $active_payment_method;
311
+						EEM_Change_Log::instance()->log(
312
+							EEM_Change_Log::type_gateway,
313
+							array('IPN data' => $_req_data),
314
+							$payment
315
+						);
316
+						break;
317
+					} catch (EventEspresso\core\exceptions\IpnException $e) {
318
+						EEM_Change_Log::instance()->log(
319
+							EEM_Change_Log::type_gateway,
320
+							array(
321
+								'message'     => 'IPN Exception: ' . $e->getMessage(),
322
+								'current_url' => EEH_URL::current_url(),
323
+								'payment'     => $e->getPaymentProperties(),
324
+								'IPN_data'    => $e->getIpnData(),
325
+							),
326
+							$obj_for_log
327
+						);
328
+						return $e->getPayment();
329
+					} catch (EE_Error $e) {
330
+						// that's fine- it apparently couldn't handle the IPN
331
+					}
332
+				}
333
+			}
334
+			// EEM_Payment_Log::instance()->log("got to 7",$transaction,$payment_method);
335
+			if ($payment instanceof EE_Payment) {
336
+				$payment->save();
337
+				//  update the TXN
338
+				$this->update_txn_based_on_payment(
339
+					$transaction,
340
+					$payment,
341
+					$update_txn,
342
+					$separate_IPN_request
343
+				);
344
+			} else {
345
+				//we couldn't find the payment for this IPN... let's try and log at least SOMETHING
346
+				if ($payment_method) {
347
+					EEM_Change_Log::instance()->log(
348
+						EEM_Change_Log::type_gateway,
349
+						array('IPN data' => $_req_data),
350
+						$payment_method
351
+					);
352
+				} elseif ($transaction) {
353
+					EEM_Change_Log::instance()->log(
354
+						EEM_Change_Log::type_gateway,
355
+						array('IPN data' => $_req_data),
356
+						$transaction
357
+					);
358
+				}
359
+			}
360
+			return $payment;
361
+		} catch (EE_Error $e) {
362
+			do_action(
363
+				'AHEE__log',
364
+				__FILE__,
365
+				__FUNCTION__,
366
+				sprintf(
367
+					__(
368
+						'Error occurred while receiving IPN. Transaction: %1$s, req data: %2$s. The error was "%3$s"',
369
+						'event_espresso'
370
+					),
371
+					print_r($transaction, true),
372
+					print_r($_req_data, true),
373
+					$e->getMessage()
374
+				)
375
+			);
376
+			throw $e;
377
+		}
378
+	}
379
+
380
+
381
+
382
+	/**
383
+	 * Removes any non-printable illegal characters from the input,
384
+	 * which might cause a raucous when trying to insert into the database
385
+	 *
386
+	 * @param  array $request_data
387
+	 * @return array
388
+	 */
389
+	protected function _remove_unusable_characters_from_array(array $request_data)
390
+	{
391
+		$return_data = array();
392
+		foreach ($request_data as $key => $value) {
393
+			$return_data[$this->_remove_unusable_characters($key)] = $this->_remove_unusable_characters(
394
+				$value
395
+			);
396
+		}
397
+		return $return_data;
398
+	}
399
+
400
+
401
+
402
+	/**
403
+	 * Removes any non-printable illegal characters from the input,
404
+	 * which might cause a raucous when trying to insert into the database
405
+	 *
406
+	 * @param string $request_data
407
+	 * @return string
408
+	 */
409
+	protected function _remove_unusable_characters($request_data)
410
+	{
411
+		return preg_replace('/[^[:print:]]/', '', $request_data);
412
+	}
413
+
414
+
415
+
416
+	/**
417
+	 * Should be called just before displaying the payment attempt results to the user,
418
+	 * when the payment attempt has finished. Some payment methods may have special
419
+	 * logic to perform here. For example, if process_payment() happens on a special request
420
+	 * and then the user is redirected to a page that displays the payment's status, this
421
+	 * should be called while loading the page that displays the payment's status. If the user is
422
+	 * sent to an offsite payment provider, this should be called upon returning from that offsite payment
423
+	 * provider.
424
+	 *
425
+	 * @param EE_Transaction|int $transaction
426
+	 * @param bool               $update_txn whether or not to call
427
+	 *                                       EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
428
+	 * @return EE_Payment
429
+	 * @throws EE_Error
430
+	 * @throws InvalidArgumentException
431
+	 * @throws ReflectionException
432
+	 * @throws RuntimeException
433
+	 * @throws InvalidDataTypeException
434
+	 * @throws InvalidInterfaceException
435
+	 * @deprecated 4.6.24 method is no longer used. Instead it is up to client code, like SPCO,
436
+	 *                                       to call handle_ipn() for offsite gateways that don't receive separate IPNs
437
+	 */
438
+	public function finalize_payment_for($transaction, $update_txn = true)
439
+	{
440
+		/** @var $transaction EE_Transaction */
441
+		$transaction         = EEM_Transaction::instance()->ensure_is_obj($transaction);
442
+		$last_payment_method = $transaction->payment_method();
443
+		if ($last_payment_method instanceof EE_Payment_Method) {
444
+			$payment = $last_payment_method->type_obj()->finalize_payment_for($transaction);
445
+			$this->update_txn_based_on_payment($transaction, $payment, $update_txn);
446
+			return $payment;
447
+		}
448
+		return null;
449
+	}
450
+
451
+
452
+
453
+	/**
454
+	 * Processes a direct refund request, saves the payment, and updates the transaction appropriately.
455
+	 *
456
+	 * @param EE_Payment_Method $payment_method
457
+	 * @param EE_Payment        $payment_to_refund
458
+	 * @param array             $refund_info
459
+	 * @return EE_Payment
460
+	 * @throws EE_Error
461
+	 * @throws InvalidArgumentException
462
+	 * @throws ReflectionException
463
+	 * @throws RuntimeException
464
+	 * @throws InvalidDataTypeException
465
+	 * @throws InvalidInterfaceException
466
+	 */
467
+	public function process_refund(
468
+		EE_Payment_Method $payment_method,
469
+		EE_Payment $payment_to_refund,
470
+		array $refund_info = array()
471
+	) {
472
+		if ($payment_method instanceof EE_Payment_Method && $payment_method->type_obj()->supports_sending_refunds()) {
473
+			$payment_method->type_obj()->process_refund($payment_to_refund, $refund_info);
474
+			$this->update_txn_based_on_payment($payment_to_refund->transaction(), $payment_to_refund);
475
+		}
476
+		return $payment_to_refund;
477
+	}
478
+
479
+
480
+
481
+	/**
482
+	 * This should be called each time there may have been an update to a
483
+	 * payment on a transaction (ie, we asked for a payment to process a
484
+	 * payment for a transaction, or we told a payment method about an IPN, or
485
+	 * we told a payment method to
486
+	 * "finalize_payment_for" (a transaction), or we told a payment method to
487
+	 * process a refund. This should handle firing the correct hooks to
488
+	 * indicate
489
+	 * what exactly happened and updating the transaction appropriately). This
490
+	 * could be integrated directly into EE_Transaction upon save, but we want
491
+	 * this logic to be separate from 'normal' plain-jane saving and updating
492
+	 * of transactions and payments, and to be tied to payment processing.
493
+	 * Note: this method DOES NOT save the payment passed into it. It is the responsibility
494
+	 * of previous code to decide whether or not to save (because the payment passed into
495
+	 * this method might be a temporary, never-to-be-saved payment from an offline gateway,
496
+	 * in which case we only want that payment object for some temporary usage during this request,
497
+	 * but we don't want it to be saved).
498
+	 *
499
+	 * @param EE_Transaction|int $transaction
500
+	 * @param EE_Payment         $payment
501
+	 * @param boolean            $update_txn
502
+	 *                        whether or not to call
503
+	 *                        EE_Transaction_Processor::
504
+	 *                        update_transaction_and_registrations_after_checkout_or_payment()
505
+	 *                        (you can save 1 DB query if you know you're going
506
+	 *                        to save it later instead)
507
+	 * @param bool               $IPN
508
+	 *                        if processing IPNs or other similar payment
509
+	 *                        related activities that occur in alternate
510
+	 *                        requests than the main one that is processing the
511
+	 *                        TXN, then set this to true to check whether the
512
+	 *                        TXN is locked before updating
513
+	 * @throws EE_Error
514
+	 * @throws InvalidArgumentException
515
+	 * @throws ReflectionException
516
+	 * @throws RuntimeException
517
+	 * @throws InvalidDataTypeException
518
+	 * @throws InvalidInterfaceException
519
+	 */
520
+	public function update_txn_based_on_payment($transaction, $payment, $update_txn = true, $IPN = false)
521
+	{
522
+		$do_action = 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__not_successful';
523
+		/** @type EE_Transaction $transaction */
524
+		$transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
525
+		// can we freely update the TXN at this moment?
526
+		if ($IPN && $transaction->is_locked()) {
527
+			// don't update the transaction at this exact moment
528
+			// because the TXN is active in another request
529
+			EE_Cron_Tasks::schedule_update_transaction_with_payment(
530
+				time(),
531
+				$transaction->ID(),
532
+				$payment->ID()
533
+			);
534
+		} else {
535
+			// verify payment and that it has been saved
536
+			if ($payment instanceof EE_Payment && $payment->ID()) {
537
+				if (
538
+					$payment->payment_method() instanceof EE_Payment_Method
539
+					&& $payment->payment_method()->type_obj() instanceof EE_PMT_Base
540
+				) {
541
+					$payment->payment_method()->type_obj()->update_txn_based_on_payment($payment);
542
+					// update TXN registrations with payment info
543
+					$this->process_registration_payments($transaction, $payment);
544
+				}
545
+				$do_action = $payment->just_approved()
546
+					? 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__successful'
547
+					: $do_action;
548
+			} else {
549
+				// send out notifications
550
+				add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
551
+				$do_action = 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__no_payment_made';
552
+			}
553
+			if ($payment instanceof EE_Payment && $payment->status() !== EEM_Payment::status_id_failed) {
554
+				/** @type EE_Transaction_Payments $transaction_payments */
555
+				$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
556
+				// set new value for total paid
557
+				$transaction_payments->calculate_total_payments_and_update_status($transaction);
558
+				// call EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment() ???
559
+				if ($update_txn) {
560
+					$this->_post_payment_processing($transaction, $payment, $IPN);
561
+				}
562
+			}
563
+			// granular hook for others to use.
564
+			do_action($do_action, $transaction, $payment);
565
+			do_action('AHEE_log', __CLASS__, __FUNCTION__, $do_action, '$do_action');
566
+			//global hook for others to use.
567
+			do_action('AHEE__EE_Payment_Processor__update_txn_based_on_payment', $transaction, $payment);
568
+		}
569
+	}
570
+
571
+
572
+
573
+	/**
574
+	 * update registrations REG_paid field after successful payment and link registrations with payment
575
+	 *
576
+	 * @param EE_Transaction    $transaction
577
+	 * @param EE_Payment        $payment
578
+	 * @param EE_Registration[] $registrations
579
+	 * @throws EE_Error
580
+	 * @throws InvalidArgumentException
581
+	 * @throws RuntimeException
582
+	 * @throws InvalidDataTypeException
583
+	 * @throws InvalidInterfaceException
584
+	 */
585
+	public function process_registration_payments(
586
+		EE_Transaction $transaction,
587
+		EE_Payment $payment,
588
+		array $registrations = array()
589
+	) {
590
+		// only process if payment was successful
591
+		if ($payment->status() !== EEM_Payment::status_id_approved) {
592
+			return;
593
+		}
594
+		//EEM_Registration::instance()->show_next_x_db_queries();
595
+		if (empty($registrations)) {
596
+			// find registrations with monies owing that can receive a payment
597
+			$registrations = $transaction->registrations(
598
+				array(
599
+					array(
600
+						// only these reg statuses can receive payments
601
+						'STS_ID'           => array('IN', EEM_Registration::reg_statuses_that_allow_payment()),
602
+						'REG_final_price'  => array('!=', 0),
603
+						'REG_final_price*' => array('!=', 'REG_paid', true),
604
+					),
605
+				)
606
+			);
607
+		}
608
+		// still nothing ??!??
609
+		if (empty($registrations)) {
610
+			return;
611
+		}
612
+		// todo: break out the following logic into a separate strategy class
613
+		// todo: named something like "Sequential_Reg_Payment_Strategy"
614
+		// todo: which would apply payments using the capitalist "first come first paid" approach
615
+		// todo: then have another strategy class like "Distributed_Reg_Payment_Strategy"
616
+		// todo: which would be the socialist "everybody gets a piece of pie" approach,
617
+		// todo: which would be better for deposits, where you want a bit of the payment applied to each registration
618
+		$refund = $payment->is_a_refund();
619
+		// how much is available to apply to registrations?
620
+		$available_payment_amount = abs($payment->amount());
621
+		foreach ($registrations as $registration) {
622
+			if ($registration instanceof EE_Registration) {
623
+				// nothing left?
624
+				if ($available_payment_amount <= 0) {
625
+					break;
626
+				}
627
+				if ($refund) {
628
+					$available_payment_amount = $this->process_registration_refund(
629
+						$registration,
630
+						$payment,
631
+						$available_payment_amount
632
+					);
633
+				} else {
634
+					$available_payment_amount = $this->process_registration_payment(
635
+						$registration,
636
+						$payment,
637
+						$available_payment_amount
638
+					);
639
+				}
640
+			}
641
+		}
642
+		if ($available_payment_amount > 0
643
+			&& apply_filters(
644
+				'FHEE__EE_Payment_Processor__process_registration_payments__display_notifications',
645
+				false
646
+			)) {
647
+			EE_Error::add_attention(
648
+				sprintf(
649
+					__(
650
+						'A remainder of %1$s exists after applying this payment to Registration(s) %2$s.%3$sPlease verify that the original payment amount of %4$s is correct. If so, you should edit this payment and select at least one additional registration in the "Registrations to Apply Payment to" section, so that the remainder of this payment can be applied to the additional registration(s).',
651
+						'event_espresso'
652
+					),
653
+					EEH_Template::format_currency($available_payment_amount),
654
+					implode(', ', array_keys($registrations)),
655
+					'<br/>',
656
+					EEH_Template::format_currency($payment->amount())
657
+				),
658
+				__FILE__,
659
+				__FUNCTION__,
660
+				__LINE__
661
+			);
662
+		}
663
+	}
664
+
665
+
666
+
667
+	/**
668
+	 * update registration REG_paid field after successful payment and link registration with payment
669
+	 *
670
+	 * @param EE_Registration $registration
671
+	 * @param EE_Payment      $payment
672
+	 * @param float           $available_payment_amount
673
+	 * @return float
674
+	 * @throws EE_Error
675
+	 * @throws InvalidArgumentException
676
+	 * @throws RuntimeException
677
+	 * @throws InvalidDataTypeException
678
+	 * @throws InvalidInterfaceException
679
+	 */
680
+	public function process_registration_payment(
681
+		EE_Registration $registration,
682
+		EE_Payment $payment,
683
+		$available_payment_amount = 0.00
684
+	) {
685
+		$owing = $registration->final_price() - $registration->paid();
686
+		if ($owing > 0) {
687
+			// don't allow payment amount to exceed the available payment amount, OR the amount owing
688
+			$payment_amount = min($available_payment_amount, $owing);
689
+			// update $available_payment_amount
690
+			$available_payment_amount -= $payment_amount;
691
+			//calculate and set new REG_paid
692
+			$registration->set_paid($registration->paid() + $payment_amount);
693
+			// now save it
694
+			$this->_apply_registration_payment($registration, $payment, $payment_amount);
695
+		}
696
+		return $available_payment_amount;
697
+	}
698
+
699
+
700
+
701
+	/**
702
+	 * update registration REG_paid field after successful payment and link registration with payment
703
+	 *
704
+	 * @param EE_Registration $registration
705
+	 * @param EE_Payment      $payment
706
+	 * @param float           $payment_amount
707
+	 * @return void
708
+	 * @throws EE_Error
709
+	 * @throws InvalidArgumentException
710
+	 * @throws InvalidDataTypeException
711
+	 * @throws InvalidInterfaceException
712
+	 */
713
+	protected function _apply_registration_payment(
714
+		EE_Registration $registration,
715
+		EE_Payment $payment,
716
+		$payment_amount = 0.00
717
+	) {
718
+		// find any existing reg payment records for this registration and payment
719
+		$existing_reg_payment = EEM_Registration_Payment::instance()->get_one(
720
+			array(array('REG_ID' => $registration->ID(), 'PAY_ID' => $payment->ID()))
721
+		);
722
+		// if existing registration payment exists
723
+		if ($existing_reg_payment instanceof EE_Registration_Payment) {
724
+			// then update that record
725
+			$existing_reg_payment->set_amount($payment_amount);
726
+			$existing_reg_payment->save();
727
+		} else {
728
+			// or add new relation between registration and payment and set amount
729
+			$registration->_add_relation_to(
730
+				$payment,
731
+				'Payment',
732
+				array('RPY_amount' => $payment_amount)
733
+			);
734
+			// make it stick
735
+			$registration->save();
736
+		}
737
+	}
738
+
739
+
740
+
741
+	/**
742
+	 * update registration REG_paid field after refund and link registration with payment
743
+	 *
744
+	 * @param EE_Registration $registration
745
+	 * @param EE_Payment      $payment
746
+	 * @param float           $available_refund_amount - IMPORTANT !!! SEND AVAILABLE REFUND AMOUNT AS A POSITIVE NUMBER
747
+	 * @return float
748
+	 * @throws EE_Error
749
+	 * @throws InvalidArgumentException
750
+	 * @throws RuntimeException
751
+	 * @throws InvalidDataTypeException
752
+	 * @throws InvalidInterfaceException
753
+	 */
754
+	public function process_registration_refund(
755
+		EE_Registration $registration,
756
+		EE_Payment $payment,
757
+		$available_refund_amount = 0.00
758
+	) {
759
+		//EEH_Debug_Tools::printr( $payment->amount(), '$payment->amount()', __FILE__, __LINE__ );
760
+		if ($registration->paid() > 0) {
761
+			// ensure $available_refund_amount is NOT negative
762
+			$available_refund_amount = (float)abs($available_refund_amount);
763
+			// don't allow refund amount to exceed the available payment amount, OR the amount paid
764
+			$refund_amount = min($available_refund_amount, (float)$registration->paid());
765
+			// update $available_payment_amount
766
+			$available_refund_amount -= $refund_amount;
767
+			//calculate and set new REG_paid
768
+			$registration->set_paid($registration->paid() - $refund_amount);
769
+			// convert payment amount back to a negative value for storage in the db
770
+			$refund_amount = (float)abs($refund_amount) * -1;
771
+			// now save it
772
+			$this->_apply_registration_payment($registration, $payment, $refund_amount);
773
+		}
774
+		return $available_refund_amount;
775
+	}
776
+
777
+
778
+
779
+	/**
780
+	 * Process payments and transaction after payment process completed.
781
+	 * ultimately this will send the TXN and payment details off so that notifications can be sent out.
782
+	 * if this request happens to be processing an IPN,
783
+	 * then we will also set the Payment Options Reg Step to completed,
784
+	 * and attempt to completely finalize the TXN if all of the other Reg Steps are completed as well.
785
+	 *
786
+	 * @param EE_Transaction $transaction
787
+	 * @param EE_Payment     $payment
788
+	 * @param bool           $IPN
789
+	 * @throws EE_Error
790
+	 * @throws InvalidArgumentException
791
+	 * @throws ReflectionException
792
+	 * @throws RuntimeException
793
+	 * @throws InvalidDataTypeException
794
+	 * @throws InvalidInterfaceException
795
+	 */
796
+	protected function _post_payment_processing(EE_Transaction $transaction, EE_Payment $payment, $IPN = false)
797
+	{
798
+		/** @type EE_Transaction_Processor $transaction_processor */
799
+		$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
800
+		// is the Payment Options Reg Step completed ?
801
+		$payment_options_step_completed = $transaction->reg_step_completed('payment_options');
802
+		// if the Payment Options Reg Step is completed...
803
+		$revisit = $payment_options_step_completed === true;
804
+		// then this is kinda sorta a revisit with regards to payments at least
805
+		$transaction_processor->set_revisit($revisit);
806
+		// if this is an IPN, let's consider the Payment Options Reg Step completed if not already
807
+		if (
808
+			$IPN
809
+			&& $payment_options_step_completed !== true
810
+			&& ($payment->is_approved() || $payment->is_pending())
811
+		) {
812
+			$payment_options_step_completed = $transaction->set_reg_step_completed(
813
+				'payment_options'
814
+			);
815
+		}
816
+		// maybe update status, but don't save transaction just yet
817
+		$transaction->update_status_based_on_total_paid(false);
818
+		// check if 'finalize_registration' step has been completed...
819
+		$finalized = $transaction->reg_step_completed('finalize_registration');
820
+		//  if this is an IPN and the final step has not been initiated
821
+		if ($IPN && $payment_options_step_completed && $finalized === false) {
822
+			// and if it hasn't already been set as being started...
823
+			$finalized = $transaction->set_reg_step_initiated('finalize_registration');
824
+		}
825
+		$transaction->save();
826
+		// because the above will return false if the final step was not fully completed, we need to check again...
827
+		if ($IPN && $finalized !== false) {
828
+			// and if we are all good to go, then send out notifications
829
+			add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
830
+			//ok, now process the transaction according to the payment
831
+			$transaction_processor->update_transaction_and_registrations_after_checkout_or_payment(
832
+				$transaction,
833
+				$payment
834
+			);
835
+		}
836
+		// DEBUG LOG
837
+		$payment_method = $payment->payment_method();
838
+		if ($payment_method instanceof EE_Payment_Method) {
839
+			$payment_method_type_obj = $payment_method->type_obj();
840
+			if ($payment_method_type_obj instanceof EE_PMT_Base) {
841
+				$gateway = $payment_method_type_obj->get_gateway();
842
+				if ($gateway instanceof EE_Gateway) {
843
+					$gateway->log(
844
+						array(
845
+							'message'               => __('Post Payment Transaction Details', 'event_espresso'),
846
+							'transaction'           => $transaction->model_field_array(),
847
+							'finalized'             => $finalized,
848
+							'IPN'                   => $IPN,
849
+							'deliver_notifications' => has_filter(
850
+								'FHEE__EED_Messages___maybe_registration__deliver_notifications'
851
+							),
852
+						),
853
+						$payment
854
+					);
855
+				}
856
+			}
857
+		}
858
+	}
859
+
860
+
861
+
862
+	/**
863
+	 * Force posts to PayPal to use TLS v1.2. See:
864
+	 * https://core.trac.wordpress.org/ticket/36320
865
+	 * https://core.trac.wordpress.org/ticket/34924#comment:15
866
+	 * https://www.paypal-knowledge.com/infocenter/index?page=content&widgetview=true&id=FAQ1914&viewlocale=en_US
867
+	 * This will affect PayPal standard, pro, express, and Payflow.
868
+	 *
869
+	 * @param $handle
870
+	 * @param $r
871
+	 * @param $url
872
+	 */
873
+	public static function _curl_requests_to_paypal_use_tls($handle, $r, $url)
874
+	{
875
+		if (strpos($url, 'https://') !== false && strpos($url, '.paypal.com') !== false) {
876
+			//Use the value of the constant CURL_SSLVERSION_TLSv1 = 1
877
+			//instead of the constant because it might not be defined
878
+			curl_setopt($handle, CURLOPT_SSLVERSION, 1);
879
+		}
880
+	}
881 881
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -37,7 +37,7 @@  discard block
 block discarded – undo
37 37
     public static function instance()
38 38
     {
39 39
         // check if class object is instantiated
40
-        if (! self::$_instance instanceof EE_Payment_Processor) {
40
+        if ( ! self::$_instance instanceof EE_Payment_Processor) {
41 41
             self::$_instance = new self();
42 42
         }
43 43
         return self::$_instance;
@@ -108,7 +108,7 @@  discard block
 block discarded – undo
108 108
         $update_txn = true,
109 109
         $cancel_url = ''
110 110
     ) {
111
-        if ((float)$amount < 0) {
111
+        if ((float) $amount < 0) {
112 112
             throw new EE_Error(
113 113
                 sprintf(
114 114
                     __(
@@ -132,7 +132,7 @@  discard block
 block discarded – undo
132 132
         if ($payment_method->type_obj() instanceof EE_PMT_Base) {
133 133
             $payment = $payment_method->type_obj()->process_payment(
134 134
                 $transaction,
135
-                min($amount, $transaction->remaining()),//make sure we don't overcharge
135
+                min($amount, $transaction->remaining()), //make sure we don't overcharge
136 136
                 $billing_form,
137 137
                 $return_url,
138 138
                 add_query_arg(array('ee_cancel_payment' => true), $cancel_url),
@@ -178,7 +178,7 @@  discard block
 block discarded – undo
178 178
         /** @type \EE_Transaction $transaction */
179 179
         $transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
180 180
         $primary_reg = $transaction->primary_registration();
181
-        if (! $primary_reg instanceof EE_Registration) {
181
+        if ( ! $primary_reg instanceof EE_Registration) {
182 182
             throw new EE_Error(
183 183
                 sprintf(
184 184
                     __(
@@ -193,7 +193,7 @@  discard block
 block discarded – undo
193 193
             $payment_method,
194 194
             true
195 195
         );
196
-        $url            = add_query_arg(
196
+        $url = add_query_arg(
197 197
             array(
198 198
                 'e_reg_url_link'    => $primary_reg->reg_url_link(),
199 199
                 'ee_payment_method' => $payment_method->slug(),
@@ -235,7 +235,7 @@  discard block
 block discarded – undo
235 235
         $separate_IPN_request = true
236 236
     ) {
237 237
         EE_Registry::instance()->load_model('Change_Log');
238
-        $_req_data = $this->_remove_unusable_characters_from_array((array)$_req_data);
238
+        $_req_data = $this->_remove_unusable_characters_from_array((array) $_req_data);
239 239
         EE_Processor_Base::set_IPN($separate_IPN_request);
240 240
         $obj_for_log = null;
241 241
         if ($transaction instanceof EE_Transaction) {
@@ -274,7 +274,7 @@  discard block
 block discarded – undo
274 274
                         EEM_Change_Log::instance()->log(
275 275
                             EEM_Change_Log::type_gateway,
276 276
                             array(
277
-                                'message'     => 'IPN Exception: ' . $e->getMessage(),
277
+                                'message'     => 'IPN Exception: '.$e->getMessage(),
278 278
                                 'current_url' => EEH_URL::current_url(),
279 279
                                 'payment'     => $e->getPaymentProperties(),
280 280
                                 'IPN_data'    => $e->getIpnData(),
@@ -318,7 +318,7 @@  discard block
 block discarded – undo
318 318
                         EEM_Change_Log::instance()->log(
319 319
                             EEM_Change_Log::type_gateway,
320 320
                             array(
321
-                                'message'     => 'IPN Exception: ' . $e->getMessage(),
321
+                                'message'     => 'IPN Exception: '.$e->getMessage(),
322 322
                                 'current_url' => EEH_URL::current_url(),
323 323
                                 'payment'     => $e->getPaymentProperties(),
324 324
                                 'IPN_data'    => $e->getIpnData(),
@@ -759,15 +759,15 @@  discard block
 block discarded – undo
759 759
         //EEH_Debug_Tools::printr( $payment->amount(), '$payment->amount()', __FILE__, __LINE__ );
760 760
         if ($registration->paid() > 0) {
761 761
             // ensure $available_refund_amount is NOT negative
762
-            $available_refund_amount = (float)abs($available_refund_amount);
762
+            $available_refund_amount = (float) abs($available_refund_amount);
763 763
             // don't allow refund amount to exceed the available payment amount, OR the amount paid
764
-            $refund_amount = min($available_refund_amount, (float)$registration->paid());
764
+            $refund_amount = min($available_refund_amount, (float) $registration->paid());
765 765
             // update $available_payment_amount
766 766
             $available_refund_amount -= $refund_amount;
767 767
             //calculate and set new REG_paid
768 768
             $registration->set_paid($registration->paid() - $refund_amount);
769 769
             // convert payment amount back to a negative value for storage in the db
770
-            $refund_amount = (float)abs($refund_amount) * -1;
770
+            $refund_amount = (float) abs($refund_amount) * -1;
771 771
             // now save it
772 772
             $this->_apply_registration_payment($registration, $payment, $refund_amount);
773 773
         }
Please login to merge, or discard this patch.
core/libraries/form_sections/form_handlers/FormHandler.php 2 patches
Indentation   +636 added lines, -636 removed lines patch added patch discarded remove patch
@@ -15,7 +15,7 @@  discard block
 block discarded – undo
15 15
 use EventEspresso\core\exceptions\InvalidFormSubmissionException;
16 16
 
17 17
 if (! defined('EVENT_ESPRESSO_VERSION')) {
18
-    exit('No direct script access allowed');
18
+	exit('No direct script access allowed');
19 19
 }
20 20
 
21 21
 
@@ -34,641 +34,641 @@  discard block
 block discarded – undo
34 34
 abstract class FormHandler implements FormHandlerInterface
35 35
 {
36 36
 
37
-    /**
38
-     * will add opening and closing HTML form tags as well as a submit button
39
-     */
40
-    const ADD_FORM_TAGS_AND_SUBMIT = 'add_form_tags_and_submit';
41
-
42
-    /**
43
-     * will add opening and closing HTML form tags but NOT a submit button
44
-     */
45
-    const ADD_FORM_TAGS_ONLY = 'add_form_tags_only';
46
-
47
-    /**
48
-     * will NOT add opening and closing HTML form tags but will add a submit button
49
-     */
50
-    const ADD_FORM_SUBMIT_ONLY = 'add_form_submit_only';
51
-
52
-    /**
53
-     * will NOT add opening and closing HTML form tags NOR a submit button
54
-     */
55
-    const DO_NOT_SETUP_FORM = 'do_not_setup_form';
56
-
57
-    /**
58
-     * if set to false, then this form has no displayable content,
59
-     * and will only be used for processing data sent passed via GET or POST
60
-     * defaults to true ( ie: form has displayable content )
61
-     *
62
-     * @var boolean $displayable
63
-     */
64
-    private $displayable = true;
65
-
66
-    /**
67
-     * @var string $form_name
68
-     */
69
-    private $form_name;
70
-
71
-    /**
72
-     * @var string $admin_name
73
-     */
74
-    private $admin_name;
75
-
76
-    /**
77
-     * @var string $slug
78
-     */
79
-    private $slug;
80
-
81
-    /**
82
-     * @var string $submit_btn_text
83
-     */
84
-    private $submit_btn_text;
85
-
86
-    /**
87
-     * @var string $form_action
88
-     */
89
-    private $form_action;
90
-
91
-    /**
92
-     * form params in key value pairs
93
-     * can be added to form action URL or as hidden inputs
94
-     *
95
-     * @var array $form_args
96
-     */
97
-    private $form_args = array();
98
-
99
-    /**
100
-     * value of one of the string constant above
101
-     *
102
-     * @var string $form_config
103
-     */
104
-    private $form_config;
105
-
106
-    /**
107
-     * whether or not the form was determined to be invalid
108
-     *
109
-     * @var boolean $form_has_errors
110
-     */
111
-    private $form_has_errors;
112
-
113
-    /**
114
-     * the absolute top level form section being used on the page
115
-     *
116
-     * @var EE_Form_Section_Proper $form
117
-     */
118
-    private $form;
119
-
120
-    /**
121
-     * @var EE_Registry $registry
122
-     */
123
-    protected $registry;
124
-
125
-
126
-
127
-    /**
128
-     * Form constructor.
129
-     *
130
-     * @param string      $form_name
131
-     * @param string      $admin_name
132
-     * @param string      $slug
133
-     * @param string      $form_action
134
-     * @param string      $form_config
135
-     * @param EE_Registry $registry
136
-     * @throws InvalidDataTypeException
137
-     * @throws DomainException
138
-     * @throws InvalidArgumentException
139
-     */
140
-    public function __construct(
141
-        $form_name,
142
-        $admin_name,
143
-        $slug,
144
-        $form_action = '',
145
-        $form_config = FormHandler::ADD_FORM_TAGS_AND_SUBMIT,
146
-        EE_Registry $registry
147
-    ) {
148
-        $this->setFormName($form_name);
149
-        $this->setAdminName($admin_name);
150
-        $this->setSlug($slug);
151
-        $this->setFormAction($form_action);
152
-        $this->setFormConfig($form_config);
153
-        $this->setSubmitBtnText(esc_html__('Submit', 'event_espresso'));
154
-        $this->registry = $registry;
155
-    }
156
-
157
-
158
-
159
-    /**
160
-     * @return array
161
-     */
162
-    public static function getFormConfigConstants()
163
-    {
164
-        return array(
165
-            FormHandler::ADD_FORM_TAGS_AND_SUBMIT,
166
-            FormHandler::ADD_FORM_TAGS_ONLY,
167
-            FormHandler::ADD_FORM_SUBMIT_ONLY,
168
-            FormHandler::DO_NOT_SETUP_FORM,
169
-        );
170
-    }
171
-
172
-
173
-
174
-    /**
175
-     * @param bool $for_display
176
-     * @return EE_Form_Section_Proper
177
-     * @throws EE_Error
178
-     * @throws LogicException
179
-     */
180
-    public function form($for_display = false)
181
-    {
182
-        if (! $this->formIsValid()) {
183
-            return null;
184
-        }
185
-        if ($for_display) {
186
-            $form_config = $this->formConfig();
187
-            if (
188
-                $form_config === FormHandler::ADD_FORM_TAGS_AND_SUBMIT
189
-                || $form_config === FormHandler::ADD_FORM_SUBMIT_ONLY
190
-            ) {
191
-                $this->appendSubmitButton();
192
-                $this->clearFormButtonFloats();
193
-            }
194
-        }
195
-        return $this->form;
196
-    }
197
-
198
-
199
-
200
-    /**
201
-     * @return boolean
202
-     * @throws LogicException
203
-     */
204
-    public function formIsValid()
205
-    {
206
-        if ($this->form instanceof EE_Form_Section_Proper) {
207
-            return true;
208
-        }
209
-        $form = apply_filters(
210
-            'FHEE__EventEspresso_core_libraries_form_sections_form_handlers_FormHandler__formIsValid__generated_form_object',
211
-            $this->generate(),
212
-            $this
213
-        );
214
-        if ($this->verifyForm($form)) {
215
-            $this->setForm($form);
216
-        }
217
-        return true;
218
-    }
219
-
220
-
221
-
222
-    /**
223
-     * @param EE_Form_Section_Proper|null $form
224
-     * @return bool
225
-     * @throws LogicException
226
-     */
227
-    public function verifyForm(EE_Form_Section_Proper $form = null)
228
-    {
229
-        $form = $form !== null ? $form : $this->form;
230
-        if ($form instanceof EE_Form_Section_Proper) {
231
-            return true;
232
-        }
233
-        throw new LogicException(
234
-            sprintf(
235
-                esc_html__('The "%1$s" form is invalid or missing. %2$s', 'event_espresso'),
236
-                $this->form_name,
237
-                var_export($form, true)
238
-            )
239
-        );
240
-    }
241
-
242
-
243
-
244
-    /**
245
-     * @param EE_Form_Section_Proper $form
246
-     */
247
-    public function setForm(EE_Form_Section_Proper $form)
248
-    {
249
-        $this->form = $form;
250
-    }
251
-
252
-
253
-
254
-    /**
255
-     * @return boolean
256
-     */
257
-    public function displayable()
258
-    {
259
-        return $this->displayable;
260
-    }
261
-
262
-
263
-
264
-    /**
265
-     * @param boolean $displayable
266
-     */
267
-    public function setDisplayable($displayable = false)
268
-    {
269
-        $this->displayable = filter_var($displayable, FILTER_VALIDATE_BOOLEAN);
270
-    }
271
-
272
-
273
-
274
-    /**
275
-     * a public name for the form that can be displayed on the frontend of a site
276
-     *
277
-     * @return string
278
-     */
279
-    public function formName()
280
-    {
281
-        return $this->form_name;
282
-    }
283
-
284
-
285
-
286
-    /**
287
-     * @param string $form_name
288
-     * @throws InvalidDataTypeException
289
-     */
290
-    public function setFormName($form_name)
291
-    {
292
-        if (! is_string($form_name)) {
293
-            throw new InvalidDataTypeException('$form_name', $form_name, 'string');
294
-        }
295
-        $this->form_name = $form_name;
296
-    }
297
-
298
-
299
-
300
-    /**
301
-     * a public name for the form that can be displayed, but only in the admin
302
-     *
303
-     * @return string
304
-     */
305
-    public function adminName()
306
-    {
307
-        return $this->admin_name;
308
-    }
309
-
310
-
311
-
312
-    /**
313
-     * @param string $admin_name
314
-     * @throws InvalidDataTypeException
315
-     */
316
-    public function setAdminName($admin_name)
317
-    {
318
-        if (! is_string($admin_name)) {
319
-            throw new InvalidDataTypeException('$admin_name', $admin_name, 'string');
320
-        }
321
-        $this->admin_name = $admin_name;
322
-    }
323
-
324
-
325
-
326
-    /**
327
-     * a URL friendly string that can be used for identifying the form
328
-     *
329
-     * @return string
330
-     */
331
-    public function slug()
332
-    {
333
-        return $this->slug;
334
-    }
335
-
336
-
337
-
338
-    /**
339
-     * @param string $slug
340
-     * @throws InvalidDataTypeException
341
-     */
342
-    public function setSlug($slug)
343
-    {
344
-        if (! is_string($slug)) {
345
-            throw new InvalidDataTypeException('$slug', $slug, 'string');
346
-        }
347
-        $this->slug = $slug;
348
-    }
349
-
350
-
351
-
352
-    /**
353
-     * @return string
354
-     */
355
-    public function submitBtnText()
356
-    {
357
-        return $this->submit_btn_text;
358
-    }
359
-
360
-
361
-
362
-    /**
363
-     * @param string $submit_btn_text
364
-     * @throws InvalidDataTypeException
365
-     * @throws InvalidArgumentException
366
-     */
367
-    public function setSubmitBtnText($submit_btn_text)
368
-    {
369
-        if (! is_string($submit_btn_text)) {
370
-            throw new InvalidDataTypeException('$submit_btn_text', $submit_btn_text, 'string');
371
-        }
372
-        if (empty($submit_btn_text)) {
373
-            throw new InvalidArgumentException(
374
-                esc_html__('Can not set Submit button text because an empty string was provided.', 'event_espresso')
375
-            );
376
-        }
377
-        $this->submit_btn_text = $submit_btn_text;
378
-    }
379
-
380
-
381
-
382
-    /**
383
-     * @return string
384
-     */
385
-    public function formAction()
386
-    {
387
-        return ! empty($this->form_args)
388
-            ? add_query_arg($this->form_args, $this->form_action)
389
-            : $this->form_action;
390
-    }
391
-
392
-
393
-
394
-    /**
395
-     * @param string $form_action
396
-     * @throws InvalidDataTypeException
397
-     */
398
-    public function setFormAction($form_action)
399
-    {
400
-        if (! is_string($form_action)) {
401
-            throw new InvalidDataTypeException('$form_action', $form_action, 'string');
402
-        }
403
-        $this->form_action = $form_action;
404
-    }
405
-
406
-
407
-
408
-    /**
409
-     * @param array $form_args
410
-     * @throws InvalidDataTypeException
411
-     * @throws InvalidArgumentException
412
-     */
413
-    public function addFormActionArgs($form_args = array())
414
-    {
415
-        if (is_object($form_args)) {
416
-            throw new InvalidDataTypeException(
417
-                '$form_args',
418
-                $form_args,
419
-                'anything other than an object was expected.'
420
-            );
421
-        }
422
-        if (empty($form_args)) {
423
-            throw new InvalidArgumentException(
424
-                esc_html__('The redirect arguments can not be an empty array.', 'event_espresso')
425
-            );
426
-        }
427
-        $this->form_args = array_merge($this->form_args, $form_args);
428
-    }
429
-
430
-
431
-
432
-    /**
433
-     * @return string
434
-     */
435
-    public function formConfig()
436
-    {
437
-        return $this->form_config;
438
-    }
439
-
440
-
441
-
442
-    /**
443
-     * @param string $form_config
444
-     * @throws DomainException
445
-     */
446
-    public function setFormConfig($form_config)
447
-    {
448
-        if (
449
-        ! in_array(
450
-            $form_config,
451
-            array(
452
-                FormHandler::ADD_FORM_TAGS_AND_SUBMIT,
453
-                FormHandler::ADD_FORM_TAGS_ONLY,
454
-                FormHandler::ADD_FORM_SUBMIT_ONLY,
455
-                FormHandler::DO_NOT_SETUP_FORM,
456
-            ),
457
-            true
458
-        )
459
-        ) {
460
-            throw new DomainException(
461
-                sprintf(
462
-                    esc_html__('"%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',
463
-                        'event_espresso'),
464
-                    $form_config
465
-                )
466
-            );
467
-        }
468
-        $this->form_config = $form_config;
469
-    }
470
-
471
-
472
-
473
-    /**
474
-     * called after the form is instantiated
475
-     * and used for performing any logic that needs to occur early
476
-     * before any of the other methods are called.
477
-     * returns true if everything is ok to proceed,
478
-     * and false if no further form logic should be implemented
479
-     *
480
-     * @return boolean
481
-     */
482
-    public function initialize()
483
-    {
484
-        $this->form_has_errors = EE_Error::has_error(true);
485
-        return true;
486
-    }
487
-
488
-
489
-
490
-    /**
491
-     * used for setting up css and js
492
-     *
493
-     * @return void
494
-     * @throws LogicException
495
-     * @throws EE_Error
496
-     */
497
-    public function enqueueStylesAndScripts()
498
-    {
499
-        $this->form()->enqueue_js();
500
-    }
501
-
502
-
503
-
504
-    /**
505
-     * creates and returns the actual form
506
-     *
507
-     * @return EE_Form_Section_Proper
508
-     */
509
-    abstract public function generate();
510
-
511
-
512
-
513
-    /**
514
-     * creates and returns an EE_Submit_Input labeled "Submit"
515
-     *
516
-     * @param string $text
517
-     * @return EE_Submit_Input
518
-     */
519
-    public function generateSubmitButton($text = '')
520
-    {
521
-        $text = ! empty($text) ? $text : $this->submitBtnText();
522
-        return new EE_Submit_Input(
523
-            array(
524
-                'html_name'             => 'ee-form-submit-' . $this->slug(),
525
-                'html_id'               => 'ee-form-submit-' . $this->slug(),
526
-                'html_class'            => 'ee-form-submit',
527
-                'html_label'            => '&nbsp;',
528
-                'other_html_attributes' => ' rel="' . $this->slug() . '"',
529
-                'default'               => $text,
530
-            )
531
-        );
532
-    }
533
-
534
-
535
-
536
-    /**
537
-     * calls generateSubmitButton() and appends it onto the form along with a float clearing div
538
-     *
539
-     * @param string $text
540
-     * @return void
541
-     * @throws LogicException
542
-     * @throws EE_Error
543
-     */
544
-    public function appendSubmitButton($text = '')
545
-    {
546
-        if ($this->form->subsection_exists($this->slug() . '-submit-btn')) {
547
-            return;
548
-        }
549
-        $this->form->add_subsections(
550
-            array($this->slug() . '-submit-btn' => $this->generateSubmitButton($text)),
551
-            null,
552
-            false
553
-        );
554
-    }
555
-
556
-
557
-
558
-    /**
559
-     * creates and returns an EE_Submit_Input labeled "Cancel"
560
-     *
561
-     * @param string $text
562
-     * @return EE_Submit_Input
563
-     */
564
-    public function generateCancelButton($text = '')
565
-    {
566
-        $cancel_button = new EE_Submit_Input(
567
-            array(
568
-                'html_name'             => 'ee-form-submit-' . $this->slug(), // YES! Same name as submit !!!
569
-                'html_id'               => 'ee-cancel-form-' . $this->slug(),
570
-                'html_class'            => 'ee-cancel-form',
571
-                'html_label'            => '&nbsp;',
572
-                'other_html_attributes' => ' rel="' . $this->slug() . '"',
573
-                'default'               => ! empty($text) ? $text : esc_html__('Cancel', 'event_espresso'),
574
-            )
575
-        );
576
-        $cancel_button->set_button_css_attributes(false);
577
-        return $cancel_button;
578
-    }
579
-
580
-
581
-
582
-    /**
583
-     * appends a float clearing div onto end of form
584
-     *
585
-     * @return void
586
-     * @throws EE_Error
587
-     */
588
-    public function clearFormButtonFloats()
589
-    {
590
-        $this->form->add_subsections(
591
-            array(
592
-                'clear-submit-btn-float' => new EE_Form_Section_HTML(
593
-                    EEH_HTML::div('', '', 'clear-float') . EEH_HTML::divx()
594
-                ),
595
-            ),
596
-            null,
597
-            false
598
-        );
599
-    }
600
-
601
-
602
-
603
-    /**
604
-     * takes the generated form and displays it along with ony other non-form HTML that may be required
605
-     * returns a string of HTML that can be directly echoed in a template
606
-     *
607
-     * @return string
608
-     * @throws LogicException
609
-     * @throws EE_Error
610
-     */
611
-    public function display()
612
-    {
613
-        $form_html = apply_filters(
614
-            'FHEE__EventEspresso_core_libraries_form_sections_form_handlers_FormHandler__display__before_form',
615
-            ''
616
-        );
617
-        $form_config = $this->formConfig();
618
-        if (
619
-            $form_config === FormHandler::ADD_FORM_TAGS_AND_SUBMIT
620
-            || $form_config === FormHandler::ADD_FORM_TAGS_ONLY
621
-        ) {
622
-            $form_html .= $this->form()->form_open($this->formAction());
623
-        }
624
-        $form_html .= $this->form(true)->get_html($this->form_has_errors);
625
-        if (
626
-            $form_config === FormHandler::ADD_FORM_TAGS_AND_SUBMIT
627
-            || $form_config === FormHandler::ADD_FORM_TAGS_ONLY
628
-        ) {
629
-            $form_html .= $this->form()->form_close();
630
-        }
631
-        $form_html .= apply_filters(
632
-            'FHEE__EventEspresso_core_libraries_form_sections_form_handlers_FormHandler__display__after_form',
633
-            ''
634
-        );
635
-        return $form_html;
636
-    }
637
-
638
-
639
-
640
-    /**
641
-     * handles processing the form submission
642
-     * returns true or false depending on whether the form was processed successfully or not
643
-     *
644
-     * @param array $submitted_form_data
645
-     * @return array
646
-     * @throws EE_Error
647
-     * @throws LogicException
648
-     * @throws InvalidFormSubmissionException
649
-     */
650
-    public function process($submitted_form_data = array())
651
-    {
652
-        if (! $this->form()->was_submitted($submitted_form_data)) {
653
-            throw new InvalidFormSubmissionException($this->form_name);
654
-        }
655
-        $this->form(true)->receive_form_submission($submitted_form_data);
656
-        if (! $this->form()->is_valid()) {
657
-            throw new InvalidFormSubmissionException(
658
-                $this->form_name,
659
-                sprintf(
660
-                    esc_html__(
661
-                        'The "%1$s" form is invalid. Please correct the following errors and resubmit: %2$s %3$s',
662
-                        'event_espresso'
663
-                    ),
664
-                    $this->form_name,
665
-                    '<br />',
666
-                    $this->form()->submission_error_message()
667
-                )
668
-            );
669
-        }
670
-        return $this->form()->valid_data();
671
-    }
37
+	/**
38
+	 * will add opening and closing HTML form tags as well as a submit button
39
+	 */
40
+	const ADD_FORM_TAGS_AND_SUBMIT = 'add_form_tags_and_submit';
41
+
42
+	/**
43
+	 * will add opening and closing HTML form tags but NOT a submit button
44
+	 */
45
+	const ADD_FORM_TAGS_ONLY = 'add_form_tags_only';
46
+
47
+	/**
48
+	 * will NOT add opening and closing HTML form tags but will add a submit button
49
+	 */
50
+	const ADD_FORM_SUBMIT_ONLY = 'add_form_submit_only';
51
+
52
+	/**
53
+	 * will NOT add opening and closing HTML form tags NOR a submit button
54
+	 */
55
+	const DO_NOT_SETUP_FORM = 'do_not_setup_form';
56
+
57
+	/**
58
+	 * if set to false, then this form has no displayable content,
59
+	 * and will only be used for processing data sent passed via GET or POST
60
+	 * defaults to true ( ie: form has displayable content )
61
+	 *
62
+	 * @var boolean $displayable
63
+	 */
64
+	private $displayable = true;
65
+
66
+	/**
67
+	 * @var string $form_name
68
+	 */
69
+	private $form_name;
70
+
71
+	/**
72
+	 * @var string $admin_name
73
+	 */
74
+	private $admin_name;
75
+
76
+	/**
77
+	 * @var string $slug
78
+	 */
79
+	private $slug;
80
+
81
+	/**
82
+	 * @var string $submit_btn_text
83
+	 */
84
+	private $submit_btn_text;
85
+
86
+	/**
87
+	 * @var string $form_action
88
+	 */
89
+	private $form_action;
90
+
91
+	/**
92
+	 * form params in key value pairs
93
+	 * can be added to form action URL or as hidden inputs
94
+	 *
95
+	 * @var array $form_args
96
+	 */
97
+	private $form_args = array();
98
+
99
+	/**
100
+	 * value of one of the string constant above
101
+	 *
102
+	 * @var string $form_config
103
+	 */
104
+	private $form_config;
105
+
106
+	/**
107
+	 * whether or not the form was determined to be invalid
108
+	 *
109
+	 * @var boolean $form_has_errors
110
+	 */
111
+	private $form_has_errors;
112
+
113
+	/**
114
+	 * the absolute top level form section being used on the page
115
+	 *
116
+	 * @var EE_Form_Section_Proper $form
117
+	 */
118
+	private $form;
119
+
120
+	/**
121
+	 * @var EE_Registry $registry
122
+	 */
123
+	protected $registry;
124
+
125
+
126
+
127
+	/**
128
+	 * Form constructor.
129
+	 *
130
+	 * @param string      $form_name
131
+	 * @param string      $admin_name
132
+	 * @param string      $slug
133
+	 * @param string      $form_action
134
+	 * @param string      $form_config
135
+	 * @param EE_Registry $registry
136
+	 * @throws InvalidDataTypeException
137
+	 * @throws DomainException
138
+	 * @throws InvalidArgumentException
139
+	 */
140
+	public function __construct(
141
+		$form_name,
142
+		$admin_name,
143
+		$slug,
144
+		$form_action = '',
145
+		$form_config = FormHandler::ADD_FORM_TAGS_AND_SUBMIT,
146
+		EE_Registry $registry
147
+	) {
148
+		$this->setFormName($form_name);
149
+		$this->setAdminName($admin_name);
150
+		$this->setSlug($slug);
151
+		$this->setFormAction($form_action);
152
+		$this->setFormConfig($form_config);
153
+		$this->setSubmitBtnText(esc_html__('Submit', 'event_espresso'));
154
+		$this->registry = $registry;
155
+	}
156
+
157
+
158
+
159
+	/**
160
+	 * @return array
161
+	 */
162
+	public static function getFormConfigConstants()
163
+	{
164
+		return array(
165
+			FormHandler::ADD_FORM_TAGS_AND_SUBMIT,
166
+			FormHandler::ADD_FORM_TAGS_ONLY,
167
+			FormHandler::ADD_FORM_SUBMIT_ONLY,
168
+			FormHandler::DO_NOT_SETUP_FORM,
169
+		);
170
+	}
171
+
172
+
173
+
174
+	/**
175
+	 * @param bool $for_display
176
+	 * @return EE_Form_Section_Proper
177
+	 * @throws EE_Error
178
+	 * @throws LogicException
179
+	 */
180
+	public function form($for_display = false)
181
+	{
182
+		if (! $this->formIsValid()) {
183
+			return null;
184
+		}
185
+		if ($for_display) {
186
+			$form_config = $this->formConfig();
187
+			if (
188
+				$form_config === FormHandler::ADD_FORM_TAGS_AND_SUBMIT
189
+				|| $form_config === FormHandler::ADD_FORM_SUBMIT_ONLY
190
+			) {
191
+				$this->appendSubmitButton();
192
+				$this->clearFormButtonFloats();
193
+			}
194
+		}
195
+		return $this->form;
196
+	}
197
+
198
+
199
+
200
+	/**
201
+	 * @return boolean
202
+	 * @throws LogicException
203
+	 */
204
+	public function formIsValid()
205
+	{
206
+		if ($this->form instanceof EE_Form_Section_Proper) {
207
+			return true;
208
+		}
209
+		$form = apply_filters(
210
+			'FHEE__EventEspresso_core_libraries_form_sections_form_handlers_FormHandler__formIsValid__generated_form_object',
211
+			$this->generate(),
212
+			$this
213
+		);
214
+		if ($this->verifyForm($form)) {
215
+			$this->setForm($form);
216
+		}
217
+		return true;
218
+	}
219
+
220
+
221
+
222
+	/**
223
+	 * @param EE_Form_Section_Proper|null $form
224
+	 * @return bool
225
+	 * @throws LogicException
226
+	 */
227
+	public function verifyForm(EE_Form_Section_Proper $form = null)
228
+	{
229
+		$form = $form !== null ? $form : $this->form;
230
+		if ($form instanceof EE_Form_Section_Proper) {
231
+			return true;
232
+		}
233
+		throw new LogicException(
234
+			sprintf(
235
+				esc_html__('The "%1$s" form is invalid or missing. %2$s', 'event_espresso'),
236
+				$this->form_name,
237
+				var_export($form, true)
238
+			)
239
+		);
240
+	}
241
+
242
+
243
+
244
+	/**
245
+	 * @param EE_Form_Section_Proper $form
246
+	 */
247
+	public function setForm(EE_Form_Section_Proper $form)
248
+	{
249
+		$this->form = $form;
250
+	}
251
+
252
+
253
+
254
+	/**
255
+	 * @return boolean
256
+	 */
257
+	public function displayable()
258
+	{
259
+		return $this->displayable;
260
+	}
261
+
262
+
263
+
264
+	/**
265
+	 * @param boolean $displayable
266
+	 */
267
+	public function setDisplayable($displayable = false)
268
+	{
269
+		$this->displayable = filter_var($displayable, FILTER_VALIDATE_BOOLEAN);
270
+	}
271
+
272
+
273
+
274
+	/**
275
+	 * a public name for the form that can be displayed on the frontend of a site
276
+	 *
277
+	 * @return string
278
+	 */
279
+	public function formName()
280
+	{
281
+		return $this->form_name;
282
+	}
283
+
284
+
285
+
286
+	/**
287
+	 * @param string $form_name
288
+	 * @throws InvalidDataTypeException
289
+	 */
290
+	public function setFormName($form_name)
291
+	{
292
+		if (! is_string($form_name)) {
293
+			throw new InvalidDataTypeException('$form_name', $form_name, 'string');
294
+		}
295
+		$this->form_name = $form_name;
296
+	}
297
+
298
+
299
+
300
+	/**
301
+	 * a public name for the form that can be displayed, but only in the admin
302
+	 *
303
+	 * @return string
304
+	 */
305
+	public function adminName()
306
+	{
307
+		return $this->admin_name;
308
+	}
309
+
310
+
311
+
312
+	/**
313
+	 * @param string $admin_name
314
+	 * @throws InvalidDataTypeException
315
+	 */
316
+	public function setAdminName($admin_name)
317
+	{
318
+		if (! is_string($admin_name)) {
319
+			throw new InvalidDataTypeException('$admin_name', $admin_name, 'string');
320
+		}
321
+		$this->admin_name = $admin_name;
322
+	}
323
+
324
+
325
+
326
+	/**
327
+	 * a URL friendly string that can be used for identifying the form
328
+	 *
329
+	 * @return string
330
+	 */
331
+	public function slug()
332
+	{
333
+		return $this->slug;
334
+	}
335
+
336
+
337
+
338
+	/**
339
+	 * @param string $slug
340
+	 * @throws InvalidDataTypeException
341
+	 */
342
+	public function setSlug($slug)
343
+	{
344
+		if (! is_string($slug)) {
345
+			throw new InvalidDataTypeException('$slug', $slug, 'string');
346
+		}
347
+		$this->slug = $slug;
348
+	}
349
+
350
+
351
+
352
+	/**
353
+	 * @return string
354
+	 */
355
+	public function submitBtnText()
356
+	{
357
+		return $this->submit_btn_text;
358
+	}
359
+
360
+
361
+
362
+	/**
363
+	 * @param string $submit_btn_text
364
+	 * @throws InvalidDataTypeException
365
+	 * @throws InvalidArgumentException
366
+	 */
367
+	public function setSubmitBtnText($submit_btn_text)
368
+	{
369
+		if (! is_string($submit_btn_text)) {
370
+			throw new InvalidDataTypeException('$submit_btn_text', $submit_btn_text, 'string');
371
+		}
372
+		if (empty($submit_btn_text)) {
373
+			throw new InvalidArgumentException(
374
+				esc_html__('Can not set Submit button text because an empty string was provided.', 'event_espresso')
375
+			);
376
+		}
377
+		$this->submit_btn_text = $submit_btn_text;
378
+	}
379
+
380
+
381
+
382
+	/**
383
+	 * @return string
384
+	 */
385
+	public function formAction()
386
+	{
387
+		return ! empty($this->form_args)
388
+			? add_query_arg($this->form_args, $this->form_action)
389
+			: $this->form_action;
390
+	}
391
+
392
+
393
+
394
+	/**
395
+	 * @param string $form_action
396
+	 * @throws InvalidDataTypeException
397
+	 */
398
+	public function setFormAction($form_action)
399
+	{
400
+		if (! is_string($form_action)) {
401
+			throw new InvalidDataTypeException('$form_action', $form_action, 'string');
402
+		}
403
+		$this->form_action = $form_action;
404
+	}
405
+
406
+
407
+
408
+	/**
409
+	 * @param array $form_args
410
+	 * @throws InvalidDataTypeException
411
+	 * @throws InvalidArgumentException
412
+	 */
413
+	public function addFormActionArgs($form_args = array())
414
+	{
415
+		if (is_object($form_args)) {
416
+			throw new InvalidDataTypeException(
417
+				'$form_args',
418
+				$form_args,
419
+				'anything other than an object was expected.'
420
+			);
421
+		}
422
+		if (empty($form_args)) {
423
+			throw new InvalidArgumentException(
424
+				esc_html__('The redirect arguments can not be an empty array.', 'event_espresso')
425
+			);
426
+		}
427
+		$this->form_args = array_merge($this->form_args, $form_args);
428
+	}
429
+
430
+
431
+
432
+	/**
433
+	 * @return string
434
+	 */
435
+	public function formConfig()
436
+	{
437
+		return $this->form_config;
438
+	}
439
+
440
+
441
+
442
+	/**
443
+	 * @param string $form_config
444
+	 * @throws DomainException
445
+	 */
446
+	public function setFormConfig($form_config)
447
+	{
448
+		if (
449
+		! in_array(
450
+			$form_config,
451
+			array(
452
+				FormHandler::ADD_FORM_TAGS_AND_SUBMIT,
453
+				FormHandler::ADD_FORM_TAGS_ONLY,
454
+				FormHandler::ADD_FORM_SUBMIT_ONLY,
455
+				FormHandler::DO_NOT_SETUP_FORM,
456
+			),
457
+			true
458
+		)
459
+		) {
460
+			throw new DomainException(
461
+				sprintf(
462
+					esc_html__('"%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',
463
+						'event_espresso'),
464
+					$form_config
465
+				)
466
+			);
467
+		}
468
+		$this->form_config = $form_config;
469
+	}
470
+
471
+
472
+
473
+	/**
474
+	 * called after the form is instantiated
475
+	 * and used for performing any logic that needs to occur early
476
+	 * before any of the other methods are called.
477
+	 * returns true if everything is ok to proceed,
478
+	 * and false if no further form logic should be implemented
479
+	 *
480
+	 * @return boolean
481
+	 */
482
+	public function initialize()
483
+	{
484
+		$this->form_has_errors = EE_Error::has_error(true);
485
+		return true;
486
+	}
487
+
488
+
489
+
490
+	/**
491
+	 * used for setting up css and js
492
+	 *
493
+	 * @return void
494
+	 * @throws LogicException
495
+	 * @throws EE_Error
496
+	 */
497
+	public function enqueueStylesAndScripts()
498
+	{
499
+		$this->form()->enqueue_js();
500
+	}
501
+
502
+
503
+
504
+	/**
505
+	 * creates and returns the actual form
506
+	 *
507
+	 * @return EE_Form_Section_Proper
508
+	 */
509
+	abstract public function generate();
510
+
511
+
512
+
513
+	/**
514
+	 * creates and returns an EE_Submit_Input labeled "Submit"
515
+	 *
516
+	 * @param string $text
517
+	 * @return EE_Submit_Input
518
+	 */
519
+	public function generateSubmitButton($text = '')
520
+	{
521
+		$text = ! empty($text) ? $text : $this->submitBtnText();
522
+		return new EE_Submit_Input(
523
+			array(
524
+				'html_name'             => 'ee-form-submit-' . $this->slug(),
525
+				'html_id'               => 'ee-form-submit-' . $this->slug(),
526
+				'html_class'            => 'ee-form-submit',
527
+				'html_label'            => '&nbsp;',
528
+				'other_html_attributes' => ' rel="' . $this->slug() . '"',
529
+				'default'               => $text,
530
+			)
531
+		);
532
+	}
533
+
534
+
535
+
536
+	/**
537
+	 * calls generateSubmitButton() and appends it onto the form along with a float clearing div
538
+	 *
539
+	 * @param string $text
540
+	 * @return void
541
+	 * @throws LogicException
542
+	 * @throws EE_Error
543
+	 */
544
+	public function appendSubmitButton($text = '')
545
+	{
546
+		if ($this->form->subsection_exists($this->slug() . '-submit-btn')) {
547
+			return;
548
+		}
549
+		$this->form->add_subsections(
550
+			array($this->slug() . '-submit-btn' => $this->generateSubmitButton($text)),
551
+			null,
552
+			false
553
+		);
554
+	}
555
+
556
+
557
+
558
+	/**
559
+	 * creates and returns an EE_Submit_Input labeled "Cancel"
560
+	 *
561
+	 * @param string $text
562
+	 * @return EE_Submit_Input
563
+	 */
564
+	public function generateCancelButton($text = '')
565
+	{
566
+		$cancel_button = new EE_Submit_Input(
567
+			array(
568
+				'html_name'             => 'ee-form-submit-' . $this->slug(), // YES! Same name as submit !!!
569
+				'html_id'               => 'ee-cancel-form-' . $this->slug(),
570
+				'html_class'            => 'ee-cancel-form',
571
+				'html_label'            => '&nbsp;',
572
+				'other_html_attributes' => ' rel="' . $this->slug() . '"',
573
+				'default'               => ! empty($text) ? $text : esc_html__('Cancel', 'event_espresso'),
574
+			)
575
+		);
576
+		$cancel_button->set_button_css_attributes(false);
577
+		return $cancel_button;
578
+	}
579
+
580
+
581
+
582
+	/**
583
+	 * appends a float clearing div onto end of form
584
+	 *
585
+	 * @return void
586
+	 * @throws EE_Error
587
+	 */
588
+	public function clearFormButtonFloats()
589
+	{
590
+		$this->form->add_subsections(
591
+			array(
592
+				'clear-submit-btn-float' => new EE_Form_Section_HTML(
593
+					EEH_HTML::div('', '', 'clear-float') . EEH_HTML::divx()
594
+				),
595
+			),
596
+			null,
597
+			false
598
+		);
599
+	}
600
+
601
+
602
+
603
+	/**
604
+	 * takes the generated form and displays it along with ony other non-form HTML that may be required
605
+	 * returns a string of HTML that can be directly echoed in a template
606
+	 *
607
+	 * @return string
608
+	 * @throws LogicException
609
+	 * @throws EE_Error
610
+	 */
611
+	public function display()
612
+	{
613
+		$form_html = apply_filters(
614
+			'FHEE__EventEspresso_core_libraries_form_sections_form_handlers_FormHandler__display__before_form',
615
+			''
616
+		);
617
+		$form_config = $this->formConfig();
618
+		if (
619
+			$form_config === FormHandler::ADD_FORM_TAGS_AND_SUBMIT
620
+			|| $form_config === FormHandler::ADD_FORM_TAGS_ONLY
621
+		) {
622
+			$form_html .= $this->form()->form_open($this->formAction());
623
+		}
624
+		$form_html .= $this->form(true)->get_html($this->form_has_errors);
625
+		if (
626
+			$form_config === FormHandler::ADD_FORM_TAGS_AND_SUBMIT
627
+			|| $form_config === FormHandler::ADD_FORM_TAGS_ONLY
628
+		) {
629
+			$form_html .= $this->form()->form_close();
630
+		}
631
+		$form_html .= apply_filters(
632
+			'FHEE__EventEspresso_core_libraries_form_sections_form_handlers_FormHandler__display__after_form',
633
+			''
634
+		);
635
+		return $form_html;
636
+	}
637
+
638
+
639
+
640
+	/**
641
+	 * handles processing the form submission
642
+	 * returns true or false depending on whether the form was processed successfully or not
643
+	 *
644
+	 * @param array $submitted_form_data
645
+	 * @return array
646
+	 * @throws EE_Error
647
+	 * @throws LogicException
648
+	 * @throws InvalidFormSubmissionException
649
+	 */
650
+	public function process($submitted_form_data = array())
651
+	{
652
+		if (! $this->form()->was_submitted($submitted_form_data)) {
653
+			throw new InvalidFormSubmissionException($this->form_name);
654
+		}
655
+		$this->form(true)->receive_form_submission($submitted_form_data);
656
+		if (! $this->form()->is_valid()) {
657
+			throw new InvalidFormSubmissionException(
658
+				$this->form_name,
659
+				sprintf(
660
+					esc_html__(
661
+						'The "%1$s" form is invalid. Please correct the following errors and resubmit: %2$s %3$s',
662
+						'event_espresso'
663
+					),
664
+					$this->form_name,
665
+					'<br />',
666
+					$this->form()->submission_error_message()
667
+				)
668
+			);
669
+		}
670
+		return $this->form()->valid_data();
671
+	}
672 672
 
673 673
 
674 674
 
Please login to merge, or discard this patch.
Spacing   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -14,7 +14,7 @@  discard block
 block discarded – undo
14 14
 use EventEspresso\core\exceptions\InvalidDataTypeException;
15 15
 use EventEspresso\core\exceptions\InvalidFormSubmissionException;
16 16
 
17
-if (! defined('EVENT_ESPRESSO_VERSION')) {
17
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
18 18
     exit('No direct script access allowed');
19 19
 }
20 20
 
@@ -179,7 +179,7 @@  discard block
 block discarded – undo
179 179
      */
180 180
     public function form($for_display = false)
181 181
     {
182
-        if (! $this->formIsValid()) {
182
+        if ( ! $this->formIsValid()) {
183 183
             return null;
184 184
         }
185 185
         if ($for_display) {
@@ -289,7 +289,7 @@  discard block
 block discarded – undo
289 289
      */
290 290
     public function setFormName($form_name)
291 291
     {
292
-        if (! is_string($form_name)) {
292
+        if ( ! is_string($form_name)) {
293 293
             throw new InvalidDataTypeException('$form_name', $form_name, 'string');
294 294
         }
295 295
         $this->form_name = $form_name;
@@ -315,7 +315,7 @@  discard block
 block discarded – undo
315 315
      */
316 316
     public function setAdminName($admin_name)
317 317
     {
318
-        if (! is_string($admin_name)) {
318
+        if ( ! is_string($admin_name)) {
319 319
             throw new InvalidDataTypeException('$admin_name', $admin_name, 'string');
320 320
         }
321 321
         $this->admin_name = $admin_name;
@@ -341,7 +341,7 @@  discard block
 block discarded – undo
341 341
      */
342 342
     public function setSlug($slug)
343 343
     {
344
-        if (! is_string($slug)) {
344
+        if ( ! is_string($slug)) {
345 345
             throw new InvalidDataTypeException('$slug', $slug, 'string');
346 346
         }
347 347
         $this->slug = $slug;
@@ -366,7 +366,7 @@  discard block
 block discarded – undo
366 366
      */
367 367
     public function setSubmitBtnText($submit_btn_text)
368 368
     {
369
-        if (! is_string($submit_btn_text)) {
369
+        if ( ! is_string($submit_btn_text)) {
370 370
             throw new InvalidDataTypeException('$submit_btn_text', $submit_btn_text, 'string');
371 371
         }
372 372
         if (empty($submit_btn_text)) {
@@ -397,7 +397,7 @@  discard block
 block discarded – undo
397 397
      */
398 398
     public function setFormAction($form_action)
399 399
     {
400
-        if (! is_string($form_action)) {
400
+        if ( ! is_string($form_action)) {
401 401
             throw new InvalidDataTypeException('$form_action', $form_action, 'string');
402 402
         }
403 403
         $this->form_action = $form_action;
@@ -521,11 +521,11 @@  discard block
 block discarded – undo
521 521
         $text = ! empty($text) ? $text : $this->submitBtnText();
522 522
         return new EE_Submit_Input(
523 523
             array(
524
-                'html_name'             => 'ee-form-submit-' . $this->slug(),
525
-                'html_id'               => 'ee-form-submit-' . $this->slug(),
524
+                'html_name'             => 'ee-form-submit-'.$this->slug(),
525
+                'html_id'               => 'ee-form-submit-'.$this->slug(),
526 526
                 'html_class'            => 'ee-form-submit',
527 527
                 'html_label'            => '&nbsp;',
528
-                'other_html_attributes' => ' rel="' . $this->slug() . '"',
528
+                'other_html_attributes' => ' rel="'.$this->slug().'"',
529 529
                 'default'               => $text,
530 530
             )
531 531
         );
@@ -543,11 +543,11 @@  discard block
 block discarded – undo
543 543
      */
544 544
     public function appendSubmitButton($text = '')
545 545
     {
546
-        if ($this->form->subsection_exists($this->slug() . '-submit-btn')) {
546
+        if ($this->form->subsection_exists($this->slug().'-submit-btn')) {
547 547
             return;
548 548
         }
549 549
         $this->form->add_subsections(
550
-            array($this->slug() . '-submit-btn' => $this->generateSubmitButton($text)),
550
+            array($this->slug().'-submit-btn' => $this->generateSubmitButton($text)),
551 551
             null,
552 552
             false
553 553
         );
@@ -565,11 +565,11 @@  discard block
 block discarded – undo
565 565
     {
566 566
         $cancel_button = new EE_Submit_Input(
567 567
             array(
568
-                'html_name'             => 'ee-form-submit-' . $this->slug(), // YES! Same name as submit !!!
569
-                'html_id'               => 'ee-cancel-form-' . $this->slug(),
568
+                'html_name'             => 'ee-form-submit-'.$this->slug(), // YES! Same name as submit !!!
569
+                'html_id'               => 'ee-cancel-form-'.$this->slug(),
570 570
                 'html_class'            => 'ee-cancel-form',
571 571
                 'html_label'            => '&nbsp;',
572
-                'other_html_attributes' => ' rel="' . $this->slug() . '"',
572
+                'other_html_attributes' => ' rel="'.$this->slug().'"',
573 573
                 'default'               => ! empty($text) ? $text : esc_html__('Cancel', 'event_espresso'),
574 574
             )
575 575
         );
@@ -590,7 +590,7 @@  discard block
 block discarded – undo
590 590
         $this->form->add_subsections(
591 591
             array(
592 592
                 'clear-submit-btn-float' => new EE_Form_Section_HTML(
593
-                    EEH_HTML::div('', '', 'clear-float') . EEH_HTML::divx()
593
+                    EEH_HTML::div('', '', 'clear-float').EEH_HTML::divx()
594 594
                 ),
595 595
             ),
596 596
             null,
@@ -649,11 +649,11 @@  discard block
 block discarded – undo
649 649
      */
650 650
     public function process($submitted_form_data = array())
651 651
     {
652
-        if (! $this->form()->was_submitted($submitted_form_data)) {
652
+        if ( ! $this->form()->was_submitted($submitted_form_data)) {
653 653
             throw new InvalidFormSubmissionException($this->form_name);
654 654
         }
655 655
         $this->form(true)->receive_form_submission($submitted_form_data);
656
-        if (! $this->form()->is_valid()) {
656
+        if ( ! $this->form()->is_valid()) {
657 657
             throw new InvalidFormSubmissionException(
658 658
                 $this->form_name,
659 659
                 sprintf(
Please login to merge, or discard this patch.