Completed
Branch FET/event-question-group-refac... (8c9768)
by
unknown
27:04 queued 17:53
created
core/services/request/files/FilesDataHandler.php 2 patches
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -114,7 +114,7 @@  discard block
 block discarded – undo
114 114
      */
115 115
     protected function isStrangeFilesArray($files_data)
116 116
     {
117
-        if (!is_array($files_data)) {
117
+        if ( ! is_array($files_data)) {
118 118
             throw new UnexpectedValueException(
119 119
                 sprintf(
120 120
                     esc_html__(
@@ -126,7 +126,7 @@  discard block
 block discarded – undo
126 126
             );
127 127
         }
128 128
         $first_value = reset($files_data);
129
-        if (!is_array($first_value)) {
129
+        if ( ! is_array($first_value)) {
130 130
             throw new UnexpectedValueException(
131 131
                 sprintf(
132 132
                     esc_html__(
@@ -160,14 +160,14 @@  discard block
 block discarded – undo
160 160
         $sane_files_array = [];
161 161
         foreach ($files_data as $top_level_name => $top_level_children) {
162 162
             $sub_array = [];
163
-            $sane_files_array[ $top_level_name ] = [];
163
+            $sane_files_array[$top_level_name] = [];
164 164
             foreach ($top_level_children as $file_data_part => $second_level_children) {
165 165
                 foreach ($second_level_children as $next_level_name => $sub_values) {
166
-                    $sub_array[ $next_level_name ] = $this->organizeFilesData($sub_values, $file_data_part);
166
+                    $sub_array[$next_level_name] = $this->organizeFilesData($sub_values, $file_data_part);
167 167
                 }
168
-                $sane_files_array[ $top_level_name ] = array_replace_recursive(
168
+                $sane_files_array[$top_level_name] = array_replace_recursive(
169 169
                     $sub_array,
170
-                    $sane_files_array[ $top_level_name ]
170
+                    $sane_files_array[$top_level_name]
171 171
                 );
172 172
             }
173 173
         }
@@ -184,7 +184,7 @@  discard block
 block discarded – undo
184 184
      */
185 185
     protected function organizeFilesData($data, $type)
186 186
     {
187
-        if (! is_array($data)) {
187
+        if ( ! is_array($data)) {
188 188
             return [
189 189
                 $type => $data
190 190
             ];
@@ -192,9 +192,9 @@  discard block
 block discarded – undo
192 192
         $organized_data = [];
193 193
         foreach ($data as $input_name_part => $sub_inputs_or_value) {
194 194
             if (is_array($sub_inputs_or_value)) {
195
-                $organized_data[ $input_name_part ] = $this->organizeFilesData($sub_inputs_or_value, $type);
195
+                $organized_data[$input_name_part] = $this->organizeFilesData($sub_inputs_or_value, $type);
196 196
             } else {
197
-                $organized_data[ $input_name_part ][ $type ] = $sub_inputs_or_value;
197
+                $organized_data[$input_name_part][$type] = $sub_inputs_or_value;
198 198
             }
199 199
         }
200 200
         return $organized_data;
@@ -212,7 +212,7 @@  discard block
 block discarded – undo
212 212
      */
213 213
     protected function createFileObjects($organized_files, $name_parts_so_far = [])
214 214
     {
215
-        if (!is_array($organized_files)) {
215
+        if ( ! is_array($organized_files)) {
216 216
             throw new UnexpectedValueException(
217 217
                 sprintf(
218 218
                     esc_html__(
@@ -255,7 +255,7 @@  discard block
 block discarded – undo
255 255
      */
256 256
     protected function inputNameFromParts($parts)
257 257
     {
258
-        if (!is_array($parts)) {
258
+        if ( ! is_array($parts)) {
259 259
             throw new UnexpectedValueException(esc_html__('Name parts should be an array.', 'event_espresso'));
260 260
         }
261 261
         $generated_string = '';
@@ -263,7 +263,7 @@  discard block
 block discarded – undo
263 263
             if ($generated_string === '') {
264 264
                 $generated_string = (string) $part;
265 265
             } else {
266
-                $generated_string .= '[' . (string) $part . ']';
266
+                $generated_string .= '['.(string) $part.']';
267 267
             }
268 268
         }
269 269
         return $generated_string;
Please login to merge, or discard this patch.
Indentation   +246 added lines, -246 removed lines patch added patch discarded remove patch
@@ -38,264 +38,264 @@
 block discarded – undo
38 38
  */
39 39
 class FilesDataHandler
40 40
 {
41
-    /**
42
-     * @var Request
43
-     */
44
-    protected $request;
41
+	/**
42
+	 * @var Request
43
+	 */
44
+	protected $request;
45 45
 
46
-    /**
47
-     * @var CollectionInterface | FileSubmissionInterface[]
48
-     */
49
-    protected $file_objects;
46
+	/**
47
+	 * @var CollectionInterface | FileSubmissionInterface[]
48
+	 */
49
+	protected $file_objects;
50 50
 
51
-    /**
52
-     * @var bool
53
-     */
54
-    protected $initialized = false;
51
+	/**
52
+	 * @var bool
53
+	 */
54
+	protected $initialized = false;
55 55
 
56
-    /**
57
-     * FilesDataHandler constructor.
58
-     * @param Request $request
59
-     */
60
-    public function __construct(Request $request)
61
-    {
62
-        $this->request = $request;
63
-    }
56
+	/**
57
+	 * FilesDataHandler constructor.
58
+	 * @param Request $request
59
+	 */
60
+	public function __construct(Request $request)
61
+	{
62
+		$this->request = $request;
63
+	}
64 64
 
65
-    /**
66
-     * @since 4.9.80.p
67
-     * @return CollectionInterface | FileSubmissionInterface[]
68
-     * @throws UnexpectedValueException
69
-     * @throws InvalidArgumentException
70
-     */
71
-    protected function getFileObjects()
72
-    {
73
-        $this->initialize();
74
-        return $this->file_objects;
75
-    }
65
+	/**
66
+	 * @since 4.9.80.p
67
+	 * @return CollectionInterface | FileSubmissionInterface[]
68
+	 * @throws UnexpectedValueException
69
+	 * @throws InvalidArgumentException
70
+	 */
71
+	protected function getFileObjects()
72
+	{
73
+		$this->initialize();
74
+		return $this->file_objects;
75
+	}
76 76
 
77
-    /**
78
-     * Sets up the file objects from the request's $_FILES data.
79
-     * @since 4.9.80.p
80
-     * @throws UnexpectedValueException
81
-     * @throws InvalidArgumentException
82
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
83
-     */
84
-    protected function initialize()
85
-    {
86
-        if ($this->initialized) {
87
-            return;
88
-        }
89
-        $this->file_objects = new Collection(
90
-            // collection interface
91
-            'EventEspresso\core\services\request\files\FileSubmissionInterface',
92
-            // collection name
93
-            'submitted_files'
94
-        );
95
-        $files_raw_data = $this->request->filesParams();
96
-        if (empty($files_raw_data)) {
97
-            return;
98
-        }
99
-        if ($this->isStrangeFilesArray($files_raw_data)) {
100
-            $data = $this->fixFilesDataArray($files_raw_data);
101
-        } else {
102
-            $data = $files_raw_data;
103
-        }
104
-        $this->createFileObjects($data);
105
-        $this->initialized = true;
106
-    }
77
+	/**
78
+	 * Sets up the file objects from the request's $_FILES data.
79
+	 * @since 4.9.80.p
80
+	 * @throws UnexpectedValueException
81
+	 * @throws InvalidArgumentException
82
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
83
+	 */
84
+	protected function initialize()
85
+	{
86
+		if ($this->initialized) {
87
+			return;
88
+		}
89
+		$this->file_objects = new Collection(
90
+			// collection interface
91
+			'EventEspresso\core\services\request\files\FileSubmissionInterface',
92
+			// collection name
93
+			'submitted_files'
94
+		);
95
+		$files_raw_data = $this->request->filesParams();
96
+		if (empty($files_raw_data)) {
97
+			return;
98
+		}
99
+		if ($this->isStrangeFilesArray($files_raw_data)) {
100
+			$data = $this->fixFilesDataArray($files_raw_data);
101
+		} else {
102
+			$data = $files_raw_data;
103
+		}
104
+		$this->createFileObjects($data);
105
+		$this->initialized = true;
106
+	}
107 107
 
108
-    /**
109
-     * Detects if $_FILES is a weird multi-dimensional array that needs fixing or not.
110
-     * @since 4.9.80.p
111
-     * @param $files_data
112
-     * @return bool
113
-     * @throws UnexpectedValueException
114
-     */
115
-    protected function isStrangeFilesArray($files_data)
116
-    {
117
-        if (!is_array($files_data)) {
118
-            throw new UnexpectedValueException(
119
-                sprintf(
120
-                    esc_html__(
121
-                        'Unexpected PHP $_FILES data format. "%1$s" was expected to be an array.',
122
-                        'event_espresso'
123
-                    ),
124
-                    (string) $files_data
125
-                )
126
-            );
127
-        }
128
-        $first_value = reset($files_data);
129
-        if (!is_array($first_value)) {
130
-            throw new UnexpectedValueException(
131
-                sprintf(
132
-                    esc_html__(
133
-                        'Unexpected PHP $_FILES data format. "%1$s" was expected to be an array.',
134
-                        'event_espresso'
135
-                    ),
136
-                    (string) $first_value
137
-                )
138
-            );
139
-        }
140
-        $first_sub_array_item = reset($first_value);
141
-        if (is_array($first_sub_array_item)) {
142
-            // not just a 2d array
143
-            return true;
144
-        }
145
-        // yep, just 2d array
146
-        return false;
147
-    }
108
+	/**
109
+	 * Detects if $_FILES is a weird multi-dimensional array that needs fixing or not.
110
+	 * @since 4.9.80.p
111
+	 * @param $files_data
112
+	 * @return bool
113
+	 * @throws UnexpectedValueException
114
+	 */
115
+	protected function isStrangeFilesArray($files_data)
116
+	{
117
+		if (!is_array($files_data)) {
118
+			throw new UnexpectedValueException(
119
+				sprintf(
120
+					esc_html__(
121
+						'Unexpected PHP $_FILES data format. "%1$s" was expected to be an array.',
122
+						'event_espresso'
123
+					),
124
+					(string) $files_data
125
+				)
126
+			);
127
+		}
128
+		$first_value = reset($files_data);
129
+		if (!is_array($first_value)) {
130
+			throw new UnexpectedValueException(
131
+				sprintf(
132
+					esc_html__(
133
+						'Unexpected PHP $_FILES data format. "%1$s" was expected to be an array.',
134
+						'event_espresso'
135
+					),
136
+					(string) $first_value
137
+				)
138
+			);
139
+		}
140
+		$first_sub_array_item = reset($first_value);
141
+		if (is_array($first_sub_array_item)) {
142
+			// not just a 2d array
143
+			return true;
144
+		}
145
+		// yep, just 2d array
146
+		return false;
147
+	}
148 148
 
149
-    /**
150
-     * Takes into account that $_FILES does a weird thing when you have hierarchical form names (eg `<input type="file"
151
-     * name="my[hierarchical][form]">`): it leaves the top-level form part alone, but replaces the SECOND part with
152
-     * "name", "size", "tmp_name", etc. So that file's data is located at "my[name][hierarchical][form]",
153
-     * "my[size][hierarchical][form]", "my[tmp_name][hierarchical][form]", etc. It's really weird.
154
-     * @since 4.9.80.p
155
-     * @param $files_data
156
-     * @return array
157
-     */
158
-    protected function fixFilesDataArray($files_data)
159
-    {
160
-        $sane_files_array = [];
161
-        foreach ($files_data as $top_level_name => $top_level_children) {
162
-            $sub_array = [];
163
-            $sane_files_array[ $top_level_name ] = [];
164
-            foreach ($top_level_children as $file_data_part => $second_level_children) {
165
-                foreach ($second_level_children as $next_level_name => $sub_values) {
166
-                    $sub_array[ $next_level_name ] = $this->organizeFilesData($sub_values, $file_data_part);
167
-                }
168
-                $sane_files_array[ $top_level_name ] = array_replace_recursive(
169
-                    $sub_array,
170
-                    $sane_files_array[ $top_level_name ]
171
-                );
172
-            }
173
-        }
174
-        return $sane_files_array;
175
-    }
149
+	/**
150
+	 * Takes into account that $_FILES does a weird thing when you have hierarchical form names (eg `<input type="file"
151
+	 * name="my[hierarchical][form]">`): it leaves the top-level form part alone, but replaces the SECOND part with
152
+	 * "name", "size", "tmp_name", etc. So that file's data is located at "my[name][hierarchical][form]",
153
+	 * "my[size][hierarchical][form]", "my[tmp_name][hierarchical][form]", etc. It's really weird.
154
+	 * @since 4.9.80.p
155
+	 * @param $files_data
156
+	 * @return array
157
+	 */
158
+	protected function fixFilesDataArray($files_data)
159
+	{
160
+		$sane_files_array = [];
161
+		foreach ($files_data as $top_level_name => $top_level_children) {
162
+			$sub_array = [];
163
+			$sane_files_array[ $top_level_name ] = [];
164
+			foreach ($top_level_children as $file_data_part => $second_level_children) {
165
+				foreach ($second_level_children as $next_level_name => $sub_values) {
166
+					$sub_array[ $next_level_name ] = $this->organizeFilesData($sub_values, $file_data_part);
167
+				}
168
+				$sane_files_array[ $top_level_name ] = array_replace_recursive(
169
+					$sub_array,
170
+					$sane_files_array[ $top_level_name ]
171
+				);
172
+			}
173
+		}
174
+		return $sane_files_array;
175
+	}
176 176
 
177
-    /**
178
-     * Recursively explores the array until it finds a leaf node, and tacks `$type` as a final index in front of it.
179
-     * @since 4.9.80.p
180
-     * @param $data array|string
181
-     * @param $type 'name', 'tmp_name', 'size', or 'error'
182
-     * @param $name string
183
-     * @return array|string
184
-     */
185
-    protected function organizeFilesData($data, $type)
186
-    {
187
-        if (! is_array($data)) {
188
-            return [
189
-                $type => $data
190
-            ];
191
-        }
192
-        $organized_data = [];
193
-        foreach ($data as $input_name_part => $sub_inputs_or_value) {
194
-            if (is_array($sub_inputs_or_value)) {
195
-                $organized_data[ $input_name_part ] = $this->organizeFilesData($sub_inputs_or_value, $type);
196
-            } else {
197
-                $organized_data[ $input_name_part ][ $type ] = $sub_inputs_or_value;
198
-            }
199
-        }
200
-        return $organized_data;
201
-    }
177
+	/**
178
+	 * Recursively explores the array until it finds a leaf node, and tacks `$type` as a final index in front of it.
179
+	 * @since 4.9.80.p
180
+	 * @param $data array|string
181
+	 * @param $type 'name', 'tmp_name', 'size', or 'error'
182
+	 * @param $name string
183
+	 * @return array|string
184
+	 */
185
+	protected function organizeFilesData($data, $type)
186
+	{
187
+		if (! is_array($data)) {
188
+			return [
189
+				$type => $data
190
+			];
191
+		}
192
+		$organized_data = [];
193
+		foreach ($data as $input_name_part => $sub_inputs_or_value) {
194
+			if (is_array($sub_inputs_or_value)) {
195
+				$organized_data[ $input_name_part ] = $this->organizeFilesData($sub_inputs_or_value, $type);
196
+			} else {
197
+				$organized_data[ $input_name_part ][ $type ] = $sub_inputs_or_value;
198
+			}
199
+		}
200
+		return $organized_data;
201
+	}
202 202
 
203
-    /**
204
-     * Takes the organized $_FILES array (where all file info is located at the same spot as you'd expect an input
205
-     * to be in $_GET or $_POST, with all the file's data located side-by-side in an array) and creates a
206
-     * multi-dimensional array of FileSubmissionInterface objects. Stores it in `$this->file_objects`.
207
-     * @since 4.9.80.p
208
-     * @param array $organized_files $_FILES but organized like $_POST
209
-     * @param array $name_parts_so_far for multidimensional HTML form names,
210
-     * @throws UnexpectedValueException
211
-     * @throws InvalidArgumentException
212
-     */
213
-    protected function createFileObjects($organized_files, $name_parts_so_far = [])
214
-    {
215
-        if (!is_array($organized_files)) {
216
-            throw new UnexpectedValueException(
217
-                sprintf(
218
-                    esc_html__(
219
-                        'Unexpected PHP $organized_files data format. "%1$s" was expected to be an array.',
220
-                        'event_espresso'
221
-                    ),
222
-                    (string) $organized_files
223
-                )
224
-            );
225
-        }
226
-        foreach ($organized_files as $key => $value) {
227
-            $this_input_name_parts = $name_parts_so_far;
228
-            array_push(
229
-                $this_input_name_parts,
230
-                $key
231
-            );
232
-            if (isset($value['name'], $value['tmp_name'], $value['size'])) {
233
-                $html_name = $this->inputNameFromParts($this_input_name_parts);
234
-                $this->file_objects->add(
235
-                    new FileSubmission(
236
-                        $value['name'],
237
-                        $value['tmp_name'],
238
-                        $value['size'],
239
-                        $value['error']
240
-                    ),
241
-                    $html_name
242
-                );
243
-            } else {
244
-                $this->createFileObjects($value, $this_input_name_parts);
245
-            }
246
-        }
247
-    }
203
+	/**
204
+	 * Takes the organized $_FILES array (where all file info is located at the same spot as you'd expect an input
205
+	 * to be in $_GET or $_POST, with all the file's data located side-by-side in an array) and creates a
206
+	 * multi-dimensional array of FileSubmissionInterface objects. Stores it in `$this->file_objects`.
207
+	 * @since 4.9.80.p
208
+	 * @param array $organized_files $_FILES but organized like $_POST
209
+	 * @param array $name_parts_so_far for multidimensional HTML form names,
210
+	 * @throws UnexpectedValueException
211
+	 * @throws InvalidArgumentException
212
+	 */
213
+	protected function createFileObjects($organized_files, $name_parts_so_far = [])
214
+	{
215
+		if (!is_array($organized_files)) {
216
+			throw new UnexpectedValueException(
217
+				sprintf(
218
+					esc_html__(
219
+						'Unexpected PHP $organized_files data format. "%1$s" was expected to be an array.',
220
+						'event_espresso'
221
+					),
222
+					(string) $organized_files
223
+				)
224
+			);
225
+		}
226
+		foreach ($organized_files as $key => $value) {
227
+			$this_input_name_parts = $name_parts_so_far;
228
+			array_push(
229
+				$this_input_name_parts,
230
+				$key
231
+			);
232
+			if (isset($value['name'], $value['tmp_name'], $value['size'])) {
233
+				$html_name = $this->inputNameFromParts($this_input_name_parts);
234
+				$this->file_objects->add(
235
+					new FileSubmission(
236
+						$value['name'],
237
+						$value['tmp_name'],
238
+						$value['size'],
239
+						$value['error']
240
+					),
241
+					$html_name
242
+				);
243
+			} else {
244
+				$this->createFileObjects($value, $this_input_name_parts);
245
+			}
246
+		}
247
+	}
248 248
 
249
-    /**
250
-     * Takes the input name parts, like `['my', 'great', 'file', 'input1']`
251
-     * and returns the HTML name for it, "my[great][file][input1]"
252
-     * @since 4.9.80.p
253
-     * @param $parts
254
-     * @throws UnexpectedValueException
255
-     */
256
-    protected function inputNameFromParts($parts)
257
-    {
258
-        if (!is_array($parts)) {
259
-            throw new UnexpectedValueException(esc_html__('Name parts should be an array.', 'event_espresso'));
260
-        }
261
-        $generated_string = '';
262
-        foreach ($parts as $part) {
263
-            if ($generated_string === '') {
264
-                $generated_string = (string) $part;
265
-            } else {
266
-                $generated_string .= '[' . (string) $part . ']';
267
-            }
268
-        }
269
-        return $generated_string;
270
-    }
249
+	/**
250
+	 * Takes the input name parts, like `['my', 'great', 'file', 'input1']`
251
+	 * and returns the HTML name for it, "my[great][file][input1]"
252
+	 * @since 4.9.80.p
253
+	 * @param $parts
254
+	 * @throws UnexpectedValueException
255
+	 */
256
+	protected function inputNameFromParts($parts)
257
+	{
258
+		if (!is_array($parts)) {
259
+			throw new UnexpectedValueException(esc_html__('Name parts should be an array.', 'event_espresso'));
260
+		}
261
+		$generated_string = '';
262
+		foreach ($parts as $part) {
263
+			if ($generated_string === '') {
264
+				$generated_string = (string) $part;
265
+			} else {
266
+				$generated_string .= '[' . (string) $part . ']';
267
+			}
268
+		}
269
+		return $generated_string;
270
+	}
271 271
 
272
-    /**
273
-     * Gets the input by the indicated $name_parts.
274
-     * Eg if you're looking for an input named "my[great][file][input1]", $name_parts
275
-     * should be `['my', 'great', 'file', 'input1']`.
276
-     * Alternatively, you could use `FileDataHandler::getFileObject('my[great][file][input1]');`
277
-     * @since 4.9.80.p
278
-     * @param $name_parts
279
-     * @throws UnexpectedValueException
280
-     * @return FileSubmissionInterface
281
-     */
282
-    public function getFileObjectFromNameParts($name_parts)
283
-    {
284
-        return $this->getFileObjects()->get($this->inputNameFromParts($name_parts));
285
-    }
272
+	/**
273
+	 * Gets the input by the indicated $name_parts.
274
+	 * Eg if you're looking for an input named "my[great][file][input1]", $name_parts
275
+	 * should be `['my', 'great', 'file', 'input1']`.
276
+	 * Alternatively, you could use `FileDataHandler::getFileObject('my[great][file][input1]');`
277
+	 * @since 4.9.80.p
278
+	 * @param $name_parts
279
+	 * @throws UnexpectedValueException
280
+	 * @return FileSubmissionInterface
281
+	 */
282
+	public function getFileObjectFromNameParts($name_parts)
283
+	{
284
+		return $this->getFileObjects()->get($this->inputNameFromParts($name_parts));
285
+	}
286 286
 
287
-    /**
288
-     * Gets the FileSubmissionInterface corresponding to the HTML name provided.
289
-     * @since 4.9.80.p
290
-     * @param $html_name
291
-     * @return mixed
292
-     * @throws InvalidArgumentException
293
-     * @throws UnexpectedValueException
294
-     */
295
-    public function getFileObject($html_name)
296
-    {
297
-        return $this->getFileObjects()->get($html_name);
298
-    }
287
+	/**
288
+	 * Gets the FileSubmissionInterface corresponding to the HTML name provided.
289
+	 * @since 4.9.80.p
290
+	 * @param $html_name
291
+	 * @return mixed
292
+	 * @throws InvalidArgumentException
293
+	 * @throws UnexpectedValueException
294
+	 */
295
+	public function getFileObject($html_name)
296
+	{
297
+		return $this->getFileObjects()->get($html_name);
298
+	}
299 299
 }
300 300
 // End of file FilesDataHandler.php
301 301
 // Location: EventEspresso\core\services\request\files/FilesDataHandler.php
Please login to merge, or discard this patch.
strategies/validation/EE_Text_Validation_Strategy.strategy.php 2 patches
Indentation   +41 added lines, -41 removed lines patch added patch discarded remove patch
@@ -10,53 +10,53 @@
 block discarded – undo
10 10
 class EE_Text_Validation_Strategy extends EE_Validation_Strategy_Base
11 11
 {
12 12
 
13
-    protected $_regex = null;
14
-    /**
15
-     *
16
-     * @param string $validation_error_message
17
-     * @param string $regex a PHP regex; the javascript regex will be derived from this
18
-     */
19
-    public function __construct($validation_error_message = null, $regex = null)
20
-    {
21
-        $this->_regex = $regex;
22
-        parent::__construct($validation_error_message);
23
-    }
13
+	protected $_regex = null;
14
+	/**
15
+	 *
16
+	 * @param string $validation_error_message
17
+	 * @param string $regex a PHP regex; the javascript regex will be derived from this
18
+	 */
19
+	public function __construct($validation_error_message = null, $regex = null)
20
+	{
21
+		$this->_regex = $regex;
22
+		parent::__construct($validation_error_message);
23
+	}
24 24
 
25
-    /**
26
-     * @param $normalized_value
27
-     */
28
-    public function validate($normalized_value)
29
-    {
30
-        $string_normalized_value = (string) $normalized_value;
31
-        if ($this->_regex &&  $string_normalized_value) {
32
-            if (! preg_match($this->_regex, $string_normalized_value)) {
33
-                throw new EE_Validation_Error($this->get_validation_error_message(), 'regex');
34
-            }
35
-        }
36
-    }
25
+	/**
26
+	 * @param $normalized_value
27
+	 */
28
+	public function validate($normalized_value)
29
+	{
30
+		$string_normalized_value = (string) $normalized_value;
31
+		if ($this->_regex &&  $string_normalized_value) {
32
+			if (! preg_match($this->_regex, $string_normalized_value)) {
33
+				throw new EE_Validation_Error($this->get_validation_error_message(), 'regex');
34
+			}
35
+		}
36
+	}
37 37
 
38
-    /**
39
-     * @return array
40
-     */
41
-    public function get_jquery_validation_rule_array()
42
-    {
43
-        if ($this->_regex !== null) {
44
-            return array( 'regex'=> $this->regex_js(), 'messages' => array( 'regex' => $this->get_validation_error_message() ) );
45
-        } else {
46
-            return array();
47
-        }
48
-    }
38
+	/**
39
+	 * @return array
40
+	 */
41
+	public function get_jquery_validation_rule_array()
42
+	{
43
+		if ($this->_regex !== null) {
44
+			return array( 'regex'=> $this->regex_js(), 'messages' => array( 'regex' => $this->get_validation_error_message() ) );
45
+		} else {
46
+			return array();
47
+		}
48
+	}
49 49
 
50 50
 /**
51 51
  * Translates a PHP regex into a javscript regex (eg, PHP needs separate delimieters, whereas
52 52
  * javscript does not
53 53
  * @return string
54 54
  */
55
-    public function regex_js()
56
-    {
57
-        // first character must be the delimiter
58
-        $delimeter = $this->_regex[0];
59
-        $last_occurence_of_delimieter = strrpos($this->_regex, $delimeter);
60
-        return substr($this->_regex, 1, $last_occurence_of_delimieter - 1);
61
-    }
55
+	public function regex_js()
56
+	{
57
+		// first character must be the delimiter
58
+		$delimeter = $this->_regex[0];
59
+		$last_occurence_of_delimieter = strrpos($this->_regex, $delimeter);
60
+		return substr($this->_regex, 1, $last_occurence_of_delimieter - 1);
61
+	}
62 62
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -28,8 +28,8 @@  discard block
 block discarded – undo
28 28
     public function validate($normalized_value)
29 29
     {
30 30
         $string_normalized_value = (string) $normalized_value;
31
-        if ($this->_regex &&  $string_normalized_value) {
32
-            if (! preg_match($this->_regex, $string_normalized_value)) {
31
+        if ($this->_regex && $string_normalized_value) {
32
+            if ( ! preg_match($this->_regex, $string_normalized_value)) {
33 33
                 throw new EE_Validation_Error($this->get_validation_error_message(), 'regex');
34 34
             }
35 35
         }
@@ -41,7 +41,7 @@  discard block
 block discarded – undo
41 41
     public function get_jquery_validation_rule_array()
42 42
     {
43 43
         if ($this->_regex !== null) {
44
-            return array( 'regex'=> $this->regex_js(), 'messages' => array( 'regex' => $this->get_validation_error_message() ) );
44
+            return array('regex'=> $this->regex_js(), 'messages' => array('regex' => $this->get_validation_error_message()));
45 45
         } else {
46 46
             return array();
47 47
         }
Please login to merge, or discard this patch.
core/libraries/form_sections/inputs/EE_Form_Input_Base.input.php 1 patch
Indentation   +1236 added lines, -1236 removed lines patch added patch discarded remove patch
@@ -11,1240 +11,1240 @@
 block discarded – undo
11 11
 abstract class EE_Form_Input_Base extends EE_Form_Section_Validatable
12 12
 {
13 13
 
14
-    /**
15
-     * the input's name attribute
16
-     *
17
-     * @var string
18
-     */
19
-    protected $_html_name;
20
-
21
-    /**
22
-     * id for the html label tag
23
-     *
24
-     * @var string
25
-     */
26
-    protected $_html_label_id;
27
-
28
-    /**
29
-     * class for teh html label tag
30
-     *
31
-     * @var string
32
-     */
33
-    protected $_html_label_class;
34
-
35
-    /**
36
-     * any additional html attributes that you may want to add
37
-     *
38
-     * @var string
39
-     */
40
-    protected $_html_other_attributes;
41
-
42
-    /**
43
-     * style for teh html label tag
44
-     *
45
-     * @var string
46
-     */
47
-    protected $_html_label_style;
48
-
49
-    /**
50
-     * text to be placed in the html label
51
-     *
52
-     * @var string
53
-     */
54
-    protected $_html_label_text;
55
-
56
-    /**
57
-     * the full html label. If used, all other html_label_* properties are invalid
58
-     *
59
-     * @var string
60
-     */
61
-    protected $_html_label;
62
-
63
-    /**
64
-     * HTML to use for help text (normally placed below form input), in a span which normally
65
-     * has a class of 'description'
66
-     *
67
-     * @var string
68
-     */
69
-    protected $_html_help_text;
70
-
71
-    /**
72
-     * CSS classes for displaying the help span
73
-     *
74
-     * @var string
75
-     */
76
-    protected $_html_help_class = 'description';
77
-
78
-    /**
79
-     * CSS to put in the style attribute on the help span
80
-     *
81
-     * @var string
82
-     */
83
-    protected $_html_help_style;
84
-
85
-    /**
86
-     * Stores whether or not this input's response is required.
87
-     * Because certain styling elements may also want to know that this
88
-     * input is required etc.
89
-     *
90
-     * @var boolean
91
-     */
92
-    protected $_required;
93
-
94
-    /**
95
-     * css class added to required inputs
96
-     *
97
-     * @var string
98
-     */
99
-    protected $_required_css_class = 'ee-required';
100
-
101
-    /**
102
-     * css styles applied to button type inputs
103
-     *
104
-     * @var string
105
-     */
106
-    protected $_button_css_attributes;
107
-
108
-    /**
109
-     * The raw data submitted for this, like in the $_POST super global.
110
-     * Generally unsafe for usage in client code
111
-     *
112
-     * @var mixed string or array
113
-     */
114
-    protected $_raw_value;
115
-
116
-    /**
117
-     * Value normalized according to the input's normalization strategy.
118
-     * The normalization strategy dictates whether this is a string, int, float,
119
-     * boolean, or array of any of those.
120
-     *
121
-     * @var mixed
122
-     */
123
-    protected $_normalized_value;
124
-
125
-
126
-    /**
127
-     * Normalized default value either initially set on the input, or provided by calling
128
-     * set_default().
129
-     * @var mixed
130
-     */
131
-    protected $_default;
132
-
133
-    /**
134
-     * Strategy used for displaying this field.
135
-     * Child classes must use _get_display_strategy to access it.
136
-     *
137
-     * @var EE_Display_Strategy_Base
138
-     */
139
-    private $_display_strategy;
140
-
141
-    /**
142
-     * Gets all the validation strategies used on this field
143
-     *
144
-     * @var EE_Validation_Strategy_Base[]
145
-     */
146
-    private $_validation_strategies = array();
147
-
148
-    /**
149
-     * The normalization strategy for this field
150
-     *
151
-     * @var EE_Normalization_Strategy_Base
152
-     */
153
-    private $_normalization_strategy;
154
-
155
-    /**
156
-     * Strategy for removing sensitive data after we're done with the form input
157
-     *
158
-     * @var EE_Sensitive_Data_Removal_Base
159
-     */
160
-    protected $_sensitive_data_removal_strategy;
161
-
162
-    /**
163
-     * Whether this input has been disabled or not.
164
-     * If it's disabled while rendering, an extra hidden input is added that indicates it has been knowingly disabled.
165
-     * (Client-side code that wants to dynamically disable it must also add this hidden input).
166
-     * When the form is submitted, if the input is disabled in the PHP formsection, then input is ignored.
167
-     * If the input is missing from the $_REQUEST data but the hidden input indicating the input is disabled, then the input is again ignored.
168
-     *
169
-     * @var boolean
170
-     */
171
-    protected $disabled = false;
172
-
173
-
174
-
175
-    /**
176
-     * @param array                         $input_args       {
177
-     * @type string                         $html_name        the html name for the input
178
-     * @type string                         $html_label_id    the id attribute to give to the html label tag
179
-     * @type string                         $html_label_class the class attribute to give to the html label tag
180
-     * @type string                         $html_label_style the style attribute to give ot teh label tag
181
-     * @type string                         $html_label_text  the text to put in the label tag
182
-     * @type string                         $html_label       the full html label. If used,
183
-     *                                                        all other html_label_* args are invalid
184
-     * @type string                         $html_help_text   text to put in help element
185
-     * @type string                         $html_help_style  style attribute to give to teh help element
186
-     * @type string                         $html_help_class  class attribute to give to the help element
187
-     * @type string                         $default          default value NORMALIZED (eg, if providing the default
188
-     *       for a Yes_No_Input, you should provide TRUE or FALSE, not '1' or '0')
189
-     * @type EE_Display_Strategy_Base       $display          strategy
190
-     * @type EE_Normalization_Strategy_Base $normalization_strategy
191
-     * @type EE_Validation_Strategy_Base[]  $validation_strategies
192
-     * @type boolean                        $ignore_input special argument which can be used to avoid adding any validation strategies,
193
-     *                                                    and sets the normalization strategy to the Null normalization. This is good
194
-     *                                                    when you want the input to be totally ignored server-side (like when using
195
-     *                                                    React.js form inputs)
196
-     *                                                        }
197
-     */
198
-    public function __construct($input_args = array())
199
-    {
200
-        $input_args = (array) apply_filters('FHEE__EE_Form_Input_Base___construct__input_args', $input_args, $this);
201
-        // the following properties must be cast as arrays
202
-        if (isset($input_args['validation_strategies'])) {
203
-            foreach ((array) $input_args['validation_strategies'] as $validation_strategy) {
204
-                if ($validation_strategy instanceof EE_Validation_Strategy_Base && empty($input_args['ignore_input'])) {
205
-                    $this->_validation_strategies[ get_class($validation_strategy) ] = $validation_strategy;
206
-                }
207
-            }
208
-            unset($input_args['validation_strategies']);
209
-        }
210
-        if (isset($input_args['ignore_input'])) {
211
-            $this->_validation_strategies = array();
212
-        }
213
-        // loop thru incoming options
214
-        foreach ($input_args as $key => $value) {
215
-            // add underscore to $key to match property names
216
-            $_key = '_' . $key;
217
-            if (property_exists($this, $_key)) {
218
-                $this->{$_key} = $value;
219
-            }
220
-        }
221
-        // ensure that "required" is set correctly
222
-        $this->set_required(
223
-            $this->_required,
224
-            isset($input_args['required_validation_error_message'])
225
-            ? $input_args['required_validation_error_message']
226
-            : null
227
-        );
228
-        // $this->_html_name_specified = isset( $input_args['html_name'] ) ? TRUE : FALSE;
229
-        $this->_display_strategy->_construct_finalize($this);
230
-        foreach ($this->_validation_strategies as $validation_strategy) {
231
-            $validation_strategy->_construct_finalize($this);
232
-        }
233
-        if (isset($input_args['ignore_input'])) {
234
-            $this->_normalization_strategy = new EE_Null_Normalization();
235
-        }
236
-        if (! $this->_normalization_strategy) {
237
-                $this->_normalization_strategy = new EE_Text_Normalization();
238
-        }
239
-        $this->_normalization_strategy->_construct_finalize($this);
240
-        // at least we can use the normalization strategy to populate the default
241
-        if (isset($input_args['default'])) {
242
-            $this->set_default($input_args['default']);
243
-            unset($input_args['default']);
244
-        }
245
-        if (! $this->_sensitive_data_removal_strategy) {
246
-            $this->_sensitive_data_removal_strategy = new EE_No_Sensitive_Data_Removal();
247
-        }
248
-        $this->_sensitive_data_removal_strategy->_construct_finalize($this);
249
-        parent::__construct($input_args);
250
-    }
251
-
252
-
253
-
254
-    /**
255
-     * Sets the html_name to its default value, if none was specified in teh constructor.
256
-     * Calculation involves using the name and the parent's html_name
257
-     *
258
-     * @throws \EE_Error
259
-     */
260
-    protected function _set_default_html_name_if_empty()
261
-    {
262
-        if (! $this->_html_name) {
263
-            $this->_html_name = $this->name();
264
-            if ($this->_parent_section && $this->_parent_section instanceof EE_Form_Section_Proper) {
265
-                $this->_html_name = $this->_parent_section->html_name_prefix() . "[{$this->name()}]";
266
-            }
267
-        }
268
-    }
269
-
270
-
271
-
272
-    /**
273
-     * @param $parent_form_section
274
-     * @param $name
275
-     * @throws \EE_Error
276
-     */
277
-    public function _construct_finalize($parent_form_section, $name)
278
-    {
279
-        parent::_construct_finalize($parent_form_section, $name);
280
-        if ($this->_html_label === null && $this->_html_label_text === null) {
281
-            $this->_html_label_text = ucwords(str_replace("_", " ", $name));
282
-        }
283
-        do_action('AHEE__EE_Form_Input_Base___construct_finalize__end', $this, $parent_form_section, $name);
284
-    }
285
-
286
-
287
-
288
-    /**
289
-     * Returns the strategy for displaying this form input. If none is set, throws an exception.
290
-     *
291
-     * @return EE_Display_Strategy_Base
292
-     * @throws EE_Error
293
-     */
294
-    protected function _get_display_strategy()
295
-    {
296
-        $this->ensure_construct_finalized_called();
297
-        if (! $this->_display_strategy || ! $this->_display_strategy instanceof EE_Display_Strategy_Base) {
298
-            throw new EE_Error(
299
-                sprintf(
300
-                    __(
301
-                        "Cannot get display strategy for form input with name %s and id %s, because it has not been set in the constructor",
302
-                        "event_espresso"
303
-                    ),
304
-                    $this->html_name(),
305
-                    $this->html_id()
306
-                )
307
-            );
308
-        } else {
309
-            return $this->_display_strategy;
310
-        }
311
-    }
312
-
313
-
314
-
315
-    /**
316
-     * Sets the display strategy.
317
-     *
318
-     * @param EE_Display_Strategy_Base $strategy
319
-     */
320
-    protected function _set_display_strategy(EE_Display_Strategy_Base $strategy)
321
-    {
322
-        $this->_display_strategy = $strategy;
323
-    }
324
-
325
-
326
-
327
-    /**
328
-     * Sets the sanitization strategy
329
-     *
330
-     * @param EE_Normalization_Strategy_Base $strategy
331
-     */
332
-    protected function _set_normalization_strategy(EE_Normalization_Strategy_Base $strategy)
333
-    {
334
-        $this->_normalization_strategy = $strategy;
335
-    }
336
-
337
-
338
-
339
-    /**
340
-     * Gets sensitive_data_removal_strategy
341
-     *
342
-     * @return EE_Sensitive_Data_Removal_Base
343
-     */
344
-    public function get_sensitive_data_removal_strategy()
345
-    {
346
-        return $this->_sensitive_data_removal_strategy;
347
-    }
348
-
349
-
350
-
351
-    /**
352
-     * Sets sensitive_data_removal_strategy
353
-     *
354
-     * @param EE_Sensitive_Data_Removal_Base $sensitive_data_removal_strategy
355
-     * @return boolean
356
-     */
357
-    public function set_sensitive_data_removal_strategy($sensitive_data_removal_strategy)
358
-    {
359
-        $this->_sensitive_data_removal_strategy = $sensitive_data_removal_strategy;
360
-    }
361
-
362
-
363
-
364
-    /**
365
-     * Gets the display strategy for this input
366
-     *
367
-     * @return EE_Display_Strategy_Base
368
-     */
369
-    public function get_display_strategy()
370
-    {
371
-        return $this->_display_strategy;
372
-    }
373
-
374
-
375
-
376
-    /**
377
-     * Overwrites the display strategy
378
-     *
379
-     * @param EE_Display_Strategy_Base $display_strategy
380
-     */
381
-    public function set_display_strategy($display_strategy)
382
-    {
383
-        $this->_display_strategy = $display_strategy;
384
-        $this->_display_strategy->_construct_finalize($this);
385
-    }
386
-
387
-
388
-
389
-    /**
390
-     * Gets the normalization strategy set on this input
391
-     *
392
-     * @return EE_Normalization_Strategy_Base
393
-     */
394
-    public function get_normalization_strategy()
395
-    {
396
-        return $this->_normalization_strategy;
397
-    }
398
-
399
-
400
-
401
-    /**
402
-     * Overwrites the normalization strategy
403
-     *
404
-     * @param EE_Normalization_Strategy_Base $normalization_strategy
405
-     */
406
-    public function set_normalization_strategy($normalization_strategy)
407
-    {
408
-        $this->_normalization_strategy = $normalization_strategy;
409
-        $this->_normalization_strategy->_construct_finalize($this);
410
-    }
411
-
412
-
413
-
414
-    /**
415
-     * Returns all teh validation strategies which apply to this field, numerically indexed
416
-     *
417
-     * @return EE_Validation_Strategy_Base[]
418
-     */
419
-    public function get_validation_strategies()
420
-    {
421
-        return $this->_validation_strategies;
422
-    }
423
-
424
-
425
-
426
-    /**
427
-     * Adds this strategy to the field so it will be used in both JS validation and server-side validation
428
-     *
429
-     * @param EE_Validation_Strategy_Base $validation_strategy
430
-     * @return void
431
-     */
432
-    protected function _add_validation_strategy(EE_Validation_Strategy_Base $validation_strategy)
433
-    {
434
-        $validation_strategy->_construct_finalize($this);
435
-        $this->_validation_strategies[] = $validation_strategy;
436
-    }
437
-
438
-
439
-
440
-    /**
441
-     * Adds a new validation strategy onto the form input
442
-     *
443
-     * @param EE_Validation_Strategy_Base $validation_strategy
444
-     * @return void
445
-     */
446
-    public function add_validation_strategy(EE_Validation_Strategy_Base $validation_strategy)
447
-    {
448
-        $this->_add_validation_strategy($validation_strategy);
449
-    }
450
-
451
-
452
-
453
-    /**
454
-     * The classname of the validation strategy to remove
455
-     *
456
-     * @param string $validation_strategy_classname
457
-     */
458
-    public function remove_validation_strategy($validation_strategy_classname)
459
-    {
460
-        foreach ($this->_validation_strategies as $key => $validation_strategy) {
461
-            if ($validation_strategy instanceof $validation_strategy_classname
462
-                || is_subclass_of($validation_strategy, $validation_strategy_classname)
463
-            ) {
464
-                unset($this->_validation_strategies[ $key ]);
465
-            }
466
-        }
467
-    }
468
-
469
-
470
-
471
-    /**
472
-     * returns true if input employs any of the validation strategy defined by the supplied array of classnames
473
-     *
474
-     * @param array $validation_strategy_classnames
475
-     * @return bool
476
-     */
477
-    public function has_validation_strategy($validation_strategy_classnames)
478
-    {
479
-        $validation_strategy_classnames = is_array($validation_strategy_classnames)
480
-            ? $validation_strategy_classnames
481
-            : array($validation_strategy_classnames);
482
-        foreach ($this->_validation_strategies as $key => $validation_strategy) {
483
-            if (in_array($key, $validation_strategy_classnames)) {
484
-                return true;
485
-            }
486
-        }
487
-        return false;
488
-    }
489
-
490
-
491
-
492
-    /**
493
-     * Gets the HTML
494
-     *
495
-     * @return string
496
-     */
497
-    public function get_html()
498
-    {
499
-        return $this->_parent_section->get_html_for_input($this);
500
-    }
501
-
502
-
503
-
504
-    /**
505
-     * Gets the HTML for the input itself (no label or errors) according to the
506
-     * input's display strategy
507
-     * Makes sure the JS and CSS are enqueued for it
508
-     *
509
-     * @return string
510
-     * @throws \EE_Error
511
-     */
512
-    public function get_html_for_input()
513
-    {
514
-        return $this->_form_html_filter
515
-            ? $this->_form_html_filter->filterHtml(
516
-                $this->_get_display_strategy()->display(),
517
-                $this
518
-            )
519
-            : $this->_get_display_strategy()->display();
520
-    }
521
-
522
-
523
-
524
-    /**
525
-     * @return string
526
-     */
527
-    public function html_other_attributes()
528
-    {
529
-        return ! empty($this->_html_other_attributes) ? ' ' . $this->_html_other_attributes : '';
530
-    }
531
-
532
-
533
-
534
-    /**
535
-     * @param string $html_other_attributes
536
-     */
537
-    public function set_html_other_attributes($html_other_attributes)
538
-    {
539
-        $this->_html_other_attributes = $html_other_attributes;
540
-    }
541
-
542
-
543
-
544
-    /**
545
-     * Gets the HTML for displaying the label for this form input
546
-     * according to the form section's layout strategy
547
-     *
548
-     * @return string
549
-     */
550
-    public function get_html_for_label()
551
-    {
552
-        return $this->_parent_section->get_layout_strategy()->display_label($this);
553
-    }
554
-
555
-
556
-
557
-    /**
558
-     * Gets the HTML for displaying the errors section for this form input
559
-     * according to the form section's layout strategy
560
-     *
561
-     * @return string
562
-     */
563
-    public function get_html_for_errors()
564
-    {
565
-        return $this->_parent_section->get_layout_strategy()->display_errors($this);
566
-    }
567
-
568
-
569
-
570
-    /**
571
-     * Gets the HTML for displaying the help text for this form input
572
-     * according to the form section's layout strategy
573
-     *
574
-     * @return string
575
-     */
576
-    public function get_html_for_help()
577
-    {
578
-        return $this->_parent_section->get_layout_strategy()->display_help_text($this);
579
-    }
580
-
581
-
582
-
583
-    /**
584
-     * Validates the input's sanitized value (assumes _sanitize() has already been called)
585
-     * and returns whether or not the form input's submitted value is value
586
-     *
587
-     * @return boolean
588
-     */
589
-    protected function _validate()
590
-    {
591
-        if ($this->isDisabled()) {
592
-            return true;
593
-        }
594
-        foreach ($this->_validation_strategies as $validation_strategy) {
595
-            if ($validation_strategy instanceof EE_Validation_Strategy_Base) {
596
-                try {
597
-                    $validation_strategy->validate($this->normalized_value());
598
-                } catch (EE_Validation_Error $e) {
599
-                    $this->add_validation_error($e);
600
-                }
601
-            }
602
-        }
603
-        if ($this->get_validation_errors()) {
604
-            return false;
605
-        } else {
606
-            return true;
607
-        }
608
-    }
609
-
610
-
611
-
612
-    /**
613
-     * Performs basic sanitization on this value. But what sanitization can be performed anyways?
614
-     * This value MIGHT be allowed to have tags, so we can't really remove them.
615
-     *
616
-     * @param string $value
617
-     * @return null|string
618
-     */
619
-    protected function _sanitize($value)
620
-    {
621
-        return $value !== null ? stripslashes(html_entity_decode(trim($value))) : null;
622
-    }
623
-
624
-
625
-
626
-    /**
627
-     * Picks out the form value that relates to this form input,
628
-     * and stores it as the sanitized value on the form input, and sets the normalized value.
629
-     * Returns whether or not any validation errors occurred
630
-     *
631
-     * @param array $req_data like $_POST
632
-     * @return boolean whether or not there was an error
633
-     * @throws \EE_Error
634
-     */
635
-    protected function _normalize($req_data)
636
-    {
637
-        // any existing validation errors don't apply so clear them
638
-        $this->_validation_errors = array();
639
-        // if the input is disabled, ignore whatever input was sent in
640
-        if ($this->isDisabled()) {
641
-            $this->_set_raw_value(null);
642
-            $this->_set_normalized_value($this->get_default());
643
-            return false;
644
-        }
645
-        try {
646
-            $raw_input = $this->find_form_data_for_this_section($req_data);
647
-            // super simple sanitization for now
648
-            if (is_array($raw_input)) {
649
-                $raw_value = array();
650
-                foreach ($raw_input as $key => $value) {
651
-                    $raw_value[ $key ] = $this->_sanitize($value);
652
-                }
653
-                $this->_set_raw_value($raw_value);
654
-            } else {
655
-                $this->_set_raw_value($this->_sanitize($raw_input));
656
-            }
657
-            // we want to mostly leave the input alone in case we need to re-display it to the user
658
-            $this->_set_normalized_value($this->_normalization_strategy->normalize($this->raw_value()));
659
-            return false;
660
-        } catch (EE_Validation_Error $e) {
661
-            $this->add_validation_error($e);
662
-            return true;
663
-        }
664
-    }
665
-
666
-
667
-
668
-    /**
669
-     * @return string
670
-     */
671
-    public function html_name()
672
-    {
673
-        $this->_set_default_html_name_if_empty();
674
-        return $this->_html_name;
675
-    }
676
-
677
-
678
-
679
-    /**
680
-     * @return string
681
-     */
682
-    public function html_label_id()
683
-    {
684
-        return ! empty($this->_html_label_id) ? $this->_html_label_id : $this->html_id() . '-lbl';
685
-    }
686
-
687
-
688
-
689
-    /**
690
-     * @return string
691
-     */
692
-    public function html_label_class()
693
-    {
694
-        return $this->_html_label_class;
695
-    }
696
-
697
-
698
-
699
-    /**
700
-     * @return string
701
-     */
702
-    public function html_label_style()
703
-    {
704
-        return $this->_html_label_style;
705
-    }
706
-
707
-
708
-
709
-    /**
710
-     * @return string
711
-     */
712
-    public function html_label_text()
713
-    {
714
-        return $this->_html_label_text;
715
-    }
716
-
717
-
718
-
719
-    /**
720
-     * @return string
721
-     */
722
-    public function html_help_text()
723
-    {
724
-        return $this->_html_help_text;
725
-    }
726
-
727
-
728
-
729
-    /**
730
-     * @return string
731
-     */
732
-    public function html_help_class()
733
-    {
734
-        return $this->_html_help_class;
735
-    }
736
-
737
-
738
-
739
-    /**
740
-     * @return string
741
-     */
742
-    public function html_help_style()
743
-    {
744
-        return $this->_html_style;
745
-    }
746
-
747
-
748
-
749
-    /**
750
-     * returns the raw, UNSAFE, input, almost exactly as the user submitted it.
751
-     * Please note that almost all client code should instead use the normalized_value;
752
-     * or possibly raw_value_in_form (which prepares the string for displaying in an HTML attribute on a tag,
753
-     * mostly by escaping quotes)
754
-     * Note, we do not store the exact original value sent in the user's request because
755
-     * it may have malicious content, and we MIGHT want to store the form input in a transient or something...
756
-     * in which case, we would have stored the malicious content to our database.
757
-     *
758
-     * @return string
759
-     */
760
-    public function raw_value()
761
-    {
762
-        return $this->_raw_value;
763
-    }
764
-
765
-
766
-
767
-    /**
768
-     * Returns a string safe to usage in form inputs when displaying, because
769
-     * it escapes all html entities
770
-     *
771
-     * @return string
772
-     */
773
-    public function raw_value_in_form()
774
-    {
775
-        return htmlentities($this->raw_value(), ENT_QUOTES, 'UTF-8');
776
-    }
777
-
778
-
779
-
780
-    /**
781
-     * returns the value after it's been sanitized, and then converted into it's proper type
782
-     * in PHP. Eg, a string, an int, an array,
783
-     *
784
-     * @return mixed
785
-     */
786
-    public function normalized_value()
787
-    {
788
-        return $this->_normalized_value;
789
-    }
790
-
791
-
792
-
793
-    /**
794
-     * Returns the normalized value is a presentable way. By default this is just
795
-     * the normalized value by itself, but it can be overridden for when that's not
796
-     * the best thing to display
797
-     *
798
-     * @return string
799
-     */
800
-    public function pretty_value()
801
-    {
802
-        return $this->_normalized_value;
803
-    }
804
-
805
-
806
-
807
-    /**
808
-     * When generating the JS for the jquery validation rules like<br>
809
-     * <code>$( "#myform" ).validate({
810
-     * rules: {
811
-     * password: "required",
812
-     * password_again: {
813
-     * equalTo: "#password"
814
-     * }
815
-     * }
816
-     * });</code>
817
-     * if this field had the name 'password_again', it should return
818
-     * <br><code>password_again: {
819
-     * equalTo: "#password"
820
-     * }</code>
821
-     *
822
-     * @return array
823
-     */
824
-    public function get_jquery_validation_rules()
825
-    {
826
-        $jquery_validation_js = array();
827
-        $jquery_validation_rules = array();
828
-        foreach ($this->get_validation_strategies() as $validation_strategy) {
829
-            $jquery_validation_rules = array_replace_recursive(
830
-                $jquery_validation_rules,
831
-                $validation_strategy->get_jquery_validation_rule_array()
832
-            );
833
-        }
834
-        if (! empty($jquery_validation_rules)) {
835
-            foreach ($this->get_display_strategy()->get_html_input_ids(true) as $html_id_with_pound_sign) {
836
-                $jquery_validation_js[ $html_id_with_pound_sign ] = $jquery_validation_rules;
837
-            }
838
-        }
839
-        return $jquery_validation_js;
840
-    }
841
-
842
-
843
-
844
-    /**
845
-     * Sets the input's default value for use in displaying in the form. Note: value should be
846
-     * normalized (Eg, if providing a default of ra Yes_NO_Input you would provide TRUE or FALSE, not '1' or '0')
847
-     *
848
-     * @param mixed $value
849
-     * @return void
850
-     */
851
-    public function set_default($value)
852
-    {
853
-        $this->_default = $value;
854
-        $this->_set_normalized_value($value);
855
-        $this->_set_raw_value($value);
856
-    }
857
-
858
-
859
-
860
-    /**
861
-     * Sets the normalized value on this input
862
-     *
863
-     * @param mixed $value
864
-     */
865
-    protected function _set_normalized_value($value)
866
-    {
867
-        $this->_normalized_value = $value;
868
-    }
869
-
870
-
871
-
872
-    /**
873
-     * Sets the raw value on this input (ie, exactly as the user submitted it)
874
-     *
875
-     * @param mixed $value
876
-     */
877
-    protected function _set_raw_value($value)
878
-    {
879
-        $this->_raw_value = $this->_normalization_strategy->unnormalize($value);
880
-    }
881
-
882
-
883
-
884
-    /**
885
-     * Sets the HTML label text after it has already been defined
886
-     *
887
-     * @param string $label
888
-     * @return void
889
-     */
890
-    public function set_html_label_text($label)
891
-    {
892
-        $this->_html_label_text = $label;
893
-    }
894
-
895
-
896
-
897
-    /**
898
-     * Sets whether or not this field is required, and adjusts the validation strategy.
899
-     * If you want to use the EE_Conditionally_Required_Validation_Strategy,
900
-     * please add it as a validation strategy using add_validation_strategy as normal
901
-     *
902
-     * @param boolean $required boolean
903
-     * @param null    $required_text
904
-     */
905
-    public function set_required($required = true, $required_text = null)
906
-    {
907
-        $required = filter_var($required, FILTER_VALIDATE_BOOLEAN);
908
-        // whether $required is a string or a boolean, we want to add a required validation strategy
909
-        if ($required) {
910
-            $this->_add_validation_strategy(new EE_Required_Validation_Strategy($required_text));
911
-        } else {
912
-            $this->remove_validation_strategy('EE_Required_Validation_Strategy');
913
-        }
914
-        $this->_required = $required;
915
-    }
916
-
917
-
918
-
919
-    /**
920
-     * Returns whether or not this field is required
921
-     *
922
-     * @return boolean
923
-     */
924
-    public function required()
925
-    {
926
-        return $this->_required;
927
-    }
928
-
929
-
930
-
931
-    /**
932
-     * @param string $required_css_class
933
-     */
934
-    public function set_required_css_class($required_css_class)
935
-    {
936
-        $this->_required_css_class = $required_css_class;
937
-    }
938
-
939
-
940
-
941
-    /**
942
-     * @return string
943
-     */
944
-    public function required_css_class()
945
-    {
946
-        return $this->_required_css_class;
947
-    }
948
-
949
-
950
-
951
-    /**
952
-     * @param bool $add_required
953
-     * @return string
954
-     */
955
-    public function html_class($add_required = false)
956
-    {
957
-        return $add_required && $this->required()
958
-            ? $this->required_css_class() . ' ' . $this->_html_class
959
-            : $this->_html_class;
960
-    }
961
-
962
-
963
-    /**
964
-     * Sets the help text, in case
965
-     *
966
-     * @param string $text
967
-     */
968
-    public function set_html_help_text($text)
969
-    {
970
-        $this->_html_help_text = $text;
971
-    }
972
-
973
-
974
-
975
-    /**
976
-     * Uses the sensitive data removal strategy to remove the sensitive data from this
977
-     * input. If there is any kind of sensitive data removal on this input, we clear
978
-     * out the raw value completely
979
-     *
980
-     * @return void
981
-     */
982
-    public function clean_sensitive_data()
983
-    {
984
-        // if we do ANY kind of sensitive data removal on this, then just clear out the raw value
985
-        // if we need more logic than this we'll make a strategy for it
986
-        if ($this->_sensitive_data_removal_strategy
987
-            && ! $this->_sensitive_data_removal_strategy instanceof EE_No_Sensitive_Data_Removal
988
-        ) {
989
-            $this->_set_raw_value(null);
990
-        }
991
-        // and clean the normalized value according to the appropriate strategy
992
-        $this->_set_normalized_value(
993
-            $this->get_sensitive_data_removal_strategy()->remove_sensitive_data(
994
-                $this->_normalized_value
995
-            )
996
-        );
997
-    }
998
-
999
-
1000
-
1001
-    /**
1002
-     * @param bool   $primary
1003
-     * @param string $button_size
1004
-     * @param string $other_attributes
1005
-     */
1006
-    public function set_button_css_attributes($primary = true, $button_size = '', $other_attributes = '')
1007
-    {
1008
-        $button_css_attributes = 'button';
1009
-        $button_css_attributes .= $primary === true ? ' button-primary' : ' button-secondary';
1010
-        switch ($button_size) {
1011
-            case 'xs':
1012
-            case 'extra-small':
1013
-                $button_css_attributes .= ' button-xs';
1014
-                break;
1015
-            case 'sm':
1016
-            case 'small':
1017
-                $button_css_attributes .= ' button-sm';
1018
-                break;
1019
-            case 'lg':
1020
-            case 'large':
1021
-                $button_css_attributes .= ' button-lg';
1022
-                break;
1023
-            case 'block':
1024
-                $button_css_attributes .= ' button-block';
1025
-                break;
1026
-            case 'md':
1027
-            case 'medium':
1028
-            default:
1029
-                $button_css_attributes .= '';
1030
-        }
1031
-        $this->_button_css_attributes .= ! empty($other_attributes)
1032
-            ? $button_css_attributes . ' ' . $other_attributes
1033
-            : $button_css_attributes;
1034
-    }
1035
-
1036
-
1037
-
1038
-    /**
1039
-     * @return string
1040
-     */
1041
-    public function button_css_attributes()
1042
-    {
1043
-        if (empty($this->_button_css_attributes)) {
1044
-            $this->set_button_css_attributes();
1045
-        }
1046
-        return $this->_button_css_attributes;
1047
-    }
1048
-
1049
-
1050
-
1051
-    /**
1052
-     * find_form_data_for_this_section
1053
-     * using this section's name and its parents, finds the value of the form data that corresponds to it.
1054
-     * For example, if this form section's HTML name is my_form[subform][form_input_1],
1055
-     * then it's value should be in $_REQUEST at $_REQUEST['my_form']['subform']['form_input_1'].
1056
-     * (If that doesn't exist, we also check for this subsection's name
1057
-     * at the TOP LEVEL of the request data. Eg $_REQUEST['form_input_1'].)
1058
-     * This function finds its value in the form.
1059
-     *
1060
-     * @param array $req_data
1061
-     * @return mixed whatever the raw value of this form section is in the request data
1062
-     * @throws \EE_Error
1063
-     */
1064
-    public function find_form_data_for_this_section($req_data)
1065
-    {
1066
-        $name_parts = $this->getInputNameParts();
1067
-        // now get the value for the input
1068
-        $value = $this->findRequestForSectionUsingNameParts($name_parts, $req_data);
1069
-        // check if this thing's name is at the TOP level of the request data
1070
-        if ($value === null && isset($req_data[ $this->name() ])) {
1071
-            $value = $req_data[ $this->name() ];
1072
-        }
1073
-        return $value;
1074
-    }
1075
-
1076
-
1077
-
1078
-    /**
1079
-     * If this input's name is something like "foo[bar][baz]"
1080
-     * returns an array like `array('foo','bar',baz')`
1081
-     * @return array
1082
-     */
1083
-    protected function getInputNameParts()
1084
-    {
1085
-        // break up the html name by "[]"
1086
-        if (strpos($this->html_name(), '[') !== false) {
1087
-            $before_any_brackets = substr($this->html_name(), 0, strpos($this->html_name(), '['));
1088
-        } else {
1089
-            $before_any_brackets = $this->html_name();
1090
-        }
1091
-        // grab all of the segments
1092
-        preg_match_all('~\[([^]]*)\]~', $this->html_name(), $matches);
1093
-        if (isset($matches[1]) && is_array($matches[1])) {
1094
-            $name_parts = $matches[1];
1095
-            array_unshift($name_parts, $before_any_brackets);
1096
-        } else {
1097
-            $name_parts = array($before_any_brackets);
1098
-        }
1099
-        return $name_parts;
1100
-    }
1101
-
1102
-
1103
-
1104
-    /**
1105
-     * @param array $html_name_parts
1106
-     * @param array $req_data
1107
-     * @return array | NULL
1108
-     */
1109
-    public function findRequestForSectionUsingNameParts($html_name_parts, $req_data)
1110
-    {
1111
-        $first_part_to_consider = array_shift($html_name_parts);
1112
-        if (isset($req_data[ $first_part_to_consider ])) {
1113
-            if (empty($html_name_parts)) {
1114
-                return $req_data[ $first_part_to_consider ];
1115
-            } else {
1116
-                return $this->findRequestForSectionUsingNameParts(
1117
-                    $html_name_parts,
1118
-                    $req_data[ $first_part_to_consider ]
1119
-                );
1120
-            }
1121
-        } else {
1122
-            return null;
1123
-        }
1124
-    }
1125
-
1126
-
1127
-
1128
-    /**
1129
-     * Checks if this form input's data is in the request data
1130
-     *
1131
-     * @param array $req_data like $_POST
1132
-     * @return boolean
1133
-     * @throws \EE_Error
1134
-     */
1135
-    public function form_data_present_in($req_data = null)
1136
-    {
1137
-        if ($req_data === null) {
1138
-            $req_data = $_POST;
1139
-        }
1140
-        $checked_value = $this->find_form_data_for_this_section($req_data);
1141
-        if ($checked_value !== null) {
1142
-            return true;
1143
-        } else {
1144
-            return false;
1145
-        }
1146
-    }
1147
-
1148
-
1149
-
1150
-    /**
1151
-     * Overrides parent to add js data from validation and display strategies
1152
-     *
1153
-     * @param array $form_other_js_data
1154
-     * @return array
1155
-     */
1156
-    public function get_other_js_data($form_other_js_data = array())
1157
-    {
1158
-        $form_other_js_data = $this->get_other_js_data_from_strategies($form_other_js_data);
1159
-        return $form_other_js_data;
1160
-    }
1161
-
1162
-
1163
-
1164
-    /**
1165
-     * Gets other JS data for localization from this input's strategies, like
1166
-     * the validation strategies and the display strategy
1167
-     *
1168
-     * @param array $form_other_js_data
1169
-     * @return array
1170
-     */
1171
-    public function get_other_js_data_from_strategies($form_other_js_data = array())
1172
-    {
1173
-        $form_other_js_data = $this->get_display_strategy()->get_other_js_data($form_other_js_data);
1174
-        foreach ($this->get_validation_strategies() as $validation_strategy) {
1175
-            $form_other_js_data = $validation_strategy->get_other_js_data($form_other_js_data);
1176
-        }
1177
-        return $form_other_js_data;
1178
-    }
1179
-
1180
-
1181
-
1182
-    /**
1183
-     * Override parent because we want to give our strategies an opportunity to enqueue some js and css
1184
-     *
1185
-     * @return void
1186
-     */
1187
-    public function enqueue_js()
1188
-    {
1189
-        // ask our display strategy and validation strategies if they have js to enqueue
1190
-        $this->enqueue_js_from_strategies();
1191
-    }
1192
-
1193
-
1194
-
1195
-    /**
1196
-     * Tells strategies when its ok to enqueue their js and css
1197
-     *
1198
-     * @return void
1199
-     */
1200
-    public function enqueue_js_from_strategies()
1201
-    {
1202
-        $this->get_display_strategy()->enqueue_js();
1203
-        foreach ($this->get_validation_strategies() as $validation_strategy) {
1204
-            $validation_strategy->enqueue_js();
1205
-        }
1206
-    }
1207
-
1208
-
1209
-
1210
-    /**
1211
-     * Gets the default value set on the input (not the current value, which may have been
1212
-     * changed because of a form submission). If no default was set, this us null.
1213
-     * @return mixed
1214
-     */
1215
-    public function get_default()
1216
-    {
1217
-        return $this->_default;
1218
-    }
1219
-
1220
-
1221
-
1222
-    /**
1223
-     * Makes this input disabled. That means it will have the HTML attribute 'disabled="disabled"',
1224
-     * and server-side if any input was received it will be ignored
1225
-     */
1226
-    public function disable($disable = true)
1227
-    {
1228
-        $disabled_attribute = ' disabled="disabled"';
1229
-        $this->disabled = filter_var($disable, FILTER_VALIDATE_BOOLEAN);
1230
-        if ($this->disabled) {
1231
-            if (strpos($this->_other_html_attributes, $disabled_attribute) === false) {
1232
-                $this->_other_html_attributes .= $disabled_attribute;
1233
-            }
1234
-            $this->_set_normalized_value($this->get_default());
1235
-        } else {
1236
-            $this->_other_html_attributes = str_replace($disabled_attribute, '', $this->_other_html_attributes);
1237
-        }
1238
-    }
1239
-
1240
-
1241
-
1242
-    /**
1243
-     * Returns whether or not this input is currently disabled.
1244
-     * @return bool
1245
-     */
1246
-    public function isDisabled()
1247
-    {
1248
-        return $this->disabled;
1249
-    }
14
+	/**
15
+	 * the input's name attribute
16
+	 *
17
+	 * @var string
18
+	 */
19
+	protected $_html_name;
20
+
21
+	/**
22
+	 * id for the html label tag
23
+	 *
24
+	 * @var string
25
+	 */
26
+	protected $_html_label_id;
27
+
28
+	/**
29
+	 * class for teh html label tag
30
+	 *
31
+	 * @var string
32
+	 */
33
+	protected $_html_label_class;
34
+
35
+	/**
36
+	 * any additional html attributes that you may want to add
37
+	 *
38
+	 * @var string
39
+	 */
40
+	protected $_html_other_attributes;
41
+
42
+	/**
43
+	 * style for teh html label tag
44
+	 *
45
+	 * @var string
46
+	 */
47
+	protected $_html_label_style;
48
+
49
+	/**
50
+	 * text to be placed in the html label
51
+	 *
52
+	 * @var string
53
+	 */
54
+	protected $_html_label_text;
55
+
56
+	/**
57
+	 * the full html label. If used, all other html_label_* properties are invalid
58
+	 *
59
+	 * @var string
60
+	 */
61
+	protected $_html_label;
62
+
63
+	/**
64
+	 * HTML to use for help text (normally placed below form input), in a span which normally
65
+	 * has a class of 'description'
66
+	 *
67
+	 * @var string
68
+	 */
69
+	protected $_html_help_text;
70
+
71
+	/**
72
+	 * CSS classes for displaying the help span
73
+	 *
74
+	 * @var string
75
+	 */
76
+	protected $_html_help_class = 'description';
77
+
78
+	/**
79
+	 * CSS to put in the style attribute on the help span
80
+	 *
81
+	 * @var string
82
+	 */
83
+	protected $_html_help_style;
84
+
85
+	/**
86
+	 * Stores whether or not this input's response is required.
87
+	 * Because certain styling elements may also want to know that this
88
+	 * input is required etc.
89
+	 *
90
+	 * @var boolean
91
+	 */
92
+	protected $_required;
93
+
94
+	/**
95
+	 * css class added to required inputs
96
+	 *
97
+	 * @var string
98
+	 */
99
+	protected $_required_css_class = 'ee-required';
100
+
101
+	/**
102
+	 * css styles applied to button type inputs
103
+	 *
104
+	 * @var string
105
+	 */
106
+	protected $_button_css_attributes;
107
+
108
+	/**
109
+	 * The raw data submitted for this, like in the $_POST super global.
110
+	 * Generally unsafe for usage in client code
111
+	 *
112
+	 * @var mixed string or array
113
+	 */
114
+	protected $_raw_value;
115
+
116
+	/**
117
+	 * Value normalized according to the input's normalization strategy.
118
+	 * The normalization strategy dictates whether this is a string, int, float,
119
+	 * boolean, or array of any of those.
120
+	 *
121
+	 * @var mixed
122
+	 */
123
+	protected $_normalized_value;
124
+
125
+
126
+	/**
127
+	 * Normalized default value either initially set on the input, or provided by calling
128
+	 * set_default().
129
+	 * @var mixed
130
+	 */
131
+	protected $_default;
132
+
133
+	/**
134
+	 * Strategy used for displaying this field.
135
+	 * Child classes must use _get_display_strategy to access it.
136
+	 *
137
+	 * @var EE_Display_Strategy_Base
138
+	 */
139
+	private $_display_strategy;
140
+
141
+	/**
142
+	 * Gets all the validation strategies used on this field
143
+	 *
144
+	 * @var EE_Validation_Strategy_Base[]
145
+	 */
146
+	private $_validation_strategies = array();
147
+
148
+	/**
149
+	 * The normalization strategy for this field
150
+	 *
151
+	 * @var EE_Normalization_Strategy_Base
152
+	 */
153
+	private $_normalization_strategy;
154
+
155
+	/**
156
+	 * Strategy for removing sensitive data after we're done with the form input
157
+	 *
158
+	 * @var EE_Sensitive_Data_Removal_Base
159
+	 */
160
+	protected $_sensitive_data_removal_strategy;
161
+
162
+	/**
163
+	 * Whether this input has been disabled or not.
164
+	 * If it's disabled while rendering, an extra hidden input is added that indicates it has been knowingly disabled.
165
+	 * (Client-side code that wants to dynamically disable it must also add this hidden input).
166
+	 * When the form is submitted, if the input is disabled in the PHP formsection, then input is ignored.
167
+	 * If the input is missing from the $_REQUEST data but the hidden input indicating the input is disabled, then the input is again ignored.
168
+	 *
169
+	 * @var boolean
170
+	 */
171
+	protected $disabled = false;
172
+
173
+
174
+
175
+	/**
176
+	 * @param array                         $input_args       {
177
+	 * @type string                         $html_name        the html name for the input
178
+	 * @type string                         $html_label_id    the id attribute to give to the html label tag
179
+	 * @type string                         $html_label_class the class attribute to give to the html label tag
180
+	 * @type string                         $html_label_style the style attribute to give ot teh label tag
181
+	 * @type string                         $html_label_text  the text to put in the label tag
182
+	 * @type string                         $html_label       the full html label. If used,
183
+	 *                                                        all other html_label_* args are invalid
184
+	 * @type string                         $html_help_text   text to put in help element
185
+	 * @type string                         $html_help_style  style attribute to give to teh help element
186
+	 * @type string                         $html_help_class  class attribute to give to the help element
187
+	 * @type string                         $default          default value NORMALIZED (eg, if providing the default
188
+	 *       for a Yes_No_Input, you should provide TRUE or FALSE, not '1' or '0')
189
+	 * @type EE_Display_Strategy_Base       $display          strategy
190
+	 * @type EE_Normalization_Strategy_Base $normalization_strategy
191
+	 * @type EE_Validation_Strategy_Base[]  $validation_strategies
192
+	 * @type boolean                        $ignore_input special argument which can be used to avoid adding any validation strategies,
193
+	 *                                                    and sets the normalization strategy to the Null normalization. This is good
194
+	 *                                                    when you want the input to be totally ignored server-side (like when using
195
+	 *                                                    React.js form inputs)
196
+	 *                                                        }
197
+	 */
198
+	public function __construct($input_args = array())
199
+	{
200
+		$input_args = (array) apply_filters('FHEE__EE_Form_Input_Base___construct__input_args', $input_args, $this);
201
+		// the following properties must be cast as arrays
202
+		if (isset($input_args['validation_strategies'])) {
203
+			foreach ((array) $input_args['validation_strategies'] as $validation_strategy) {
204
+				if ($validation_strategy instanceof EE_Validation_Strategy_Base && empty($input_args['ignore_input'])) {
205
+					$this->_validation_strategies[ get_class($validation_strategy) ] = $validation_strategy;
206
+				}
207
+			}
208
+			unset($input_args['validation_strategies']);
209
+		}
210
+		if (isset($input_args['ignore_input'])) {
211
+			$this->_validation_strategies = array();
212
+		}
213
+		// loop thru incoming options
214
+		foreach ($input_args as $key => $value) {
215
+			// add underscore to $key to match property names
216
+			$_key = '_' . $key;
217
+			if (property_exists($this, $_key)) {
218
+				$this->{$_key} = $value;
219
+			}
220
+		}
221
+		// ensure that "required" is set correctly
222
+		$this->set_required(
223
+			$this->_required,
224
+			isset($input_args['required_validation_error_message'])
225
+			? $input_args['required_validation_error_message']
226
+			: null
227
+		);
228
+		// $this->_html_name_specified = isset( $input_args['html_name'] ) ? TRUE : FALSE;
229
+		$this->_display_strategy->_construct_finalize($this);
230
+		foreach ($this->_validation_strategies as $validation_strategy) {
231
+			$validation_strategy->_construct_finalize($this);
232
+		}
233
+		if (isset($input_args['ignore_input'])) {
234
+			$this->_normalization_strategy = new EE_Null_Normalization();
235
+		}
236
+		if (! $this->_normalization_strategy) {
237
+				$this->_normalization_strategy = new EE_Text_Normalization();
238
+		}
239
+		$this->_normalization_strategy->_construct_finalize($this);
240
+		// at least we can use the normalization strategy to populate the default
241
+		if (isset($input_args['default'])) {
242
+			$this->set_default($input_args['default']);
243
+			unset($input_args['default']);
244
+		}
245
+		if (! $this->_sensitive_data_removal_strategy) {
246
+			$this->_sensitive_data_removal_strategy = new EE_No_Sensitive_Data_Removal();
247
+		}
248
+		$this->_sensitive_data_removal_strategy->_construct_finalize($this);
249
+		parent::__construct($input_args);
250
+	}
251
+
252
+
253
+
254
+	/**
255
+	 * Sets the html_name to its default value, if none was specified in teh constructor.
256
+	 * Calculation involves using the name and the parent's html_name
257
+	 *
258
+	 * @throws \EE_Error
259
+	 */
260
+	protected function _set_default_html_name_if_empty()
261
+	{
262
+		if (! $this->_html_name) {
263
+			$this->_html_name = $this->name();
264
+			if ($this->_parent_section && $this->_parent_section instanceof EE_Form_Section_Proper) {
265
+				$this->_html_name = $this->_parent_section->html_name_prefix() . "[{$this->name()}]";
266
+			}
267
+		}
268
+	}
269
+
270
+
271
+
272
+	/**
273
+	 * @param $parent_form_section
274
+	 * @param $name
275
+	 * @throws \EE_Error
276
+	 */
277
+	public function _construct_finalize($parent_form_section, $name)
278
+	{
279
+		parent::_construct_finalize($parent_form_section, $name);
280
+		if ($this->_html_label === null && $this->_html_label_text === null) {
281
+			$this->_html_label_text = ucwords(str_replace("_", " ", $name));
282
+		}
283
+		do_action('AHEE__EE_Form_Input_Base___construct_finalize__end', $this, $parent_form_section, $name);
284
+	}
285
+
286
+
287
+
288
+	/**
289
+	 * Returns the strategy for displaying this form input. If none is set, throws an exception.
290
+	 *
291
+	 * @return EE_Display_Strategy_Base
292
+	 * @throws EE_Error
293
+	 */
294
+	protected function _get_display_strategy()
295
+	{
296
+		$this->ensure_construct_finalized_called();
297
+		if (! $this->_display_strategy || ! $this->_display_strategy instanceof EE_Display_Strategy_Base) {
298
+			throw new EE_Error(
299
+				sprintf(
300
+					__(
301
+						"Cannot get display strategy for form input with name %s and id %s, because it has not been set in the constructor",
302
+						"event_espresso"
303
+					),
304
+					$this->html_name(),
305
+					$this->html_id()
306
+				)
307
+			);
308
+		} else {
309
+			return $this->_display_strategy;
310
+		}
311
+	}
312
+
313
+
314
+
315
+	/**
316
+	 * Sets the display strategy.
317
+	 *
318
+	 * @param EE_Display_Strategy_Base $strategy
319
+	 */
320
+	protected function _set_display_strategy(EE_Display_Strategy_Base $strategy)
321
+	{
322
+		$this->_display_strategy = $strategy;
323
+	}
324
+
325
+
326
+
327
+	/**
328
+	 * Sets the sanitization strategy
329
+	 *
330
+	 * @param EE_Normalization_Strategy_Base $strategy
331
+	 */
332
+	protected function _set_normalization_strategy(EE_Normalization_Strategy_Base $strategy)
333
+	{
334
+		$this->_normalization_strategy = $strategy;
335
+	}
336
+
337
+
338
+
339
+	/**
340
+	 * Gets sensitive_data_removal_strategy
341
+	 *
342
+	 * @return EE_Sensitive_Data_Removal_Base
343
+	 */
344
+	public function get_sensitive_data_removal_strategy()
345
+	{
346
+		return $this->_sensitive_data_removal_strategy;
347
+	}
348
+
349
+
350
+
351
+	/**
352
+	 * Sets sensitive_data_removal_strategy
353
+	 *
354
+	 * @param EE_Sensitive_Data_Removal_Base $sensitive_data_removal_strategy
355
+	 * @return boolean
356
+	 */
357
+	public function set_sensitive_data_removal_strategy($sensitive_data_removal_strategy)
358
+	{
359
+		$this->_sensitive_data_removal_strategy = $sensitive_data_removal_strategy;
360
+	}
361
+
362
+
363
+
364
+	/**
365
+	 * Gets the display strategy for this input
366
+	 *
367
+	 * @return EE_Display_Strategy_Base
368
+	 */
369
+	public function get_display_strategy()
370
+	{
371
+		return $this->_display_strategy;
372
+	}
373
+
374
+
375
+
376
+	/**
377
+	 * Overwrites the display strategy
378
+	 *
379
+	 * @param EE_Display_Strategy_Base $display_strategy
380
+	 */
381
+	public function set_display_strategy($display_strategy)
382
+	{
383
+		$this->_display_strategy = $display_strategy;
384
+		$this->_display_strategy->_construct_finalize($this);
385
+	}
386
+
387
+
388
+
389
+	/**
390
+	 * Gets the normalization strategy set on this input
391
+	 *
392
+	 * @return EE_Normalization_Strategy_Base
393
+	 */
394
+	public function get_normalization_strategy()
395
+	{
396
+		return $this->_normalization_strategy;
397
+	}
398
+
399
+
400
+
401
+	/**
402
+	 * Overwrites the normalization strategy
403
+	 *
404
+	 * @param EE_Normalization_Strategy_Base $normalization_strategy
405
+	 */
406
+	public function set_normalization_strategy($normalization_strategy)
407
+	{
408
+		$this->_normalization_strategy = $normalization_strategy;
409
+		$this->_normalization_strategy->_construct_finalize($this);
410
+	}
411
+
412
+
413
+
414
+	/**
415
+	 * Returns all teh validation strategies which apply to this field, numerically indexed
416
+	 *
417
+	 * @return EE_Validation_Strategy_Base[]
418
+	 */
419
+	public function get_validation_strategies()
420
+	{
421
+		return $this->_validation_strategies;
422
+	}
423
+
424
+
425
+
426
+	/**
427
+	 * Adds this strategy to the field so it will be used in both JS validation and server-side validation
428
+	 *
429
+	 * @param EE_Validation_Strategy_Base $validation_strategy
430
+	 * @return void
431
+	 */
432
+	protected function _add_validation_strategy(EE_Validation_Strategy_Base $validation_strategy)
433
+	{
434
+		$validation_strategy->_construct_finalize($this);
435
+		$this->_validation_strategies[] = $validation_strategy;
436
+	}
437
+
438
+
439
+
440
+	/**
441
+	 * Adds a new validation strategy onto the form input
442
+	 *
443
+	 * @param EE_Validation_Strategy_Base $validation_strategy
444
+	 * @return void
445
+	 */
446
+	public function add_validation_strategy(EE_Validation_Strategy_Base $validation_strategy)
447
+	{
448
+		$this->_add_validation_strategy($validation_strategy);
449
+	}
450
+
451
+
452
+
453
+	/**
454
+	 * The classname of the validation strategy to remove
455
+	 *
456
+	 * @param string $validation_strategy_classname
457
+	 */
458
+	public function remove_validation_strategy($validation_strategy_classname)
459
+	{
460
+		foreach ($this->_validation_strategies as $key => $validation_strategy) {
461
+			if ($validation_strategy instanceof $validation_strategy_classname
462
+				|| is_subclass_of($validation_strategy, $validation_strategy_classname)
463
+			) {
464
+				unset($this->_validation_strategies[ $key ]);
465
+			}
466
+		}
467
+	}
468
+
469
+
470
+
471
+	/**
472
+	 * returns true if input employs any of the validation strategy defined by the supplied array of classnames
473
+	 *
474
+	 * @param array $validation_strategy_classnames
475
+	 * @return bool
476
+	 */
477
+	public function has_validation_strategy($validation_strategy_classnames)
478
+	{
479
+		$validation_strategy_classnames = is_array($validation_strategy_classnames)
480
+			? $validation_strategy_classnames
481
+			: array($validation_strategy_classnames);
482
+		foreach ($this->_validation_strategies as $key => $validation_strategy) {
483
+			if (in_array($key, $validation_strategy_classnames)) {
484
+				return true;
485
+			}
486
+		}
487
+		return false;
488
+	}
489
+
490
+
491
+
492
+	/**
493
+	 * Gets the HTML
494
+	 *
495
+	 * @return string
496
+	 */
497
+	public function get_html()
498
+	{
499
+		return $this->_parent_section->get_html_for_input($this);
500
+	}
501
+
502
+
503
+
504
+	/**
505
+	 * Gets the HTML for the input itself (no label or errors) according to the
506
+	 * input's display strategy
507
+	 * Makes sure the JS and CSS are enqueued for it
508
+	 *
509
+	 * @return string
510
+	 * @throws \EE_Error
511
+	 */
512
+	public function get_html_for_input()
513
+	{
514
+		return $this->_form_html_filter
515
+			? $this->_form_html_filter->filterHtml(
516
+				$this->_get_display_strategy()->display(),
517
+				$this
518
+			)
519
+			: $this->_get_display_strategy()->display();
520
+	}
521
+
522
+
523
+
524
+	/**
525
+	 * @return string
526
+	 */
527
+	public function html_other_attributes()
528
+	{
529
+		return ! empty($this->_html_other_attributes) ? ' ' . $this->_html_other_attributes : '';
530
+	}
531
+
532
+
533
+
534
+	/**
535
+	 * @param string $html_other_attributes
536
+	 */
537
+	public function set_html_other_attributes($html_other_attributes)
538
+	{
539
+		$this->_html_other_attributes = $html_other_attributes;
540
+	}
541
+
542
+
543
+
544
+	/**
545
+	 * Gets the HTML for displaying the label for this form input
546
+	 * according to the form section's layout strategy
547
+	 *
548
+	 * @return string
549
+	 */
550
+	public function get_html_for_label()
551
+	{
552
+		return $this->_parent_section->get_layout_strategy()->display_label($this);
553
+	}
554
+
555
+
556
+
557
+	/**
558
+	 * Gets the HTML for displaying the errors section for this form input
559
+	 * according to the form section's layout strategy
560
+	 *
561
+	 * @return string
562
+	 */
563
+	public function get_html_for_errors()
564
+	{
565
+		return $this->_parent_section->get_layout_strategy()->display_errors($this);
566
+	}
567
+
568
+
569
+
570
+	/**
571
+	 * Gets the HTML for displaying the help text for this form input
572
+	 * according to the form section's layout strategy
573
+	 *
574
+	 * @return string
575
+	 */
576
+	public function get_html_for_help()
577
+	{
578
+		return $this->_parent_section->get_layout_strategy()->display_help_text($this);
579
+	}
580
+
581
+
582
+
583
+	/**
584
+	 * Validates the input's sanitized value (assumes _sanitize() has already been called)
585
+	 * and returns whether or not the form input's submitted value is value
586
+	 *
587
+	 * @return boolean
588
+	 */
589
+	protected function _validate()
590
+	{
591
+		if ($this->isDisabled()) {
592
+			return true;
593
+		}
594
+		foreach ($this->_validation_strategies as $validation_strategy) {
595
+			if ($validation_strategy instanceof EE_Validation_Strategy_Base) {
596
+				try {
597
+					$validation_strategy->validate($this->normalized_value());
598
+				} catch (EE_Validation_Error $e) {
599
+					$this->add_validation_error($e);
600
+				}
601
+			}
602
+		}
603
+		if ($this->get_validation_errors()) {
604
+			return false;
605
+		} else {
606
+			return true;
607
+		}
608
+	}
609
+
610
+
611
+
612
+	/**
613
+	 * Performs basic sanitization on this value. But what sanitization can be performed anyways?
614
+	 * This value MIGHT be allowed to have tags, so we can't really remove them.
615
+	 *
616
+	 * @param string $value
617
+	 * @return null|string
618
+	 */
619
+	protected function _sanitize($value)
620
+	{
621
+		return $value !== null ? stripslashes(html_entity_decode(trim($value))) : null;
622
+	}
623
+
624
+
625
+
626
+	/**
627
+	 * Picks out the form value that relates to this form input,
628
+	 * and stores it as the sanitized value on the form input, and sets the normalized value.
629
+	 * Returns whether or not any validation errors occurred
630
+	 *
631
+	 * @param array $req_data like $_POST
632
+	 * @return boolean whether or not there was an error
633
+	 * @throws \EE_Error
634
+	 */
635
+	protected function _normalize($req_data)
636
+	{
637
+		// any existing validation errors don't apply so clear them
638
+		$this->_validation_errors = array();
639
+		// if the input is disabled, ignore whatever input was sent in
640
+		if ($this->isDisabled()) {
641
+			$this->_set_raw_value(null);
642
+			$this->_set_normalized_value($this->get_default());
643
+			return false;
644
+		}
645
+		try {
646
+			$raw_input = $this->find_form_data_for_this_section($req_data);
647
+			// super simple sanitization for now
648
+			if (is_array($raw_input)) {
649
+				$raw_value = array();
650
+				foreach ($raw_input as $key => $value) {
651
+					$raw_value[ $key ] = $this->_sanitize($value);
652
+				}
653
+				$this->_set_raw_value($raw_value);
654
+			} else {
655
+				$this->_set_raw_value($this->_sanitize($raw_input));
656
+			}
657
+			// we want to mostly leave the input alone in case we need to re-display it to the user
658
+			$this->_set_normalized_value($this->_normalization_strategy->normalize($this->raw_value()));
659
+			return false;
660
+		} catch (EE_Validation_Error $e) {
661
+			$this->add_validation_error($e);
662
+			return true;
663
+		}
664
+	}
665
+
666
+
667
+
668
+	/**
669
+	 * @return string
670
+	 */
671
+	public function html_name()
672
+	{
673
+		$this->_set_default_html_name_if_empty();
674
+		return $this->_html_name;
675
+	}
676
+
677
+
678
+
679
+	/**
680
+	 * @return string
681
+	 */
682
+	public function html_label_id()
683
+	{
684
+		return ! empty($this->_html_label_id) ? $this->_html_label_id : $this->html_id() . '-lbl';
685
+	}
686
+
687
+
688
+
689
+	/**
690
+	 * @return string
691
+	 */
692
+	public function html_label_class()
693
+	{
694
+		return $this->_html_label_class;
695
+	}
696
+
697
+
698
+
699
+	/**
700
+	 * @return string
701
+	 */
702
+	public function html_label_style()
703
+	{
704
+		return $this->_html_label_style;
705
+	}
706
+
707
+
708
+
709
+	/**
710
+	 * @return string
711
+	 */
712
+	public function html_label_text()
713
+	{
714
+		return $this->_html_label_text;
715
+	}
716
+
717
+
718
+
719
+	/**
720
+	 * @return string
721
+	 */
722
+	public function html_help_text()
723
+	{
724
+		return $this->_html_help_text;
725
+	}
726
+
727
+
728
+
729
+	/**
730
+	 * @return string
731
+	 */
732
+	public function html_help_class()
733
+	{
734
+		return $this->_html_help_class;
735
+	}
736
+
737
+
738
+
739
+	/**
740
+	 * @return string
741
+	 */
742
+	public function html_help_style()
743
+	{
744
+		return $this->_html_style;
745
+	}
746
+
747
+
748
+
749
+	/**
750
+	 * returns the raw, UNSAFE, input, almost exactly as the user submitted it.
751
+	 * Please note that almost all client code should instead use the normalized_value;
752
+	 * or possibly raw_value_in_form (which prepares the string for displaying in an HTML attribute on a tag,
753
+	 * mostly by escaping quotes)
754
+	 * Note, we do not store the exact original value sent in the user's request because
755
+	 * it may have malicious content, and we MIGHT want to store the form input in a transient or something...
756
+	 * in which case, we would have stored the malicious content to our database.
757
+	 *
758
+	 * @return string
759
+	 */
760
+	public function raw_value()
761
+	{
762
+		return $this->_raw_value;
763
+	}
764
+
765
+
766
+
767
+	/**
768
+	 * Returns a string safe to usage in form inputs when displaying, because
769
+	 * it escapes all html entities
770
+	 *
771
+	 * @return string
772
+	 */
773
+	public function raw_value_in_form()
774
+	{
775
+		return htmlentities($this->raw_value(), ENT_QUOTES, 'UTF-8');
776
+	}
777
+
778
+
779
+
780
+	/**
781
+	 * returns the value after it's been sanitized, and then converted into it's proper type
782
+	 * in PHP. Eg, a string, an int, an array,
783
+	 *
784
+	 * @return mixed
785
+	 */
786
+	public function normalized_value()
787
+	{
788
+		return $this->_normalized_value;
789
+	}
790
+
791
+
792
+
793
+	/**
794
+	 * Returns the normalized value is a presentable way. By default this is just
795
+	 * the normalized value by itself, but it can be overridden for when that's not
796
+	 * the best thing to display
797
+	 *
798
+	 * @return string
799
+	 */
800
+	public function pretty_value()
801
+	{
802
+		return $this->_normalized_value;
803
+	}
804
+
805
+
806
+
807
+	/**
808
+	 * When generating the JS for the jquery validation rules like<br>
809
+	 * <code>$( "#myform" ).validate({
810
+	 * rules: {
811
+	 * password: "required",
812
+	 * password_again: {
813
+	 * equalTo: "#password"
814
+	 * }
815
+	 * }
816
+	 * });</code>
817
+	 * if this field had the name 'password_again', it should return
818
+	 * <br><code>password_again: {
819
+	 * equalTo: "#password"
820
+	 * }</code>
821
+	 *
822
+	 * @return array
823
+	 */
824
+	public function get_jquery_validation_rules()
825
+	{
826
+		$jquery_validation_js = array();
827
+		$jquery_validation_rules = array();
828
+		foreach ($this->get_validation_strategies() as $validation_strategy) {
829
+			$jquery_validation_rules = array_replace_recursive(
830
+				$jquery_validation_rules,
831
+				$validation_strategy->get_jquery_validation_rule_array()
832
+			);
833
+		}
834
+		if (! empty($jquery_validation_rules)) {
835
+			foreach ($this->get_display_strategy()->get_html_input_ids(true) as $html_id_with_pound_sign) {
836
+				$jquery_validation_js[ $html_id_with_pound_sign ] = $jquery_validation_rules;
837
+			}
838
+		}
839
+		return $jquery_validation_js;
840
+	}
841
+
842
+
843
+
844
+	/**
845
+	 * Sets the input's default value for use in displaying in the form. Note: value should be
846
+	 * normalized (Eg, if providing a default of ra Yes_NO_Input you would provide TRUE or FALSE, not '1' or '0')
847
+	 *
848
+	 * @param mixed $value
849
+	 * @return void
850
+	 */
851
+	public function set_default($value)
852
+	{
853
+		$this->_default = $value;
854
+		$this->_set_normalized_value($value);
855
+		$this->_set_raw_value($value);
856
+	}
857
+
858
+
859
+
860
+	/**
861
+	 * Sets the normalized value on this input
862
+	 *
863
+	 * @param mixed $value
864
+	 */
865
+	protected function _set_normalized_value($value)
866
+	{
867
+		$this->_normalized_value = $value;
868
+	}
869
+
870
+
871
+
872
+	/**
873
+	 * Sets the raw value on this input (ie, exactly as the user submitted it)
874
+	 *
875
+	 * @param mixed $value
876
+	 */
877
+	protected function _set_raw_value($value)
878
+	{
879
+		$this->_raw_value = $this->_normalization_strategy->unnormalize($value);
880
+	}
881
+
882
+
883
+
884
+	/**
885
+	 * Sets the HTML label text after it has already been defined
886
+	 *
887
+	 * @param string $label
888
+	 * @return void
889
+	 */
890
+	public function set_html_label_text($label)
891
+	{
892
+		$this->_html_label_text = $label;
893
+	}
894
+
895
+
896
+
897
+	/**
898
+	 * Sets whether or not this field is required, and adjusts the validation strategy.
899
+	 * If you want to use the EE_Conditionally_Required_Validation_Strategy,
900
+	 * please add it as a validation strategy using add_validation_strategy as normal
901
+	 *
902
+	 * @param boolean $required boolean
903
+	 * @param null    $required_text
904
+	 */
905
+	public function set_required($required = true, $required_text = null)
906
+	{
907
+		$required = filter_var($required, FILTER_VALIDATE_BOOLEAN);
908
+		// whether $required is a string or a boolean, we want to add a required validation strategy
909
+		if ($required) {
910
+			$this->_add_validation_strategy(new EE_Required_Validation_Strategy($required_text));
911
+		} else {
912
+			$this->remove_validation_strategy('EE_Required_Validation_Strategy');
913
+		}
914
+		$this->_required = $required;
915
+	}
916
+
917
+
918
+
919
+	/**
920
+	 * Returns whether or not this field is required
921
+	 *
922
+	 * @return boolean
923
+	 */
924
+	public function required()
925
+	{
926
+		return $this->_required;
927
+	}
928
+
929
+
930
+
931
+	/**
932
+	 * @param string $required_css_class
933
+	 */
934
+	public function set_required_css_class($required_css_class)
935
+	{
936
+		$this->_required_css_class = $required_css_class;
937
+	}
938
+
939
+
940
+
941
+	/**
942
+	 * @return string
943
+	 */
944
+	public function required_css_class()
945
+	{
946
+		return $this->_required_css_class;
947
+	}
948
+
949
+
950
+
951
+	/**
952
+	 * @param bool $add_required
953
+	 * @return string
954
+	 */
955
+	public function html_class($add_required = false)
956
+	{
957
+		return $add_required && $this->required()
958
+			? $this->required_css_class() . ' ' . $this->_html_class
959
+			: $this->_html_class;
960
+	}
961
+
962
+
963
+	/**
964
+	 * Sets the help text, in case
965
+	 *
966
+	 * @param string $text
967
+	 */
968
+	public function set_html_help_text($text)
969
+	{
970
+		$this->_html_help_text = $text;
971
+	}
972
+
973
+
974
+
975
+	/**
976
+	 * Uses the sensitive data removal strategy to remove the sensitive data from this
977
+	 * input. If there is any kind of sensitive data removal on this input, we clear
978
+	 * out the raw value completely
979
+	 *
980
+	 * @return void
981
+	 */
982
+	public function clean_sensitive_data()
983
+	{
984
+		// if we do ANY kind of sensitive data removal on this, then just clear out the raw value
985
+		// if we need more logic than this we'll make a strategy for it
986
+		if ($this->_sensitive_data_removal_strategy
987
+			&& ! $this->_sensitive_data_removal_strategy instanceof EE_No_Sensitive_Data_Removal
988
+		) {
989
+			$this->_set_raw_value(null);
990
+		}
991
+		// and clean the normalized value according to the appropriate strategy
992
+		$this->_set_normalized_value(
993
+			$this->get_sensitive_data_removal_strategy()->remove_sensitive_data(
994
+				$this->_normalized_value
995
+			)
996
+		);
997
+	}
998
+
999
+
1000
+
1001
+	/**
1002
+	 * @param bool   $primary
1003
+	 * @param string $button_size
1004
+	 * @param string $other_attributes
1005
+	 */
1006
+	public function set_button_css_attributes($primary = true, $button_size = '', $other_attributes = '')
1007
+	{
1008
+		$button_css_attributes = 'button';
1009
+		$button_css_attributes .= $primary === true ? ' button-primary' : ' button-secondary';
1010
+		switch ($button_size) {
1011
+			case 'xs':
1012
+			case 'extra-small':
1013
+				$button_css_attributes .= ' button-xs';
1014
+				break;
1015
+			case 'sm':
1016
+			case 'small':
1017
+				$button_css_attributes .= ' button-sm';
1018
+				break;
1019
+			case 'lg':
1020
+			case 'large':
1021
+				$button_css_attributes .= ' button-lg';
1022
+				break;
1023
+			case 'block':
1024
+				$button_css_attributes .= ' button-block';
1025
+				break;
1026
+			case 'md':
1027
+			case 'medium':
1028
+			default:
1029
+				$button_css_attributes .= '';
1030
+		}
1031
+		$this->_button_css_attributes .= ! empty($other_attributes)
1032
+			? $button_css_attributes . ' ' . $other_attributes
1033
+			: $button_css_attributes;
1034
+	}
1035
+
1036
+
1037
+
1038
+	/**
1039
+	 * @return string
1040
+	 */
1041
+	public function button_css_attributes()
1042
+	{
1043
+		if (empty($this->_button_css_attributes)) {
1044
+			$this->set_button_css_attributes();
1045
+		}
1046
+		return $this->_button_css_attributes;
1047
+	}
1048
+
1049
+
1050
+
1051
+	/**
1052
+	 * find_form_data_for_this_section
1053
+	 * using this section's name and its parents, finds the value of the form data that corresponds to it.
1054
+	 * For example, if this form section's HTML name is my_form[subform][form_input_1],
1055
+	 * then it's value should be in $_REQUEST at $_REQUEST['my_form']['subform']['form_input_1'].
1056
+	 * (If that doesn't exist, we also check for this subsection's name
1057
+	 * at the TOP LEVEL of the request data. Eg $_REQUEST['form_input_1'].)
1058
+	 * This function finds its value in the form.
1059
+	 *
1060
+	 * @param array $req_data
1061
+	 * @return mixed whatever the raw value of this form section is in the request data
1062
+	 * @throws \EE_Error
1063
+	 */
1064
+	public function find_form_data_for_this_section($req_data)
1065
+	{
1066
+		$name_parts = $this->getInputNameParts();
1067
+		// now get the value for the input
1068
+		$value = $this->findRequestForSectionUsingNameParts($name_parts, $req_data);
1069
+		// check if this thing's name is at the TOP level of the request data
1070
+		if ($value === null && isset($req_data[ $this->name() ])) {
1071
+			$value = $req_data[ $this->name() ];
1072
+		}
1073
+		return $value;
1074
+	}
1075
+
1076
+
1077
+
1078
+	/**
1079
+	 * If this input's name is something like "foo[bar][baz]"
1080
+	 * returns an array like `array('foo','bar',baz')`
1081
+	 * @return array
1082
+	 */
1083
+	protected function getInputNameParts()
1084
+	{
1085
+		// break up the html name by "[]"
1086
+		if (strpos($this->html_name(), '[') !== false) {
1087
+			$before_any_brackets = substr($this->html_name(), 0, strpos($this->html_name(), '['));
1088
+		} else {
1089
+			$before_any_brackets = $this->html_name();
1090
+		}
1091
+		// grab all of the segments
1092
+		preg_match_all('~\[([^]]*)\]~', $this->html_name(), $matches);
1093
+		if (isset($matches[1]) && is_array($matches[1])) {
1094
+			$name_parts = $matches[1];
1095
+			array_unshift($name_parts, $before_any_brackets);
1096
+		} else {
1097
+			$name_parts = array($before_any_brackets);
1098
+		}
1099
+		return $name_parts;
1100
+	}
1101
+
1102
+
1103
+
1104
+	/**
1105
+	 * @param array $html_name_parts
1106
+	 * @param array $req_data
1107
+	 * @return array | NULL
1108
+	 */
1109
+	public function findRequestForSectionUsingNameParts($html_name_parts, $req_data)
1110
+	{
1111
+		$first_part_to_consider = array_shift($html_name_parts);
1112
+		if (isset($req_data[ $first_part_to_consider ])) {
1113
+			if (empty($html_name_parts)) {
1114
+				return $req_data[ $first_part_to_consider ];
1115
+			} else {
1116
+				return $this->findRequestForSectionUsingNameParts(
1117
+					$html_name_parts,
1118
+					$req_data[ $first_part_to_consider ]
1119
+				);
1120
+			}
1121
+		} else {
1122
+			return null;
1123
+		}
1124
+	}
1125
+
1126
+
1127
+
1128
+	/**
1129
+	 * Checks if this form input's data is in the request data
1130
+	 *
1131
+	 * @param array $req_data like $_POST
1132
+	 * @return boolean
1133
+	 * @throws \EE_Error
1134
+	 */
1135
+	public function form_data_present_in($req_data = null)
1136
+	{
1137
+		if ($req_data === null) {
1138
+			$req_data = $_POST;
1139
+		}
1140
+		$checked_value = $this->find_form_data_for_this_section($req_data);
1141
+		if ($checked_value !== null) {
1142
+			return true;
1143
+		} else {
1144
+			return false;
1145
+		}
1146
+	}
1147
+
1148
+
1149
+
1150
+	/**
1151
+	 * Overrides parent to add js data from validation and display strategies
1152
+	 *
1153
+	 * @param array $form_other_js_data
1154
+	 * @return array
1155
+	 */
1156
+	public function get_other_js_data($form_other_js_data = array())
1157
+	{
1158
+		$form_other_js_data = $this->get_other_js_data_from_strategies($form_other_js_data);
1159
+		return $form_other_js_data;
1160
+	}
1161
+
1162
+
1163
+
1164
+	/**
1165
+	 * Gets other JS data for localization from this input's strategies, like
1166
+	 * the validation strategies and the display strategy
1167
+	 *
1168
+	 * @param array $form_other_js_data
1169
+	 * @return array
1170
+	 */
1171
+	public function get_other_js_data_from_strategies($form_other_js_data = array())
1172
+	{
1173
+		$form_other_js_data = $this->get_display_strategy()->get_other_js_data($form_other_js_data);
1174
+		foreach ($this->get_validation_strategies() as $validation_strategy) {
1175
+			$form_other_js_data = $validation_strategy->get_other_js_data($form_other_js_data);
1176
+		}
1177
+		return $form_other_js_data;
1178
+	}
1179
+
1180
+
1181
+
1182
+	/**
1183
+	 * Override parent because we want to give our strategies an opportunity to enqueue some js and css
1184
+	 *
1185
+	 * @return void
1186
+	 */
1187
+	public function enqueue_js()
1188
+	{
1189
+		// ask our display strategy and validation strategies if they have js to enqueue
1190
+		$this->enqueue_js_from_strategies();
1191
+	}
1192
+
1193
+
1194
+
1195
+	/**
1196
+	 * Tells strategies when its ok to enqueue their js and css
1197
+	 *
1198
+	 * @return void
1199
+	 */
1200
+	public function enqueue_js_from_strategies()
1201
+	{
1202
+		$this->get_display_strategy()->enqueue_js();
1203
+		foreach ($this->get_validation_strategies() as $validation_strategy) {
1204
+			$validation_strategy->enqueue_js();
1205
+		}
1206
+	}
1207
+
1208
+
1209
+
1210
+	/**
1211
+	 * Gets the default value set on the input (not the current value, which may have been
1212
+	 * changed because of a form submission). If no default was set, this us null.
1213
+	 * @return mixed
1214
+	 */
1215
+	public function get_default()
1216
+	{
1217
+		return $this->_default;
1218
+	}
1219
+
1220
+
1221
+
1222
+	/**
1223
+	 * Makes this input disabled. That means it will have the HTML attribute 'disabled="disabled"',
1224
+	 * and server-side if any input was received it will be ignored
1225
+	 */
1226
+	public function disable($disable = true)
1227
+	{
1228
+		$disabled_attribute = ' disabled="disabled"';
1229
+		$this->disabled = filter_var($disable, FILTER_VALIDATE_BOOLEAN);
1230
+		if ($this->disabled) {
1231
+			if (strpos($this->_other_html_attributes, $disabled_attribute) === false) {
1232
+				$this->_other_html_attributes .= $disabled_attribute;
1233
+			}
1234
+			$this->_set_normalized_value($this->get_default());
1235
+		} else {
1236
+			$this->_other_html_attributes = str_replace($disabled_attribute, '', $this->_other_html_attributes);
1237
+		}
1238
+	}
1239
+
1240
+
1241
+
1242
+	/**
1243
+	 * Returns whether or not this input is currently disabled.
1244
+	 * @return bool
1245
+	 */
1246
+	public function isDisabled()
1247
+	{
1248
+		return $this->disabled;
1249
+	}
1250 1250
 }
Please login to merge, or discard this patch.
core/helpers/EEH_File.helper.php 2 patches
Indentation   +662 added lines, -662 removed lines patch added patch discarded remove patch
@@ -24,666 +24,666 @@
 block discarded – undo
24 24
 class EEH_File extends EEH_Base implements EEHI_File
25 25
 {
26 26
 
27
-    /**
28
-     * @var string $_credentials_form
29
-     */
30
-    private static $_credentials_form;
31
-
32
-    protected static $_wp_filesystem_direct;
33
-
34
-    /**
35
-     * @param string|null $filepath the filepath we want to work in. If its in the
36
-     * wp uploads directory, we'll want to just use the filesystem directly.
37
-     * If not provided, we have to assume its not in the uploads directory
38
-     * @throws EE_Error if filesystem credentials are required
39
-     * @return WP_Filesystem_Base
40
-     */
41
-    private static function _get_wp_filesystem($filepath = null)
42
-    {
43
-        if (apply_filters(
44
-            'FHEE__EEH_File___get_wp_filesystem__allow_using_filesystem_direct',
45
-            $filepath && EEH_File::is_in_uploads_folder($filepath),
46
-            $filepath
47
-        ) ) {
48
-            if (! EEH_File::$_wp_filesystem_direct instanceof WP_Filesystem_Direct) {
49
-                require_once(ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php');
50
-                $method = 'direct';
51
-                $wp_filesystem_direct_file = apply_filters('filesystem_method_file', ABSPATH . 'wp-admin/includes/class-wp-filesystem-' . $method . '.php', $method);
52
-                // check constants defined, just like in wp-admin/includes/file.php's WP_Filesystem()
53
-                if (! defined('FS_CHMOD_DIR')) {
54
-                    define('FS_CHMOD_DIR', ( fileperms(ABSPATH) & 0777 | 0755 ));
55
-                }
56
-                if (! defined('FS_CHMOD_FILE')) {
57
-                    define('FS_CHMOD_FILE', ( fileperms(ABSPATH . 'index.php') & 0777 | 0644 ));
58
-                }
59
-                require_once($wp_filesystem_direct_file);
60
-                EEH_File::$_wp_filesystem_direct = new WP_Filesystem_Direct(array());
61
-            }
62
-            return EEH_File::$_wp_filesystem_direct;
63
-        }
64
-        global $wp_filesystem;
65
-        // no filesystem setup ???
66
-        if (! $wp_filesystem instanceof WP_Filesystem_Base) {
67
-            // if some eager beaver's just trying to get in there too early...
68
-            // let them do it, because we are one of those eager beavers! :P
69
-            /**
70
-             * more explanations are probably merited. http://codex.wordpress.org/Filesystem_API#Initializing_WP_Filesystem_Base
71
-             * says WP_Filesystem should be used after 'wp_loaded', but currently EE's activation process
72
-             * is setup to mostly happen on 'init', and refactoring to have it happen on
73
-             * 'wp_loaded' is too much work on a BETA milestone.
74
-             * So this fix is expected to work if the WP files are owned by the server user,
75
-             * but probably not if the user needs to enter their FTP credentials to modify files
76
-             * and there may be troubles if the WP files are owned by a different user
77
-             * than the server user. But both of these issues should exist in 4.4 and earlier too
78
-             */
79
-            if (false && ! did_action('wp_loaded')) {
80
-                $msg = __('An attempt to access and/or write to a file on the server could not be completed due to a lack of sufficient credentials.', 'event_espresso');
81
-                if (WP_DEBUG) {
82
-                    $msg .= '<br />' .  __('The WP Filesystem can not be accessed until after the "wp_loaded" hook has run, so it\'s best not to attempt access until the "admin_init" hookpoint.', 'event_espresso');
83
-                }
84
-                throw new EE_Error($msg);
85
-            } else {
86
-                // should be loaded if we are past the wp_loaded hook...
87
-                if (! function_exists('WP_Filesystem')) {
88
-                    require_once(ABSPATH . 'wp-admin/includes/file.php');
89
-                    require_once(ABSPATH . 'wp-admin/includes/template.php');
90
-                }
91
-                // turn on output buffering so that we can capture the credentials form
92
-                ob_start();
93
-                $credentials = request_filesystem_credentials('');
94
-                // store credentials form for the time being
95
-                EEH_File::$_credentials_form = ob_get_clean();
96
-                // basically check for direct or previously configured access
97
-                if (! WP_Filesystem($credentials)) {
98
-                    // if credentials do NOT exist
99
-                    if ($credentials === false) {
100
-                        add_action('admin_notices', array( 'EEH_File', 'display_request_filesystem_credentials_form' ), 999);
101
-                        throw new EE_Error(__('An attempt to access and/or write to a file on the server could not be completed due to a lack of sufficient credentials.', 'event_espresso'));
102
-                    } elseif (is_wp_error($wp_filesystem->errors) && $wp_filesystem->errors->get_error_code()) {
103
-                        add_action('admin_notices', array( 'EEH_File', 'display_request_filesystem_credentials_form' ), 999);
104
-                        throw new EE_Error(
105
-                            sprintf(
106
-                                __('WP Filesystem Error: $1%s', 'event_espresso'),
107
-                                $wp_filesystem->errors->get_error_message()
108
-                            )
109
-                        );
110
-                    }
111
-                }
112
-            }
113
-        }
114
-        return $wp_filesystem;
115
-    }
116
-
117
-    /**
118
-     * display_request_filesystem_credentials_form
119
-     */
120
-    public static function display_request_filesystem_credentials_form()
121
-    {
122
-        if (! empty(EEH_File::$_credentials_form)) {
123
-            echo '<div class="updated espresso-notices-attention"><p>' . EEH_File::$_credentials_form . '</p></div>';
124
-        }
125
-    }
126
-
127
-
128
-
129
-    /**
130
-     *    verify_filepath_and_permissions
131
-     *    checks that a file is readable and has sufficient file permissions set to access
132
-     *
133
-     * @access public
134
-     * @param string $full_file_path - full server path to the folder or file
135
-     * @param string $file_name      - name of file if checking a file
136
-     * @param string $file_ext       - file extension (ie: "php") if checking a file
137
-     * @param string $type_of_file   - general type of file (ie: "module"), this is only used to improve error messages
138
-     * @throws EE_Error if filesystem credentials are required
139
-     * @return bool
140
-     */
141
-    public static function verify_filepath_and_permissions($full_file_path = '', $file_name = '', $file_ext = '', $type_of_file = '')
142
-    {
143
-        // load WP_Filesystem and set file permissions
144
-        $wp_filesystem = EEH_File::_get_wp_filesystem($full_file_path);
145
-        $full_file_path = EEH_File::standardise_directory_separators($full_file_path);
146
-        if (! $wp_filesystem->is_readable(EEH_File::convert_local_filepath_to_remote_filepath($full_file_path))) {
147
-            $file_name = ! empty($type_of_file) ? $file_name . ' ' . $type_of_file : $file_name;
148
-            $file_name .= ! empty($file_ext) ? ' file' : ' folder';
149
-            $msg = sprintf(
150
-                __('The requested %1$s could not be found or is not readable, possibly due to an incorrect filepath, or incorrect file permissions.%2$s', 'event_espresso'),
151
-                $file_name,
152
-                '<br />'
153
-            );
154
-            if (EEH_File::exists($full_file_path)) {
155
-                $msg .= EEH_File::_permissions_error_for_unreadable_filepath($full_file_path, $type_of_file);
156
-            } else {
157
-                // no file permissions means the file was not found
158
-                $msg .= sprintf(
159
-                    __('Please ensure the following path is correct: "%s".', 'event_espresso'),
160
-                    $full_file_path
161
-                );
162
-            }
163
-            if (defined('WP_DEBUG') && WP_DEBUG) {
164
-                throw new EE_Error($msg . '||' . $msg);
165
-            }
166
-            return false;
167
-        }
168
-        return true;
169
-    }
170
-
171
-
172
-
173
-    /**
174
-     * _permissions_error_for_unreadable_filepath - attempts to determine why permissions are set incorrectly for a file or folder
175
-     *
176
-     * @access private
177
-     * @param string $full_file_path - full server path to the folder or file
178
-     * @param string $type_of_file - general type of file (ie: "module"), this is only used to improve error messages
179
-     * @throws EE_Error if filesystem credentials are required
180
-     * @return string
181
-     */
182
-    private static function _permissions_error_for_unreadable_filepath($full_file_path = '', $type_of_file = '')
183
-    {
184
-        // load WP_Filesystem and set file permissions
185
-        $wp_filesystem = EEH_File::_get_wp_filesystem($full_file_path);
186
-        // check file permissions
187
-        $perms = $wp_filesystem->getchmod(EEH_File::convert_local_filepath_to_remote_filepath($full_file_path));
188
-        if ($perms) {
189
-            // file permissions exist, but way be set incorrectly
190
-            $type_of_file = ! empty($type_of_file) ? $type_of_file . ' ' : '';
191
-            $type_of_file .= ! empty($type_of_file) ? 'file' : 'folder';
192
-            return sprintf(
193
-                __('File permissions for the requested %1$s are currently set at "%2$s". The recommended permissions are 644 for files and 755 for folders.', 'event_espresso'),
194
-                $type_of_file,
195
-                $perms
196
-            );
197
-        } else {
198
-            // file exists but file permissions could not be read ?!?!
199
-            return sprintf(
200
-                __('Please ensure that the server and/or PHP configuration allows the current process to access the following file: "%s".', 'event_espresso'),
201
-                $full_file_path
202
-            );
203
-        }
204
-    }
205
-
206
-
207
-
208
-    /**
209
-     * ensure_folder_exists_and_is_writable
210
-     * ensures that a folder exists and is writable, will attempt to create folder if it does not exist
211
-     * Also ensures all the parent folders exist, and if not tries to create them.
212
-     * Also, if this function creates the folder, adds a .htaccess file and index.html file
213
-     * @param string $folder
214
-     * @throws EE_Error if the folder exists and is writeable, but for some reason we
215
-     * can't write to it
216
-     * @return bool false if folder isn't writable; true if it exists and is writeable,
217
-     */
218
-    public static function ensure_folder_exists_and_is_writable($folder = '')
219
-    {
220
-        if (empty($folder)) {
221
-            return false;
222
-        }
223
-        // remove ending DS
224
-        $folder = EEH_File::standardise_directory_separators(rtrim($folder, '/\\'));
225
-        $parent_folder = EEH_File::get_parent_folder($folder);
226
-        // add DS to folder
227
-        $folder = EEH_File::end_with_directory_separator($folder);
228
-        $wp_filesystem = EEH_File::_get_wp_filesystem($folder);
229
-        if (! $wp_filesystem->is_dir(EEH_File::convert_local_filepath_to_remote_filepath($folder))) {
230
-            // ok so it doesn't exist. Does its parent? Can we write to it?
231
-            if (! EEH_File::ensure_folder_exists_and_is_writable($parent_folder)) {
232
-                return false;
233
-            }
234
-            if (! EEH_File::verify_is_writable($parent_folder, 'folder')) {
235
-                return false;
236
-            } else {
237
-                if (! $wp_filesystem->mkdir(EEH_File::convert_local_filepath_to_remote_filepath($folder))) {
238
-                    if (defined('WP_DEBUG') && WP_DEBUG) {
239
-                        $msg = sprintf(__('"%s" could not be created.', 'event_espresso'), $folder);
240
-                        $msg .= EEH_File::_permissions_error_for_unreadable_filepath($folder);
241
-                        throw new EE_Error($msg);
242
-                    }
243
-                    return false;
244
-                }
245
-                EEH_File::add_index_file($folder);
246
-            }
247
-        } elseif (! EEH_File::verify_is_writable($folder, 'folder')) {
248
-            return false;
249
-        }
250
-        return true;
251
-    }
252
-
253
-
254
-
255
-    /**
256
-     * verify_is_writable - checks if a file or folder is writable
257
-     * @param string $full_path      - full server path to file or folder
258
-     * @param string $file_or_folder - whether checking a file or folder
259
-     * @throws EE_Error if filesystem credentials are required
260
-     * @return bool
261
-     */
262
-    public static function verify_is_writable($full_path = '', $file_or_folder = 'folder')
263
-    {
264
-        // load WP_Filesystem and set file permissions
265
-        $wp_filesystem = EEH_File::_get_wp_filesystem($full_path);
266
-        $full_path = EEH_File::standardise_directory_separators($full_path);
267
-        if (! $wp_filesystem->is_writable(EEH_File::convert_local_filepath_to_remote_filepath($full_path))) {
268
-            if (defined('WP_DEBUG') && WP_DEBUG) {
269
-                $msg = sprintf(__('The "%1$s" %2$s is not writable.', 'event_espresso'), $full_path, $file_or_folder);
270
-                $msg .= EEH_File::_permissions_error_for_unreadable_filepath($full_path);
271
-                throw new EE_Error($msg);
272
-            }
273
-            return false;
274
-        }
275
-        return true;
276
-    }
277
-
278
-
279
-
280
-    /**
281
-     * ensure_file_exists_and_is_writable
282
-     * ensures that a file exists and is writable, will attempt to create file if it does not exist.
283
-     * Also ensures all the parent folders exist, and if not tries to create them.
284
-     * @param string $full_file_path
285
-     * @throws EE_Error if filesystem credentials are required
286
-     * @return bool
287
-     */
288
-    public static function ensure_file_exists_and_is_writable($full_file_path = '')
289
-    {
290
-        // load WP_Filesystem and set file permissions
291
-        $wp_filesystem = EEH_File::_get_wp_filesystem($full_file_path);
292
-        $full_file_path = EEH_File::standardise_directory_separators($full_file_path);
293
-        $parent_folder = EEH_File::get_parent_folder($full_file_path);
294
-        if (! EEH_File::exists($full_file_path)) {
295
-            if (! EEH_File::ensure_folder_exists_and_is_writable($parent_folder)) {
296
-                return false;
297
-            }
298
-            if (! $wp_filesystem->touch(EEH_File::convert_local_filepath_to_remote_filepath($full_file_path))) {
299
-                if (defined('WP_DEBUG') && WP_DEBUG) {
300
-                    $msg = sprintf(__('The "%s" file could not be created.', 'event_espresso'), $full_file_path);
301
-                    $msg .= EEH_File::_permissions_error_for_unreadable_filepath($full_file_path);
302
-                    throw new EE_Error($msg);
303
-                }
304
-                return false;
305
-            }
306
-        }
307
-        if (! EEH_File::verify_is_writable($full_file_path, 'file')) {
308
-            return false;
309
-        }
310
-        return true;
311
-    }
312
-
313
-    /**
314
-     * Gets the parent folder. If provided with file, gets the folder that contains it.
315
-     * If provided a folder, gets its parent folder.
316
-     * @param string $file_or_folder_path
317
-     * @return string parent folder, ENDING with a directory separator
318
-     */
319
-    public static function get_parent_folder($file_or_folder_path)
320
-    {
321
-        // find the last DS, ignoring a DS on the very end
322
-        // eg if given "/var/something/somewhere/", we want to get "somewhere"'s
323
-        // parent folder, "/var/something/"
324
-        $ds = strlen($file_or_folder_path) > 1
325
-            ? strrpos($file_or_folder_path, DS, -2)
326
-            : strlen($file_or_folder_path);
327
-        return substr($file_or_folder_path, 0, $ds + 1);
328
-    }
329
-
330
-    // public static function ensure_folder_exists_recursively( $folder ) {
331
-    //
332
-    // }
333
-
334
-
335
-
336
-    /**
337
-     * get_file_contents
338
-     * @param string $full_file_path
339
-     * @throws EE_Error if filesystem credentials are required
340
-     * @return string
341
-     */
342
-    public static function get_file_contents($full_file_path = '')
343
-    {
344
-        $full_file_path = EEH_File::standardise_directory_separators($full_file_path);
345
-        if (EEH_File::verify_filepath_and_permissions($full_file_path, EEH_File::get_filename_from_filepath($full_file_path), EEH_File::get_file_extension($full_file_path))) {
346
-            // load WP_Filesystem and set file permissions
347
-            $wp_filesystem = EEH_File::_get_wp_filesystem($full_file_path);
348
-            return $wp_filesystem->get_contents(EEH_File::convert_local_filepath_to_remote_filepath($full_file_path));
349
-        }
350
-        return '';
351
-    }
352
-
353
-
354
-
355
-    /**
356
-     * write_file
357
-     * @param string $full_file_path
358
-     * @param string $file_contents - the content to be written to the file
359
-     * @param string $file_type
360
-     * @throws EE_Error if filesystem credentials are required
361
-     * @return bool
362
-     */
363
-    public static function write_to_file($full_file_path = '', $file_contents = '', $file_type = '')
364
-    {
365
-        $full_file_path = EEH_File::standardise_directory_separators($full_file_path);
366
-        $file_type = ! empty($file_type) ? rtrim($file_type, ' ') . ' ' : '';
367
-        $folder = EEH_File::remove_filename_from_filepath($full_file_path);
368
-        if (! EEH_File::verify_is_writable($folder, 'folder')) {
369
-            if (defined('WP_DEBUG') && WP_DEBUG) {
370
-                $msg = sprintf(__('The %1$sfile located at "%2$s" is not writable.', 'event_espresso'), $file_type, $full_file_path);
371
-                $msg .= EEH_File::_permissions_error_for_unreadable_filepath($full_file_path);
372
-                throw new EE_Error($msg);
373
-            }
374
-            return false;
375
-        }
376
-        // load WP_Filesystem and set file permissions
377
-        $wp_filesystem = EEH_File::_get_wp_filesystem($full_file_path);
378
-        // write the file
379
-        if (! $wp_filesystem->put_contents(EEH_File::convert_local_filepath_to_remote_filepath($full_file_path), $file_contents)) {
380
-            if (defined('WP_DEBUG') && WP_DEBUG) {
381
-                $msg = sprintf(__('The %1$sfile located at "%2$s" could not be written to.', 'event_espresso'), $file_type, $full_file_path);
382
-                $msg .= EEH_File::_permissions_error_for_unreadable_filepath($full_file_path, 'f');
383
-                throw new EE_Error($msg);
384
-            }
385
-            return false;
386
-        }
387
-        return true;
388
-    }
389
-
390
-    /**
391
-     * Wrapper for WP_Filesystem_Base::delete
392
-     *
393
-     * @param string $filepath
394
-     * @param boolean $recursive
395
-     * @param boolean|string $type 'd' for directory, 'f' for file
396
-     * @throws EE_Error if filesystem credentials are required
397
-     * @return boolean
398
-     */
399
-    public static function delete($filepath, $recursive = false, $type = false)
400
-    {
401
-        $wp_filesystem = EEH_File::_get_wp_filesystem();
402
-        return $wp_filesystem->delete($filepath, $recursive, $type) ? true : false;
403
-    }
404
-
405
-
406
-
407
-    /**
408
-     * exists
409
-     * checks if a file exists using the WP filesystem
410
-     * @param string $full_file_path
411
-     * @throws EE_Error if filesystem credentials are required
412
-     * @return bool
413
-     */
414
-    public static function exists($full_file_path = '')
415
-    {
416
-        $wp_filesystem = EEH_File::_get_wp_filesystem($full_file_path);
417
-        return $wp_filesystem->exists(EEH_File::convert_local_filepath_to_remote_filepath($full_file_path)) ? true : false;
418
-    }
419
-
420
-
421
-
422
-    /**
423
-     * is_readable
424
-     * checks if a file is_readable using the WP filesystem
425
-     *
426
-     * @param string $full_file_path
427
-     * @throws EE_Error if filesystem credentials are required
428
-     * @return bool
429
-     */
430
-    public static function is_readable($full_file_path = '')
431
-    {
432
-        $wp_filesystem = EEH_File::_get_wp_filesystem($full_file_path);
433
-        if ($wp_filesystem->is_readable(EEH_File::convert_local_filepath_to_remote_filepath($full_file_path))) {
434
-            return true;
435
-        } else {
436
-            return false;
437
-        }
438
-    }
439
-
440
-
441
-
442
-    /**
443
-     * remove_filename_from_filepath
444
-     * given a full path to a file including the filename itself, this removes  the filename and returns the path, up to, but NOT including the filename OR slash
445
-     *
446
-     * @param string $full_file_path
447
-     * @return string
448
-     */
449
-    public static function remove_filename_from_filepath($full_file_path = '')
450
-    {
451
-        return pathinfo($full_file_path, PATHINFO_DIRNAME);
452
-    }
453
-
454
-
455
-    /**
456
-     * get_filename_from_filepath. Arguably the same as basename()
457
-     *
458
-     * @param string $full_file_path
459
-     * @return string
460
-     */
461
-    public static function get_filename_from_filepath($full_file_path = '')
462
-    {
463
-        return pathinfo($full_file_path, PATHINFO_BASENAME);
464
-    }
465
-
466
-
467
-    /**
468
-     * get_file_extension
469
-     *
470
-     * @param string $full_file_path
471
-     * @return string
472
-     */
473
-    public static function get_file_extension($full_file_path = '')
474
-    {
475
-        return pathinfo($full_file_path, PATHINFO_EXTENSION);
476
-    }
477
-
478
-
479
-
480
-    /**
481
-     * add_htaccess_deny_from_all so the webserver cannot access this folder
482
-     * @param string $folder
483
-     * @throws EE_Error if filesystem credentials are required
484
-     * @return bool
485
-     */
486
-    public static function add_htaccess_deny_from_all($folder = '')
487
-    {
488
-        $folder = EEH_File::standardise_and_end_with_directory_separator($folder);
489
-        if (! EEH_File::exists($folder . '.htaccess')) {
490
-            if (! EEH_File::write_to_file($folder . '.htaccess', 'deny from all', '.htaccess')) {
491
-                return false;
492
-            }
493
-        }
494
-
495
-        return true;
496
-    }
497
-
498
-    /**
499
-     * Adds an index file to this folder, so folks can't list all the file's contents
500
-     * @param string $folder
501
-     * @throws EE_Error if filesystem credentials are required
502
-     * @return boolean
503
-     */
504
-    public static function add_index_file($folder)
505
-    {
506
-        $folder = EEH_File::standardise_and_end_with_directory_separator($folder);
507
-        if (! EEH_File::exists($folder . 'index.php')) {
508
-            if (! EEH_File::write_to_file($folder . 'index.php', 'You are not permitted to read from this folder', '.php')) {
509
-                return false;
510
-            }
511
-        }
512
-        return true;
513
-    }
514
-
515
-
516
-
517
-    /**
518
-     * Given that the file in $file_path has the normal name, (ie, CLASSNAME.whatever.php),
519
-     * extract that classname.
520
-     * @param string $file_path
521
-     * @return string
522
-     */
523
-    public static function get_classname_from_filepath_with_standard_filename($file_path)
524
-    {
525
-        // extract file from path
526
-        $filename = basename($file_path);
527
-        // now remove the first period and everything after
528
-        $pos_of_first_period = strpos($filename, '.');
529
-        return substr($filename, 0, $pos_of_first_period);
530
-    }
531
-
532
-
533
-
534
-    /**
535
-     * standardise_directory_separators
536
-     *  convert all directory separators in a file path to whatever is set for DS
537
-     * @param string $file_path
538
-     * @return string
539
-     */
540
-    public static function standardise_directory_separators($file_path)
541
-    {
542
-        return str_replace(array( '\\', '/' ), DS, $file_path);
543
-    }
544
-
545
-
546
-
547
-    /**
548
-     * end_with_directory_separator
549
-     *  ensures that file path ends with DS
550
-     * @param string $file_path
551
-     * @return string
552
-     */
553
-    public static function end_with_directory_separator($file_path)
554
-    {
555
-        return rtrim($file_path, '/\\') . DS;
556
-    }
557
-
558
-
559
-
560
-    /**
561
-     * shorthand for both EEH_FIle::end_with_directory_separator AND EEH_File::standardise_directory_separators
562
-     * @param $file_path
563
-     * @return string
564
-     */
565
-    public static function standardise_and_end_with_directory_separator($file_path)
566
-    {
567
-        return self::end_with_directory_separator(self::standardise_directory_separators($file_path));
568
-    }
569
-
570
-
571
-
572
-    /**
573
-     * takes the folder name (with or without trailing slash) and finds the files it in,
574
-     * and what the class's name inside of each should be.
575
-     * @param array $folder_paths
576
-     * @param boolean $index_numerically if TRUE, the returned array will be indexed numerically;
577
-     *      if FALSE (Default), returned array will be indexed by the filenames minus extensions.
578
-     *      Set it TRUE if you know there are files in the directory with the same name but different extensions
579
-     * @throws EE_Error if filesystem credentials are required
580
-     * @return array if $index_numerically == TRUE keys are numeric ,
581
-     *      if $index_numerically == FALSE (Default) keys are what the class names SHOULD be;
582
-     *       and values are their filepaths
583
-     */
584
-    public static function get_contents_of_folders($folder_paths = array(), $index_numerically = false)
585
-    {
586
-        $class_to_folder_path = array();
587
-        foreach ($folder_paths as $folder_path) {
588
-            $folder_path = self::standardise_and_end_with_directory_separator($folder_path);
589
-            // load WP_Filesystem and set file permissions
590
-            $files_in_folder = glob($folder_path . '*');
591
-            $class_to_folder_path = array();
592
-            if ($files_in_folder) {
593
-                foreach ($files_in_folder as $file_path) {
594
-                    // only add files, not folders
595
-                    if (! is_dir($file_path)) {
596
-                        if ($index_numerically) {
597
-                            $class_to_folder_path[] = $file_path;
598
-                        } else {
599
-                            $classname = self::get_classname_from_filepath_with_standard_filename($file_path);
600
-                            $class_to_folder_path[ $classname ] = $file_path;
601
-                        }
602
-                    }
603
-                }
604
-            }
605
-        }
606
-        return $class_to_folder_path;
607
-    }
608
-
609
-
610
-
611
-    /**
612
-     * Copies a file. Mostly a wrapper of WP_Filesystem::copy
613
-     * @param string $source_file
614
-     * @param string $destination_file
615
-     * @param boolean $overwrite
616
-     * @throws EE_Error if filesystem credentials are required
617
-     * @return boolean success
618
-     */
619
-    public static function copy($source_file, $destination_file, $overwrite = false)
620
-    {
621
-        $full_source_path = EEH_File::standardise_directory_separators($source_file);
622
-        if (! EEH_File::exists($full_source_path)) {
623
-            if (defined('WP_DEBUG') && WP_DEBUG) {
624
-                $msg = sprintf(__('The file located at "%2$s" is not readable or doesn\'t exist.', 'event_espresso'), $full_source_path);
625
-                $msg .= EEH_File::_permissions_error_for_unreadable_filepath($full_source_path);
626
-                throw new EE_Error($msg);
627
-            }
628
-            return false;
629
-        }
630
-
631
-        $full_dest_path = EEH_File::standardise_directory_separators($destination_file);
632
-        $folder = EEH_File::remove_filename_from_filepath($full_dest_path);
633
-        EEH_File::ensure_folder_exists_and_is_writable($folder);
634
-        if (! EEH_File::verify_is_writable($folder, 'folder')) {
635
-            if (defined('WP_DEBUG') && WP_DEBUG) {
636
-                $msg = sprintf(__('The file located at "%2$s" is not writable.', 'event_espresso'), $full_dest_path);
637
-                $msg .= EEH_File::_permissions_error_for_unreadable_filepath($full_dest_path);
638
-                throw new EE_Error($msg);
639
-            }
640
-            return false;
641
-        }
642
-
643
-        // load WP_Filesystem and set file permissions
644
-        $wp_filesystem = EEH_File::_get_wp_filesystem($destination_file);
645
-        // write the file
646
-        if (! $wp_filesystem->copy(
647
-            EEH_File::convert_local_filepath_to_remote_filepath($full_source_path),
648
-            EEH_File::convert_local_filepath_to_remote_filepath($full_dest_path),
649
-            $overwrite
650
-        )) {
651
-            if (defined('WP_DEBUG') && WP_DEBUG) {
652
-                $msg = sprintf(__('Attempted writing to file %1$s, but could not, probably because of permissions issues', 'event_espresso'), $full_source_path);
653
-                $msg .= EEH_File::_permissions_error_for_unreadable_filepath($full_source_path, 'f');
654
-                throw new EE_Error($msg);
655
-            }
656
-            return false;
657
-        }
658
-        return true;
659
-    }
660
-
661
-    /**
662
-     * Reports whether or not the filepath is in the EE uploads folder or not
663
-     * @param string $filepath
664
-     * @return boolean
665
-     */
666
-    public static function is_in_uploads_folder($filepath)
667
-    {
668
-        $uploads = wp_upload_dir();
669
-        return strpos($filepath, $uploads['basedir']) === 0 ? true : false;
670
-    }
671
-
672
-    /**
673
-     * Given a "local" filepath (what you probably thought was the only filepath),
674
-     * converts it into a "remote" filepath (the filepath the currently-in-use
675
-     * $wp_filesystem needs to use access the folder or file).
676
-     * See http://wordpress.stackexchange.com/questions/124900/using-wp-filesystem-in-plugins
677
-     * @param WP_Filesystem_Base $wp_filesystem we aren't initially sure which one
678
-     * is in use, so you need to provide it
679
-     * @param string $local_filepath the filepath to the folder/file locally
680
-     * @throws EE_Error if filesystem credentials are required
681
-     * @return string the remote filepath (eg the filepath the filesystem method, eg
682
-     * ftp or ssh, will use to access the folder
683
-     */
684
-    public static function convert_local_filepath_to_remote_filepath($local_filepath)
685
-    {
686
-        $wp_filesystem = EEH_File::_get_wp_filesystem($local_filepath);
687
-        return str_replace(WP_CONTENT_DIR . DS, $wp_filesystem->wp_content_dir(), $local_filepath);
688
-    }
27
+	/**
28
+	 * @var string $_credentials_form
29
+	 */
30
+	private static $_credentials_form;
31
+
32
+	protected static $_wp_filesystem_direct;
33
+
34
+	/**
35
+	 * @param string|null $filepath the filepath we want to work in. If its in the
36
+	 * wp uploads directory, we'll want to just use the filesystem directly.
37
+	 * If not provided, we have to assume its not in the uploads directory
38
+	 * @throws EE_Error if filesystem credentials are required
39
+	 * @return WP_Filesystem_Base
40
+	 */
41
+	private static function _get_wp_filesystem($filepath = null)
42
+	{
43
+		if (apply_filters(
44
+			'FHEE__EEH_File___get_wp_filesystem__allow_using_filesystem_direct',
45
+			$filepath && EEH_File::is_in_uploads_folder($filepath),
46
+			$filepath
47
+		) ) {
48
+			if (! EEH_File::$_wp_filesystem_direct instanceof WP_Filesystem_Direct) {
49
+				require_once(ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php');
50
+				$method = 'direct';
51
+				$wp_filesystem_direct_file = apply_filters('filesystem_method_file', ABSPATH . 'wp-admin/includes/class-wp-filesystem-' . $method . '.php', $method);
52
+				// check constants defined, just like in wp-admin/includes/file.php's WP_Filesystem()
53
+				if (! defined('FS_CHMOD_DIR')) {
54
+					define('FS_CHMOD_DIR', ( fileperms(ABSPATH) & 0777 | 0755 ));
55
+				}
56
+				if (! defined('FS_CHMOD_FILE')) {
57
+					define('FS_CHMOD_FILE', ( fileperms(ABSPATH . 'index.php') & 0777 | 0644 ));
58
+				}
59
+				require_once($wp_filesystem_direct_file);
60
+				EEH_File::$_wp_filesystem_direct = new WP_Filesystem_Direct(array());
61
+			}
62
+			return EEH_File::$_wp_filesystem_direct;
63
+		}
64
+		global $wp_filesystem;
65
+		// no filesystem setup ???
66
+		if (! $wp_filesystem instanceof WP_Filesystem_Base) {
67
+			// if some eager beaver's just trying to get in there too early...
68
+			// let them do it, because we are one of those eager beavers! :P
69
+			/**
70
+			 * more explanations are probably merited. http://codex.wordpress.org/Filesystem_API#Initializing_WP_Filesystem_Base
71
+			 * says WP_Filesystem should be used after 'wp_loaded', but currently EE's activation process
72
+			 * is setup to mostly happen on 'init', and refactoring to have it happen on
73
+			 * 'wp_loaded' is too much work on a BETA milestone.
74
+			 * So this fix is expected to work if the WP files are owned by the server user,
75
+			 * but probably not if the user needs to enter their FTP credentials to modify files
76
+			 * and there may be troubles if the WP files are owned by a different user
77
+			 * than the server user. But both of these issues should exist in 4.4 and earlier too
78
+			 */
79
+			if (false && ! did_action('wp_loaded')) {
80
+				$msg = __('An attempt to access and/or write to a file on the server could not be completed due to a lack of sufficient credentials.', 'event_espresso');
81
+				if (WP_DEBUG) {
82
+					$msg .= '<br />' .  __('The WP Filesystem can not be accessed until after the "wp_loaded" hook has run, so it\'s best not to attempt access until the "admin_init" hookpoint.', 'event_espresso');
83
+				}
84
+				throw new EE_Error($msg);
85
+			} else {
86
+				// should be loaded if we are past the wp_loaded hook...
87
+				if (! function_exists('WP_Filesystem')) {
88
+					require_once(ABSPATH . 'wp-admin/includes/file.php');
89
+					require_once(ABSPATH . 'wp-admin/includes/template.php');
90
+				}
91
+				// turn on output buffering so that we can capture the credentials form
92
+				ob_start();
93
+				$credentials = request_filesystem_credentials('');
94
+				// store credentials form for the time being
95
+				EEH_File::$_credentials_form = ob_get_clean();
96
+				// basically check for direct or previously configured access
97
+				if (! WP_Filesystem($credentials)) {
98
+					// if credentials do NOT exist
99
+					if ($credentials === false) {
100
+						add_action('admin_notices', array( 'EEH_File', 'display_request_filesystem_credentials_form' ), 999);
101
+						throw new EE_Error(__('An attempt to access and/or write to a file on the server could not be completed due to a lack of sufficient credentials.', 'event_espresso'));
102
+					} elseif (is_wp_error($wp_filesystem->errors) && $wp_filesystem->errors->get_error_code()) {
103
+						add_action('admin_notices', array( 'EEH_File', 'display_request_filesystem_credentials_form' ), 999);
104
+						throw new EE_Error(
105
+							sprintf(
106
+								__('WP Filesystem Error: $1%s', 'event_espresso'),
107
+								$wp_filesystem->errors->get_error_message()
108
+							)
109
+						);
110
+					}
111
+				}
112
+			}
113
+		}
114
+		return $wp_filesystem;
115
+	}
116
+
117
+	/**
118
+	 * display_request_filesystem_credentials_form
119
+	 */
120
+	public static function display_request_filesystem_credentials_form()
121
+	{
122
+		if (! empty(EEH_File::$_credentials_form)) {
123
+			echo '<div class="updated espresso-notices-attention"><p>' . EEH_File::$_credentials_form . '</p></div>';
124
+		}
125
+	}
126
+
127
+
128
+
129
+	/**
130
+	 *    verify_filepath_and_permissions
131
+	 *    checks that a file is readable and has sufficient file permissions set to access
132
+	 *
133
+	 * @access public
134
+	 * @param string $full_file_path - full server path to the folder or file
135
+	 * @param string $file_name      - name of file if checking a file
136
+	 * @param string $file_ext       - file extension (ie: "php") if checking a file
137
+	 * @param string $type_of_file   - general type of file (ie: "module"), this is only used to improve error messages
138
+	 * @throws EE_Error if filesystem credentials are required
139
+	 * @return bool
140
+	 */
141
+	public static function verify_filepath_and_permissions($full_file_path = '', $file_name = '', $file_ext = '', $type_of_file = '')
142
+	{
143
+		// load WP_Filesystem and set file permissions
144
+		$wp_filesystem = EEH_File::_get_wp_filesystem($full_file_path);
145
+		$full_file_path = EEH_File::standardise_directory_separators($full_file_path);
146
+		if (! $wp_filesystem->is_readable(EEH_File::convert_local_filepath_to_remote_filepath($full_file_path))) {
147
+			$file_name = ! empty($type_of_file) ? $file_name . ' ' . $type_of_file : $file_name;
148
+			$file_name .= ! empty($file_ext) ? ' file' : ' folder';
149
+			$msg = sprintf(
150
+				__('The requested %1$s could not be found or is not readable, possibly due to an incorrect filepath, or incorrect file permissions.%2$s', 'event_espresso'),
151
+				$file_name,
152
+				'<br />'
153
+			);
154
+			if (EEH_File::exists($full_file_path)) {
155
+				$msg .= EEH_File::_permissions_error_for_unreadable_filepath($full_file_path, $type_of_file);
156
+			} else {
157
+				// no file permissions means the file was not found
158
+				$msg .= sprintf(
159
+					__('Please ensure the following path is correct: "%s".', 'event_espresso'),
160
+					$full_file_path
161
+				);
162
+			}
163
+			if (defined('WP_DEBUG') && WP_DEBUG) {
164
+				throw new EE_Error($msg . '||' . $msg);
165
+			}
166
+			return false;
167
+		}
168
+		return true;
169
+	}
170
+
171
+
172
+
173
+	/**
174
+	 * _permissions_error_for_unreadable_filepath - attempts to determine why permissions are set incorrectly for a file or folder
175
+	 *
176
+	 * @access private
177
+	 * @param string $full_file_path - full server path to the folder or file
178
+	 * @param string $type_of_file - general type of file (ie: "module"), this is only used to improve error messages
179
+	 * @throws EE_Error if filesystem credentials are required
180
+	 * @return string
181
+	 */
182
+	private static function _permissions_error_for_unreadable_filepath($full_file_path = '', $type_of_file = '')
183
+	{
184
+		// load WP_Filesystem and set file permissions
185
+		$wp_filesystem = EEH_File::_get_wp_filesystem($full_file_path);
186
+		// check file permissions
187
+		$perms = $wp_filesystem->getchmod(EEH_File::convert_local_filepath_to_remote_filepath($full_file_path));
188
+		if ($perms) {
189
+			// file permissions exist, but way be set incorrectly
190
+			$type_of_file = ! empty($type_of_file) ? $type_of_file . ' ' : '';
191
+			$type_of_file .= ! empty($type_of_file) ? 'file' : 'folder';
192
+			return sprintf(
193
+				__('File permissions for the requested %1$s are currently set at "%2$s". The recommended permissions are 644 for files and 755 for folders.', 'event_espresso'),
194
+				$type_of_file,
195
+				$perms
196
+			);
197
+		} else {
198
+			// file exists but file permissions could not be read ?!?!
199
+			return sprintf(
200
+				__('Please ensure that the server and/or PHP configuration allows the current process to access the following file: "%s".', 'event_espresso'),
201
+				$full_file_path
202
+			);
203
+		}
204
+	}
205
+
206
+
207
+
208
+	/**
209
+	 * ensure_folder_exists_and_is_writable
210
+	 * ensures that a folder exists and is writable, will attempt to create folder if it does not exist
211
+	 * Also ensures all the parent folders exist, and if not tries to create them.
212
+	 * Also, if this function creates the folder, adds a .htaccess file and index.html file
213
+	 * @param string $folder
214
+	 * @throws EE_Error if the folder exists and is writeable, but for some reason we
215
+	 * can't write to it
216
+	 * @return bool false if folder isn't writable; true if it exists and is writeable,
217
+	 */
218
+	public static function ensure_folder_exists_and_is_writable($folder = '')
219
+	{
220
+		if (empty($folder)) {
221
+			return false;
222
+		}
223
+		// remove ending DS
224
+		$folder = EEH_File::standardise_directory_separators(rtrim($folder, '/\\'));
225
+		$parent_folder = EEH_File::get_parent_folder($folder);
226
+		// add DS to folder
227
+		$folder = EEH_File::end_with_directory_separator($folder);
228
+		$wp_filesystem = EEH_File::_get_wp_filesystem($folder);
229
+		if (! $wp_filesystem->is_dir(EEH_File::convert_local_filepath_to_remote_filepath($folder))) {
230
+			// ok so it doesn't exist. Does its parent? Can we write to it?
231
+			if (! EEH_File::ensure_folder_exists_and_is_writable($parent_folder)) {
232
+				return false;
233
+			}
234
+			if (! EEH_File::verify_is_writable($parent_folder, 'folder')) {
235
+				return false;
236
+			} else {
237
+				if (! $wp_filesystem->mkdir(EEH_File::convert_local_filepath_to_remote_filepath($folder))) {
238
+					if (defined('WP_DEBUG') && WP_DEBUG) {
239
+						$msg = sprintf(__('"%s" could not be created.', 'event_espresso'), $folder);
240
+						$msg .= EEH_File::_permissions_error_for_unreadable_filepath($folder);
241
+						throw new EE_Error($msg);
242
+					}
243
+					return false;
244
+				}
245
+				EEH_File::add_index_file($folder);
246
+			}
247
+		} elseif (! EEH_File::verify_is_writable($folder, 'folder')) {
248
+			return false;
249
+		}
250
+		return true;
251
+	}
252
+
253
+
254
+
255
+	/**
256
+	 * verify_is_writable - checks if a file or folder is writable
257
+	 * @param string $full_path      - full server path to file or folder
258
+	 * @param string $file_or_folder - whether checking a file or folder
259
+	 * @throws EE_Error if filesystem credentials are required
260
+	 * @return bool
261
+	 */
262
+	public static function verify_is_writable($full_path = '', $file_or_folder = 'folder')
263
+	{
264
+		// load WP_Filesystem and set file permissions
265
+		$wp_filesystem = EEH_File::_get_wp_filesystem($full_path);
266
+		$full_path = EEH_File::standardise_directory_separators($full_path);
267
+		if (! $wp_filesystem->is_writable(EEH_File::convert_local_filepath_to_remote_filepath($full_path))) {
268
+			if (defined('WP_DEBUG') && WP_DEBUG) {
269
+				$msg = sprintf(__('The "%1$s" %2$s is not writable.', 'event_espresso'), $full_path, $file_or_folder);
270
+				$msg .= EEH_File::_permissions_error_for_unreadable_filepath($full_path);
271
+				throw new EE_Error($msg);
272
+			}
273
+			return false;
274
+		}
275
+		return true;
276
+	}
277
+
278
+
279
+
280
+	/**
281
+	 * ensure_file_exists_and_is_writable
282
+	 * ensures that a file exists and is writable, will attempt to create file if it does not exist.
283
+	 * Also ensures all the parent folders exist, and if not tries to create them.
284
+	 * @param string $full_file_path
285
+	 * @throws EE_Error if filesystem credentials are required
286
+	 * @return bool
287
+	 */
288
+	public static function ensure_file_exists_and_is_writable($full_file_path = '')
289
+	{
290
+		// load WP_Filesystem and set file permissions
291
+		$wp_filesystem = EEH_File::_get_wp_filesystem($full_file_path);
292
+		$full_file_path = EEH_File::standardise_directory_separators($full_file_path);
293
+		$parent_folder = EEH_File::get_parent_folder($full_file_path);
294
+		if (! EEH_File::exists($full_file_path)) {
295
+			if (! EEH_File::ensure_folder_exists_and_is_writable($parent_folder)) {
296
+				return false;
297
+			}
298
+			if (! $wp_filesystem->touch(EEH_File::convert_local_filepath_to_remote_filepath($full_file_path))) {
299
+				if (defined('WP_DEBUG') && WP_DEBUG) {
300
+					$msg = sprintf(__('The "%s" file could not be created.', 'event_espresso'), $full_file_path);
301
+					$msg .= EEH_File::_permissions_error_for_unreadable_filepath($full_file_path);
302
+					throw new EE_Error($msg);
303
+				}
304
+				return false;
305
+			}
306
+		}
307
+		if (! EEH_File::verify_is_writable($full_file_path, 'file')) {
308
+			return false;
309
+		}
310
+		return true;
311
+	}
312
+
313
+	/**
314
+	 * Gets the parent folder. If provided with file, gets the folder that contains it.
315
+	 * If provided a folder, gets its parent folder.
316
+	 * @param string $file_or_folder_path
317
+	 * @return string parent folder, ENDING with a directory separator
318
+	 */
319
+	public static function get_parent_folder($file_or_folder_path)
320
+	{
321
+		// find the last DS, ignoring a DS on the very end
322
+		// eg if given "/var/something/somewhere/", we want to get "somewhere"'s
323
+		// parent folder, "/var/something/"
324
+		$ds = strlen($file_or_folder_path) > 1
325
+			? strrpos($file_or_folder_path, DS, -2)
326
+			: strlen($file_or_folder_path);
327
+		return substr($file_or_folder_path, 0, $ds + 1);
328
+	}
329
+
330
+	// public static function ensure_folder_exists_recursively( $folder ) {
331
+	//
332
+	// }
333
+
334
+
335
+
336
+	/**
337
+	 * get_file_contents
338
+	 * @param string $full_file_path
339
+	 * @throws EE_Error if filesystem credentials are required
340
+	 * @return string
341
+	 */
342
+	public static function get_file_contents($full_file_path = '')
343
+	{
344
+		$full_file_path = EEH_File::standardise_directory_separators($full_file_path);
345
+		if (EEH_File::verify_filepath_and_permissions($full_file_path, EEH_File::get_filename_from_filepath($full_file_path), EEH_File::get_file_extension($full_file_path))) {
346
+			// load WP_Filesystem and set file permissions
347
+			$wp_filesystem = EEH_File::_get_wp_filesystem($full_file_path);
348
+			return $wp_filesystem->get_contents(EEH_File::convert_local_filepath_to_remote_filepath($full_file_path));
349
+		}
350
+		return '';
351
+	}
352
+
353
+
354
+
355
+	/**
356
+	 * write_file
357
+	 * @param string $full_file_path
358
+	 * @param string $file_contents - the content to be written to the file
359
+	 * @param string $file_type
360
+	 * @throws EE_Error if filesystem credentials are required
361
+	 * @return bool
362
+	 */
363
+	public static function write_to_file($full_file_path = '', $file_contents = '', $file_type = '')
364
+	{
365
+		$full_file_path = EEH_File::standardise_directory_separators($full_file_path);
366
+		$file_type = ! empty($file_type) ? rtrim($file_type, ' ') . ' ' : '';
367
+		$folder = EEH_File::remove_filename_from_filepath($full_file_path);
368
+		if (! EEH_File::verify_is_writable($folder, 'folder')) {
369
+			if (defined('WP_DEBUG') && WP_DEBUG) {
370
+				$msg = sprintf(__('The %1$sfile located at "%2$s" is not writable.', 'event_espresso'), $file_type, $full_file_path);
371
+				$msg .= EEH_File::_permissions_error_for_unreadable_filepath($full_file_path);
372
+				throw new EE_Error($msg);
373
+			}
374
+			return false;
375
+		}
376
+		// load WP_Filesystem and set file permissions
377
+		$wp_filesystem = EEH_File::_get_wp_filesystem($full_file_path);
378
+		// write the file
379
+		if (! $wp_filesystem->put_contents(EEH_File::convert_local_filepath_to_remote_filepath($full_file_path), $file_contents)) {
380
+			if (defined('WP_DEBUG') && WP_DEBUG) {
381
+				$msg = sprintf(__('The %1$sfile located at "%2$s" could not be written to.', 'event_espresso'), $file_type, $full_file_path);
382
+				$msg .= EEH_File::_permissions_error_for_unreadable_filepath($full_file_path, 'f');
383
+				throw new EE_Error($msg);
384
+			}
385
+			return false;
386
+		}
387
+		return true;
388
+	}
389
+
390
+	/**
391
+	 * Wrapper for WP_Filesystem_Base::delete
392
+	 *
393
+	 * @param string $filepath
394
+	 * @param boolean $recursive
395
+	 * @param boolean|string $type 'd' for directory, 'f' for file
396
+	 * @throws EE_Error if filesystem credentials are required
397
+	 * @return boolean
398
+	 */
399
+	public static function delete($filepath, $recursive = false, $type = false)
400
+	{
401
+		$wp_filesystem = EEH_File::_get_wp_filesystem();
402
+		return $wp_filesystem->delete($filepath, $recursive, $type) ? true : false;
403
+	}
404
+
405
+
406
+
407
+	/**
408
+	 * exists
409
+	 * checks if a file exists using the WP filesystem
410
+	 * @param string $full_file_path
411
+	 * @throws EE_Error if filesystem credentials are required
412
+	 * @return bool
413
+	 */
414
+	public static function exists($full_file_path = '')
415
+	{
416
+		$wp_filesystem = EEH_File::_get_wp_filesystem($full_file_path);
417
+		return $wp_filesystem->exists(EEH_File::convert_local_filepath_to_remote_filepath($full_file_path)) ? true : false;
418
+	}
419
+
420
+
421
+
422
+	/**
423
+	 * is_readable
424
+	 * checks if a file is_readable using the WP filesystem
425
+	 *
426
+	 * @param string $full_file_path
427
+	 * @throws EE_Error if filesystem credentials are required
428
+	 * @return bool
429
+	 */
430
+	public static function is_readable($full_file_path = '')
431
+	{
432
+		$wp_filesystem = EEH_File::_get_wp_filesystem($full_file_path);
433
+		if ($wp_filesystem->is_readable(EEH_File::convert_local_filepath_to_remote_filepath($full_file_path))) {
434
+			return true;
435
+		} else {
436
+			return false;
437
+		}
438
+	}
439
+
440
+
441
+
442
+	/**
443
+	 * remove_filename_from_filepath
444
+	 * given a full path to a file including the filename itself, this removes  the filename and returns the path, up to, but NOT including the filename OR slash
445
+	 *
446
+	 * @param string $full_file_path
447
+	 * @return string
448
+	 */
449
+	public static function remove_filename_from_filepath($full_file_path = '')
450
+	{
451
+		return pathinfo($full_file_path, PATHINFO_DIRNAME);
452
+	}
453
+
454
+
455
+	/**
456
+	 * get_filename_from_filepath. Arguably the same as basename()
457
+	 *
458
+	 * @param string $full_file_path
459
+	 * @return string
460
+	 */
461
+	public static function get_filename_from_filepath($full_file_path = '')
462
+	{
463
+		return pathinfo($full_file_path, PATHINFO_BASENAME);
464
+	}
465
+
466
+
467
+	/**
468
+	 * get_file_extension
469
+	 *
470
+	 * @param string $full_file_path
471
+	 * @return string
472
+	 */
473
+	public static function get_file_extension($full_file_path = '')
474
+	{
475
+		return pathinfo($full_file_path, PATHINFO_EXTENSION);
476
+	}
477
+
478
+
479
+
480
+	/**
481
+	 * add_htaccess_deny_from_all so the webserver cannot access this folder
482
+	 * @param string $folder
483
+	 * @throws EE_Error if filesystem credentials are required
484
+	 * @return bool
485
+	 */
486
+	public static function add_htaccess_deny_from_all($folder = '')
487
+	{
488
+		$folder = EEH_File::standardise_and_end_with_directory_separator($folder);
489
+		if (! EEH_File::exists($folder . '.htaccess')) {
490
+			if (! EEH_File::write_to_file($folder . '.htaccess', 'deny from all', '.htaccess')) {
491
+				return false;
492
+			}
493
+		}
494
+
495
+		return true;
496
+	}
497
+
498
+	/**
499
+	 * Adds an index file to this folder, so folks can't list all the file's contents
500
+	 * @param string $folder
501
+	 * @throws EE_Error if filesystem credentials are required
502
+	 * @return boolean
503
+	 */
504
+	public static function add_index_file($folder)
505
+	{
506
+		$folder = EEH_File::standardise_and_end_with_directory_separator($folder);
507
+		if (! EEH_File::exists($folder . 'index.php')) {
508
+			if (! EEH_File::write_to_file($folder . 'index.php', 'You are not permitted to read from this folder', '.php')) {
509
+				return false;
510
+			}
511
+		}
512
+		return true;
513
+	}
514
+
515
+
516
+
517
+	/**
518
+	 * Given that the file in $file_path has the normal name, (ie, CLASSNAME.whatever.php),
519
+	 * extract that classname.
520
+	 * @param string $file_path
521
+	 * @return string
522
+	 */
523
+	public static function get_classname_from_filepath_with_standard_filename($file_path)
524
+	{
525
+		// extract file from path
526
+		$filename = basename($file_path);
527
+		// now remove the first period and everything after
528
+		$pos_of_first_period = strpos($filename, '.');
529
+		return substr($filename, 0, $pos_of_first_period);
530
+	}
531
+
532
+
533
+
534
+	/**
535
+	 * standardise_directory_separators
536
+	 *  convert all directory separators in a file path to whatever is set for DS
537
+	 * @param string $file_path
538
+	 * @return string
539
+	 */
540
+	public static function standardise_directory_separators($file_path)
541
+	{
542
+		return str_replace(array( '\\', '/' ), DS, $file_path);
543
+	}
544
+
545
+
546
+
547
+	/**
548
+	 * end_with_directory_separator
549
+	 *  ensures that file path ends with DS
550
+	 * @param string $file_path
551
+	 * @return string
552
+	 */
553
+	public static function end_with_directory_separator($file_path)
554
+	{
555
+		return rtrim($file_path, '/\\') . DS;
556
+	}
557
+
558
+
559
+
560
+	/**
561
+	 * shorthand for both EEH_FIle::end_with_directory_separator AND EEH_File::standardise_directory_separators
562
+	 * @param $file_path
563
+	 * @return string
564
+	 */
565
+	public static function standardise_and_end_with_directory_separator($file_path)
566
+	{
567
+		return self::end_with_directory_separator(self::standardise_directory_separators($file_path));
568
+	}
569
+
570
+
571
+
572
+	/**
573
+	 * takes the folder name (with or without trailing slash) and finds the files it in,
574
+	 * and what the class's name inside of each should be.
575
+	 * @param array $folder_paths
576
+	 * @param boolean $index_numerically if TRUE, the returned array will be indexed numerically;
577
+	 *      if FALSE (Default), returned array will be indexed by the filenames minus extensions.
578
+	 *      Set it TRUE if you know there are files in the directory with the same name but different extensions
579
+	 * @throws EE_Error if filesystem credentials are required
580
+	 * @return array if $index_numerically == TRUE keys are numeric ,
581
+	 *      if $index_numerically == FALSE (Default) keys are what the class names SHOULD be;
582
+	 *       and values are their filepaths
583
+	 */
584
+	public static function get_contents_of_folders($folder_paths = array(), $index_numerically = false)
585
+	{
586
+		$class_to_folder_path = array();
587
+		foreach ($folder_paths as $folder_path) {
588
+			$folder_path = self::standardise_and_end_with_directory_separator($folder_path);
589
+			// load WP_Filesystem and set file permissions
590
+			$files_in_folder = glob($folder_path . '*');
591
+			$class_to_folder_path = array();
592
+			if ($files_in_folder) {
593
+				foreach ($files_in_folder as $file_path) {
594
+					// only add files, not folders
595
+					if (! is_dir($file_path)) {
596
+						if ($index_numerically) {
597
+							$class_to_folder_path[] = $file_path;
598
+						} else {
599
+							$classname = self::get_classname_from_filepath_with_standard_filename($file_path);
600
+							$class_to_folder_path[ $classname ] = $file_path;
601
+						}
602
+					}
603
+				}
604
+			}
605
+		}
606
+		return $class_to_folder_path;
607
+	}
608
+
609
+
610
+
611
+	/**
612
+	 * Copies a file. Mostly a wrapper of WP_Filesystem::copy
613
+	 * @param string $source_file
614
+	 * @param string $destination_file
615
+	 * @param boolean $overwrite
616
+	 * @throws EE_Error if filesystem credentials are required
617
+	 * @return boolean success
618
+	 */
619
+	public static function copy($source_file, $destination_file, $overwrite = false)
620
+	{
621
+		$full_source_path = EEH_File::standardise_directory_separators($source_file);
622
+		if (! EEH_File::exists($full_source_path)) {
623
+			if (defined('WP_DEBUG') && WP_DEBUG) {
624
+				$msg = sprintf(__('The file located at "%2$s" is not readable or doesn\'t exist.', 'event_espresso'), $full_source_path);
625
+				$msg .= EEH_File::_permissions_error_for_unreadable_filepath($full_source_path);
626
+				throw new EE_Error($msg);
627
+			}
628
+			return false;
629
+		}
630
+
631
+		$full_dest_path = EEH_File::standardise_directory_separators($destination_file);
632
+		$folder = EEH_File::remove_filename_from_filepath($full_dest_path);
633
+		EEH_File::ensure_folder_exists_and_is_writable($folder);
634
+		if (! EEH_File::verify_is_writable($folder, 'folder')) {
635
+			if (defined('WP_DEBUG') && WP_DEBUG) {
636
+				$msg = sprintf(__('The file located at "%2$s" is not writable.', 'event_espresso'), $full_dest_path);
637
+				$msg .= EEH_File::_permissions_error_for_unreadable_filepath($full_dest_path);
638
+				throw new EE_Error($msg);
639
+			}
640
+			return false;
641
+		}
642
+
643
+		// load WP_Filesystem and set file permissions
644
+		$wp_filesystem = EEH_File::_get_wp_filesystem($destination_file);
645
+		// write the file
646
+		if (! $wp_filesystem->copy(
647
+			EEH_File::convert_local_filepath_to_remote_filepath($full_source_path),
648
+			EEH_File::convert_local_filepath_to_remote_filepath($full_dest_path),
649
+			$overwrite
650
+		)) {
651
+			if (defined('WP_DEBUG') && WP_DEBUG) {
652
+				$msg = sprintf(__('Attempted writing to file %1$s, but could not, probably because of permissions issues', 'event_espresso'), $full_source_path);
653
+				$msg .= EEH_File::_permissions_error_for_unreadable_filepath($full_source_path, 'f');
654
+				throw new EE_Error($msg);
655
+			}
656
+			return false;
657
+		}
658
+		return true;
659
+	}
660
+
661
+	/**
662
+	 * Reports whether or not the filepath is in the EE uploads folder or not
663
+	 * @param string $filepath
664
+	 * @return boolean
665
+	 */
666
+	public static function is_in_uploads_folder($filepath)
667
+	{
668
+		$uploads = wp_upload_dir();
669
+		return strpos($filepath, $uploads['basedir']) === 0 ? true : false;
670
+	}
671
+
672
+	/**
673
+	 * Given a "local" filepath (what you probably thought was the only filepath),
674
+	 * converts it into a "remote" filepath (the filepath the currently-in-use
675
+	 * $wp_filesystem needs to use access the folder or file).
676
+	 * See http://wordpress.stackexchange.com/questions/124900/using-wp-filesystem-in-plugins
677
+	 * @param WP_Filesystem_Base $wp_filesystem we aren't initially sure which one
678
+	 * is in use, so you need to provide it
679
+	 * @param string $local_filepath the filepath to the folder/file locally
680
+	 * @throws EE_Error if filesystem credentials are required
681
+	 * @return string the remote filepath (eg the filepath the filesystem method, eg
682
+	 * ftp or ssh, will use to access the folder
683
+	 */
684
+	public static function convert_local_filepath_to_remote_filepath($local_filepath)
685
+	{
686
+		$wp_filesystem = EEH_File::_get_wp_filesystem($local_filepath);
687
+		return str_replace(WP_CONTENT_DIR . DS, $wp_filesystem->wp_content_dir(), $local_filepath);
688
+	}
689 689
 }
Please login to merge, or discard this patch.
Spacing   +48 added lines, -48 removed lines patch added patch discarded remove patch
@@ -44,17 +44,17 @@  discard block
 block discarded – undo
44 44
             'FHEE__EEH_File___get_wp_filesystem__allow_using_filesystem_direct',
45 45
             $filepath && EEH_File::is_in_uploads_folder($filepath),
46 46
             $filepath
47
-        ) ) {
48
-            if (! EEH_File::$_wp_filesystem_direct instanceof WP_Filesystem_Direct) {
49
-                require_once(ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php');
47
+        )) {
48
+            if ( ! EEH_File::$_wp_filesystem_direct instanceof WP_Filesystem_Direct) {
49
+                require_once(ABSPATH.'wp-admin/includes/class-wp-filesystem-base.php');
50 50
                 $method = 'direct';
51
-                $wp_filesystem_direct_file = apply_filters('filesystem_method_file', ABSPATH . 'wp-admin/includes/class-wp-filesystem-' . $method . '.php', $method);
51
+                $wp_filesystem_direct_file = apply_filters('filesystem_method_file', ABSPATH.'wp-admin/includes/class-wp-filesystem-'.$method.'.php', $method);
52 52
                 // check constants defined, just like in wp-admin/includes/file.php's WP_Filesystem()
53
-                if (! defined('FS_CHMOD_DIR')) {
54
-                    define('FS_CHMOD_DIR', ( fileperms(ABSPATH) & 0777 | 0755 ));
53
+                if ( ! defined('FS_CHMOD_DIR')) {
54
+                    define('FS_CHMOD_DIR', (fileperms(ABSPATH) & 0777 | 0755));
55 55
                 }
56
-                if (! defined('FS_CHMOD_FILE')) {
57
-                    define('FS_CHMOD_FILE', ( fileperms(ABSPATH . 'index.php') & 0777 | 0644 ));
56
+                if ( ! defined('FS_CHMOD_FILE')) {
57
+                    define('FS_CHMOD_FILE', (fileperms(ABSPATH.'index.php') & 0777 | 0644));
58 58
                 }
59 59
                 require_once($wp_filesystem_direct_file);
60 60
                 EEH_File::$_wp_filesystem_direct = new WP_Filesystem_Direct(array());
@@ -63,7 +63,7 @@  discard block
 block discarded – undo
63 63
         }
64 64
         global $wp_filesystem;
65 65
         // no filesystem setup ???
66
-        if (! $wp_filesystem instanceof WP_Filesystem_Base) {
66
+        if ( ! $wp_filesystem instanceof WP_Filesystem_Base) {
67 67
             // if some eager beaver's just trying to get in there too early...
68 68
             // let them do it, because we are one of those eager beavers! :P
69 69
             /**
@@ -79,14 +79,14 @@  discard block
 block discarded – undo
79 79
             if (false && ! did_action('wp_loaded')) {
80 80
                 $msg = __('An attempt to access and/or write to a file on the server could not be completed due to a lack of sufficient credentials.', 'event_espresso');
81 81
                 if (WP_DEBUG) {
82
-                    $msg .= '<br />' .  __('The WP Filesystem can not be accessed until after the "wp_loaded" hook has run, so it\'s best not to attempt access until the "admin_init" hookpoint.', 'event_espresso');
82
+                    $msg .= '<br />'.__('The WP Filesystem can not be accessed until after the "wp_loaded" hook has run, so it\'s best not to attempt access until the "admin_init" hookpoint.', 'event_espresso');
83 83
                 }
84 84
                 throw new EE_Error($msg);
85 85
             } else {
86 86
                 // should be loaded if we are past the wp_loaded hook...
87
-                if (! function_exists('WP_Filesystem')) {
88
-                    require_once(ABSPATH . 'wp-admin/includes/file.php');
89
-                    require_once(ABSPATH . 'wp-admin/includes/template.php');
87
+                if ( ! function_exists('WP_Filesystem')) {
88
+                    require_once(ABSPATH.'wp-admin/includes/file.php');
89
+                    require_once(ABSPATH.'wp-admin/includes/template.php');
90 90
                 }
91 91
                 // turn on output buffering so that we can capture the credentials form
92 92
                 ob_start();
@@ -94,13 +94,13 @@  discard block
 block discarded – undo
94 94
                 // store credentials form for the time being
95 95
                 EEH_File::$_credentials_form = ob_get_clean();
96 96
                 // basically check for direct or previously configured access
97
-                if (! WP_Filesystem($credentials)) {
97
+                if ( ! WP_Filesystem($credentials)) {
98 98
                     // if credentials do NOT exist
99 99
                     if ($credentials === false) {
100
-                        add_action('admin_notices', array( 'EEH_File', 'display_request_filesystem_credentials_form' ), 999);
100
+                        add_action('admin_notices', array('EEH_File', 'display_request_filesystem_credentials_form'), 999);
101 101
                         throw new EE_Error(__('An attempt to access and/or write to a file on the server could not be completed due to a lack of sufficient credentials.', 'event_espresso'));
102 102
                     } elseif (is_wp_error($wp_filesystem->errors) && $wp_filesystem->errors->get_error_code()) {
103
-                        add_action('admin_notices', array( 'EEH_File', 'display_request_filesystem_credentials_form' ), 999);
103
+                        add_action('admin_notices', array('EEH_File', 'display_request_filesystem_credentials_form'), 999);
104 104
                         throw new EE_Error(
105 105
                             sprintf(
106 106
                                 __('WP Filesystem Error: $1%s', 'event_espresso'),
@@ -119,8 +119,8 @@  discard block
 block discarded – undo
119 119
      */
120 120
     public static function display_request_filesystem_credentials_form()
121 121
     {
122
-        if (! empty(EEH_File::$_credentials_form)) {
123
-            echo '<div class="updated espresso-notices-attention"><p>' . EEH_File::$_credentials_form . '</p></div>';
122
+        if ( ! empty(EEH_File::$_credentials_form)) {
123
+            echo '<div class="updated espresso-notices-attention"><p>'.EEH_File::$_credentials_form.'</p></div>';
124 124
         }
125 125
     }
126 126
 
@@ -143,8 +143,8 @@  discard block
 block discarded – undo
143 143
         // load WP_Filesystem and set file permissions
144 144
         $wp_filesystem = EEH_File::_get_wp_filesystem($full_file_path);
145 145
         $full_file_path = EEH_File::standardise_directory_separators($full_file_path);
146
-        if (! $wp_filesystem->is_readable(EEH_File::convert_local_filepath_to_remote_filepath($full_file_path))) {
147
-            $file_name = ! empty($type_of_file) ? $file_name . ' ' . $type_of_file : $file_name;
146
+        if ( ! $wp_filesystem->is_readable(EEH_File::convert_local_filepath_to_remote_filepath($full_file_path))) {
147
+            $file_name = ! empty($type_of_file) ? $file_name.' '.$type_of_file : $file_name;
148 148
             $file_name .= ! empty($file_ext) ? ' file' : ' folder';
149 149
             $msg = sprintf(
150 150
                 __('The requested %1$s could not be found or is not readable, possibly due to an incorrect filepath, or incorrect file permissions.%2$s', 'event_espresso'),
@@ -161,7 +161,7 @@  discard block
 block discarded – undo
161 161
                 );
162 162
             }
163 163
             if (defined('WP_DEBUG') && WP_DEBUG) {
164
-                throw new EE_Error($msg . '||' . $msg);
164
+                throw new EE_Error($msg.'||'.$msg);
165 165
             }
166 166
             return false;
167 167
         }
@@ -187,7 +187,7 @@  discard block
 block discarded – undo
187 187
         $perms = $wp_filesystem->getchmod(EEH_File::convert_local_filepath_to_remote_filepath($full_file_path));
188 188
         if ($perms) {
189 189
             // file permissions exist, but way be set incorrectly
190
-            $type_of_file = ! empty($type_of_file) ? $type_of_file . ' ' : '';
190
+            $type_of_file = ! empty($type_of_file) ? $type_of_file.' ' : '';
191 191
             $type_of_file .= ! empty($type_of_file) ? 'file' : 'folder';
192 192
             return sprintf(
193 193
                 __('File permissions for the requested %1$s are currently set at "%2$s". The recommended permissions are 644 for files and 755 for folders.', 'event_espresso'),
@@ -226,15 +226,15 @@  discard block
 block discarded – undo
226 226
         // add DS to folder
227 227
         $folder = EEH_File::end_with_directory_separator($folder);
228 228
         $wp_filesystem = EEH_File::_get_wp_filesystem($folder);
229
-        if (! $wp_filesystem->is_dir(EEH_File::convert_local_filepath_to_remote_filepath($folder))) {
229
+        if ( ! $wp_filesystem->is_dir(EEH_File::convert_local_filepath_to_remote_filepath($folder))) {
230 230
             // ok so it doesn't exist. Does its parent? Can we write to it?
231
-            if (! EEH_File::ensure_folder_exists_and_is_writable($parent_folder)) {
231
+            if ( ! EEH_File::ensure_folder_exists_and_is_writable($parent_folder)) {
232 232
                 return false;
233 233
             }
234
-            if (! EEH_File::verify_is_writable($parent_folder, 'folder')) {
234
+            if ( ! EEH_File::verify_is_writable($parent_folder, 'folder')) {
235 235
                 return false;
236 236
             } else {
237
-                if (! $wp_filesystem->mkdir(EEH_File::convert_local_filepath_to_remote_filepath($folder))) {
237
+                if ( ! $wp_filesystem->mkdir(EEH_File::convert_local_filepath_to_remote_filepath($folder))) {
238 238
                     if (defined('WP_DEBUG') && WP_DEBUG) {
239 239
                         $msg = sprintf(__('"%s" could not be created.', 'event_espresso'), $folder);
240 240
                         $msg .= EEH_File::_permissions_error_for_unreadable_filepath($folder);
@@ -244,7 +244,7 @@  discard block
 block discarded – undo
244 244
                 }
245 245
                 EEH_File::add_index_file($folder);
246 246
             }
247
-        } elseif (! EEH_File::verify_is_writable($folder, 'folder')) {
247
+        } elseif ( ! EEH_File::verify_is_writable($folder, 'folder')) {
248 248
             return false;
249 249
         }
250 250
         return true;
@@ -264,7 +264,7 @@  discard block
 block discarded – undo
264 264
         // load WP_Filesystem and set file permissions
265 265
         $wp_filesystem = EEH_File::_get_wp_filesystem($full_path);
266 266
         $full_path = EEH_File::standardise_directory_separators($full_path);
267
-        if (! $wp_filesystem->is_writable(EEH_File::convert_local_filepath_to_remote_filepath($full_path))) {
267
+        if ( ! $wp_filesystem->is_writable(EEH_File::convert_local_filepath_to_remote_filepath($full_path))) {
268 268
             if (defined('WP_DEBUG') && WP_DEBUG) {
269 269
                 $msg = sprintf(__('The "%1$s" %2$s is not writable.', 'event_espresso'), $full_path, $file_or_folder);
270 270
                 $msg .= EEH_File::_permissions_error_for_unreadable_filepath($full_path);
@@ -291,11 +291,11 @@  discard block
 block discarded – undo
291 291
         $wp_filesystem = EEH_File::_get_wp_filesystem($full_file_path);
292 292
         $full_file_path = EEH_File::standardise_directory_separators($full_file_path);
293 293
         $parent_folder = EEH_File::get_parent_folder($full_file_path);
294
-        if (! EEH_File::exists($full_file_path)) {
295
-            if (! EEH_File::ensure_folder_exists_and_is_writable($parent_folder)) {
294
+        if ( ! EEH_File::exists($full_file_path)) {
295
+            if ( ! EEH_File::ensure_folder_exists_and_is_writable($parent_folder)) {
296 296
                 return false;
297 297
             }
298
-            if (! $wp_filesystem->touch(EEH_File::convert_local_filepath_to_remote_filepath($full_file_path))) {
298
+            if ( ! $wp_filesystem->touch(EEH_File::convert_local_filepath_to_remote_filepath($full_file_path))) {
299 299
                 if (defined('WP_DEBUG') && WP_DEBUG) {
300 300
                     $msg = sprintf(__('The "%s" file could not be created.', 'event_espresso'), $full_file_path);
301 301
                     $msg .= EEH_File::_permissions_error_for_unreadable_filepath($full_file_path);
@@ -304,7 +304,7 @@  discard block
 block discarded – undo
304 304
                 return false;
305 305
             }
306 306
         }
307
-        if (! EEH_File::verify_is_writable($full_file_path, 'file')) {
307
+        if ( ! EEH_File::verify_is_writable($full_file_path, 'file')) {
308 308
             return false;
309 309
         }
310 310
         return true;
@@ -363,9 +363,9 @@  discard block
 block discarded – undo
363 363
     public static function write_to_file($full_file_path = '', $file_contents = '', $file_type = '')
364 364
     {
365 365
         $full_file_path = EEH_File::standardise_directory_separators($full_file_path);
366
-        $file_type = ! empty($file_type) ? rtrim($file_type, ' ') . ' ' : '';
366
+        $file_type = ! empty($file_type) ? rtrim($file_type, ' ').' ' : '';
367 367
         $folder = EEH_File::remove_filename_from_filepath($full_file_path);
368
-        if (! EEH_File::verify_is_writable($folder, 'folder')) {
368
+        if ( ! EEH_File::verify_is_writable($folder, 'folder')) {
369 369
             if (defined('WP_DEBUG') && WP_DEBUG) {
370 370
                 $msg = sprintf(__('The %1$sfile located at "%2$s" is not writable.', 'event_espresso'), $file_type, $full_file_path);
371 371
                 $msg .= EEH_File::_permissions_error_for_unreadable_filepath($full_file_path);
@@ -376,7 +376,7 @@  discard block
 block discarded – undo
376 376
         // load WP_Filesystem and set file permissions
377 377
         $wp_filesystem = EEH_File::_get_wp_filesystem($full_file_path);
378 378
         // write the file
379
-        if (! $wp_filesystem->put_contents(EEH_File::convert_local_filepath_to_remote_filepath($full_file_path), $file_contents)) {
379
+        if ( ! $wp_filesystem->put_contents(EEH_File::convert_local_filepath_to_remote_filepath($full_file_path), $file_contents)) {
380 380
             if (defined('WP_DEBUG') && WP_DEBUG) {
381 381
                 $msg = sprintf(__('The %1$sfile located at "%2$s" could not be written to.', 'event_espresso'), $file_type, $full_file_path);
382 382
                 $msg .= EEH_File::_permissions_error_for_unreadable_filepath($full_file_path, 'f');
@@ -486,8 +486,8 @@  discard block
 block discarded – undo
486 486
     public static function add_htaccess_deny_from_all($folder = '')
487 487
     {
488 488
         $folder = EEH_File::standardise_and_end_with_directory_separator($folder);
489
-        if (! EEH_File::exists($folder . '.htaccess')) {
490
-            if (! EEH_File::write_to_file($folder . '.htaccess', 'deny from all', '.htaccess')) {
489
+        if ( ! EEH_File::exists($folder.'.htaccess')) {
490
+            if ( ! EEH_File::write_to_file($folder.'.htaccess', 'deny from all', '.htaccess')) {
491 491
                 return false;
492 492
             }
493 493
         }
@@ -504,8 +504,8 @@  discard block
 block discarded – undo
504 504
     public static function add_index_file($folder)
505 505
     {
506 506
         $folder = EEH_File::standardise_and_end_with_directory_separator($folder);
507
-        if (! EEH_File::exists($folder . 'index.php')) {
508
-            if (! EEH_File::write_to_file($folder . 'index.php', 'You are not permitted to read from this folder', '.php')) {
507
+        if ( ! EEH_File::exists($folder.'index.php')) {
508
+            if ( ! EEH_File::write_to_file($folder.'index.php', 'You are not permitted to read from this folder', '.php')) {
509 509
                 return false;
510 510
             }
511 511
         }
@@ -539,7 +539,7 @@  discard block
 block discarded – undo
539 539
      */
540 540
     public static function standardise_directory_separators($file_path)
541 541
     {
542
-        return str_replace(array( '\\', '/' ), DS, $file_path);
542
+        return str_replace(array('\\', '/'), DS, $file_path);
543 543
     }
544 544
 
545 545
 
@@ -552,7 +552,7 @@  discard block
 block discarded – undo
552 552
      */
553 553
     public static function end_with_directory_separator($file_path)
554 554
     {
555
-        return rtrim($file_path, '/\\') . DS;
555
+        return rtrim($file_path, '/\\').DS;
556 556
     }
557 557
 
558 558
 
@@ -587,17 +587,17 @@  discard block
 block discarded – undo
587 587
         foreach ($folder_paths as $folder_path) {
588 588
             $folder_path = self::standardise_and_end_with_directory_separator($folder_path);
589 589
             // load WP_Filesystem and set file permissions
590
-            $files_in_folder = glob($folder_path . '*');
590
+            $files_in_folder = glob($folder_path.'*');
591 591
             $class_to_folder_path = array();
592 592
             if ($files_in_folder) {
593 593
                 foreach ($files_in_folder as $file_path) {
594 594
                     // only add files, not folders
595
-                    if (! is_dir($file_path)) {
595
+                    if ( ! is_dir($file_path)) {
596 596
                         if ($index_numerically) {
597 597
                             $class_to_folder_path[] = $file_path;
598 598
                         } else {
599 599
                             $classname = self::get_classname_from_filepath_with_standard_filename($file_path);
600
-                            $class_to_folder_path[ $classname ] = $file_path;
600
+                            $class_to_folder_path[$classname] = $file_path;
601 601
                         }
602 602
                     }
603 603
                 }
@@ -619,7 +619,7 @@  discard block
 block discarded – undo
619 619
     public static function copy($source_file, $destination_file, $overwrite = false)
620 620
     {
621 621
         $full_source_path = EEH_File::standardise_directory_separators($source_file);
622
-        if (! EEH_File::exists($full_source_path)) {
622
+        if ( ! EEH_File::exists($full_source_path)) {
623 623
             if (defined('WP_DEBUG') && WP_DEBUG) {
624 624
                 $msg = sprintf(__('The file located at "%2$s" is not readable or doesn\'t exist.', 'event_espresso'), $full_source_path);
625 625
                 $msg .= EEH_File::_permissions_error_for_unreadable_filepath($full_source_path);
@@ -631,7 +631,7 @@  discard block
 block discarded – undo
631 631
         $full_dest_path = EEH_File::standardise_directory_separators($destination_file);
632 632
         $folder = EEH_File::remove_filename_from_filepath($full_dest_path);
633 633
         EEH_File::ensure_folder_exists_and_is_writable($folder);
634
-        if (! EEH_File::verify_is_writable($folder, 'folder')) {
634
+        if ( ! EEH_File::verify_is_writable($folder, 'folder')) {
635 635
             if (defined('WP_DEBUG') && WP_DEBUG) {
636 636
                 $msg = sprintf(__('The file located at "%2$s" is not writable.', 'event_espresso'), $full_dest_path);
637 637
                 $msg .= EEH_File::_permissions_error_for_unreadable_filepath($full_dest_path);
@@ -643,7 +643,7 @@  discard block
 block discarded – undo
643 643
         // load WP_Filesystem and set file permissions
644 644
         $wp_filesystem = EEH_File::_get_wp_filesystem($destination_file);
645 645
         // write the file
646
-        if (! $wp_filesystem->copy(
646
+        if ( ! $wp_filesystem->copy(
647 647
             EEH_File::convert_local_filepath_to_remote_filepath($full_source_path),
648 648
             EEH_File::convert_local_filepath_to_remote_filepath($full_dest_path),
649 649
             $overwrite
@@ -684,6 +684,6 @@  discard block
 block discarded – undo
684 684
     public static function convert_local_filepath_to_remote_filepath($local_filepath)
685 685
     {
686 686
         $wp_filesystem = EEH_File::_get_wp_filesystem($local_filepath);
687
-        return str_replace(WP_CONTENT_DIR . DS, $wp_filesystem->wp_content_dir(), $local_filepath);
687
+        return str_replace(WP_CONTENT_DIR.DS, $wp_filesystem->wp_content_dir(), $local_filepath);
688 688
     }
689 689
 }
Please login to merge, or discard this patch.
core/services/request/files/FileSubmission.php 2 patches
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -93,7 +93,7 @@  discard block
 block discarded – undo
93 93
      */
94 94
     public function getType()
95 95
     {
96
-        if (!$this->type) {
96
+        if ( ! $this->type) {
97 97
             $this->type = $this->determineType();
98 98
         }
99 99
         return $this->type;
@@ -105,7 +105,7 @@  discard block
 block discarded – undo
105 105
      */
106 106
     protected function determineType()
107 107
     {
108
-        if (!$this->getTmpFile()) {
108
+        if ( ! $this->getTmpFile()) {
109 109
             return '';
110 110
         }
111 111
         $finfo = new finfo(FILEINFO_MIME_TYPE);
@@ -119,7 +119,7 @@  discard block
 block discarded – undo
119 119
      */
120 120
     public function getExtension()
121 121
     {
122
-        if (!$this->extension) {
122
+        if ( ! $this->extension) {
123 123
             $this->extension = $this->determineExtension();
124 124
         }
125 125
         return $this->extension;
Please login to merge, or discard this patch.
Indentation   +158 added lines, -158 removed lines patch added patch discarded remove patch
@@ -19,164 +19,164 @@
 block discarded – undo
19 19
  */
20 20
 class FileSubmission implements FileSubmissionInterface
21 21
 {
22
-    /**
23
-     * @var string original name on the client machine
24
-     */
25
-    protected $name;
26
-
27
-    /**
28
-     * @var string mime type
29
-     */
30
-    protected $type;
31
-
32
-    /**
33
-     * @var string file extension
34
-     */
35
-    protected $extension;
36
-
37
-    /**
38
-     * @var int in bytes
39
-     */
40
-    protected $size;
41
-
42
-    /**
43
-     * @var string local filepath to the temporary file
44
-     */
45
-    protected $tmp_file;
46
-
47
-    /**
48
-     * @var int one of UPLOAD_ERR_OK, UPLOAD_ERR_NO_FILE, UPLOAD_ERR_INI_SIZE, UPLOAD_ERR_FORM_SIZE or other values
49
-     * although those aren't expected.
50
-     */
51
-    protected $error_code;
52
-
53
-    /**
54
-     * FileSubmission constructor.
55
-     * @param $name
56
-     * @param $tmp_file
57
-     * @param $size
58
-     * @param null $error_code
59
-     * @throws InvalidArgumentException
60
-     */
61
-    public function __construct($name, $tmp_file, $size, $error_code = null)
62
-    {
63
-        $this->name = basename($name);
64
-        $scheme = parse_url($tmp_file, PHP_URL_SCHEME);
65
-        if (in_array($scheme, ['http', 'https'])) {
66
-            // Wait a minute- just local filepaths please, no URL schemes allowed!
67
-            throw new InvalidArgumentException(
68
-                sprintf(
69
-                    // @codingStandardsIgnoreStart
70
-                    esc_html__('The scheme ("%1$s") on the temporary file ("%2$s") indicates is located elsewhere, that’s not ok!', 'event_espresso'),
71
-                    // @codingStandardsIgnoreEnd
72
-                    $scheme,
73
-                    $tmp_file
74
-                )
75
-            );
76
-        }
77
-        $this->tmp_file = (string) $tmp_file;
78
-        $this->size = (int) $size;
79
-        $this->error_code = (int) $error_code;
80
-    }
81
-
82
-    /**
83
-     * @return string
84
-     */
85
-    public function getName()
86
-    {
87
-        return $this->name;
88
-    }
89
-
90
-    /**
91
-     * Gets the file's mime type
92
-     * @return string
93
-     */
94
-    public function getType()
95
-    {
96
-        if (!$this->type) {
97
-            $this->type = $this->determineType();
98
-        }
99
-        return $this->type;
100
-    }
101
-
102
-    /**
103
-     * @since 4.9.80.p
104
-     * @return string
105
-     */
106
-    protected function determineType()
107
-    {
108
-        if (!$this->getTmpFile()) {
109
-            return '';
110
-        }
111
-        $finfo = new finfo(FILEINFO_MIME_TYPE);
112
-        return $finfo->file($this->getTmpFile());
113
-    }
114
-
115
-    /**
116
-     * Gets the file's extension.
117
-     * @since 4.9.80.p
118
-     * @return string
119
-     */
120
-    public function getExtension()
121
-    {
122
-        if (!$this->extension) {
123
-            $this->extension = $this->determineExtension();
124
-        }
125
-        return $this->extension;
126
-    }
127
-
128
-    /**
129
-     * Determine's the file's extension given the temporary file.
130
-     * @since 4.9.80.p
131
-     * @return string
132
-     */
133
-    protected function determineExtension()
134
-    {
135
-        $position_of_period = strrpos($this->getName(), '.');
136
-        if ($position_of_period === false) {
137
-            return '';
138
-        }
139
-        return mb_substr(
140
-            $this->getName(),
141
-            $position_of_period + 1
142
-        );
143
-    }
144
-
145
-    /**
146
-     * Gets the size of the file
147
-     * @return int
148
-     */
149
-    public function getSize()
150
-    {
151
-        return $this->size;
152
-    }
153
-
154
-    /**
155
-     * Gets the path to the temporary file which was uploaded.
156
-     * @return string
157
-     */
158
-    public function getTmpFile()
159
-    {
160
-        return $this->tmp_file;
161
-    }
162
-
163
-    /**
164
-     * @since 4.9.80.p
165
-     * @return string
166
-     */
167
-    public function __toString()
168
-    {
169
-        return $this->getName();
170
-    }
171
-
172
-    /**
173
-     * Gets the error code PHP reported for the file upload.
174
-     * @return string
175
-     */
176
-    public function getErrorCode()
177
-    {
178
-        return $this->error_code;
179
-    }
22
+	/**
23
+	 * @var string original name on the client machine
24
+	 */
25
+	protected $name;
26
+
27
+	/**
28
+	 * @var string mime type
29
+	 */
30
+	protected $type;
31
+
32
+	/**
33
+	 * @var string file extension
34
+	 */
35
+	protected $extension;
36
+
37
+	/**
38
+	 * @var int in bytes
39
+	 */
40
+	protected $size;
41
+
42
+	/**
43
+	 * @var string local filepath to the temporary file
44
+	 */
45
+	protected $tmp_file;
46
+
47
+	/**
48
+	 * @var int one of UPLOAD_ERR_OK, UPLOAD_ERR_NO_FILE, UPLOAD_ERR_INI_SIZE, UPLOAD_ERR_FORM_SIZE or other values
49
+	 * although those aren't expected.
50
+	 */
51
+	protected $error_code;
52
+
53
+	/**
54
+	 * FileSubmission constructor.
55
+	 * @param $name
56
+	 * @param $tmp_file
57
+	 * @param $size
58
+	 * @param null $error_code
59
+	 * @throws InvalidArgumentException
60
+	 */
61
+	public function __construct($name, $tmp_file, $size, $error_code = null)
62
+	{
63
+		$this->name = basename($name);
64
+		$scheme = parse_url($tmp_file, PHP_URL_SCHEME);
65
+		if (in_array($scheme, ['http', 'https'])) {
66
+			// Wait a minute- just local filepaths please, no URL schemes allowed!
67
+			throw new InvalidArgumentException(
68
+				sprintf(
69
+					// @codingStandardsIgnoreStart
70
+					esc_html__('The scheme ("%1$s") on the temporary file ("%2$s") indicates is located elsewhere, that’s not ok!', 'event_espresso'),
71
+					// @codingStandardsIgnoreEnd
72
+					$scheme,
73
+					$tmp_file
74
+				)
75
+			);
76
+		}
77
+		$this->tmp_file = (string) $tmp_file;
78
+		$this->size = (int) $size;
79
+		$this->error_code = (int) $error_code;
80
+	}
81
+
82
+	/**
83
+	 * @return string
84
+	 */
85
+	public function getName()
86
+	{
87
+		return $this->name;
88
+	}
89
+
90
+	/**
91
+	 * Gets the file's mime type
92
+	 * @return string
93
+	 */
94
+	public function getType()
95
+	{
96
+		if (!$this->type) {
97
+			$this->type = $this->determineType();
98
+		}
99
+		return $this->type;
100
+	}
101
+
102
+	/**
103
+	 * @since 4.9.80.p
104
+	 * @return string
105
+	 */
106
+	protected function determineType()
107
+	{
108
+		if (!$this->getTmpFile()) {
109
+			return '';
110
+		}
111
+		$finfo = new finfo(FILEINFO_MIME_TYPE);
112
+		return $finfo->file($this->getTmpFile());
113
+	}
114
+
115
+	/**
116
+	 * Gets the file's extension.
117
+	 * @since 4.9.80.p
118
+	 * @return string
119
+	 */
120
+	public function getExtension()
121
+	{
122
+		if (!$this->extension) {
123
+			$this->extension = $this->determineExtension();
124
+		}
125
+		return $this->extension;
126
+	}
127
+
128
+	/**
129
+	 * Determine's the file's extension given the temporary file.
130
+	 * @since 4.9.80.p
131
+	 * @return string
132
+	 */
133
+	protected function determineExtension()
134
+	{
135
+		$position_of_period = strrpos($this->getName(), '.');
136
+		if ($position_of_period === false) {
137
+			return '';
138
+		}
139
+		return mb_substr(
140
+			$this->getName(),
141
+			$position_of_period + 1
142
+		);
143
+	}
144
+
145
+	/**
146
+	 * Gets the size of the file
147
+	 * @return int
148
+	 */
149
+	public function getSize()
150
+	{
151
+		return $this->size;
152
+	}
153
+
154
+	/**
155
+	 * Gets the path to the temporary file which was uploaded.
156
+	 * @return string
157
+	 */
158
+	public function getTmpFile()
159
+	{
160
+		return $this->tmp_file;
161
+	}
162
+
163
+	/**
164
+	 * @since 4.9.80.p
165
+	 * @return string
166
+	 */
167
+	public function __toString()
168
+	{
169
+		return $this->getName();
170
+	}
171
+
172
+	/**
173
+	 * Gets the error code PHP reported for the file upload.
174
+	 * @return string
175
+	 */
176
+	public function getErrorCode()
177
+	{
178
+		return $this->error_code;
179
+	}
180 180
 }
181 181
 // End of file FileSubmission.php
182 182
 // Location: EventEspresso\core\services\request\files/FileSubmission.php
Please login to merge, or discard this patch.
reg_steps/payment_options/EE_SPCO_Reg_Step_Payment_Options.class.php 2 patches
Indentation   +2885 added lines, -2885 removed lines patch added patch discarded remove patch
@@ -12,2889 +12,2889 @@
 block discarded – undo
12 12
 class EE_SPCO_Reg_Step_Payment_Options extends EE_SPCO_Reg_Step
13 13
 {
14 14
 
15
-    /**
16
-     * @access protected
17
-     * @var EE_Line_Item_Display $Line_Item_Display
18
-     */
19
-    protected $line_item_display;
20
-
21
-    /**
22
-     * @access protected
23
-     * @var boolean $handle_IPN_in_this_request
24
-     */
25
-    protected $handle_IPN_in_this_request = false;
26
-
27
-
28
-    /**
29
-     *    set_hooks - for hooking into EE Core, other modules, etc
30
-     *
31
-     * @access    public
32
-     * @return    void
33
-     */
34
-    public static function set_hooks()
35
-    {
36
-        add_filter(
37
-            'FHEE__SPCO__EE_Line_Item_Filter_Collection',
38
-            array('EE_SPCO_Reg_Step_Payment_Options', 'add_spco_line_item_filters')
39
-        );
40
-        add_action(
41
-            'wp_ajax_switch_spco_billing_form',
42
-            array('EE_SPCO_Reg_Step_Payment_Options', 'switch_spco_billing_form')
43
-        );
44
-        add_action(
45
-            'wp_ajax_nopriv_switch_spco_billing_form',
46
-            array('EE_SPCO_Reg_Step_Payment_Options', 'switch_spco_billing_form')
47
-        );
48
-        add_action('wp_ajax_save_payer_details', array('EE_SPCO_Reg_Step_Payment_Options', 'save_payer_details'));
49
-        add_action(
50
-            'wp_ajax_nopriv_save_payer_details',
51
-            array('EE_SPCO_Reg_Step_Payment_Options', 'save_payer_details')
52
-        );
53
-        add_action(
54
-            'wp_ajax_get_transaction_details_for_gateways',
55
-            array('EE_SPCO_Reg_Step_Payment_Options', 'get_transaction_details')
56
-        );
57
-        add_action(
58
-            'wp_ajax_nopriv_get_transaction_details_for_gateways',
59
-            array('EE_SPCO_Reg_Step_Payment_Options', 'get_transaction_details')
60
-        );
61
-        add_filter(
62
-            'FHEE__EED_Recaptcha___bypass_recaptcha__bypass_request_params_array',
63
-            array('EE_SPCO_Reg_Step_Payment_Options', 'bypass_recaptcha_for_load_payment_method'),
64
-            10,
65
-            1
66
-        );
67
-    }
68
-
69
-
70
-    /**
71
-     *    ajax switch_spco_billing_form
72
-     *
73
-     * @throws \EE_Error
74
-     */
75
-    public static function switch_spco_billing_form()
76
-    {
77
-        EED_Single_Page_Checkout::process_ajax_request('switch_payment_method');
78
-    }
79
-
80
-
81
-    /**
82
-     *    ajax save_payer_details
83
-     *
84
-     * @throws \EE_Error
85
-     */
86
-    public static function save_payer_details()
87
-    {
88
-        EED_Single_Page_Checkout::process_ajax_request('save_payer_details_via_ajax');
89
-    }
90
-
91
-
92
-    /**
93
-     *    ajax get_transaction_details
94
-     *
95
-     * @throws \EE_Error
96
-     */
97
-    public static function get_transaction_details()
98
-    {
99
-        EED_Single_Page_Checkout::process_ajax_request('get_transaction_details_for_gateways');
100
-    }
101
-
102
-
103
-    /**
104
-     * bypass_recaptcha_for_load_payment_method
105
-     *
106
-     * @access public
107
-     * @return array
108
-     * @throws InvalidArgumentException
109
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
110
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
111
-     */
112
-    public static function bypass_recaptcha_for_load_payment_method()
113
-    {
114
-        return array(
115
-            'EESID'  => EE_Registry::instance()->SSN->id(),
116
-            'step'   => 'payment_options',
117
-            'action' => 'spco_billing_form',
118
-        );
119
-    }
120
-
121
-
122
-    /**
123
-     *    class constructor
124
-     *
125
-     * @access    public
126
-     * @param    EE_Checkout $checkout
127
-     */
128
-    public function __construct(EE_Checkout $checkout)
129
-    {
130
-        $this->_slug = 'payment_options';
131
-        $this->_name = esc_html__('Payment Options', 'event_espresso');
132
-        $this->_template = SPCO_REG_STEPS_PATH . $this->_slug . DS . 'payment_options_main.template.php';
133
-        $this->checkout = $checkout;
134
-        $this->_reset_success_message();
135
-        $this->set_instructions(
136
-            esc_html__(
137
-                'Please select a method of payment and provide any necessary billing information before proceeding.',
138
-                'event_espresso'
139
-            )
140
-        );
141
-    }
142
-
143
-
144
-    /**
145
-     * @return null
146
-     */
147
-    public function line_item_display()
148
-    {
149
-        return $this->line_item_display;
150
-    }
151
-
152
-
153
-    /**
154
-     * @param null $line_item_display
155
-     */
156
-    public function set_line_item_display($line_item_display)
157
-    {
158
-        $this->line_item_display = $line_item_display;
159
-    }
160
-
161
-
162
-    /**
163
-     * @return boolean
164
-     */
165
-    public function handle_IPN_in_this_request()
166
-    {
167
-        return $this->handle_IPN_in_this_request;
168
-    }
169
-
170
-
171
-    /**
172
-     * @param boolean $handle_IPN_in_this_request
173
-     */
174
-    public function set_handle_IPN_in_this_request($handle_IPN_in_this_request)
175
-    {
176
-        $this->handle_IPN_in_this_request = filter_var($handle_IPN_in_this_request, FILTER_VALIDATE_BOOLEAN);
177
-    }
178
-
179
-
180
-    /**
181
-     * translate_js_strings
182
-     *
183
-     * @return void
184
-     */
185
-    public function translate_js_strings()
186
-    {
187
-        EE_Registry::$i18n_js_strings['no_payment_method'] = esc_html__(
188
-            'Please select a method of payment in order to continue.',
189
-            'event_espresso'
190
-        );
191
-        EE_Registry::$i18n_js_strings['invalid_payment_method'] = esc_html__(
192
-            'A valid method of payment could not be determined. Please refresh the page and try again.',
193
-            'event_espresso'
194
-        );
195
-        EE_Registry::$i18n_js_strings['forwarding_to_offsite'] = esc_html__(
196
-            'Forwarding to Secure Payment Provider.',
197
-            'event_espresso'
198
-        );
199
-    }
200
-
201
-
202
-    /**
203
-     * enqueue_styles_and_scripts
204
-     *
205
-     * @return void
206
-     * @throws EE_Error
207
-     * @throws InvalidArgumentException
208
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
209
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
210
-     */
211
-    public function enqueue_styles_and_scripts()
212
-    {
213
-        $transaction = $this->checkout->transaction;
214
-        // if the transaction isn't set or nothing is owed on it, don't enqueue any JS
215
-        if (! $transaction instanceof EE_Transaction || EEH_Money::compare_floats($transaction->remaining(), 0)) {
216
-            return;
217
-        }
218
-        foreach (EEM_Payment_Method::instance()->get_all_for_transaction(
219
-            $transaction,
220
-            EEM_Payment_Method::scope_cart
221
-        ) 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
-                if ($registration->event()->is_sold_out() || $registration->event()->is_sold_out(true)) {
309
-                    $sold_out_events[ $registration->event()->ID() ] = $registration->event();
310
-                } else {
311
-                    $insufficient_spaces_available[ $registration->event()->ID() ] = $registration->event();
312
-                }
313
-                continue;
314
-            }
315
-            // event requires admin approval
316
-            if ($registration->status_ID() === EEM_Registration::status_id_not_approved) {
317
-                // add event to list of events with pre-approval reg status
318
-                $registrations_requiring_pre_approval[ $REG_ID ] = $registration;
319
-                do_action(
320
-                    'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__event_requires_pre_approval',
321
-                    $registration->event(),
322
-                    $this
323
-                );
324
-                continue;
325
-            }
326
-            if ($this->checkout->revisit
327
-                && $registration->status_ID() !== EEM_Registration::status_id_approved
328
-                && (
329
-                    $registration->event()->is_sold_out()
330
-                    || $registration->event()->is_sold_out(true)
331
-                )
332
-            ) {
333
-                // add event to list of events that are sold out
334
-                $sold_out_events[ $registration->event()->ID() ] = $registration->event();
335
-                do_action(
336
-                    'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__sold_out_event',
337
-                    $registration->event(),
338
-                    $this
339
-                );
340
-                continue;
341
-            }
342
-            // are they allowed to pay now and is there monies owing?
343
-            if ($registration->owes_monies_and_can_pay()) {
344
-                $registrations_requiring_payment[ $REG_ID ] = $registration;
345
-                do_action(
346
-                    'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__event_requires_payment',
347
-                    $registration->event(),
348
-                    $this
349
-                );
350
-            } elseif (! $this->checkout->revisit
351
-                      && $registration->status_ID() !== EEM_Registration::status_id_not_approved
352
-                      && $registration->ticket()->is_free()
353
-            ) {
354
-                $registrations_for_free_events[ $registration->ticket()->ID() ] = $registration;
355
-            }
356
-        }
357
-        $subsections = array();
358
-        // now decide which template to load
359
-        if (! empty($sold_out_events)) {
360
-            $subsections['sold_out_events'] = $this->_sold_out_events($sold_out_events);
361
-        }
362
-        if (! empty($insufficient_spaces_available)) {
363
-            $subsections['insufficient_space'] = $this->_insufficient_spaces_available(
364
-                $insufficient_spaces_available
365
-            );
366
-        }
367
-        if (! empty($registrations_requiring_pre_approval)) {
368
-            $subsections['registrations_requiring_pre_approval'] = $this->_registrations_requiring_pre_approval(
369
-                $registrations_requiring_pre_approval
370
-            );
371
-        }
372
-        if (! empty($registrations_for_free_events)) {
373
-            $subsections['no_payment_required'] = $this->_no_payment_required($registrations_for_free_events);
374
-        }
375
-        if (! empty($registrations_requiring_payment)) {
376
-            if ($this->checkout->amount_owing > 0) {
377
-                // autoload Line_Item_Display classes
378
-                EEH_Autoloader::register_line_item_filter_autoloaders();
379
-                $line_item_filter_processor = new EE_Line_Item_Filter_Processor(
380
-                    apply_filters(
381
-                        'FHEE__SPCO__EE_Line_Item_Filter_Collection',
382
-                        new EE_Line_Item_Filter_Collection()
383
-                    ),
384
-                    $this->checkout->cart->get_grand_total()
385
-                );
386
-                /** @var EE_Line_Item $filtered_line_item_tree */
387
-                $filtered_line_item_tree = $line_item_filter_processor->process();
388
-                EEH_Autoloader::register_line_item_display_autoloaders();
389
-                $this->set_line_item_display(new EE_Line_Item_Display('spco'));
390
-                $subsections['payment_options'] = $this->_display_payment_options(
391
-                    $this->line_item_display->display_line_item(
392
-                        $filtered_line_item_tree,
393
-                        array('registrations' => $registrations)
394
-                    )
395
-                );
396
-                $this->checkout->amount_owing = $filtered_line_item_tree->total();
397
-                $this->_apply_registration_payments_to_amount_owing($registrations);
398
-            }
399
-            $no_payment_required = false;
400
-        } else {
401
-            $this->_hide_reg_step_submit_button_if_revisit();
402
-        }
403
-        $this->_save_selected_method_of_payment();
404
-
405
-        $subsections['default_hidden_inputs'] = $this->reg_step_hidden_inputs();
406
-        $subsections['extra_hidden_inputs'] = $this->_extra_hidden_inputs($no_payment_required);
407
-
408
-        return new EE_Form_Section_Proper(
409
-            array(
410
-                'name'            => $this->reg_form_name(),
411
-                'html_id'         => $this->reg_form_name(),
412
-                'subsections'     => $subsections,
413
-                'layout_strategy' => new EE_No_Layout(),
414
-            )
415
-        );
416
-    }
417
-
418
-
419
-    /**
420
-     * add line item filters required for this reg step
421
-     * these filters are applied via this line in EE_SPCO_Reg_Step_Payment_Options::set_hooks():
422
-     *        add_filter( 'FHEE__SPCO__EE_Line_Item_Filter_Collection', array( 'EE_SPCO_Reg_Step_Payment_Options',
423
-     *        'add_spco_line_item_filters' ) ); so any code that wants to use the same set of filters during the
424
-     *        payment options reg step, can apply these filters via the following: apply_filters(
425
-     *        'FHEE__SPCO__EE_Line_Item_Filter_Collection', new EE_Line_Item_Filter_Collection() ) or to an existing
426
-     *        filter collection by passing that instead of instantiating a new collection
427
-     *
428
-     * @param \EE_Line_Item_Filter_Collection $line_item_filter_collection
429
-     * @return EE_Line_Item_Filter_Collection
430
-     * @throws EE_Error
431
-     * @throws InvalidArgumentException
432
-     * @throws ReflectionException
433
-     * @throws \EventEspresso\core\exceptions\EntityNotFoundException
434
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
435
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
436
-     * @throws \EventEspresso\core\exceptions\InvalidStatusException
437
-     */
438
-    public static function add_spco_line_item_filters(EE_Line_Item_Filter_Collection $line_item_filter_collection)
439
-    {
440
-        if (! EE_Registry::instance()->SSN instanceof EE_Session) {
441
-            return $line_item_filter_collection;
442
-        }
443
-        if (! EE_Registry::instance()->SSN->checkout() instanceof EE_Checkout) {
444
-            return $line_item_filter_collection;
445
-        }
446
-        if (! EE_Registry::instance()->SSN->checkout()->transaction instanceof EE_Transaction) {
447
-            return $line_item_filter_collection;
448
-        }
449
-        $line_item_filter_collection->add(
450
-            new EE_Billable_Line_Item_Filter(
451
-                EE_SPCO_Reg_Step_Payment_Options::remove_ejected_registrations(
452
-                    EE_Registry::instance()->SSN->checkout()->transaction->registrations(
453
-                        EE_Registry::instance()->SSN->checkout()->reg_cache_where_params
454
-                    )
455
-                )
456
-            )
457
-        );
458
-        $line_item_filter_collection->add(new EE_Non_Zero_Line_Item_Filter());
459
-        return $line_item_filter_collection;
460
-    }
461
-
462
-
463
-    /**
464
-     * remove_ejected_registrations
465
-     * if a registrant has lost their potential space at an event due to lack of payment,
466
-     * then this method removes them from the list of registrations being paid for during this request
467
-     *
468
-     * @param \EE_Registration[] $registrations
469
-     * @return EE_Registration[]
470
-     * @throws EE_Error
471
-     * @throws InvalidArgumentException
472
-     * @throws ReflectionException
473
-     * @throws \EventEspresso\core\exceptions\EntityNotFoundException
474
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
475
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
476
-     * @throws \EventEspresso\core\exceptions\InvalidStatusException
477
-     */
478
-    public static function remove_ejected_registrations(array $registrations)
479
-    {
480
-        $ejected_registrations = EE_SPCO_Reg_Step_Payment_Options::find_registrations_that_lost_their_space(
481
-            $registrations,
482
-            EE_Registry::instance()->SSN->checkout()->revisit
483
-        );
484
-        foreach ($registrations as $REG_ID => $registration) {
485
-            // has this registration lost it's space ?
486
-            if (isset($ejected_registrations[ $REG_ID ])) {
487
-                unset($registrations[ $REG_ID ]);
488
-                continue;
489
-            }
490
-        }
491
-        return $registrations;
492
-    }
493
-
494
-
495
-    /**
496
-     * find_registrations_that_lost_their_space
497
-     * If a registrant chooses an offline payment method like Invoice,
498
-     * then no space is reserved for them at the event until they fully pay fo that site
499
-     * (unless the event's default reg status is set to APPROVED)
500
-     * if a registrant then later returns to pay, but the number of spaces available has been reduced due to sales,
501
-     * then this method will determine which registrations have lost the ability to complete the reg process.
502
-     *
503
-     * @param \EE_Registration[] $registrations
504
-     * @param bool               $revisit
505
-     * @return array
506
-     * @throws EE_Error
507
-     * @throws InvalidArgumentException
508
-     * @throws ReflectionException
509
-     * @throws \EventEspresso\core\exceptions\EntityNotFoundException
510
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
511
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
512
-     * @throws \EventEspresso\core\exceptions\InvalidStatusException
513
-     */
514
-    public static function find_registrations_that_lost_their_space(array $registrations, $revisit = false)
515
-    {
516
-        // registrations per event
517
-        $event_reg_count = array();
518
-        // spaces left per event
519
-        $event_spaces_remaining = array();
520
-        // tickets left sorted by ID
521
-        $tickets_remaining = array();
522
-        // registrations that have lost their space
523
-        $ejected_registrations = array();
524
-        foreach ($registrations as $REG_ID => $registration) {
525
-            if ($registration->status_ID() === EEM_Registration::status_id_approved
526
-                || apply_filters(
527
-                    'FHEE__EE_SPCO_Reg_Step_Payment_Options__find_registrations_that_lost_their_space__allow_reg_payment',
528
-                    false,
529
-                    $registration,
530
-                    $revisit
531
-                )
532
-            ) {
533
-                continue;
534
-            }
535
-            $EVT_ID = $registration->event_ID();
536
-            $ticket = $registration->ticket();
537
-            if (! isset($tickets_remaining[ $ticket->ID() ])) {
538
-                $tickets_remaining[ $ticket->ID() ] = $ticket->remaining();
539
-            }
540
-            if ($tickets_remaining[ $ticket->ID() ] > 0) {
541
-                if (! isset($event_reg_count[ $EVT_ID ])) {
542
-                    $event_reg_count[ $EVT_ID ] = 0;
543
-                }
544
-                $event_reg_count[ $EVT_ID ]++;
545
-                if (! isset($event_spaces_remaining[ $EVT_ID ])) {
546
-                    $event_spaces_remaining[ $EVT_ID ] = $registration->event()->spaces_remaining_for_sale();
547
-                }
548
-            }
549
-            if ($revisit
550
-                && ($tickets_remaining[ $ticket->ID() ] === 0
551
-                    || $event_reg_count[ $EVT_ID ] > $event_spaces_remaining[ $EVT_ID ]
552
-                )
553
-            ) {
554
-                $ejected_registrations[ $REG_ID ] = $registration->event();
555
-                if ($registration->status_ID() !== EEM_Registration::status_id_wait_list) {
556
-                    /** @type EE_Registration_Processor $registration_processor */
557
-                    $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
558
-                    // at this point, we should have enough details about the registrant to consider the registration
559
-                    // NOT incomplete
560
-                    $registration_processor->manually_update_registration_status(
561
-                        $registration,
562
-                        EEM_Registration::status_id_wait_list
563
-                    );
564
-                }
565
-            }
566
-        }
567
-        return $ejected_registrations;
568
-    }
569
-
570
-
571
-    /**
572
-     * _hide_reg_step_submit_button
573
-     * removes the html for the reg step submit button
574
-     * by replacing it with an empty string via filter callback
575
-     *
576
-     * @return void
577
-     */
578
-    protected function _adjust_registration_status_if_event_old_sold()
579
-    {
580
-    }
581
-
582
-
583
-    /**
584
-     * _hide_reg_step_submit_button
585
-     * removes the html for the reg step submit button
586
-     * by replacing it with an empty string via filter callback
587
-     *
588
-     * @return void
589
-     */
590
-    protected function _hide_reg_step_submit_button_if_revisit()
591
-    {
592
-        if ($this->checkout->revisit) {
593
-            add_filter('FHEE__EE_SPCO_Reg_Step__reg_step_submit_button__sbmt_btn_html', '__return_empty_string');
594
-        }
595
-    }
596
-
597
-
598
-    /**
599
-     * sold_out_events
600
-     * displays notices regarding events that have sold out since hte registrant first signed up
601
-     *
602
-     * @param \EE_Event[] $sold_out_events_array
603
-     * @return \EE_Form_Section_Proper
604
-     * @throws \EE_Error
605
-     */
606
-    private function _sold_out_events($sold_out_events_array = array())
607
-    {
608
-        // set some defaults
609
-        $this->checkout->selected_method_of_payment = 'events_sold_out';
610
-        $sold_out_events = '';
611
-        foreach ($sold_out_events_array as $sold_out_event) {
612
-            $sold_out_events .= EEH_HTML::li(
613
-                EEH_HTML::span(
614
-                    '  ' . $sold_out_event->name(),
615
-                    '',
616
-                    'dashicons dashicons-marker ee-icon-size-16 pink-text'
617
-                )
618
-            );
619
-        }
620
-        return new EE_Form_Section_Proper(
621
-            array(
622
-                'layout_strategy' => new EE_Template_Layout(
623
-                    array(
624
-                        'layout_template_file' => SPCO_REG_STEPS_PATH
625
-                                                  . $this->_slug
626
-                                                  . DS
627
-                                                  . 'sold_out_events.template.php',
628
-                        'template_args'        => apply_filters(
629
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___sold_out_events__template_args',
630
-                            array(
631
-                                'sold_out_events'     => $sold_out_events,
632
-                                'sold_out_events_msg' => apply_filters(
633
-                                    'FHEE__EE_SPCO_Reg_Step_Payment_Options___sold_out_events__sold_out_events_msg',
634
-                                    sprintf(
635
-                                        esc_html__(
636
-                                            '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',
637
-                                            'event_espresso'
638
-                                        ),
639
-                                        '<strong>',
640
-                                        '</strong>',
641
-                                        '<br />'
642
-                                    )
643
-                                ),
644
-                            )
645
-                        ),
646
-                    )
647
-                ),
648
-            )
649
-        );
650
-    }
651
-
652
-
653
-    /**
654
-     * _insufficient_spaces_available
655
-     * displays notices regarding events that do not have enough remaining spaces
656
-     * to satisfy the current number of registrations looking to pay
657
-     *
658
-     * @param \EE_Event[] $insufficient_spaces_events_array
659
-     * @return \EE_Form_Section_Proper
660
-     * @throws \EE_Error
661
-     */
662
-    private function _insufficient_spaces_available($insufficient_spaces_events_array = array())
663
-    {
664
-        // set some defaults
665
-        $this->checkout->selected_method_of_payment = 'invoice';
666
-        $insufficient_space_events = '';
667
-        foreach ($insufficient_spaces_events_array as $event) {
668
-            if ($event instanceof EE_Event) {
669
-                $insufficient_space_events .= EEH_HTML::li(
670
-                    EEH_HTML::span(' ' . $event->name(), '', 'dashicons dashicons-marker ee-icon-size-16 pink-text')
671
-                );
672
-            }
673
-        }
674
-        return new EE_Form_Section_Proper(
675
-            array(
676
-                'subsections'     => array(
677
-                    'default_hidden_inputs' => $this->reg_step_hidden_inputs(),
678
-                    'extra_hidden_inputs'   => $this->_extra_hidden_inputs(),
679
-                ),
680
-                'layout_strategy' => new EE_Template_Layout(
681
-                    array(
682
-                        'layout_template_file' => SPCO_REG_STEPS_PATH
683
-                                                  . $this->_slug
684
-                                                  . DS
685
-                                                  . 'sold_out_events.template.php',
686
-                        'template_args'        => apply_filters(
687
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___insufficient_spaces_available__template_args',
688
-                            array(
689
-                                'sold_out_events'     => $insufficient_space_events,
690
-                                'sold_out_events_msg' => apply_filters(
691
-                                    'FHEE__EE_SPCO_Reg_Step_Payment_Options___insufficient_spaces_available__insufficient_space_msg',
692
-                                    esc_html__(
693
-                                        '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.',
694
-                                        'event_espresso'
695
-                                    )
696
-                                ),
697
-                            )
698
-                        ),
699
-                    )
700
-                ),
701
-            )
702
-        );
703
-    }
704
-
705
-
706
-    /**
707
-     * registrations_requiring_pre_approval
708
-     *
709
-     * @param array $registrations_requiring_pre_approval
710
-     * @return EE_Form_Section_Proper
711
-     * @throws EE_Error
712
-     * @throws \EventEspresso\core\exceptions\EntityNotFoundException
713
-     */
714
-    private function _registrations_requiring_pre_approval($registrations_requiring_pre_approval = array())
715
-    {
716
-        $events_requiring_pre_approval = '';
717
-        foreach ($registrations_requiring_pre_approval as $registration) {
718
-            if ($registration instanceof EE_Registration && $registration->event() instanceof EE_Event) {
719
-                $events_requiring_pre_approval[ $registration->event()->ID() ] = EEH_HTML::li(
720
-                    EEH_HTML::span(
721
-                        '',
722
-                        '',
723
-                        'dashicons dashicons-marker ee-icon-size-16 orange-text'
724
-                    )
725
-                    . EEH_HTML::span($registration->event()->name(), '', 'orange-text')
726
-                );
727
-            }
728
-        }
729
-        return new EE_Form_Section_Proper(
730
-            array(
731
-                'layout_strategy' => new EE_Template_Layout(
732
-                    array(
733
-                        'layout_template_file' => SPCO_REG_STEPS_PATH
734
-                                                  . $this->_slug
735
-                                                  . DS
736
-                                                  . 'events_requiring_pre_approval.template.php', // layout_template
737
-                        'template_args'        => apply_filters(
738
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___sold_out_events__template_args',
739
-                            array(
740
-                                'events_requiring_pre_approval'     => implode('', $events_requiring_pre_approval),
741
-                                'events_requiring_pre_approval_msg' => apply_filters(
742
-                                    'FHEE__EE_SPCO_Reg_Step_Payment_Options___events_requiring_pre_approval__events_requiring_pre_approval_msg',
743
-                                    esc_html__(
744
-                                        '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.',
745
-                                        'event_espresso'
746
-                                    )
747
-                                ),
748
-                            )
749
-                        ),
750
-                    )
751
-                ),
752
-            )
753
-        );
754
-    }
755
-
756
-
757
-    /**
758
-     * _no_payment_required
759
-     *
760
-     * @param \EE_Event[] $registrations_for_free_events
761
-     * @return \EE_Form_Section_Proper
762
-     * @throws \EE_Error
763
-     */
764
-    private function _no_payment_required($registrations_for_free_events = array())
765
-    {
766
-        // set some defaults
767
-        $this->checkout->selected_method_of_payment = 'no_payment_required';
768
-        // generate no_payment_required form
769
-        return new EE_Form_Section_Proper(
770
-            array(
771
-                'layout_strategy' => new EE_Template_Layout(
772
-                    array(
773
-                        'layout_template_file' => SPCO_REG_STEPS_PATH
774
-                                                  . $this->_slug
775
-                                                  . DS
776
-                                                  . 'no_payment_required.template.php', // layout_template
777
-                        'template_args'        => apply_filters(
778
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___no_payment_required__template_args',
779
-                            array(
780
-                                'revisit'                       => $this->checkout->revisit,
781
-                                'registrations'                 => array(),
782
-                                'ticket_count'                  => array(),
783
-                                'registrations_for_free_events' => $registrations_for_free_events,
784
-                                'no_payment_required_msg'       => EEH_HTML::p(
785
-                                    esc_html__('This is a free event, so no billing will occur.', 'event_espresso')
786
-                                ),
787
-                            )
788
-                        ),
789
-                    )
790
-                ),
791
-            )
792
-        );
793
-    }
794
-
795
-
796
-    /**
797
-     * _display_payment_options
798
-     *
799
-     * @param string $transaction_details
800
-     * @return EE_Form_Section_Proper
801
-     * @throws EE_Error
802
-     * @throws InvalidArgumentException
803
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
804
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
805
-     */
806
-    private function _display_payment_options($transaction_details = '')
807
-    {
808
-        // has method_of_payment been set by no-js user?
809
-        $this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment();
810
-        // build payment options form
811
-        return apply_filters(
812
-            'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__payment_options_form',
813
-            new EE_Form_Section_Proper(
814
-                array(
815
-                    'subsections'     => array(
816
-                        'before_payment_options' => apply_filters(
817
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__before_payment_options',
818
-                            new EE_Form_Section_Proper(
819
-                                array('layout_strategy' => new EE_Div_Per_Section_Layout())
820
-                            )
821
-                        ),
822
-                        'payment_options'        => $this->_setup_payment_options(),
823
-                        'after_payment_options'  => apply_filters(
824
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__after_payment_options',
825
-                            new EE_Form_Section_Proper(
826
-                                array('layout_strategy' => new EE_Div_Per_Section_Layout())
827
-                            )
828
-                        ),
829
-                    ),
830
-                    'layout_strategy' => new EE_Template_Layout(
831
-                        array(
832
-                            'layout_template_file' => $this->_template,
833
-                            'template_args'        => apply_filters(
834
-                                'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__template_args',
835
-                                array(
836
-                                    'reg_count'                 => $this->line_item_display->total_items(),
837
-                                    'transaction_details'       => $transaction_details,
838
-                                    'available_payment_methods' => array(),
839
-                                )
840
-                            ),
841
-                        )
842
-                    ),
843
-                )
844
-            )
845
-        );
846
-    }
847
-
848
-
849
-    /**
850
-     * _extra_hidden_inputs
851
-     *
852
-     * @param bool $no_payment_required
853
-     * @return \EE_Form_Section_Proper
854
-     * @throws \EE_Error
855
-     */
856
-    private function _extra_hidden_inputs($no_payment_required = true)
857
-    {
858
-        return new EE_Form_Section_Proper(
859
-            array(
860
-                'html_id'         => 'ee-' . $this->slug() . '-extra-hidden-inputs',
861
-                'layout_strategy' => new EE_Div_Per_Section_Layout(),
862
-                'subsections'     => array(
863
-                    'spco_no_payment_required' => new EE_Hidden_Input(
864
-                        array(
865
-                            'normalization_strategy' => new EE_Boolean_Normalization(),
866
-                            'html_name'              => 'spco_no_payment_required',
867
-                            'html_id'                => 'spco-no-payment-required-payment_options',
868
-                            'default'                => $no_payment_required,
869
-                        )
870
-                    ),
871
-                    'spco_transaction_id'      => new EE_Fixed_Hidden_Input(
872
-                        array(
873
-                            'normalization_strategy' => new EE_Int_Normalization(),
874
-                            'html_name'              => 'spco_transaction_id',
875
-                            'html_id'                => 'spco-transaction-id',
876
-                            'default'                => $this->checkout->transaction->ID(),
877
-                        )
878
-                    ),
879
-                ),
880
-            )
881
-        );
882
-    }
883
-
884
-
885
-    /**
886
-     *    _apply_registration_payments_to_amount_owing
887
-     *
888
-     * @access protected
889
-     * @param array $registrations
890
-     * @throws EE_Error
891
-     */
892
-    protected function _apply_registration_payments_to_amount_owing(array $registrations)
893
-    {
894
-        $payments = array();
895
-        foreach ($registrations as $registration) {
896
-            if ($registration instanceof EE_Registration && $registration->owes_monies_and_can_pay()) {
897
-                $payments += $registration->registration_payments();
898
-            }
899
-        }
900
-        if (! empty($payments)) {
901
-            foreach ($payments as $payment) {
902
-                if ($payment instanceof EE_Registration_Payment) {
903
-                    $this->checkout->amount_owing -= $payment->amount();
904
-                }
905
-            }
906
-        }
907
-    }
908
-
909
-
910
-    /**
911
-     *    _reset_selected_method_of_payment
912
-     *
913
-     * @access    private
914
-     * @param    bool $force_reset
915
-     * @return void
916
-     * @throws InvalidArgumentException
917
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
918
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
919
-     */
920
-    private function _reset_selected_method_of_payment($force_reset = false)
921
-    {
922
-        $reset_payment_method = $force_reset
923
-            ? true
924
-            : sanitize_text_field(EE_Registry::instance()->REQ->get('reset_payment_method', false));
925
-        if ($reset_payment_method) {
926
-            $this->checkout->selected_method_of_payment = null;
927
-            $this->checkout->payment_method = null;
928
-            $this->checkout->billing_form = null;
929
-            $this->_save_selected_method_of_payment();
930
-        }
931
-    }
932
-
933
-
934
-    /**
935
-     * _save_selected_method_of_payment
936
-     * stores the selected_method_of_payment in the session
937
-     * so that it's available for all subsequent requests including AJAX
938
-     *
939
-     * @access        private
940
-     * @param string $selected_method_of_payment
941
-     * @return void
942
-     * @throws InvalidArgumentException
943
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
944
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
945
-     */
946
-    private function _save_selected_method_of_payment($selected_method_of_payment = '')
947
-    {
948
-        $selected_method_of_payment = ! empty($selected_method_of_payment)
949
-            ? $selected_method_of_payment
950
-            : $this->checkout->selected_method_of_payment;
951
-        EE_Registry::instance()->SSN->set_session_data(
952
-            array('selected_method_of_payment' => $selected_method_of_payment)
953
-        );
954
-    }
955
-
956
-
957
-    /**
958
-     * _setup_payment_options
959
-     *
960
-     * @return EE_Form_Section_Proper
961
-     * @throws EE_Error
962
-     * @throws InvalidArgumentException
963
-     * @throws ReflectionException
964
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
965
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
966
-     */
967
-    public function _setup_payment_options()
968
-    {
969
-        // load payment method classes
970
-        $this->checkout->available_payment_methods = $this->_get_available_payment_methods();
971
-        if (empty($this->checkout->available_payment_methods)) {
972
-            EE_Error::add_error(
973
-                apply_filters(
974
-                    'FHEE__EE_SPCO_Reg_Step_Payment_Options___setup_payment_options__error_message_no_payment_methods',
975
-                    sprintf(
976
-                        esc_html__(
977
-                            '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.',
978
-                            'event_espresso'
979
-                        ),
980
-                        '<br>',
981
-                        EE_Registry::instance()->CFG->organization->get_pretty('email')
982
-                    )
983
-                ),
984
-                __FILE__,
985
-                __FUNCTION__,
986
-                __LINE__
987
-            );
988
-        }
989
-        // switch up header depending on number of available payment methods
990
-        $payment_method_header = count($this->checkout->available_payment_methods) > 1
991
-            ? apply_filters(
992
-                'FHEE__registration_page_payment_options__method_of_payment_hdr',
993
-                esc_html__('Please Select Your Method of Payment', 'event_espresso')
994
-            )
995
-            : apply_filters(
996
-                'FHEE__registration_page_payment_options__method_of_payment_hdr',
997
-                esc_html__('Method of Payment', 'event_espresso')
998
-            );
999
-        $available_payment_methods = array(
1000
-            // display the "Payment Method" header
1001
-            'payment_method_header' => new EE_Form_Section_HTML(
1002
-                EEH_HTML::h4($payment_method_header, 'method-of-payment-hdr')
1003
-            ),
1004
-        );
1005
-        // the list of actual payment methods ( invoice, paypal, etc ) in a  ( slug => HTML )  format
1006
-        $available_payment_method_options = array();
1007
-        $default_payment_method_option = array();
1008
-        // additional instructions to be displayed and hidden below payment methods (adding a clearing div to start)
1009
-        $payment_methods_billing_info = array(
1010
-            new EE_Form_Section_HTML(
1011
-                EEH_HTML::div('<br />', '', '', 'clear:both;')
1012
-            ),
1013
-        );
1014
-        // loop through payment methods
1015
-        foreach ($this->checkout->available_payment_methods as $payment_method) {
1016
-            if ($payment_method instanceof EE_Payment_Method) {
1017
-                $payment_method_button = EEH_HTML::img(
1018
-                    $payment_method->button_url(),
1019
-                    $payment_method->name(),
1020
-                    'spco-payment-method-' . $payment_method->slug() . '-btn-img',
1021
-                    'spco-payment-method-btn-img'
1022
-                );
1023
-                // check if any payment methods are set as default
1024
-                // if payment method is already selected OR nothing is selected and this payment method should be
1025
-                // open_by_default
1026
-                if (($this->checkout->selected_method_of_payment === $payment_method->slug())
1027
-                    || (! $this->checkout->selected_method_of_payment && $payment_method->open_by_default())
1028
-                ) {
1029
-                    $this->checkout->selected_method_of_payment = $payment_method->slug();
1030
-                    $this->_save_selected_method_of_payment();
1031
-                    $default_payment_method_option[ $payment_method->slug() ] = $payment_method_button;
1032
-                } else {
1033
-                    $available_payment_method_options[ $payment_method->slug() ] = $payment_method_button;
1034
-                }
1035
-                $payment_methods_billing_info[ $payment_method->slug(
1036
-                ) . '-info' ] = $this->_payment_method_billing_info(
1037
-                    $payment_method
1038
-                );
1039
-            }
1040
-        }
1041
-        // prepend available_payment_method_options with default_payment_method_option so that it appears first in list
1042
-        // of PMs
1043
-        $available_payment_method_options = $default_payment_method_option + $available_payment_method_options;
1044
-        // now generate the actual form  inputs
1045
-        $available_payment_methods['available_payment_methods'] = $this->_available_payment_method_inputs(
1046
-            $available_payment_method_options
1047
-        );
1048
-        $available_payment_methods += $payment_methods_billing_info;
1049
-        // build the available payment methods form
1050
-        return new EE_Form_Section_Proper(
1051
-            array(
1052
-                'html_id'         => 'spco-available-methods-of-payment-dv',
1053
-                'subsections'     => $available_payment_methods,
1054
-                'layout_strategy' => new EE_Div_Per_Section_Layout(),
1055
-            )
1056
-        );
1057
-    }
1058
-
1059
-
1060
-    /**
1061
-     * _get_available_payment_methods
1062
-     *
1063
-     * @return EE_Payment_Method[]
1064
-     * @throws EE_Error
1065
-     * @throws InvalidArgumentException
1066
-     * @throws ReflectionException
1067
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1068
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1069
-     */
1070
-    protected function _get_available_payment_methods()
1071
-    {
1072
-        if (! empty($this->checkout->available_payment_methods)) {
1073
-            return $this->checkout->available_payment_methods;
1074
-        }
1075
-        $available_payment_methods = array();
1076
-        // load EEM_Payment_Method
1077
-        EE_Registry::instance()->load_model('Payment_Method');
1078
-        /** @type EEM_Payment_Method $EEM_Payment_Method */
1079
-        $EEM_Payment_Method = EE_Registry::instance()->LIB->EEM_Payment_Method;
1080
-        // get all active payment methods
1081
-        $payment_methods = $EEM_Payment_Method->get_all_for_transaction(
1082
-            $this->checkout->transaction,
1083
-            EEM_Payment_Method::scope_cart
1084
-        );
1085
-        foreach ($payment_methods as $payment_method) {
1086
-            if ($payment_method instanceof EE_Payment_Method) {
1087
-                $available_payment_methods[ $payment_method->slug() ] = $payment_method;
1088
-            }
1089
-        }
1090
-        return $available_payment_methods;
1091
-    }
1092
-
1093
-
1094
-    /**
1095
-     *    _available_payment_method_inputs
1096
-     *
1097
-     * @access    private
1098
-     * @param    array $available_payment_method_options
1099
-     * @return    \EE_Form_Section_Proper
1100
-     */
1101
-    private function _available_payment_method_inputs($available_payment_method_options = array())
1102
-    {
1103
-        // generate inputs
1104
-        return new EE_Form_Section_Proper(
1105
-            array(
1106
-                'html_id'         => 'ee-available-payment-method-inputs',
1107
-                'layout_strategy' => new EE_Div_Per_Section_Layout(),
1108
-                'subsections'     => array(
1109
-                    '' => new EE_Radio_Button_Input(
1110
-                        $available_payment_method_options,
1111
-                        array(
1112
-                            'html_name'          => 'selected_method_of_payment',
1113
-                            'html_class'         => 'spco-payment-method',
1114
-                            'default'            => $this->checkout->selected_method_of_payment,
1115
-                            'label_size'         => 11,
1116
-                            'enforce_label_size' => true,
1117
-                        )
1118
-                    ),
1119
-                ),
1120
-            )
1121
-        );
1122
-    }
1123
-
1124
-
1125
-    /**
1126
-     *    _payment_method_billing_info
1127
-     *
1128
-     * @access    private
1129
-     * @param    EE_Payment_Method $payment_method
1130
-     * @return EE_Form_Section_Proper
1131
-     * @throws EE_Error
1132
-     * @throws InvalidArgumentException
1133
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1134
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1135
-     */
1136
-    private function _payment_method_billing_info(EE_Payment_Method $payment_method)
1137
-    {
1138
-        $currently_selected = $this->checkout->selected_method_of_payment === $payment_method->slug()
1139
-            ? true
1140
-            : false;
1141
-        // generate the billing form for payment method
1142
-        $billing_form = $currently_selected
1143
-            ? $this->_get_billing_form_for_payment_method($payment_method)
1144
-            : new EE_Form_Section_HTML();
1145
-        $this->checkout->billing_form = $currently_selected
1146
-            ? $billing_form
1147
-            : $this->checkout->billing_form;
1148
-        // it's all in the details
1149
-        $info_html = EEH_HTML::h3(
1150
-            esc_html__('Important information regarding your payment', 'event_espresso'),
1151
-            '',
1152
-            'spco-payment-method-hdr'
1153
-        );
1154
-        // add some info regarding the step, either from what's saved in the admin,
1155
-        // or a default string depending on whether the PM has a billing form or not
1156
-        if ($payment_method->description()) {
1157
-            $payment_method_info = $payment_method->description();
1158
-        } elseif ($billing_form instanceof EE_Billing_Info_Form) {
1159
-            $payment_method_info = sprintf(
1160
-                esc_html__(
1161
-                    'Please provide the following billing information, then click the "%1$s" button below in order to proceed.',
1162
-                    'event_espresso'
1163
-                ),
1164
-                $this->submit_button_text()
1165
-            );
1166
-        } else {
1167
-            $payment_method_info = sprintf(
1168
-                esc_html__('Please click the "%1$s" button below in order to proceed.', 'event_espresso'),
1169
-                $this->submit_button_text()
1170
-            );
1171
-        }
1172
-        $info_html .= EEH_HTML::div(
1173
-            apply_filters(
1174
-                'FHEE__EE_SPCO_Reg_Step_Payment_Options___payment_method_billing_info__payment_method_info',
1175
-                $payment_method_info
1176
-            ),
1177
-            '',
1178
-            'spco-payment-method-desc ee-attention'
1179
-        );
1180
-        return new EE_Form_Section_Proper(
1181
-            array(
1182
-                'html_id'         => 'spco-payment-method-info-' . $payment_method->slug(),
1183
-                'html_class'      => 'spco-payment-method-info-dv',
1184
-                // only display the selected or default PM
1185
-                'html_style'      => $currently_selected ? '' : 'display:none;',
1186
-                'layout_strategy' => new EE_Div_Per_Section_Layout(),
1187
-                'subsections'     => array(
1188
-                    'info'         => new EE_Form_Section_HTML($info_html),
1189
-                    'billing_form' => $currently_selected ? $billing_form : new EE_Form_Section_HTML(),
1190
-                ),
1191
-            )
1192
-        );
1193
-    }
1194
-
1195
-
1196
-    /**
1197
-     * get_billing_form_html_for_payment_method
1198
-     *
1199
-     * @access public
1200
-     * @return string
1201
-     * @throws EE_Error
1202
-     * @throws InvalidArgumentException
1203
-     * @throws ReflectionException
1204
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1205
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1206
-     */
1207
-    public function get_billing_form_html_for_payment_method()
1208
-    {
1209
-        // how have they chosen to pay?
1210
-        $this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
1211
-        $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment();
1212
-        if (! $this->checkout->payment_method instanceof EE_Payment_Method) {
1213
-            return false;
1214
-        }
1215
-        if (apply_filters(
1216
-            'FHEE__EE_SPCO_Reg_Step_Payment_Options__registration_checkout__selected_payment_method__display_success',
1217
-            false
1218
-        )) {
1219
-            EE_Error::add_success(
1220
-                apply_filters(
1221
-                    'FHEE__Single_Page_Checkout__registration_checkout__selected_payment_method',
1222
-                    sprintf(
1223
-                        esc_html__(
1224
-                            'You have selected "%s" as your method of payment. Please note the important payment information below.',
1225
-                            'event_espresso'
1226
-                        ),
1227
-                        $this->checkout->payment_method->name()
1228
-                    )
1229
-                )
1230
-            );
1231
-        }
1232
-        // now generate billing form for selected method of payment
1233
-        $payment_method_billing_form = $this->_get_billing_form_for_payment_method($this->checkout->payment_method);
1234
-        // fill form with attendee info if applicable
1235
-        if ($payment_method_billing_form instanceof EE_Billing_Attendee_Info_Form
1236
-            && $this->checkout->transaction_has_primary_registrant()
1237
-        ) {
1238
-            $payment_method_billing_form->populate_from_attendee(
1239
-                $this->checkout->transaction->primary_registration()->attendee()
1240
-            );
1241
-        }
1242
-        // and debug content
1243
-        if ($payment_method_billing_form instanceof EE_Billing_Info_Form
1244
-            && $this->checkout->payment_method->type_obj() instanceof EE_PMT_Base
1245
-        ) {
1246
-            $payment_method_billing_form =
1247
-                $this->checkout->payment_method->type_obj()->apply_billing_form_debug_settings(
1248
-                    $payment_method_billing_form
1249
-                );
1250
-        }
1251
-        $billing_info = $payment_method_billing_form instanceof EE_Form_Section_Proper
1252
-            ? $payment_method_billing_form->get_html()
1253
-            : '';
1254
-        $this->checkout->json_response->set_return_data(array('payment_method_info' => $billing_info));
1255
-        // localize validation rules for main form
1256
-        $this->checkout->current_step->reg_form->localize_validation_rules();
1257
-        $this->checkout->json_response->add_validation_rules(EE_Form_Section_Proper::js_localization());
1258
-        return true;
1259
-    }
1260
-
1261
-
1262
-    /**
1263
-     * _get_billing_form_for_payment_method
1264
-     *
1265
-     * @access private
1266
-     * @param EE_Payment_Method $payment_method
1267
-     * @return EE_Billing_Info_Form|EE_Form_Section_HTML
1268
-     * @throws EE_Error
1269
-     * @throws InvalidArgumentException
1270
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1271
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1272
-     */
1273
-    private function _get_billing_form_for_payment_method(EE_Payment_Method $payment_method)
1274
-    {
1275
-        $billing_form = $payment_method->type_obj()->billing_form(
1276
-            $this->checkout->transaction,
1277
-            array('amount_owing' => $this->checkout->amount_owing)
1278
-        );
1279
-        if ($billing_form instanceof EE_Billing_Info_Form) {
1280
-            if (apply_filters(
1281
-                'FHEE__EE_SPCO_Reg_Step_Payment_Options__registration_checkout__selected_payment_method__display_success',
1282
-                false
1283
-            )
1284
-                && EE_Registry::instance()->REQ->is_set('payment_method')
1285
-            ) {
1286
-                EE_Error::add_success(
1287
-                    apply_filters(
1288
-                        'FHEE__Single_Page_Checkout__registration_checkout__selected_payment_method',
1289
-                        sprintf(
1290
-                            esc_html__(
1291
-                                'You have selected "%s" as your method of payment. Please note the important payment information below.',
1292
-                                'event_espresso'
1293
-                            ),
1294
-                            $payment_method->name()
1295
-                        )
1296
-                    )
1297
-                );
1298
-            }
1299
-            return apply_filters(
1300
-                'FHEE__EE_SPCO_Reg_Step_Payment_Options___get_billing_form_for_payment_method__billing_form',
1301
-                $billing_form,
1302
-                $payment_method
1303
-            );
1304
-        }
1305
-        // no actual billing form, so return empty HTML form section
1306
-        return new EE_Form_Section_HTML();
1307
-    }
1308
-
1309
-
1310
-    /**
1311
-     * _get_selected_method_of_payment
1312
-     *
1313
-     * @access private
1314
-     * @param boolean $required whether to throw an error if the "selected_method_of_payment"
1315
-     *                          is not found in the incoming request
1316
-     * @param string  $request_param
1317
-     * @return NULL|string
1318
-     * @throws EE_Error
1319
-     * @throws InvalidArgumentException
1320
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1321
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1322
-     */
1323
-    private function _get_selected_method_of_payment(
1324
-        $required = false,
1325
-        $request_param = 'selected_method_of_payment'
1326
-    ) {
1327
-        // is selected_method_of_payment set in the request ?
1328
-        $selected_method_of_payment = EE_Registry::instance()->REQ->get($request_param, false);
1329
-        if ($selected_method_of_payment) {
1330
-            // sanitize it
1331
-            $selected_method_of_payment = is_array($selected_method_of_payment)
1332
-                ? array_shift($selected_method_of_payment)
1333
-                : $selected_method_of_payment;
1334
-            $selected_method_of_payment = sanitize_text_field($selected_method_of_payment);
1335
-            // store it in the session so that it's available for all subsequent requests including AJAX
1336
-            $this->_save_selected_method_of_payment($selected_method_of_payment);
1337
-        } else {
1338
-            // or is is set in the session ?
1339
-            $selected_method_of_payment = EE_Registry::instance()->SSN->get_session_data(
1340
-                'selected_method_of_payment'
1341
-            );
1342
-        }
1343
-        // do ya really really gotta have it?
1344
-        if (empty($selected_method_of_payment) && $required) {
1345
-            EE_Error::add_error(
1346
-                sprintf(
1347
-                    esc_html__(
1348
-                        '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.',
1349
-                        'event_espresso'
1350
-                    ),
1351
-                    '<br/>',
1352
-                    '<br/>',
1353
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
1354
-                ),
1355
-                __FILE__,
1356
-                __FUNCTION__,
1357
-                __LINE__
1358
-            );
1359
-            return null;
1360
-        }
1361
-        return $selected_method_of_payment;
1362
-    }
1363
-
1364
-
1365
-
1366
-
1367
-
1368
-
1369
-    /********************************************************************************************************/
1370
-    /***********************************  SWITCH PAYMENT METHOD  ************************************/
1371
-    /********************************************************************************************************/
1372
-    /**
1373
-     * switch_payment_method
1374
-     *
1375
-     * @access public
1376
-     * @return string
1377
-     * @throws EE_Error
1378
-     * @throws InvalidArgumentException
1379
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1380
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1381
-     */
1382
-    public function switch_payment_method()
1383
-    {
1384
-        if (! $this->_verify_payment_method_is_set()) {
1385
-            return false;
1386
-        }
1387
-        if (apply_filters(
1388
-            'FHEE__EE_SPCO_Reg_Step_Payment_Options__registration_checkout__selected_payment_method__display_success',
1389
-            false
1390
-        )) {
1391
-            EE_Error::add_success(
1392
-                apply_filters(
1393
-                    'FHEE__Single_Page_Checkout__registration_checkout__selected_payment_method',
1394
-                    sprintf(
1395
-                        esc_html__(
1396
-                            'You have selected "%s" as your method of payment. Please note the important payment information below.',
1397
-                            'event_espresso'
1398
-                        ),
1399
-                        $this->checkout->payment_method->name()
1400
-                    )
1401
-                )
1402
-            );
1403
-        }
1404
-        // generate billing form for selected method of payment if it hasn't been done already
1405
-        if ($this->checkout->payment_method->type_obj()->has_billing_form()) {
1406
-            $this->checkout->billing_form = $this->_get_billing_form_for_payment_method(
1407
-                $this->checkout->payment_method
1408
-            );
1409
-        }
1410
-        // fill form with attendee info if applicable
1411
-        if (apply_filters(
1412
-            'FHEE__populate_billing_form_fields_from_attendee',
1413
-            (
1414
-                $this->checkout->billing_form instanceof EE_Billing_Attendee_Info_Form
1415
-                && $this->checkout->transaction_has_primary_registrant()
1416
-            ),
1417
-            $this->checkout->billing_form,
1418
-            $this->checkout->transaction
1419
-        )
1420
-        ) {
1421
-            $this->checkout->billing_form->populate_from_attendee(
1422
-                $this->checkout->transaction->primary_registration()->attendee()
1423
-            );
1424
-        }
1425
-        // and debug content
1426
-        if ($this->checkout->billing_form instanceof EE_Billing_Info_Form
1427
-            && $this->checkout->payment_method->type_obj() instanceof EE_PMT_Base
1428
-        ) {
1429
-            $this->checkout->billing_form =
1430
-                $this->checkout->payment_method->type_obj()->apply_billing_form_debug_settings(
1431
-                    $this->checkout->billing_form
1432
-                );
1433
-        }
1434
-        // get html and validation rules for form
1435
-        if ($this->checkout->billing_form instanceof EE_Form_Section_Proper) {
1436
-            $this->checkout->json_response->set_return_data(
1437
-                array('payment_method_info' => $this->checkout->billing_form->get_html())
1438
-            );
1439
-            // localize validation rules for main form
1440
-            $this->checkout->billing_form->localize_validation_rules(true);
1441
-            $this->checkout->json_response->add_validation_rules(EE_Form_Section_Proper::js_localization());
1442
-        } else {
1443
-            $this->checkout->json_response->set_return_data(array('payment_method_info' => ''));
1444
-        }
1445
-        // prevents advancement to next step
1446
-        $this->checkout->continue_reg = false;
1447
-        return true;
1448
-    }
1449
-
1450
-
1451
-    /**
1452
-     * _verify_payment_method_is_set
1453
-     *
1454
-     * @return bool
1455
-     * @throws EE_Error
1456
-     * @throws InvalidArgumentException
1457
-     * @throws ReflectionException
1458
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1459
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1460
-     */
1461
-    protected function _verify_payment_method_is_set()
1462
-    {
1463
-        // generate billing form for selected method of payment if it hasn't been done already
1464
-        if (empty($this->checkout->selected_method_of_payment)) {
1465
-            // how have they chosen to pay?
1466
-            $this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
1467
-        } else {
1468
-            // choose your own adventure based on method_of_payment
1469
-            switch ($this->checkout->selected_method_of_payment) {
1470
-                case 'events_sold_out':
1471
-                    EE_Error::add_attention(
1472
-                        apply_filters(
1473
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___verify_payment_method_is_set__sold_out_events_msg',
1474
-                            esc_html__(
1475
-                                '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.',
1476
-                                'event_espresso'
1477
-                            )
1478
-                        ),
1479
-                        __FILE__,
1480
-                        __FUNCTION__,
1481
-                        __LINE__
1482
-                    );
1483
-                    return false;
1484
-                    break;
1485
-                case 'payments_closed':
1486
-                    EE_Error::add_attention(
1487
-                        apply_filters(
1488
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___verify_payment_method_is_set__payments_closed_msg',
1489
-                            esc_html__(
1490
-                                '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.',
1491
-                                'event_espresso'
1492
-                            )
1493
-                        ),
1494
-                        __FILE__,
1495
-                        __FUNCTION__,
1496
-                        __LINE__
1497
-                    );
1498
-                    return false;
1499
-                    break;
1500
-                case 'no_payment_required':
1501
-                    EE_Error::add_attention(
1502
-                        apply_filters(
1503
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___verify_payment_method_is_set__no_payment_required_msg',
1504
-                            esc_html__(
1505
-                                '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.',
1506
-                                'event_espresso'
1507
-                            )
1508
-                        ),
1509
-                        __FILE__,
1510
-                        __FUNCTION__,
1511
-                        __LINE__
1512
-                    );
1513
-                    return false;
1514
-                    break;
1515
-                default:
1516
-            }
1517
-        }
1518
-        // verify payment method
1519
-        if (! $this->checkout->payment_method instanceof EE_Payment_Method) {
1520
-            // get payment method for selected method of payment
1521
-            $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment();
1522
-        }
1523
-        return $this->checkout->payment_method instanceof EE_Payment_Method ? true : false;
1524
-    }
1525
-
1526
-
1527
-
1528
-    /********************************************************************************************************/
1529
-    /***************************************  SAVE PAYER DETAILS  ****************************************/
1530
-    /********************************************************************************************************/
1531
-    /**
1532
-     * save_payer_details_via_ajax
1533
-     *
1534
-     * @return void
1535
-     * @throws EE_Error
1536
-     * @throws InvalidArgumentException
1537
-     * @throws ReflectionException
1538
-     * @throws RuntimeException
1539
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1540
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1541
-     */
1542
-    public function save_payer_details_via_ajax()
1543
-    {
1544
-        if (! $this->_verify_payment_method_is_set()) {
1545
-            return;
1546
-        }
1547
-        // generate billing form for selected method of payment if it hasn't been done already
1548
-        if ($this->checkout->payment_method->type_obj()->has_billing_form()) {
1549
-            $this->checkout->billing_form = $this->_get_billing_form_for_payment_method(
1550
-                $this->checkout->payment_method
1551
-            );
1552
-        }
1553
-        // generate primary attendee from payer info if applicable
1554
-        if (! $this->checkout->transaction_has_primary_registrant()) {
1555
-            $attendee = $this->_create_attendee_from_request_data();
1556
-            if ($attendee instanceof EE_Attendee) {
1557
-                foreach ($this->checkout->transaction->registrations() as $registration) {
1558
-                    if ($registration->is_primary_registrant()) {
1559
-                        $this->checkout->primary_attendee_obj = $attendee;
1560
-                        $registration->_add_relation_to($attendee, 'Attendee');
1561
-                        $registration->set_attendee_id($attendee->ID());
1562
-                        $registration->update_cache_after_object_save('Attendee', $attendee);
1563
-                    }
1564
-                }
1565
-            }
1566
-        }
1567
-    }
1568
-
1569
-
1570
-    /**
1571
-     * create_attendee_from_request_data
1572
-     * uses info from alternate GET or POST data (such as AJAX) to create a new attendee
1573
-     *
1574
-     * @return EE_Attendee
1575
-     * @throws EE_Error
1576
-     * @throws InvalidArgumentException
1577
-     * @throws ReflectionException
1578
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1579
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1580
-     */
1581
-    protected function _create_attendee_from_request_data()
1582
-    {
1583
-        // get State ID
1584
-        $STA_ID = ! empty($_REQUEST['state']) ? sanitize_text_field($_REQUEST['state']) : '';
1585
-        if (! empty($STA_ID)) {
1586
-            // can we get state object from name ?
1587
-            EE_Registry::instance()->load_model('State');
1588
-            $state = EEM_State::instance()->get_col(array(array('STA_name' => $STA_ID), 'limit' => 1), 'STA_ID');
1589
-            $STA_ID = is_array($state) && ! empty($state) ? reset($state) : $STA_ID;
1590
-        }
1591
-        // get Country ISO
1592
-        $CNT_ISO = ! empty($_REQUEST['country']) ? sanitize_text_field($_REQUEST['country']) : '';
1593
-        if (! empty($CNT_ISO)) {
1594
-            // can we get country object from name ?
1595
-            EE_Registry::instance()->load_model('Country');
1596
-            $country = EEM_Country::instance()->get_col(
1597
-                array(array('CNT_name' => $CNT_ISO), 'limit' => 1),
1598
-                'CNT_ISO'
1599
-            );
1600
-            $CNT_ISO = is_array($country) && ! empty($country) ? reset($country) : $CNT_ISO;
1601
-        }
1602
-        // grab attendee data
1603
-        $attendee_data = array(
1604
-            'ATT_fname'    => ! empty($_REQUEST['first_name']) ? sanitize_text_field($_REQUEST['first_name']) : '',
1605
-            'ATT_lname'    => ! empty($_REQUEST['last_name']) ? sanitize_text_field($_REQUEST['last_name']) : '',
1606
-            'ATT_email'    => ! empty($_REQUEST['email']) ? sanitize_email($_REQUEST['email']) : '',
1607
-            'ATT_address'  => ! empty($_REQUEST['address']) ? sanitize_text_field($_REQUEST['address']) : '',
1608
-            'ATT_address2' => ! empty($_REQUEST['address2']) ? sanitize_text_field($_REQUEST['address2']) : '',
1609
-            'ATT_city'     => ! empty($_REQUEST['city']) ? sanitize_text_field($_REQUEST['city']) : '',
1610
-            'STA_ID'       => $STA_ID,
1611
-            'CNT_ISO'      => $CNT_ISO,
1612
-            'ATT_zip'      => ! empty($_REQUEST['zip']) ? sanitize_text_field($_REQUEST['zip']) : '',
1613
-            'ATT_phone'    => ! empty($_REQUEST['phone']) ? sanitize_text_field($_REQUEST['phone']) : '',
1614
-        );
1615
-        // validate the email address since it is the most important piece of info
1616
-        if (empty($attendee_data['ATT_email']) || $attendee_data['ATT_email'] !== $_REQUEST['email']) {
1617
-            EE_Error::add_error(
1618
-                esc_html__('An invalid email address was submitted.', 'event_espresso'),
1619
-                __FILE__,
1620
-                __FUNCTION__,
1621
-                __LINE__
1622
-            );
1623
-        }
1624
-        // does this attendee already exist in the db ? we're searching using a combination of first name, last name,
1625
-        // AND email address
1626
-        if (! empty($attendee_data['ATT_fname'])
1627
-            && ! empty($attendee_data['ATT_lname'])
1628
-            && ! empty($attendee_data['ATT_email'])
1629
-        ) {
1630
-            $existing_attendee = EE_Registry::instance()->LIB->EEM_Attendee->find_existing_attendee(
1631
-                array(
1632
-                    'ATT_fname' => $attendee_data['ATT_fname'],
1633
-                    'ATT_lname' => $attendee_data['ATT_lname'],
1634
-                    'ATT_email' => $attendee_data['ATT_email'],
1635
-                )
1636
-            );
1637
-            if ($existing_attendee instanceof EE_Attendee) {
1638
-                return $existing_attendee;
1639
-            }
1640
-        }
1641
-        // no existing attendee? kk let's create a new one
1642
-        // kinda lame, but we need a first and last name to create an attendee, so use the email address if those
1643
-        // don't exist
1644
-        $attendee_data['ATT_fname'] = ! empty($attendee_data['ATT_fname'])
1645
-            ? $attendee_data['ATT_fname']
1646
-            : $attendee_data['ATT_email'];
1647
-        $attendee_data['ATT_lname'] = ! empty($attendee_data['ATT_lname'])
1648
-            ? $attendee_data['ATT_lname']
1649
-            : $attendee_data['ATT_email'];
1650
-        return EE_Attendee::new_instance($attendee_data);
1651
-    }
1652
-
1653
-
1654
-
1655
-    /********************************************************************************************************/
1656
-    /****************************************  PROCESS REG STEP  *****************************************/
1657
-    /********************************************************************************************************/
1658
-    /**
1659
-     * process_reg_step
1660
-     *
1661
-     * @return bool
1662
-     * @throws EE_Error
1663
-     * @throws InvalidArgumentException
1664
-     * @throws ReflectionException
1665
-     * @throws \EventEspresso\core\exceptions\EntityNotFoundException
1666
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1667
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1668
-     * @throws \EventEspresso\core\exceptions\InvalidStatusException
1669
-     */
1670
-    public function process_reg_step()
1671
-    {
1672
-        // how have they chosen to pay?
1673
-        $this->checkout->selected_method_of_payment = $this->checkout->transaction->is_free()
1674
-            ? 'no_payment_required'
1675
-            : $this->_get_selected_method_of_payment(true);
1676
-        // choose your own adventure based on method_of_payment
1677
-        switch ($this->checkout->selected_method_of_payment) {
1678
-            case 'events_sold_out':
1679
-                $this->checkout->redirect = true;
1680
-                $this->checkout->redirect_url = $this->checkout->cancel_page_url;
1681
-                $this->checkout->json_response->set_redirect_url($this->checkout->redirect_url);
1682
-                // mark this reg step as completed
1683
-                $this->set_completed();
1684
-                return false;
1685
-                break;
1686
-
1687
-            case 'payments_closed':
1688
-                if (apply_filters(
1689
-                    'FHEE__EE_SPCO_Reg_Step_Payment_Options__process_reg_step__payments_closed__display_success',
1690
-                    false
1691
-                )) {
1692
-                    EE_Error::add_success(
1693
-                        esc_html__('no payment required at this time.', 'event_espresso'),
1694
-                        __FILE__,
1695
-                        __FUNCTION__,
1696
-                        __LINE__
1697
-                    );
1698
-                }
1699
-                // mark this reg step as completed
1700
-                $this->set_completed();
1701
-                return true;
1702
-                break;
1703
-
1704
-            case 'no_payment_required':
1705
-                if (apply_filters(
1706
-                    'FHEE__EE_SPCO_Reg_Step_Payment_Options__process_reg_step__no_payment_required__display_success',
1707
-                    false
1708
-                )) {
1709
-                    EE_Error::add_success(
1710
-                        esc_html__('no payment required.', 'event_espresso'),
1711
-                        __FILE__,
1712
-                        __FUNCTION__,
1713
-                        __LINE__
1714
-                    );
1715
-                }
1716
-                // mark this reg step as completed
1717
-                $this->set_completed();
1718
-                return true;
1719
-                break;
1720
-
1721
-            default:
1722
-                $registrations = EE_Registry::instance()->SSN->checkout()->transaction->registrations(
1723
-                    EE_Registry::instance()->SSN->checkout()->reg_cache_where_params
1724
-                );
1725
-                $ejected_registrations = EE_SPCO_Reg_Step_Payment_Options::find_registrations_that_lost_their_space(
1726
-                    $registrations,
1727
-                    EE_Registry::instance()->SSN->checkout()->revisit
1728
-                );
1729
-                // calculate difference between the two arrays
1730
-                $registrations = array_diff($registrations, $ejected_registrations);
1731
-                if (empty($registrations)) {
1732
-                    $this->_redirect_because_event_sold_out();
1733
-                    return false;
1734
-                }
1735
-                $payment_successful = $this->_process_payment();
1736
-                if ($payment_successful) {
1737
-                    $this->checkout->continue_reg = true;
1738
-                    $this->_maybe_set_completed($this->checkout->payment_method);
1739
-                } else {
1740
-                    $this->checkout->continue_reg = false;
1741
-                }
1742
-                return $payment_successful;
1743
-        }
1744
-    }
1745
-
1746
-
1747
-    /**
1748
-     * _redirect_because_event_sold_out
1749
-     *
1750
-     * @access protected
1751
-     * @return void
1752
-     */
1753
-    protected function _redirect_because_event_sold_out()
1754
-    {
1755
-        $this->checkout->continue_reg = false;
1756
-        // set redirect URL
1757
-        $this->checkout->redirect_url = add_query_arg(
1758
-            array('e_reg_url_link' => $this->checkout->reg_url_link),
1759
-            $this->checkout->current_step->reg_step_url()
1760
-        );
1761
-        $this->checkout->json_response->set_redirect_url($this->checkout->redirect_url);
1762
-    }
1763
-
1764
-
1765
-    /**
1766
-     * _maybe_set_completed
1767
-     *
1768
-     * @access protected
1769
-     * @param \EE_Payment_Method $payment_method
1770
-     * @return void
1771
-     * @throws \EE_Error
1772
-     */
1773
-    protected function _maybe_set_completed(EE_Payment_Method $payment_method)
1774
-    {
1775
-        switch ($payment_method->type_obj()->payment_occurs()) {
1776
-            case EE_PMT_Base::offsite:
1777
-                break;
1778
-            case EE_PMT_Base::onsite:
1779
-            case EE_PMT_Base::offline:
1780
-                // mark this reg step as completed
1781
-                $this->set_completed();
1782
-                break;
1783
-        }
1784
-    }
1785
-
1786
-
1787
-    /**
1788
-     *    update_reg_step
1789
-     *    this is the final step after a user  revisits the site to retry a payment
1790
-     *
1791
-     * @return bool
1792
-     * @throws EE_Error
1793
-     * @throws InvalidArgumentException
1794
-     * @throws ReflectionException
1795
-     * @throws \EventEspresso\core\exceptions\EntityNotFoundException
1796
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1797
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1798
-     * @throws \EventEspresso\core\exceptions\InvalidStatusException
1799
-     */
1800
-    public function update_reg_step()
1801
-    {
1802
-        $success = true;
1803
-        // if payment required
1804
-        if ($this->checkout->transaction->total() > 0) {
1805
-            do_action(
1806
-                'AHEE__EE_Single_Page_Checkout__process_finalize_registration__before_gateway',
1807
-                $this->checkout->transaction
1808
-            );
1809
-            // attempt payment via payment method
1810
-            $success = $this->process_reg_step();
1811
-        }
1812
-        if ($success && ! $this->checkout->redirect) {
1813
-            $this->checkout->cart->get_grand_total()->save_this_and_descendants_to_txn(
1814
-                $this->checkout->transaction->ID()
1815
-            );
1816
-            // set return URL
1817
-            $this->checkout->redirect_url = add_query_arg(
1818
-                array('e_reg_url_link' => $this->checkout->reg_url_link),
1819
-                $this->checkout->thank_you_page_url
1820
-            );
1821
-        }
1822
-        return $success;
1823
-    }
1824
-
1825
-
1826
-    /**
1827
-     *    _process_payment
1828
-     *
1829
-     * @access private
1830
-     * @return bool
1831
-     * @throws EE_Error
1832
-     * @throws InvalidArgumentException
1833
-     * @throws ReflectionException
1834
-     * @throws RuntimeException
1835
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1836
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1837
-     */
1838
-    private function _process_payment()
1839
-    {
1840
-        // basically confirm that the event hasn't sold out since they hit the page
1841
-        if (! $this->_last_second_ticket_verifications()) {
1842
-            return false;
1843
-        }
1844
-        // ya gotta make a choice man
1845
-        if (empty($this->checkout->selected_method_of_payment)) {
1846
-            $this->checkout->json_response->set_plz_select_method_of_payment(
1847
-                esc_html__('Please select a method of payment before proceeding.', 'event_espresso')
1848
-            );
1849
-            return false;
1850
-        }
1851
-        // get EE_Payment_Method object
1852
-        if (! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()) {
1853
-            return false;
1854
-        }
1855
-        // setup billing form
1856
-        if ($this->checkout->payment_method->is_on_site()) {
1857
-            $this->checkout->billing_form = $this->_get_billing_form_for_payment_method(
1858
-                $this->checkout->payment_method
1859
-            );
1860
-            // bad billing form ?
1861
-            if (! $this->_billing_form_is_valid()) {
1862
-                return false;
1863
-            }
1864
-        }
1865
-        // ensure primary registrant has been fully processed
1866
-        if (! $this->_setup_primary_registrant_prior_to_payment()) {
1867
-            return false;
1868
-        }
1869
-        // if session is close to expiring (under 10 minutes by default)
1870
-        if ((time() - EE_Registry::instance()->SSN->expiration()) < EE_Registry::instance()->SSN->extension()) {
1871
-            // add some time to session expiration so that payment can be completed
1872
-            EE_Registry::instance()->SSN->extend_expiration();
1873
-        }
1874
-        /** @type EE_Transaction_Processor $transaction_processor */
1875
-        // $transaction_processor = EE_Registry::instance()->load_class( 'Transaction_Processor' );
1876
-        // in case a registrant leaves to an Off-Site Gateway and never returns, we want to approve any registrations
1877
-        // for events with a default reg status of Approved
1878
-        // $transaction_processor->toggle_registration_statuses_for_default_approved_events(
1879
-        //      $this->checkout->transaction, $this->checkout->reg_cache_where_params
1880
-        // );
1881
-        // attempt payment
1882
-        $payment = $this->_attempt_payment($this->checkout->payment_method);
1883
-        // process results
1884
-        $payment = $this->_validate_payment($payment);
1885
-        $payment = $this->_post_payment_processing($payment);
1886
-        // verify payment
1887
-        if ($payment instanceof EE_Payment) {
1888
-            // store that for later
1889
-            $this->checkout->payment = $payment;
1890
-            // we can also consider the TXN to not have been failed, so temporarily upgrade it's status to abandoned
1891
-            $this->checkout->transaction->toggle_failed_transaction_status();
1892
-            $payment_status = $payment->status();
1893
-            if ($payment_status === EEM_Payment::status_id_approved
1894
-                || $payment_status === EEM_Payment::status_id_pending
1895
-            ) {
1896
-                return true;
1897
-            } else {
1898
-                return false;
1899
-            }
1900
-        } elseif ($payment === true) {
1901
-            // please note that offline payment methods will NOT make a payment,
1902
-            // but instead just mark themselves as the PMD_ID on the transaction, and return true
1903
-            $this->checkout->payment = $payment;
1904
-            return true;
1905
-        }
1906
-        // where's my money?
1907
-        return false;
1908
-    }
1909
-
1910
-
1911
-    /**
1912
-     * _last_second_ticket_verifications
1913
-     *
1914
-     * @access public
1915
-     * @return bool
1916
-     * @throws EE_Error
1917
-     */
1918
-    protected function _last_second_ticket_verifications()
1919
-    {
1920
-        // don't bother re-validating if not a return visit
1921
-        if (! $this->checkout->revisit) {
1922
-            return true;
1923
-        }
1924
-        $registrations = $this->checkout->transaction->registrations();
1925
-        if (empty($registrations)) {
1926
-            return false;
1927
-        }
1928
-        foreach ($registrations as $registration) {
1929
-            if ($registration instanceof EE_Registration && ! $registration->is_approved()) {
1930
-                $event = $registration->event_obj();
1931
-                if ($event instanceof EE_Event && $event->is_sold_out(true)) {
1932
-                    EE_Error::add_error(
1933
-                        apply_filters(
1934
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___last_second_ticket_verifications__sold_out_events_msg',
1935
-                            sprintf(
1936
-                                esc_html__(
1937
-                                    '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.',
1938
-                                    'event_espresso'
1939
-                                ),
1940
-                                $event->name()
1941
-                            )
1942
-                        ),
1943
-                        __FILE__,
1944
-                        __FUNCTION__,
1945
-                        __LINE__
1946
-                    );
1947
-                    return false;
1948
-                }
1949
-            }
1950
-        }
1951
-        return true;
1952
-    }
1953
-
1954
-
1955
-    /**
1956
-     * redirect_form
1957
-     *
1958
-     * @access public
1959
-     * @return bool
1960
-     * @throws EE_Error
1961
-     * @throws InvalidArgumentException
1962
-     * @throws ReflectionException
1963
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1964
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1965
-     */
1966
-    public function redirect_form()
1967
-    {
1968
-        $payment_method_billing_info = $this->_payment_method_billing_info(
1969
-            $this->_get_payment_method_for_selected_method_of_payment()
1970
-        );
1971
-        $html = $payment_method_billing_info->get_html();
1972
-        $html .= $this->checkout->redirect_form;
1973
-        EE_Registry::instance()->REQ->add_output($html);
1974
-        return true;
1975
-    }
1976
-
1977
-
1978
-    /**
1979
-     * _billing_form_is_valid
1980
-     *
1981
-     * @access private
1982
-     * @return bool
1983
-     * @throws \EE_Error
1984
-     */
1985
-    private function _billing_form_is_valid()
1986
-    {
1987
-        if (! $this->checkout->payment_method->type_obj()->has_billing_form()) {
1988
-            return true;
1989
-        }
1990
-        if ($this->checkout->billing_form instanceof EE_Billing_Info_Form) {
1991
-            if ($this->checkout->billing_form->was_submitted()) {
1992
-                $this->checkout->billing_form->receive_form_submission();
1993
-                if ($this->checkout->billing_form->is_valid()) {
1994
-                    return true;
1995
-                }
1996
-                $validation_errors = $this->checkout->billing_form->get_validation_errors_accumulated();
1997
-                $error_strings = array();
1998
-                foreach ($validation_errors as $validation_error) {
1999
-                    if ($validation_error instanceof EE_Validation_Error) {
2000
-                        $form_section = $validation_error->get_form_section();
2001
-                        if ($form_section instanceof EE_Form_Input_Base) {
2002
-                            $label = $form_section->html_label_text();
2003
-                        } elseif ($form_section instanceof EE_Form_Section_Base) {
2004
-                            $label = $form_section->name();
2005
-                        } else {
2006
-                            $label = esc_html__('Validation Error', 'event_espresso');
2007
-                        }
2008
-                        $error_strings[] = sprintf('%1$s: %2$s', $label, $validation_error->getMessage());
2009
-                    }
2010
-                }
2011
-                EE_Error::add_error(
2012
-                    sprintf(
2013
-                        esc_html__(
2014
-                            'One or more billing form inputs are invalid and require correction before proceeding. %1$s %2$s',
2015
-                            'event_espresso'
2016
-                        ),
2017
-                        '<br/>',
2018
-                        implode('<br/>', $error_strings)
2019
-                    ),
2020
-                    __FILE__,
2021
-                    __FUNCTION__,
2022
-                    __LINE__
2023
-                );
2024
-            } else {
2025
-                EE_Error::add_error(
2026
-                    esc_html__(
2027
-                        'The billing form was not submitted or something prevented it\'s submission.',
2028
-                        'event_espresso'
2029
-                    ),
2030
-                    __FILE__,
2031
-                    __FUNCTION__,
2032
-                    __LINE__
2033
-                );
2034
-            }
2035
-        } else {
2036
-            EE_Error::add_error(
2037
-                esc_html__(
2038
-                    'The submitted billing form is invalid possibly due to a technical reason.',
2039
-                    'event_espresso'
2040
-                ),
2041
-                __FILE__,
2042
-                __FUNCTION__,
2043
-                __LINE__
2044
-            );
2045
-        }
2046
-        return false;
2047
-    }
2048
-
2049
-
2050
-    /**
2051
-     * _setup_primary_registrant_prior_to_payment
2052
-     * ensures that the primary registrant has a valid attendee object created with the critical details populated
2053
-     * (first & last name & email) and that both the transaction object and primary registration object have been saved
2054
-     * plz note that any other registrations will NOT be saved at this point (because they may not have any details
2055
-     * yet)
2056
-     *
2057
-     * @access private
2058
-     * @return bool
2059
-     * @throws EE_Error
2060
-     * @throws InvalidArgumentException
2061
-     * @throws ReflectionException
2062
-     * @throws RuntimeException
2063
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2064
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2065
-     */
2066
-    private function _setup_primary_registrant_prior_to_payment()
2067
-    {
2068
-        // check if transaction has a primary registrant and that it has a related Attendee object
2069
-        // if not, then we need to at least gather some primary registrant data before attempting payment
2070
-        if ($this->checkout->billing_form instanceof EE_Billing_Attendee_Info_Form
2071
-            && ! $this->checkout->transaction_has_primary_registrant()
2072
-            && ! $this->_capture_primary_registration_data_from_billing_form()
2073
-        ) {
2074
-            return false;
2075
-        }
2076
-        // because saving an object clears it's cache, we need to do the chevy shuffle
2077
-        // grab the primary_registration object
2078
-        $primary_registration = $this->checkout->transaction->primary_registration();
2079
-        // at this point we'll consider a TXN to not have been failed
2080
-        $this->checkout->transaction->toggle_failed_transaction_status();
2081
-        // save the TXN ( which clears cached copy of primary_registration)
2082
-        $this->checkout->transaction->save();
2083
-        // grab TXN ID and save it to the primary_registration
2084
-        $primary_registration->set_transaction_id($this->checkout->transaction->ID());
2085
-        // save what we have so far
2086
-        $primary_registration->save();
2087
-        return true;
2088
-    }
2089
-
2090
-
2091
-    /**
2092
-     * _capture_primary_registration_data_from_billing_form
2093
-     *
2094
-     * @access private
2095
-     * @return bool
2096
-     * @throws EE_Error
2097
-     * @throws InvalidArgumentException
2098
-     * @throws ReflectionException
2099
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2100
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2101
-     */
2102
-    private function _capture_primary_registration_data_from_billing_form()
2103
-    {
2104
-        // convert billing form data into an attendee
2105
-        $this->checkout->primary_attendee_obj = $this->checkout->billing_form->create_attendee_from_billing_form_data();
2106
-        if (! $this->checkout->primary_attendee_obj instanceof EE_Attendee) {
2107
-            EE_Error::add_error(
2108
-                sprintf(
2109
-                    esc_html__(
2110
-                        'The billing form details could not be used for attendee details due to a technical issue.%sPlease try again or contact %s for assistance.',
2111
-                        'event_espresso'
2112
-                    ),
2113
-                    '<br/>',
2114
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
2115
-                ),
2116
-                __FILE__,
2117
-                __FUNCTION__,
2118
-                __LINE__
2119
-            );
2120
-            return false;
2121
-        }
2122
-        $primary_registration = $this->checkout->transaction->primary_registration();
2123
-        if (! $primary_registration instanceof EE_Registration) {
2124
-            EE_Error::add_error(
2125
-                sprintf(
2126
-                    esc_html__(
2127
-                        'The primary registrant for this transaction could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.',
2128
-                        'event_espresso'
2129
-                    ),
2130
-                    '<br/>',
2131
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
2132
-                ),
2133
-                __FILE__,
2134
-                __FUNCTION__,
2135
-                __LINE__
2136
-            );
2137
-            return false;
2138
-        }
2139
-        if (! $primary_registration->_add_relation_to($this->checkout->primary_attendee_obj, 'Attendee')
2140
-              instanceof
2141
-              EE_Attendee
2142
-        ) {
2143
-            EE_Error::add_error(
2144
-                sprintf(
2145
-                    esc_html__(
2146
-                        'The primary registrant could not be associated with this transaction due to a technical issue.%sPlease try again or contact %s for assistance.',
2147
-                        'event_espresso'
2148
-                    ),
2149
-                    '<br/>',
2150
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
2151
-                ),
2152
-                __FILE__,
2153
-                __FUNCTION__,
2154
-                __LINE__
2155
-            );
2156
-            return false;
2157
-        }
2158
-        /** @type EE_Registration_Processor $registration_processor */
2159
-        $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
2160
-        // at this point, we should have enough details about the registrant to consider the registration NOT incomplete
2161
-        $registration_processor->toggle_incomplete_registration_status_to_default($primary_registration);
2162
-        return true;
2163
-    }
2164
-
2165
-
2166
-    /**
2167
-     * _get_payment_method_for_selected_method_of_payment
2168
-     * retrieves a valid payment method
2169
-     *
2170
-     * @access public
2171
-     * @return EE_Payment_Method
2172
-     * @throws EE_Error
2173
-     * @throws InvalidArgumentException
2174
-     * @throws ReflectionException
2175
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2176
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2177
-     */
2178
-    private function _get_payment_method_for_selected_method_of_payment()
2179
-    {
2180
-        if ($this->checkout->selected_method_of_payment === 'events_sold_out') {
2181
-            $this->_redirect_because_event_sold_out();
2182
-            return null;
2183
-        }
2184
-        // get EE_Payment_Method object
2185
-        if (isset($this->checkout->available_payment_methods[ $this->checkout->selected_method_of_payment ])) {
2186
-            $payment_method = $this->checkout->available_payment_methods[ $this->checkout->selected_method_of_payment ];
2187
-        } else {
2188
-            // load EEM_Payment_Method
2189
-            EE_Registry::instance()->load_model('Payment_Method');
2190
-            /** @type EEM_Payment_Method $EEM_Payment_Method */
2191
-            $EEM_Payment_Method = EE_Registry::instance()->LIB->EEM_Payment_Method;
2192
-            $payment_method = $EEM_Payment_Method->get_one_by_slug($this->checkout->selected_method_of_payment);
2193
-        }
2194
-        // verify $payment_method
2195
-        if (! $payment_method instanceof EE_Payment_Method) {
2196
-            // not a payment
2197
-            EE_Error::add_error(
2198
-                sprintf(
2199
-                    esc_html__(
2200
-                        'The selected method of payment could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.',
2201
-                        'event_espresso'
2202
-                    ),
2203
-                    '<br/>',
2204
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
2205
-                ),
2206
-                __FILE__,
2207
-                __FUNCTION__,
2208
-                __LINE__
2209
-            );
2210
-            return null;
2211
-        }
2212
-        // and verify it has a valid Payment_Method Type object
2213
-        if (! $payment_method->type_obj() instanceof EE_PMT_Base) {
2214
-            // not a payment
2215
-            EE_Error::add_error(
2216
-                sprintf(
2217
-                    esc_html__(
2218
-                        'A valid payment method could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.',
2219
-                        'event_espresso'
2220
-                    ),
2221
-                    '<br/>',
2222
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
2223
-                ),
2224
-                __FILE__,
2225
-                __FUNCTION__,
2226
-                __LINE__
2227
-            );
2228
-            return null;
2229
-        }
2230
-        return $payment_method;
2231
-    }
2232
-
2233
-
2234
-    /**
2235
-     *    _attempt_payment
2236
-     *
2237
-     * @access    private
2238
-     * @type    EE_Payment_Method $payment_method
2239
-     * @return mixed EE_Payment | boolean
2240
-     * @throws EE_Error
2241
-     * @throws InvalidArgumentException
2242
-     * @throws ReflectionException
2243
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2244
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2245
-     */
2246
-    private function _attempt_payment(EE_Payment_Method $payment_method)
2247
-    {
2248
-        $payment = null;
2249
-        $this->checkout->transaction->save();
2250
-        $payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2251
-        if (! $payment_processor instanceof EE_Payment_Processor) {
2252
-            return false;
2253
-        }
2254
-        try {
2255
-            $payment_processor->set_revisit($this->checkout->revisit);
2256
-            // generate payment object
2257
-            $payment = $payment_processor->process_payment(
2258
-                $payment_method,
2259
-                $this->checkout->transaction,
2260
-                $this->checkout->amount_owing,
2261
-                $this->checkout->billing_form,
2262
-                $this->_get_return_url($payment_method),
2263
-                'CART',
2264
-                $this->checkout->admin_request,
2265
-                true,
2266
-                $this->reg_step_url()
2267
-            );
2268
-        } catch (Exception $e) {
2269
-            $this->_handle_payment_processor_exception($e);
2270
-        }
2271
-        return $payment;
2272
-    }
2273
-
2274
-
2275
-    /**
2276
-     * _handle_payment_processor_exception
2277
-     *
2278
-     * @access protected
2279
-     * @param \Exception $e
2280
-     * @return void
2281
-     * @throws EE_Error
2282
-     * @throws InvalidArgumentException
2283
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2284
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2285
-     */
2286
-    protected function _handle_payment_processor_exception(Exception $e)
2287
-    {
2288
-        EE_Error::add_error(
2289
-            sprintf(
2290
-                esc_html__(
2291
-                    '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',
2292
-                    'event_espresso'
2293
-                ),
2294
-                '<br/>',
2295
-                EE_Registry::instance()->CFG->organization->get_pretty('email'),
2296
-                $e->getMessage(),
2297
-                $e->getFile(),
2298
-                $e->getLine()
2299
-            ),
2300
-            __FILE__,
2301
-            __FUNCTION__,
2302
-            __LINE__
2303
-        );
2304
-    }
2305
-
2306
-
2307
-    /**
2308
-     * _get_return_url
2309
-     *
2310
-     * @access protected
2311
-     * @param \EE_Payment_Method $payment_method
2312
-     * @return string
2313
-     * @throws \EE_Error
2314
-     */
2315
-    protected function _get_return_url(EE_Payment_Method $payment_method)
2316
-    {
2317
-        $return_url = '';
2318
-        switch ($payment_method->type_obj()->payment_occurs()) {
2319
-            case EE_PMT_Base::offsite:
2320
-                $return_url = add_query_arg(
2321
-                    array(
2322
-                        'action'                     => 'process_gateway_response',
2323
-                        'selected_method_of_payment' => $this->checkout->selected_method_of_payment,
2324
-                        'spco_txn'                   => $this->checkout->transaction->ID(),
2325
-                    ),
2326
-                    $this->reg_step_url()
2327
-                );
2328
-                break;
2329
-            case EE_PMT_Base::onsite:
2330
-            case EE_PMT_Base::offline:
2331
-                $return_url = $this->checkout->next_step->reg_step_url();
2332
-                break;
2333
-        }
2334
-        return $return_url;
2335
-    }
2336
-
2337
-
2338
-    /**
2339
-     * _validate_payment
2340
-     *
2341
-     * @access private
2342
-     * @param EE_Payment $payment
2343
-     * @return EE_Payment|FALSE
2344
-     * @throws EE_Error
2345
-     * @throws InvalidArgumentException
2346
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2347
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2348
-     */
2349
-    private function _validate_payment($payment = null)
2350
-    {
2351
-        if ($this->checkout->payment_method->is_off_line()) {
2352
-            return true;
2353
-        }
2354
-        // verify payment object
2355
-        if (! $payment instanceof EE_Payment) {
2356
-            // not a payment
2357
-            EE_Error::add_error(
2358
-                sprintf(
2359
-                    esc_html__(
2360
-                        'A valid payment was not generated due to a technical issue.%1$sPlease try again or contact %2$s for assistance.',
2361
-                        'event_espresso'
2362
-                    ),
2363
-                    '<br/>',
2364
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
2365
-                ),
2366
-                __FILE__,
2367
-                __FUNCTION__,
2368
-                __LINE__
2369
-            );
2370
-            return false;
2371
-        }
2372
-        return $payment;
2373
-    }
2374
-
2375
-
2376
-    /**
2377
-     * _post_payment_processing
2378
-     *
2379
-     * @access private
2380
-     * @param EE_Payment|bool $payment
2381
-     * @return bool
2382
-     * @throws EE_Error
2383
-     * @throws InvalidArgumentException
2384
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2385
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2386
-     */
2387
-    private function _post_payment_processing($payment = null)
2388
-    {
2389
-        // Off-Line payment?
2390
-        if ($payment === true) {
2391
-            // $this->_setup_redirect_for_next_step();
2392
-            return true;
2393
-            // On-Site payment?
2394
-        } elseif ($this->checkout->payment_method->is_on_site()) {
2395
-            if (! $this->_process_payment_status($payment, EE_PMT_Base::onsite)) {
2396
-                // $this->_setup_redirect_for_next_step();
2397
-                $this->checkout->continue_reg = false;
2398
-            }
2399
-            // Off-Site payment?
2400
-        } elseif ($this->checkout->payment_method->is_off_site()) {
2401
-            // if a payment object was made and it specifies a redirect url, then we'll setup that redirect info
2402
-            if ($payment instanceof EE_Payment && $payment->redirect_url()) {
2403
-                do_action('AHEE_log', __CLASS__, __FUNCTION__, $payment->redirect_url(), '$payment->redirect_url()');
2404
-                $this->checkout->redirect = true;
2405
-                $this->checkout->redirect_form = $payment->redirect_form();
2406
-                $this->checkout->redirect_url = $this->reg_step_url('redirect_form');
2407
-                // set JSON response
2408
-                $this->checkout->json_response->set_redirect_form($this->checkout->redirect_form);
2409
-                // and lastly, let's bump the payment status to pending
2410
-                $payment->set_status(EEM_Payment::status_id_pending);
2411
-                $payment->save();
2412
-            } else {
2413
-                // not a payment
2414
-                $this->checkout->continue_reg = false;
2415
-                EE_Error::add_error(
2416
-                    sprintf(
2417
-                        esc_html__(
2418
-                            'It appears the Off Site Payment Method was not configured properly.%sPlease try again or contact %s for assistance.',
2419
-                            'event_espresso'
2420
-                        ),
2421
-                        '<br/>',
2422
-                        EE_Registry::instance()->CFG->organization->get_pretty('email')
2423
-                    ),
2424
-                    __FILE__,
2425
-                    __FUNCTION__,
2426
-                    __LINE__
2427
-                );
2428
-            }
2429
-        } else {
2430
-            // ummm ya... not Off-Line, not On-Site, not off-Site ????
2431
-            $this->checkout->continue_reg = false;
2432
-            return false;
2433
-        }
2434
-        return $payment;
2435
-    }
2436
-
2437
-
2438
-    /**
2439
-     *    _process_payment_status
2440
-     *
2441
-     * @access private
2442
-     * @type    EE_Payment $payment
2443
-     * @param string       $payment_occurs
2444
-     * @return bool
2445
-     * @throws EE_Error
2446
-     * @throws InvalidArgumentException
2447
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2448
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2449
-     */
2450
-    private function _process_payment_status($payment, $payment_occurs = EE_PMT_Base::offline)
2451
-    {
2452
-        // off-line payment? carry on
2453
-        if ($payment_occurs === EE_PMT_Base::offline) {
2454
-            return true;
2455
-        }
2456
-        // verify payment validity
2457
-        if ($payment instanceof EE_Payment) {
2458
-            do_action('AHEE_log', __CLASS__, __FUNCTION__, $payment->status(), '$payment->status()');
2459
-            $msg = $payment->gateway_response();
2460
-            // check results
2461
-            switch ($payment->status()) {
2462
-                // good payment
2463
-                case EEM_Payment::status_id_approved:
2464
-                    EE_Error::add_success(
2465
-                        esc_html__('Your payment was processed successfully.', 'event_espresso'),
2466
-                        __FILE__,
2467
-                        __FUNCTION__,
2468
-                        __LINE__
2469
-                    );
2470
-                    return true;
2471
-                    break;
2472
-                // slow payment
2473
-                case EEM_Payment::status_id_pending:
2474
-                    if (empty($msg)) {
2475
-                        $msg = esc_html__(
2476
-                            'Your payment appears to have been processed successfully, but the Instant Payment Notification has not yet been received. It should arrive shortly.',
2477
-                            'event_espresso'
2478
-                        );
2479
-                    }
2480
-                    EE_Error::add_success($msg, __FILE__, __FUNCTION__, __LINE__);
2481
-                    return true;
2482
-                    break;
2483
-                // don't wanna payment
2484
-                case EEM_Payment::status_id_cancelled:
2485
-                    if (empty($msg)) {
2486
-                        $msg = _n(
2487
-                            'Payment cancelled. Please try again.',
2488
-                            'Payment cancelled. Please try again or select another method of payment.',
2489
-                            count($this->checkout->available_payment_methods),
2490
-                            'event_espresso'
2491
-                        );
2492
-                    }
2493
-                    EE_Error::add_attention($msg, __FILE__, __FUNCTION__, __LINE__);
2494
-                    return false;
2495
-                    break;
2496
-                // not enough payment
2497
-                case EEM_Payment::status_id_declined:
2498
-                    if (empty($msg)) {
2499
-                        $msg = _n(
2500
-                            'We\'re sorry but your payment was declined. Please try again.',
2501
-                            'We\'re sorry but your payment was declined. Please try again or select another method of payment.',
2502
-                            count($this->checkout->available_payment_methods),
2503
-                            'event_espresso'
2504
-                        );
2505
-                    }
2506
-                    EE_Error::add_attention($msg, __FILE__, __FUNCTION__, __LINE__);
2507
-                    return false;
2508
-                    break;
2509
-                // bad payment
2510
-                case EEM_Payment::status_id_failed:
2511
-                    if (! empty($msg)) {
2512
-                        EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2513
-                        return false;
2514
-                    }
2515
-                    // default to error below
2516
-                    break;
2517
-            }
2518
-        }
2519
-        // off-site payment gateway responses are too unreliable, so let's just assume that
2520
-        // the payment processing is just running slower than the registrant's request
2521
-        if ($payment_occurs === EE_PMT_Base::offsite) {
2522
-            return true;
2523
-        }
2524
-        EE_Error::add_error(
2525
-            sprintf(
2526
-                esc_html__(
2527
-                    'Your payment could not be processed successfully due to a technical issue.%sPlease try again or contact %s for assistance.',
2528
-                    'event_espresso'
2529
-                ),
2530
-                '<br/>',
2531
-                EE_Registry::instance()->CFG->organization->get_pretty('email')
2532
-            ),
2533
-            __FILE__,
2534
-            __FUNCTION__,
2535
-            __LINE__
2536
-        );
2537
-        return false;
2538
-    }
2539
-
2540
-
2541
-
2542
-
2543
-
2544
-
2545
-    /********************************************************************************************************/
2546
-    /**********************************  PROCESS GATEWAY RESPONSE  **********************************/
2547
-    /********************************************************************************************************/
2548
-    /**
2549
-     * process_gateway_response
2550
-     * this is the return point for Off-Site Payment Methods
2551
-     * It will attempt to "handle the IPN" if it appears that this has not already occurred,
2552
-     * otherwise, it will load up the last payment made for the TXN.
2553
-     * If the payment retrieved looks good, it will then either:
2554
-     *    complete the current step and allow advancement to the next reg step
2555
-     *        or present the payment options again
2556
-     *
2557
-     * @access private
2558
-     * @return EE_Payment|FALSE
2559
-     * @throws EE_Error
2560
-     * @throws InvalidArgumentException
2561
-     * @throws ReflectionException
2562
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2563
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2564
-     * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
2565
-     */
2566
-    public function process_gateway_response()
2567
-    {
2568
-        $payment = null;
2569
-        // how have they chosen to pay?
2570
-        $this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
2571
-        // get EE_Payment_Method object
2572
-        if (! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()) {
2573
-            $this->checkout->continue_reg = false;
2574
-            return false;
2575
-        }
2576
-        if (! $this->checkout->payment_method->is_off_site()) {
2577
-            return false;
2578
-        }
2579
-        $this->_validate_offsite_return();
2580
-        // DEBUG LOG
2581
-        // $this->checkout->log(
2582
-        //     __CLASS__,
2583
-        //     __FUNCTION__,
2584
-        //     __LINE__,
2585
-        //     array(
2586
-        //         'selected_method_of_payment' => $this->checkout->selected_method_of_payment,
2587
-        //         'payment_method'             => $this->checkout->payment_method,
2588
-        //     ),
2589
-        //     true
2590
-        // );
2591
-        // verify TXN
2592
-        if ($this->checkout->transaction instanceof EE_Transaction) {
2593
-            $gateway = $this->checkout->payment_method->type_obj()->get_gateway();
2594
-            if (! $gateway instanceof EE_Offsite_Gateway) {
2595
-                $this->checkout->continue_reg = false;
2596
-                return false;
2597
-            }
2598
-            $payment = $this->_process_off_site_payment($gateway);
2599
-            $payment = $this->_process_cancelled_payments($payment);
2600
-            $payment = $this->_validate_payment($payment);
2601
-            // if payment was not declined by the payment gateway or cancelled by the registrant
2602
-            if ($this->_process_payment_status($payment, EE_PMT_Base::offsite)) {
2603
-                // $this->_setup_redirect_for_next_step();
2604
-                // store that for later
2605
-                $this->checkout->payment = $payment;
2606
-                // mark this reg step as completed, as long as gateway doesn't use a separate IPN request,
2607
-                // because we will complete this step during the IPN processing then
2608
-                if ($gateway instanceof EE_Offsite_Gateway && ! $this->handle_IPN_in_this_request()) {
2609
-                    $this->set_completed();
2610
-                }
2611
-                return true;
2612
-            }
2613
-        }
2614
-        // DEBUG LOG
2615
-        // $this->checkout->log(
2616
-        //     __CLASS__,
2617
-        //     __FUNCTION__,
2618
-        //     __LINE__,
2619
-        //     array('payment' => $payment)
2620
-        // );
2621
-        $this->checkout->continue_reg = false;
2622
-        return false;
2623
-    }
2624
-
2625
-
2626
-    /**
2627
-     * _validate_return
2628
-     *
2629
-     * @access private
2630
-     * @return void
2631
-     * @throws EE_Error
2632
-     * @throws InvalidArgumentException
2633
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2634
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2635
-     * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
2636
-     */
2637
-    private function _validate_offsite_return()
2638
-    {
2639
-        $TXN_ID = (int) EE_Registry::instance()->REQ->get('spco_txn', 0);
2640
-        if ($TXN_ID !== $this->checkout->transaction->ID()) {
2641
-            // Houston... we might have a problem
2642
-            $invalid_TXN = false;
2643
-            // first gather some info
2644
-            $valid_TXN = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
2645
-            $primary_registrant = $valid_TXN instanceof EE_Transaction
2646
-                ? $valid_TXN->primary_registration()
2647
-                : null;
2648
-            // let's start by retrieving the cart for this TXN
2649
-            $cart = $this->checkout->get_cart_for_transaction($this->checkout->transaction);
2650
-            if ($cart instanceof EE_Cart) {
2651
-                // verify that the current cart has tickets
2652
-                $tickets = $cart->get_tickets();
2653
-                if (empty($tickets)) {
2654
-                    $invalid_TXN = true;
2655
-                }
2656
-            } else {
2657
-                $invalid_TXN = true;
2658
-            }
2659
-            $valid_TXN_SID = $primary_registrant instanceof EE_Registration
2660
-                ? $primary_registrant->session_ID()
2661
-                : null;
2662
-            // validate current Session ID and compare against valid TXN session ID
2663
-            if ($invalid_TXN // if this is already true, then skip other checks
2664
-                || EE_Session::instance()->id() === null
2665
-                || (
2666
-                    // WARNING !!!
2667
-                    // this could be PayPal sending back duplicate requests (ya they do that)
2668
-                    // or it **could** mean someone is simply registering AGAIN after having just done so
2669
-                    // so now we need to determine if this current TXN looks valid or not
2670
-                    // and whether this reg step has even been started ?
2671
-                    EE_Session::instance()->id() === $valid_TXN_SID
2672
-                    // really? you're half way through this reg step, but you never started it ?
2673
-                    && $this->checkout->transaction->reg_step_completed($this->slug()) === false
2674
-                )
2675
-            ) {
2676
-                $invalid_TXN = true;
2677
-            }
2678
-            if ($invalid_TXN) {
2679
-                // is the valid TXN completed ?
2680
-                if ($valid_TXN instanceof EE_Transaction) {
2681
-                    // has this step even been started ?
2682
-                    $reg_step_completed = $valid_TXN->reg_step_completed($this->slug());
2683
-                    if ($reg_step_completed !== false && $reg_step_completed !== true) {
2684
-                        // so it **looks** like this is a double request from PayPal
2685
-                        // so let's try to pick up where we left off
2686
-                        $this->checkout->transaction = $valid_TXN;
2687
-                        $this->checkout->refresh_all_entities(true);
2688
-                        return;
2689
-                    }
2690
-                }
2691
-                // you appear to be lost?
2692
-                $this->_redirect_wayward_request($primary_registrant);
2693
-            }
2694
-        }
2695
-    }
2696
-
2697
-
2698
-    /**
2699
-     * _redirect_wayward_request
2700
-     *
2701
-     * @access private
2702
-     * @param \EE_Registration|null $primary_registrant
2703
-     * @return bool
2704
-     * @throws EE_Error
2705
-     * @throws InvalidArgumentException
2706
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2707
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2708
-     */
2709
-    private function _redirect_wayward_request(EE_Registration $primary_registrant)
2710
-    {
2711
-        if (! $primary_registrant instanceof EE_Registration) {
2712
-            // try redirecting based on the current TXN
2713
-            $primary_registrant = $this->checkout->transaction instanceof EE_Transaction
2714
-                ? $this->checkout->transaction->primary_registration()
2715
-                : null;
2716
-        }
2717
-        if (! $primary_registrant instanceof EE_Registration) {
2718
-            EE_Error::add_error(
2719
-                sprintf(
2720
-                    esc_html__(
2721
-                        '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.',
2722
-                        'event_espresso'
2723
-                    ),
2724
-                    '<br/>',
2725
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
2726
-                ),
2727
-                __FILE__,
2728
-                __FUNCTION__,
2729
-                __LINE__
2730
-            );
2731
-            return false;
2732
-        }
2733
-        // make sure transaction is not locked
2734
-        $this->checkout->transaction->unlock();
2735
-        wp_safe_redirect(
2736
-            add_query_arg(
2737
-                array(
2738
-                    'e_reg_url_link' => $primary_registrant->reg_url_link(),
2739
-                ),
2740
-                $this->checkout->thank_you_page_url
2741
-            )
2742
-        );
2743
-        exit();
2744
-    }
2745
-
2746
-
2747
-    /**
2748
-     * _process_off_site_payment
2749
-     *
2750
-     * @access private
2751
-     * @param \EE_Offsite_Gateway $gateway
2752
-     * @return EE_Payment
2753
-     * @throws EE_Error
2754
-     * @throws InvalidArgumentException
2755
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2756
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2757
-     */
2758
-    private function _process_off_site_payment(EE_Offsite_Gateway $gateway)
2759
-    {
2760
-        try {
2761
-            $request_data = \EE_Registry::instance()->REQ->params();
2762
-            // if gateway uses_separate_IPN_request, then we don't have to process the IPN manually
2763
-            $this->set_handle_IPN_in_this_request(
2764
-                $gateway->handle_IPN_in_this_request($request_data, false)
2765
-            );
2766
-            if ($this->handle_IPN_in_this_request()) {
2767
-                // get payment details and process results
2768
-                /** @type EE_Payment_Processor $payment_processor */
2769
-                $payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2770
-                $payment = $payment_processor->process_ipn(
2771
-                    $request_data,
2772
-                    $this->checkout->transaction,
2773
-                    $this->checkout->payment_method,
2774
-                    true,
2775
-                    false
2776
-                );
2777
-                // $payment_source = 'process_ipn';
2778
-            } else {
2779
-                $payment = $this->checkout->transaction->last_payment();
2780
-                // $payment_source = 'last_payment';
2781
-            }
2782
-        } catch (Exception $e) {
2783
-            // let's just eat the exception and try to move on using any previously set payment info
2784
-            $payment = $this->checkout->transaction->last_payment();
2785
-            // $payment_source = 'last_payment after Exception';
2786
-            // but if we STILL don't have a payment object
2787
-            if (! $payment instanceof EE_Payment) {
2788
-                // then we'll object ! ( not object like a thing... but object like what a lawyer says ! )
2789
-                $this->_handle_payment_processor_exception($e);
2790
-            }
2791
-        }
2792
-        // DEBUG LOG
2793
-        // $this->checkout->log(
2794
-        //     __CLASS__,
2795
-        //     __FUNCTION__,
2796
-        //     __LINE__,
2797
-        //     array(
2798
-        //         'process_ipn_payment' => $payment,
2799
-        //         'payment_source'      => $payment_source,
2800
-        //     )
2801
-        // );
2802
-        return $payment;
2803
-    }
2804
-
2805
-
2806
-    /**
2807
-     * _process_cancelled_payments
2808
-     * just makes sure that the payment status gets updated correctly
2809
-     * so tha tan error isn't generated during payment validation
2810
-     *
2811
-     * @access private
2812
-     * @param EE_Payment $payment
2813
-     * @return EE_Payment | FALSE
2814
-     * @throws \EE_Error
2815
-     */
2816
-    private function _process_cancelled_payments($payment = null)
2817
-    {
2818
-        if ($payment instanceof EE_Payment
2819
-            && isset($_REQUEST['ee_cancel_payment'])
2820
-            && $payment->status() === EEM_Payment::status_id_failed
2821
-        ) {
2822
-            $payment->set_status(EEM_Payment::status_id_cancelled);
2823
-        }
2824
-        return $payment;
2825
-    }
2826
-
2827
-
2828
-    /**
2829
-     *    get_transaction_details_for_gateways
2830
-     *
2831
-     * @access    public
2832
-     * @return int
2833
-     * @throws EE_Error
2834
-     * @throws InvalidArgumentException
2835
-     * @throws ReflectionException
2836
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2837
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2838
-     */
2839
-    public function get_transaction_details_for_gateways()
2840
-    {
2841
-        $txn_details = array();
2842
-        // ya gotta make a choice man
2843
-        if (empty($this->checkout->selected_method_of_payment)) {
2844
-            $txn_details = array(
2845
-                'error' => esc_html__('Please select a method of payment before proceeding.', 'event_espresso'),
2846
-            );
2847
-        }
2848
-        // get EE_Payment_Method object
2849
-        if (empty($txn_details)
2850
-            &&
2851
-            ! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()
2852
-        ) {
2853
-            $txn_details = array(
2854
-                'selected_method_of_payment' => $this->checkout->selected_method_of_payment,
2855
-                'error'                      => esc_html__(
2856
-                    'A valid Payment Method could not be determined.',
2857
-                    'event_espresso'
2858
-                ),
2859
-            );
2860
-        }
2861
-        if (empty($txn_details) && $this->checkout->transaction instanceof EE_Transaction) {
2862
-            $return_url = $this->_get_return_url($this->checkout->payment_method);
2863
-            $txn_details = array(
2864
-                'TXN_ID'         => $this->checkout->transaction->ID(),
2865
-                'TXN_timestamp'  => $this->checkout->transaction->datetime(),
2866
-                'TXN_total'      => $this->checkout->transaction->total(),
2867
-                'TXN_paid'       => $this->checkout->transaction->paid(),
2868
-                'TXN_reg_steps'  => $this->checkout->transaction->reg_steps(),
2869
-                'STS_ID'         => $this->checkout->transaction->status_ID(),
2870
-                'PMD_ID'         => $this->checkout->transaction->payment_method_ID(),
2871
-                'payment_amount' => $this->checkout->amount_owing,
2872
-                'return_url'     => $return_url,
2873
-                'cancel_url'     => add_query_arg(array('ee_cancel_payment' => true), $return_url),
2874
-                'notify_url'     => EE_Config::instance()->core->txn_page_url(
2875
-                    array(
2876
-                        'e_reg_url_link'    => $this->checkout->transaction->primary_registration()->reg_url_link(),
2877
-                        'ee_payment_method' => $this->checkout->payment_method->slug(),
2878
-                    )
2879
-                ),
2880
-            );
2881
-        }
2882
-        echo wp_json_encode($txn_details);
2883
-        exit();
2884
-    }
2885
-
2886
-
2887
-    /**
2888
-     *    __sleep
2889
-     * to conserve db space, let's remove the reg_form and the EE_Checkout object from EE_SPCO_Reg_Step objects upon
2890
-     * serialization EE_Checkout will handle the reimplementation of itself upon waking, but we won't bother with the
2891
-     * reg form, because if needed, it will be regenerated anyways
2892
-     *
2893
-     * @return array
2894
-     */
2895
-    public function __sleep()
2896
-    {
2897
-        // remove the reg form and the checkout
2898
-        return array_diff(array_keys(get_object_vars($this)), array('reg_form', 'checkout', 'line_item_display'));
2899
-    }
15
+	/**
16
+	 * @access protected
17
+	 * @var EE_Line_Item_Display $Line_Item_Display
18
+	 */
19
+	protected $line_item_display;
20
+
21
+	/**
22
+	 * @access protected
23
+	 * @var boolean $handle_IPN_in_this_request
24
+	 */
25
+	protected $handle_IPN_in_this_request = false;
26
+
27
+
28
+	/**
29
+	 *    set_hooks - for hooking into EE Core, other modules, etc
30
+	 *
31
+	 * @access    public
32
+	 * @return    void
33
+	 */
34
+	public static function set_hooks()
35
+	{
36
+		add_filter(
37
+			'FHEE__SPCO__EE_Line_Item_Filter_Collection',
38
+			array('EE_SPCO_Reg_Step_Payment_Options', 'add_spco_line_item_filters')
39
+		);
40
+		add_action(
41
+			'wp_ajax_switch_spco_billing_form',
42
+			array('EE_SPCO_Reg_Step_Payment_Options', 'switch_spco_billing_form')
43
+		);
44
+		add_action(
45
+			'wp_ajax_nopriv_switch_spco_billing_form',
46
+			array('EE_SPCO_Reg_Step_Payment_Options', 'switch_spco_billing_form')
47
+		);
48
+		add_action('wp_ajax_save_payer_details', array('EE_SPCO_Reg_Step_Payment_Options', 'save_payer_details'));
49
+		add_action(
50
+			'wp_ajax_nopriv_save_payer_details',
51
+			array('EE_SPCO_Reg_Step_Payment_Options', 'save_payer_details')
52
+		);
53
+		add_action(
54
+			'wp_ajax_get_transaction_details_for_gateways',
55
+			array('EE_SPCO_Reg_Step_Payment_Options', 'get_transaction_details')
56
+		);
57
+		add_action(
58
+			'wp_ajax_nopriv_get_transaction_details_for_gateways',
59
+			array('EE_SPCO_Reg_Step_Payment_Options', 'get_transaction_details')
60
+		);
61
+		add_filter(
62
+			'FHEE__EED_Recaptcha___bypass_recaptcha__bypass_request_params_array',
63
+			array('EE_SPCO_Reg_Step_Payment_Options', 'bypass_recaptcha_for_load_payment_method'),
64
+			10,
65
+			1
66
+		);
67
+	}
68
+
69
+
70
+	/**
71
+	 *    ajax switch_spco_billing_form
72
+	 *
73
+	 * @throws \EE_Error
74
+	 */
75
+	public static function switch_spco_billing_form()
76
+	{
77
+		EED_Single_Page_Checkout::process_ajax_request('switch_payment_method');
78
+	}
79
+
80
+
81
+	/**
82
+	 *    ajax save_payer_details
83
+	 *
84
+	 * @throws \EE_Error
85
+	 */
86
+	public static function save_payer_details()
87
+	{
88
+		EED_Single_Page_Checkout::process_ajax_request('save_payer_details_via_ajax');
89
+	}
90
+
91
+
92
+	/**
93
+	 *    ajax get_transaction_details
94
+	 *
95
+	 * @throws \EE_Error
96
+	 */
97
+	public static function get_transaction_details()
98
+	{
99
+		EED_Single_Page_Checkout::process_ajax_request('get_transaction_details_for_gateways');
100
+	}
101
+
102
+
103
+	/**
104
+	 * bypass_recaptcha_for_load_payment_method
105
+	 *
106
+	 * @access public
107
+	 * @return array
108
+	 * @throws InvalidArgumentException
109
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
110
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
111
+	 */
112
+	public static function bypass_recaptcha_for_load_payment_method()
113
+	{
114
+		return array(
115
+			'EESID'  => EE_Registry::instance()->SSN->id(),
116
+			'step'   => 'payment_options',
117
+			'action' => 'spco_billing_form',
118
+		);
119
+	}
120
+
121
+
122
+	/**
123
+	 *    class constructor
124
+	 *
125
+	 * @access    public
126
+	 * @param    EE_Checkout $checkout
127
+	 */
128
+	public function __construct(EE_Checkout $checkout)
129
+	{
130
+		$this->_slug = 'payment_options';
131
+		$this->_name = esc_html__('Payment Options', 'event_espresso');
132
+		$this->_template = SPCO_REG_STEPS_PATH . $this->_slug . DS . 'payment_options_main.template.php';
133
+		$this->checkout = $checkout;
134
+		$this->_reset_success_message();
135
+		$this->set_instructions(
136
+			esc_html__(
137
+				'Please select a method of payment and provide any necessary billing information before proceeding.',
138
+				'event_espresso'
139
+			)
140
+		);
141
+	}
142
+
143
+
144
+	/**
145
+	 * @return null
146
+	 */
147
+	public function line_item_display()
148
+	{
149
+		return $this->line_item_display;
150
+	}
151
+
152
+
153
+	/**
154
+	 * @param null $line_item_display
155
+	 */
156
+	public function set_line_item_display($line_item_display)
157
+	{
158
+		$this->line_item_display = $line_item_display;
159
+	}
160
+
161
+
162
+	/**
163
+	 * @return boolean
164
+	 */
165
+	public function handle_IPN_in_this_request()
166
+	{
167
+		return $this->handle_IPN_in_this_request;
168
+	}
169
+
170
+
171
+	/**
172
+	 * @param boolean $handle_IPN_in_this_request
173
+	 */
174
+	public function set_handle_IPN_in_this_request($handle_IPN_in_this_request)
175
+	{
176
+		$this->handle_IPN_in_this_request = filter_var($handle_IPN_in_this_request, FILTER_VALIDATE_BOOLEAN);
177
+	}
178
+
179
+
180
+	/**
181
+	 * translate_js_strings
182
+	 *
183
+	 * @return void
184
+	 */
185
+	public function translate_js_strings()
186
+	{
187
+		EE_Registry::$i18n_js_strings['no_payment_method'] = esc_html__(
188
+			'Please select a method of payment in order to continue.',
189
+			'event_espresso'
190
+		);
191
+		EE_Registry::$i18n_js_strings['invalid_payment_method'] = esc_html__(
192
+			'A valid method of payment could not be determined. Please refresh the page and try again.',
193
+			'event_espresso'
194
+		);
195
+		EE_Registry::$i18n_js_strings['forwarding_to_offsite'] = esc_html__(
196
+			'Forwarding to Secure Payment Provider.',
197
+			'event_espresso'
198
+		);
199
+	}
200
+
201
+
202
+	/**
203
+	 * enqueue_styles_and_scripts
204
+	 *
205
+	 * @return void
206
+	 * @throws EE_Error
207
+	 * @throws InvalidArgumentException
208
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
209
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
210
+	 */
211
+	public function enqueue_styles_and_scripts()
212
+	{
213
+		$transaction = $this->checkout->transaction;
214
+		// if the transaction isn't set or nothing is owed on it, don't enqueue any JS
215
+		if (! $transaction instanceof EE_Transaction || EEH_Money::compare_floats($transaction->remaining(), 0)) {
216
+			return;
217
+		}
218
+		foreach (EEM_Payment_Method::instance()->get_all_for_transaction(
219
+			$transaction,
220
+			EEM_Payment_Method::scope_cart
221
+		) 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
+				if ($registration->event()->is_sold_out() || $registration->event()->is_sold_out(true)) {
309
+					$sold_out_events[ $registration->event()->ID() ] = $registration->event();
310
+				} else {
311
+					$insufficient_spaces_available[ $registration->event()->ID() ] = $registration->event();
312
+				}
313
+				continue;
314
+			}
315
+			// event requires admin approval
316
+			if ($registration->status_ID() === EEM_Registration::status_id_not_approved) {
317
+				// add event to list of events with pre-approval reg status
318
+				$registrations_requiring_pre_approval[ $REG_ID ] = $registration;
319
+				do_action(
320
+					'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__event_requires_pre_approval',
321
+					$registration->event(),
322
+					$this
323
+				);
324
+				continue;
325
+			}
326
+			if ($this->checkout->revisit
327
+				&& $registration->status_ID() !== EEM_Registration::status_id_approved
328
+				&& (
329
+					$registration->event()->is_sold_out()
330
+					|| $registration->event()->is_sold_out(true)
331
+				)
332
+			) {
333
+				// add event to list of events that are sold out
334
+				$sold_out_events[ $registration->event()->ID() ] = $registration->event();
335
+				do_action(
336
+					'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__sold_out_event',
337
+					$registration->event(),
338
+					$this
339
+				);
340
+				continue;
341
+			}
342
+			// are they allowed to pay now and is there monies owing?
343
+			if ($registration->owes_monies_and_can_pay()) {
344
+				$registrations_requiring_payment[ $REG_ID ] = $registration;
345
+				do_action(
346
+					'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__event_requires_payment',
347
+					$registration->event(),
348
+					$this
349
+				);
350
+			} elseif (! $this->checkout->revisit
351
+					  && $registration->status_ID() !== EEM_Registration::status_id_not_approved
352
+					  && $registration->ticket()->is_free()
353
+			) {
354
+				$registrations_for_free_events[ $registration->ticket()->ID() ] = $registration;
355
+			}
356
+		}
357
+		$subsections = array();
358
+		// now decide which template to load
359
+		if (! empty($sold_out_events)) {
360
+			$subsections['sold_out_events'] = $this->_sold_out_events($sold_out_events);
361
+		}
362
+		if (! empty($insufficient_spaces_available)) {
363
+			$subsections['insufficient_space'] = $this->_insufficient_spaces_available(
364
+				$insufficient_spaces_available
365
+			);
366
+		}
367
+		if (! empty($registrations_requiring_pre_approval)) {
368
+			$subsections['registrations_requiring_pre_approval'] = $this->_registrations_requiring_pre_approval(
369
+				$registrations_requiring_pre_approval
370
+			);
371
+		}
372
+		if (! empty($registrations_for_free_events)) {
373
+			$subsections['no_payment_required'] = $this->_no_payment_required($registrations_for_free_events);
374
+		}
375
+		if (! empty($registrations_requiring_payment)) {
376
+			if ($this->checkout->amount_owing > 0) {
377
+				// autoload Line_Item_Display classes
378
+				EEH_Autoloader::register_line_item_filter_autoloaders();
379
+				$line_item_filter_processor = new EE_Line_Item_Filter_Processor(
380
+					apply_filters(
381
+						'FHEE__SPCO__EE_Line_Item_Filter_Collection',
382
+						new EE_Line_Item_Filter_Collection()
383
+					),
384
+					$this->checkout->cart->get_grand_total()
385
+				);
386
+				/** @var EE_Line_Item $filtered_line_item_tree */
387
+				$filtered_line_item_tree = $line_item_filter_processor->process();
388
+				EEH_Autoloader::register_line_item_display_autoloaders();
389
+				$this->set_line_item_display(new EE_Line_Item_Display('spco'));
390
+				$subsections['payment_options'] = $this->_display_payment_options(
391
+					$this->line_item_display->display_line_item(
392
+						$filtered_line_item_tree,
393
+						array('registrations' => $registrations)
394
+					)
395
+				);
396
+				$this->checkout->amount_owing = $filtered_line_item_tree->total();
397
+				$this->_apply_registration_payments_to_amount_owing($registrations);
398
+			}
399
+			$no_payment_required = false;
400
+		} else {
401
+			$this->_hide_reg_step_submit_button_if_revisit();
402
+		}
403
+		$this->_save_selected_method_of_payment();
404
+
405
+		$subsections['default_hidden_inputs'] = $this->reg_step_hidden_inputs();
406
+		$subsections['extra_hidden_inputs'] = $this->_extra_hidden_inputs($no_payment_required);
407
+
408
+		return new EE_Form_Section_Proper(
409
+			array(
410
+				'name'            => $this->reg_form_name(),
411
+				'html_id'         => $this->reg_form_name(),
412
+				'subsections'     => $subsections,
413
+				'layout_strategy' => new EE_No_Layout(),
414
+			)
415
+		);
416
+	}
417
+
418
+
419
+	/**
420
+	 * add line item filters required for this reg step
421
+	 * these filters are applied via this line in EE_SPCO_Reg_Step_Payment_Options::set_hooks():
422
+	 *        add_filter( 'FHEE__SPCO__EE_Line_Item_Filter_Collection', array( 'EE_SPCO_Reg_Step_Payment_Options',
423
+	 *        'add_spco_line_item_filters' ) ); so any code that wants to use the same set of filters during the
424
+	 *        payment options reg step, can apply these filters via the following: apply_filters(
425
+	 *        'FHEE__SPCO__EE_Line_Item_Filter_Collection', new EE_Line_Item_Filter_Collection() ) or to an existing
426
+	 *        filter collection by passing that instead of instantiating a new collection
427
+	 *
428
+	 * @param \EE_Line_Item_Filter_Collection $line_item_filter_collection
429
+	 * @return EE_Line_Item_Filter_Collection
430
+	 * @throws EE_Error
431
+	 * @throws InvalidArgumentException
432
+	 * @throws ReflectionException
433
+	 * @throws \EventEspresso\core\exceptions\EntityNotFoundException
434
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
435
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
436
+	 * @throws \EventEspresso\core\exceptions\InvalidStatusException
437
+	 */
438
+	public static function add_spco_line_item_filters(EE_Line_Item_Filter_Collection $line_item_filter_collection)
439
+	{
440
+		if (! EE_Registry::instance()->SSN instanceof EE_Session) {
441
+			return $line_item_filter_collection;
442
+		}
443
+		if (! EE_Registry::instance()->SSN->checkout() instanceof EE_Checkout) {
444
+			return $line_item_filter_collection;
445
+		}
446
+		if (! EE_Registry::instance()->SSN->checkout()->transaction instanceof EE_Transaction) {
447
+			return $line_item_filter_collection;
448
+		}
449
+		$line_item_filter_collection->add(
450
+			new EE_Billable_Line_Item_Filter(
451
+				EE_SPCO_Reg_Step_Payment_Options::remove_ejected_registrations(
452
+					EE_Registry::instance()->SSN->checkout()->transaction->registrations(
453
+						EE_Registry::instance()->SSN->checkout()->reg_cache_where_params
454
+					)
455
+				)
456
+			)
457
+		);
458
+		$line_item_filter_collection->add(new EE_Non_Zero_Line_Item_Filter());
459
+		return $line_item_filter_collection;
460
+	}
461
+
462
+
463
+	/**
464
+	 * remove_ejected_registrations
465
+	 * if a registrant has lost their potential space at an event due to lack of payment,
466
+	 * then this method removes them from the list of registrations being paid for during this request
467
+	 *
468
+	 * @param \EE_Registration[] $registrations
469
+	 * @return EE_Registration[]
470
+	 * @throws EE_Error
471
+	 * @throws InvalidArgumentException
472
+	 * @throws ReflectionException
473
+	 * @throws \EventEspresso\core\exceptions\EntityNotFoundException
474
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
475
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
476
+	 * @throws \EventEspresso\core\exceptions\InvalidStatusException
477
+	 */
478
+	public static function remove_ejected_registrations(array $registrations)
479
+	{
480
+		$ejected_registrations = EE_SPCO_Reg_Step_Payment_Options::find_registrations_that_lost_their_space(
481
+			$registrations,
482
+			EE_Registry::instance()->SSN->checkout()->revisit
483
+		);
484
+		foreach ($registrations as $REG_ID => $registration) {
485
+			// has this registration lost it's space ?
486
+			if (isset($ejected_registrations[ $REG_ID ])) {
487
+				unset($registrations[ $REG_ID ]);
488
+				continue;
489
+			}
490
+		}
491
+		return $registrations;
492
+	}
493
+
494
+
495
+	/**
496
+	 * find_registrations_that_lost_their_space
497
+	 * If a registrant chooses an offline payment method like Invoice,
498
+	 * then no space is reserved for them at the event until they fully pay fo that site
499
+	 * (unless the event's default reg status is set to APPROVED)
500
+	 * if a registrant then later returns to pay, but the number of spaces available has been reduced due to sales,
501
+	 * then this method will determine which registrations have lost the ability to complete the reg process.
502
+	 *
503
+	 * @param \EE_Registration[] $registrations
504
+	 * @param bool               $revisit
505
+	 * @return array
506
+	 * @throws EE_Error
507
+	 * @throws InvalidArgumentException
508
+	 * @throws ReflectionException
509
+	 * @throws \EventEspresso\core\exceptions\EntityNotFoundException
510
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
511
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
512
+	 * @throws \EventEspresso\core\exceptions\InvalidStatusException
513
+	 */
514
+	public static function find_registrations_that_lost_their_space(array $registrations, $revisit = false)
515
+	{
516
+		// registrations per event
517
+		$event_reg_count = array();
518
+		// spaces left per event
519
+		$event_spaces_remaining = array();
520
+		// tickets left sorted by ID
521
+		$tickets_remaining = array();
522
+		// registrations that have lost their space
523
+		$ejected_registrations = array();
524
+		foreach ($registrations as $REG_ID => $registration) {
525
+			if ($registration->status_ID() === EEM_Registration::status_id_approved
526
+				|| apply_filters(
527
+					'FHEE__EE_SPCO_Reg_Step_Payment_Options__find_registrations_that_lost_their_space__allow_reg_payment',
528
+					false,
529
+					$registration,
530
+					$revisit
531
+				)
532
+			) {
533
+				continue;
534
+			}
535
+			$EVT_ID = $registration->event_ID();
536
+			$ticket = $registration->ticket();
537
+			if (! isset($tickets_remaining[ $ticket->ID() ])) {
538
+				$tickets_remaining[ $ticket->ID() ] = $ticket->remaining();
539
+			}
540
+			if ($tickets_remaining[ $ticket->ID() ] > 0) {
541
+				if (! isset($event_reg_count[ $EVT_ID ])) {
542
+					$event_reg_count[ $EVT_ID ] = 0;
543
+				}
544
+				$event_reg_count[ $EVT_ID ]++;
545
+				if (! isset($event_spaces_remaining[ $EVT_ID ])) {
546
+					$event_spaces_remaining[ $EVT_ID ] = $registration->event()->spaces_remaining_for_sale();
547
+				}
548
+			}
549
+			if ($revisit
550
+				&& ($tickets_remaining[ $ticket->ID() ] === 0
551
+					|| $event_reg_count[ $EVT_ID ] > $event_spaces_remaining[ $EVT_ID ]
552
+				)
553
+			) {
554
+				$ejected_registrations[ $REG_ID ] = $registration->event();
555
+				if ($registration->status_ID() !== EEM_Registration::status_id_wait_list) {
556
+					/** @type EE_Registration_Processor $registration_processor */
557
+					$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
558
+					// at this point, we should have enough details about the registrant to consider the registration
559
+					// NOT incomplete
560
+					$registration_processor->manually_update_registration_status(
561
+						$registration,
562
+						EEM_Registration::status_id_wait_list
563
+					);
564
+				}
565
+			}
566
+		}
567
+		return $ejected_registrations;
568
+	}
569
+
570
+
571
+	/**
572
+	 * _hide_reg_step_submit_button
573
+	 * removes the html for the reg step submit button
574
+	 * by replacing it with an empty string via filter callback
575
+	 *
576
+	 * @return void
577
+	 */
578
+	protected function _adjust_registration_status_if_event_old_sold()
579
+	{
580
+	}
581
+
582
+
583
+	/**
584
+	 * _hide_reg_step_submit_button
585
+	 * removes the html for the reg step submit button
586
+	 * by replacing it with an empty string via filter callback
587
+	 *
588
+	 * @return void
589
+	 */
590
+	protected function _hide_reg_step_submit_button_if_revisit()
591
+	{
592
+		if ($this->checkout->revisit) {
593
+			add_filter('FHEE__EE_SPCO_Reg_Step__reg_step_submit_button__sbmt_btn_html', '__return_empty_string');
594
+		}
595
+	}
596
+
597
+
598
+	/**
599
+	 * sold_out_events
600
+	 * displays notices regarding events that have sold out since hte registrant first signed up
601
+	 *
602
+	 * @param \EE_Event[] $sold_out_events_array
603
+	 * @return \EE_Form_Section_Proper
604
+	 * @throws \EE_Error
605
+	 */
606
+	private function _sold_out_events($sold_out_events_array = array())
607
+	{
608
+		// set some defaults
609
+		$this->checkout->selected_method_of_payment = 'events_sold_out';
610
+		$sold_out_events = '';
611
+		foreach ($sold_out_events_array as $sold_out_event) {
612
+			$sold_out_events .= EEH_HTML::li(
613
+				EEH_HTML::span(
614
+					'  ' . $sold_out_event->name(),
615
+					'',
616
+					'dashicons dashicons-marker ee-icon-size-16 pink-text'
617
+				)
618
+			);
619
+		}
620
+		return new EE_Form_Section_Proper(
621
+			array(
622
+				'layout_strategy' => new EE_Template_Layout(
623
+					array(
624
+						'layout_template_file' => SPCO_REG_STEPS_PATH
625
+												  . $this->_slug
626
+												  . DS
627
+												  . 'sold_out_events.template.php',
628
+						'template_args'        => apply_filters(
629
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___sold_out_events__template_args',
630
+							array(
631
+								'sold_out_events'     => $sold_out_events,
632
+								'sold_out_events_msg' => apply_filters(
633
+									'FHEE__EE_SPCO_Reg_Step_Payment_Options___sold_out_events__sold_out_events_msg',
634
+									sprintf(
635
+										esc_html__(
636
+											'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',
637
+											'event_espresso'
638
+										),
639
+										'<strong>',
640
+										'</strong>',
641
+										'<br />'
642
+									)
643
+								),
644
+							)
645
+						),
646
+					)
647
+				),
648
+			)
649
+		);
650
+	}
651
+
652
+
653
+	/**
654
+	 * _insufficient_spaces_available
655
+	 * displays notices regarding events that do not have enough remaining spaces
656
+	 * to satisfy the current number of registrations looking to pay
657
+	 *
658
+	 * @param \EE_Event[] $insufficient_spaces_events_array
659
+	 * @return \EE_Form_Section_Proper
660
+	 * @throws \EE_Error
661
+	 */
662
+	private function _insufficient_spaces_available($insufficient_spaces_events_array = array())
663
+	{
664
+		// set some defaults
665
+		$this->checkout->selected_method_of_payment = 'invoice';
666
+		$insufficient_space_events = '';
667
+		foreach ($insufficient_spaces_events_array as $event) {
668
+			if ($event instanceof EE_Event) {
669
+				$insufficient_space_events .= EEH_HTML::li(
670
+					EEH_HTML::span(' ' . $event->name(), '', 'dashicons dashicons-marker ee-icon-size-16 pink-text')
671
+				);
672
+			}
673
+		}
674
+		return new EE_Form_Section_Proper(
675
+			array(
676
+				'subsections'     => array(
677
+					'default_hidden_inputs' => $this->reg_step_hidden_inputs(),
678
+					'extra_hidden_inputs'   => $this->_extra_hidden_inputs(),
679
+				),
680
+				'layout_strategy' => new EE_Template_Layout(
681
+					array(
682
+						'layout_template_file' => SPCO_REG_STEPS_PATH
683
+												  . $this->_slug
684
+												  . DS
685
+												  . 'sold_out_events.template.php',
686
+						'template_args'        => apply_filters(
687
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___insufficient_spaces_available__template_args',
688
+							array(
689
+								'sold_out_events'     => $insufficient_space_events,
690
+								'sold_out_events_msg' => apply_filters(
691
+									'FHEE__EE_SPCO_Reg_Step_Payment_Options___insufficient_spaces_available__insufficient_space_msg',
692
+									esc_html__(
693
+										'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.',
694
+										'event_espresso'
695
+									)
696
+								),
697
+							)
698
+						),
699
+					)
700
+				),
701
+			)
702
+		);
703
+	}
704
+
705
+
706
+	/**
707
+	 * registrations_requiring_pre_approval
708
+	 *
709
+	 * @param array $registrations_requiring_pre_approval
710
+	 * @return EE_Form_Section_Proper
711
+	 * @throws EE_Error
712
+	 * @throws \EventEspresso\core\exceptions\EntityNotFoundException
713
+	 */
714
+	private function _registrations_requiring_pre_approval($registrations_requiring_pre_approval = array())
715
+	{
716
+		$events_requiring_pre_approval = '';
717
+		foreach ($registrations_requiring_pre_approval as $registration) {
718
+			if ($registration instanceof EE_Registration && $registration->event() instanceof EE_Event) {
719
+				$events_requiring_pre_approval[ $registration->event()->ID() ] = EEH_HTML::li(
720
+					EEH_HTML::span(
721
+						'',
722
+						'',
723
+						'dashicons dashicons-marker ee-icon-size-16 orange-text'
724
+					)
725
+					. EEH_HTML::span($registration->event()->name(), '', 'orange-text')
726
+				);
727
+			}
728
+		}
729
+		return new EE_Form_Section_Proper(
730
+			array(
731
+				'layout_strategy' => new EE_Template_Layout(
732
+					array(
733
+						'layout_template_file' => SPCO_REG_STEPS_PATH
734
+												  . $this->_slug
735
+												  . DS
736
+												  . 'events_requiring_pre_approval.template.php', // layout_template
737
+						'template_args'        => apply_filters(
738
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___sold_out_events__template_args',
739
+							array(
740
+								'events_requiring_pre_approval'     => implode('', $events_requiring_pre_approval),
741
+								'events_requiring_pre_approval_msg' => apply_filters(
742
+									'FHEE__EE_SPCO_Reg_Step_Payment_Options___events_requiring_pre_approval__events_requiring_pre_approval_msg',
743
+									esc_html__(
744
+										'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.',
745
+										'event_espresso'
746
+									)
747
+								),
748
+							)
749
+						),
750
+					)
751
+				),
752
+			)
753
+		);
754
+	}
755
+
756
+
757
+	/**
758
+	 * _no_payment_required
759
+	 *
760
+	 * @param \EE_Event[] $registrations_for_free_events
761
+	 * @return \EE_Form_Section_Proper
762
+	 * @throws \EE_Error
763
+	 */
764
+	private function _no_payment_required($registrations_for_free_events = array())
765
+	{
766
+		// set some defaults
767
+		$this->checkout->selected_method_of_payment = 'no_payment_required';
768
+		// generate no_payment_required form
769
+		return new EE_Form_Section_Proper(
770
+			array(
771
+				'layout_strategy' => new EE_Template_Layout(
772
+					array(
773
+						'layout_template_file' => SPCO_REG_STEPS_PATH
774
+												  . $this->_slug
775
+												  . DS
776
+												  . 'no_payment_required.template.php', // layout_template
777
+						'template_args'        => apply_filters(
778
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___no_payment_required__template_args',
779
+							array(
780
+								'revisit'                       => $this->checkout->revisit,
781
+								'registrations'                 => array(),
782
+								'ticket_count'                  => array(),
783
+								'registrations_for_free_events' => $registrations_for_free_events,
784
+								'no_payment_required_msg'       => EEH_HTML::p(
785
+									esc_html__('This is a free event, so no billing will occur.', 'event_espresso')
786
+								),
787
+							)
788
+						),
789
+					)
790
+				),
791
+			)
792
+		);
793
+	}
794
+
795
+
796
+	/**
797
+	 * _display_payment_options
798
+	 *
799
+	 * @param string $transaction_details
800
+	 * @return EE_Form_Section_Proper
801
+	 * @throws EE_Error
802
+	 * @throws InvalidArgumentException
803
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
804
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
805
+	 */
806
+	private function _display_payment_options($transaction_details = '')
807
+	{
808
+		// has method_of_payment been set by no-js user?
809
+		$this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment();
810
+		// build payment options form
811
+		return apply_filters(
812
+			'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__payment_options_form',
813
+			new EE_Form_Section_Proper(
814
+				array(
815
+					'subsections'     => array(
816
+						'before_payment_options' => apply_filters(
817
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__before_payment_options',
818
+							new EE_Form_Section_Proper(
819
+								array('layout_strategy' => new EE_Div_Per_Section_Layout())
820
+							)
821
+						),
822
+						'payment_options'        => $this->_setup_payment_options(),
823
+						'after_payment_options'  => apply_filters(
824
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__after_payment_options',
825
+							new EE_Form_Section_Proper(
826
+								array('layout_strategy' => new EE_Div_Per_Section_Layout())
827
+							)
828
+						),
829
+					),
830
+					'layout_strategy' => new EE_Template_Layout(
831
+						array(
832
+							'layout_template_file' => $this->_template,
833
+							'template_args'        => apply_filters(
834
+								'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__template_args',
835
+								array(
836
+									'reg_count'                 => $this->line_item_display->total_items(),
837
+									'transaction_details'       => $transaction_details,
838
+									'available_payment_methods' => array(),
839
+								)
840
+							),
841
+						)
842
+					),
843
+				)
844
+			)
845
+		);
846
+	}
847
+
848
+
849
+	/**
850
+	 * _extra_hidden_inputs
851
+	 *
852
+	 * @param bool $no_payment_required
853
+	 * @return \EE_Form_Section_Proper
854
+	 * @throws \EE_Error
855
+	 */
856
+	private function _extra_hidden_inputs($no_payment_required = true)
857
+	{
858
+		return new EE_Form_Section_Proper(
859
+			array(
860
+				'html_id'         => 'ee-' . $this->slug() . '-extra-hidden-inputs',
861
+				'layout_strategy' => new EE_Div_Per_Section_Layout(),
862
+				'subsections'     => array(
863
+					'spco_no_payment_required' => new EE_Hidden_Input(
864
+						array(
865
+							'normalization_strategy' => new EE_Boolean_Normalization(),
866
+							'html_name'              => 'spco_no_payment_required',
867
+							'html_id'                => 'spco-no-payment-required-payment_options',
868
+							'default'                => $no_payment_required,
869
+						)
870
+					),
871
+					'spco_transaction_id'      => new EE_Fixed_Hidden_Input(
872
+						array(
873
+							'normalization_strategy' => new EE_Int_Normalization(),
874
+							'html_name'              => 'spco_transaction_id',
875
+							'html_id'                => 'spco-transaction-id',
876
+							'default'                => $this->checkout->transaction->ID(),
877
+						)
878
+					),
879
+				),
880
+			)
881
+		);
882
+	}
883
+
884
+
885
+	/**
886
+	 *    _apply_registration_payments_to_amount_owing
887
+	 *
888
+	 * @access protected
889
+	 * @param array $registrations
890
+	 * @throws EE_Error
891
+	 */
892
+	protected function _apply_registration_payments_to_amount_owing(array $registrations)
893
+	{
894
+		$payments = array();
895
+		foreach ($registrations as $registration) {
896
+			if ($registration instanceof EE_Registration && $registration->owes_monies_and_can_pay()) {
897
+				$payments += $registration->registration_payments();
898
+			}
899
+		}
900
+		if (! empty($payments)) {
901
+			foreach ($payments as $payment) {
902
+				if ($payment instanceof EE_Registration_Payment) {
903
+					$this->checkout->amount_owing -= $payment->amount();
904
+				}
905
+			}
906
+		}
907
+	}
908
+
909
+
910
+	/**
911
+	 *    _reset_selected_method_of_payment
912
+	 *
913
+	 * @access    private
914
+	 * @param    bool $force_reset
915
+	 * @return void
916
+	 * @throws InvalidArgumentException
917
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
918
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
919
+	 */
920
+	private function _reset_selected_method_of_payment($force_reset = false)
921
+	{
922
+		$reset_payment_method = $force_reset
923
+			? true
924
+			: sanitize_text_field(EE_Registry::instance()->REQ->get('reset_payment_method', false));
925
+		if ($reset_payment_method) {
926
+			$this->checkout->selected_method_of_payment = null;
927
+			$this->checkout->payment_method = null;
928
+			$this->checkout->billing_form = null;
929
+			$this->_save_selected_method_of_payment();
930
+		}
931
+	}
932
+
933
+
934
+	/**
935
+	 * _save_selected_method_of_payment
936
+	 * stores the selected_method_of_payment in the session
937
+	 * so that it's available for all subsequent requests including AJAX
938
+	 *
939
+	 * @access        private
940
+	 * @param string $selected_method_of_payment
941
+	 * @return void
942
+	 * @throws InvalidArgumentException
943
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
944
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
945
+	 */
946
+	private function _save_selected_method_of_payment($selected_method_of_payment = '')
947
+	{
948
+		$selected_method_of_payment = ! empty($selected_method_of_payment)
949
+			? $selected_method_of_payment
950
+			: $this->checkout->selected_method_of_payment;
951
+		EE_Registry::instance()->SSN->set_session_data(
952
+			array('selected_method_of_payment' => $selected_method_of_payment)
953
+		);
954
+	}
955
+
956
+
957
+	/**
958
+	 * _setup_payment_options
959
+	 *
960
+	 * @return EE_Form_Section_Proper
961
+	 * @throws EE_Error
962
+	 * @throws InvalidArgumentException
963
+	 * @throws ReflectionException
964
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
965
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
966
+	 */
967
+	public function _setup_payment_options()
968
+	{
969
+		// load payment method classes
970
+		$this->checkout->available_payment_methods = $this->_get_available_payment_methods();
971
+		if (empty($this->checkout->available_payment_methods)) {
972
+			EE_Error::add_error(
973
+				apply_filters(
974
+					'FHEE__EE_SPCO_Reg_Step_Payment_Options___setup_payment_options__error_message_no_payment_methods',
975
+					sprintf(
976
+						esc_html__(
977
+							'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.',
978
+							'event_espresso'
979
+						),
980
+						'<br>',
981
+						EE_Registry::instance()->CFG->organization->get_pretty('email')
982
+					)
983
+				),
984
+				__FILE__,
985
+				__FUNCTION__,
986
+				__LINE__
987
+			);
988
+		}
989
+		// switch up header depending on number of available payment methods
990
+		$payment_method_header = count($this->checkout->available_payment_methods) > 1
991
+			? apply_filters(
992
+				'FHEE__registration_page_payment_options__method_of_payment_hdr',
993
+				esc_html__('Please Select Your Method of Payment', 'event_espresso')
994
+			)
995
+			: apply_filters(
996
+				'FHEE__registration_page_payment_options__method_of_payment_hdr',
997
+				esc_html__('Method of Payment', 'event_espresso')
998
+			);
999
+		$available_payment_methods = array(
1000
+			// display the "Payment Method" header
1001
+			'payment_method_header' => new EE_Form_Section_HTML(
1002
+				EEH_HTML::h4($payment_method_header, 'method-of-payment-hdr')
1003
+			),
1004
+		);
1005
+		// the list of actual payment methods ( invoice, paypal, etc ) in a  ( slug => HTML )  format
1006
+		$available_payment_method_options = array();
1007
+		$default_payment_method_option = array();
1008
+		// additional instructions to be displayed and hidden below payment methods (adding a clearing div to start)
1009
+		$payment_methods_billing_info = array(
1010
+			new EE_Form_Section_HTML(
1011
+				EEH_HTML::div('<br />', '', '', 'clear:both;')
1012
+			),
1013
+		);
1014
+		// loop through payment methods
1015
+		foreach ($this->checkout->available_payment_methods as $payment_method) {
1016
+			if ($payment_method instanceof EE_Payment_Method) {
1017
+				$payment_method_button = EEH_HTML::img(
1018
+					$payment_method->button_url(),
1019
+					$payment_method->name(),
1020
+					'spco-payment-method-' . $payment_method->slug() . '-btn-img',
1021
+					'spco-payment-method-btn-img'
1022
+				);
1023
+				// check if any payment methods are set as default
1024
+				// if payment method is already selected OR nothing is selected and this payment method should be
1025
+				// open_by_default
1026
+				if (($this->checkout->selected_method_of_payment === $payment_method->slug())
1027
+					|| (! $this->checkout->selected_method_of_payment && $payment_method->open_by_default())
1028
+				) {
1029
+					$this->checkout->selected_method_of_payment = $payment_method->slug();
1030
+					$this->_save_selected_method_of_payment();
1031
+					$default_payment_method_option[ $payment_method->slug() ] = $payment_method_button;
1032
+				} else {
1033
+					$available_payment_method_options[ $payment_method->slug() ] = $payment_method_button;
1034
+				}
1035
+				$payment_methods_billing_info[ $payment_method->slug(
1036
+				) . '-info' ] = $this->_payment_method_billing_info(
1037
+					$payment_method
1038
+				);
1039
+			}
1040
+		}
1041
+		// prepend available_payment_method_options with default_payment_method_option so that it appears first in list
1042
+		// of PMs
1043
+		$available_payment_method_options = $default_payment_method_option + $available_payment_method_options;
1044
+		// now generate the actual form  inputs
1045
+		$available_payment_methods['available_payment_methods'] = $this->_available_payment_method_inputs(
1046
+			$available_payment_method_options
1047
+		);
1048
+		$available_payment_methods += $payment_methods_billing_info;
1049
+		// build the available payment methods form
1050
+		return new EE_Form_Section_Proper(
1051
+			array(
1052
+				'html_id'         => 'spco-available-methods-of-payment-dv',
1053
+				'subsections'     => $available_payment_methods,
1054
+				'layout_strategy' => new EE_Div_Per_Section_Layout(),
1055
+			)
1056
+		);
1057
+	}
1058
+
1059
+
1060
+	/**
1061
+	 * _get_available_payment_methods
1062
+	 *
1063
+	 * @return EE_Payment_Method[]
1064
+	 * @throws EE_Error
1065
+	 * @throws InvalidArgumentException
1066
+	 * @throws ReflectionException
1067
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1068
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1069
+	 */
1070
+	protected function _get_available_payment_methods()
1071
+	{
1072
+		if (! empty($this->checkout->available_payment_methods)) {
1073
+			return $this->checkout->available_payment_methods;
1074
+		}
1075
+		$available_payment_methods = array();
1076
+		// load EEM_Payment_Method
1077
+		EE_Registry::instance()->load_model('Payment_Method');
1078
+		/** @type EEM_Payment_Method $EEM_Payment_Method */
1079
+		$EEM_Payment_Method = EE_Registry::instance()->LIB->EEM_Payment_Method;
1080
+		// get all active payment methods
1081
+		$payment_methods = $EEM_Payment_Method->get_all_for_transaction(
1082
+			$this->checkout->transaction,
1083
+			EEM_Payment_Method::scope_cart
1084
+		);
1085
+		foreach ($payment_methods as $payment_method) {
1086
+			if ($payment_method instanceof EE_Payment_Method) {
1087
+				$available_payment_methods[ $payment_method->slug() ] = $payment_method;
1088
+			}
1089
+		}
1090
+		return $available_payment_methods;
1091
+	}
1092
+
1093
+
1094
+	/**
1095
+	 *    _available_payment_method_inputs
1096
+	 *
1097
+	 * @access    private
1098
+	 * @param    array $available_payment_method_options
1099
+	 * @return    \EE_Form_Section_Proper
1100
+	 */
1101
+	private function _available_payment_method_inputs($available_payment_method_options = array())
1102
+	{
1103
+		// generate inputs
1104
+		return new EE_Form_Section_Proper(
1105
+			array(
1106
+				'html_id'         => 'ee-available-payment-method-inputs',
1107
+				'layout_strategy' => new EE_Div_Per_Section_Layout(),
1108
+				'subsections'     => array(
1109
+					'' => new EE_Radio_Button_Input(
1110
+						$available_payment_method_options,
1111
+						array(
1112
+							'html_name'          => 'selected_method_of_payment',
1113
+							'html_class'         => 'spco-payment-method',
1114
+							'default'            => $this->checkout->selected_method_of_payment,
1115
+							'label_size'         => 11,
1116
+							'enforce_label_size' => true,
1117
+						)
1118
+					),
1119
+				),
1120
+			)
1121
+		);
1122
+	}
1123
+
1124
+
1125
+	/**
1126
+	 *    _payment_method_billing_info
1127
+	 *
1128
+	 * @access    private
1129
+	 * @param    EE_Payment_Method $payment_method
1130
+	 * @return EE_Form_Section_Proper
1131
+	 * @throws EE_Error
1132
+	 * @throws InvalidArgumentException
1133
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1134
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1135
+	 */
1136
+	private function _payment_method_billing_info(EE_Payment_Method $payment_method)
1137
+	{
1138
+		$currently_selected = $this->checkout->selected_method_of_payment === $payment_method->slug()
1139
+			? true
1140
+			: false;
1141
+		// generate the billing form for payment method
1142
+		$billing_form = $currently_selected
1143
+			? $this->_get_billing_form_for_payment_method($payment_method)
1144
+			: new EE_Form_Section_HTML();
1145
+		$this->checkout->billing_form = $currently_selected
1146
+			? $billing_form
1147
+			: $this->checkout->billing_form;
1148
+		// it's all in the details
1149
+		$info_html = EEH_HTML::h3(
1150
+			esc_html__('Important information regarding your payment', 'event_espresso'),
1151
+			'',
1152
+			'spco-payment-method-hdr'
1153
+		);
1154
+		// add some info regarding the step, either from what's saved in the admin,
1155
+		// or a default string depending on whether the PM has a billing form or not
1156
+		if ($payment_method->description()) {
1157
+			$payment_method_info = $payment_method->description();
1158
+		} elseif ($billing_form instanceof EE_Billing_Info_Form) {
1159
+			$payment_method_info = sprintf(
1160
+				esc_html__(
1161
+					'Please provide the following billing information, then click the "%1$s" button below in order to proceed.',
1162
+					'event_espresso'
1163
+				),
1164
+				$this->submit_button_text()
1165
+			);
1166
+		} else {
1167
+			$payment_method_info = sprintf(
1168
+				esc_html__('Please click the "%1$s" button below in order to proceed.', 'event_espresso'),
1169
+				$this->submit_button_text()
1170
+			);
1171
+		}
1172
+		$info_html .= EEH_HTML::div(
1173
+			apply_filters(
1174
+				'FHEE__EE_SPCO_Reg_Step_Payment_Options___payment_method_billing_info__payment_method_info',
1175
+				$payment_method_info
1176
+			),
1177
+			'',
1178
+			'spco-payment-method-desc ee-attention'
1179
+		);
1180
+		return new EE_Form_Section_Proper(
1181
+			array(
1182
+				'html_id'         => 'spco-payment-method-info-' . $payment_method->slug(),
1183
+				'html_class'      => 'spco-payment-method-info-dv',
1184
+				// only display the selected or default PM
1185
+				'html_style'      => $currently_selected ? '' : 'display:none;',
1186
+				'layout_strategy' => new EE_Div_Per_Section_Layout(),
1187
+				'subsections'     => array(
1188
+					'info'         => new EE_Form_Section_HTML($info_html),
1189
+					'billing_form' => $currently_selected ? $billing_form : new EE_Form_Section_HTML(),
1190
+				),
1191
+			)
1192
+		);
1193
+	}
1194
+
1195
+
1196
+	/**
1197
+	 * get_billing_form_html_for_payment_method
1198
+	 *
1199
+	 * @access public
1200
+	 * @return string
1201
+	 * @throws EE_Error
1202
+	 * @throws InvalidArgumentException
1203
+	 * @throws ReflectionException
1204
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1205
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1206
+	 */
1207
+	public function get_billing_form_html_for_payment_method()
1208
+	{
1209
+		// how have they chosen to pay?
1210
+		$this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
1211
+		$this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment();
1212
+		if (! $this->checkout->payment_method instanceof EE_Payment_Method) {
1213
+			return false;
1214
+		}
1215
+		if (apply_filters(
1216
+			'FHEE__EE_SPCO_Reg_Step_Payment_Options__registration_checkout__selected_payment_method__display_success',
1217
+			false
1218
+		)) {
1219
+			EE_Error::add_success(
1220
+				apply_filters(
1221
+					'FHEE__Single_Page_Checkout__registration_checkout__selected_payment_method',
1222
+					sprintf(
1223
+						esc_html__(
1224
+							'You have selected "%s" as your method of payment. Please note the important payment information below.',
1225
+							'event_espresso'
1226
+						),
1227
+						$this->checkout->payment_method->name()
1228
+					)
1229
+				)
1230
+			);
1231
+		}
1232
+		// now generate billing form for selected method of payment
1233
+		$payment_method_billing_form = $this->_get_billing_form_for_payment_method($this->checkout->payment_method);
1234
+		// fill form with attendee info if applicable
1235
+		if ($payment_method_billing_form instanceof EE_Billing_Attendee_Info_Form
1236
+			&& $this->checkout->transaction_has_primary_registrant()
1237
+		) {
1238
+			$payment_method_billing_form->populate_from_attendee(
1239
+				$this->checkout->transaction->primary_registration()->attendee()
1240
+			);
1241
+		}
1242
+		// and debug content
1243
+		if ($payment_method_billing_form instanceof EE_Billing_Info_Form
1244
+			&& $this->checkout->payment_method->type_obj() instanceof EE_PMT_Base
1245
+		) {
1246
+			$payment_method_billing_form =
1247
+				$this->checkout->payment_method->type_obj()->apply_billing_form_debug_settings(
1248
+					$payment_method_billing_form
1249
+				);
1250
+		}
1251
+		$billing_info = $payment_method_billing_form instanceof EE_Form_Section_Proper
1252
+			? $payment_method_billing_form->get_html()
1253
+			: '';
1254
+		$this->checkout->json_response->set_return_data(array('payment_method_info' => $billing_info));
1255
+		// localize validation rules for main form
1256
+		$this->checkout->current_step->reg_form->localize_validation_rules();
1257
+		$this->checkout->json_response->add_validation_rules(EE_Form_Section_Proper::js_localization());
1258
+		return true;
1259
+	}
1260
+
1261
+
1262
+	/**
1263
+	 * _get_billing_form_for_payment_method
1264
+	 *
1265
+	 * @access private
1266
+	 * @param EE_Payment_Method $payment_method
1267
+	 * @return EE_Billing_Info_Form|EE_Form_Section_HTML
1268
+	 * @throws EE_Error
1269
+	 * @throws InvalidArgumentException
1270
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1271
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1272
+	 */
1273
+	private function _get_billing_form_for_payment_method(EE_Payment_Method $payment_method)
1274
+	{
1275
+		$billing_form = $payment_method->type_obj()->billing_form(
1276
+			$this->checkout->transaction,
1277
+			array('amount_owing' => $this->checkout->amount_owing)
1278
+		);
1279
+		if ($billing_form instanceof EE_Billing_Info_Form) {
1280
+			if (apply_filters(
1281
+				'FHEE__EE_SPCO_Reg_Step_Payment_Options__registration_checkout__selected_payment_method__display_success',
1282
+				false
1283
+			)
1284
+				&& EE_Registry::instance()->REQ->is_set('payment_method')
1285
+			) {
1286
+				EE_Error::add_success(
1287
+					apply_filters(
1288
+						'FHEE__Single_Page_Checkout__registration_checkout__selected_payment_method',
1289
+						sprintf(
1290
+							esc_html__(
1291
+								'You have selected "%s" as your method of payment. Please note the important payment information below.',
1292
+								'event_espresso'
1293
+							),
1294
+							$payment_method->name()
1295
+						)
1296
+					)
1297
+				);
1298
+			}
1299
+			return apply_filters(
1300
+				'FHEE__EE_SPCO_Reg_Step_Payment_Options___get_billing_form_for_payment_method__billing_form',
1301
+				$billing_form,
1302
+				$payment_method
1303
+			);
1304
+		}
1305
+		// no actual billing form, so return empty HTML form section
1306
+		return new EE_Form_Section_HTML();
1307
+	}
1308
+
1309
+
1310
+	/**
1311
+	 * _get_selected_method_of_payment
1312
+	 *
1313
+	 * @access private
1314
+	 * @param boolean $required whether to throw an error if the "selected_method_of_payment"
1315
+	 *                          is not found in the incoming request
1316
+	 * @param string  $request_param
1317
+	 * @return NULL|string
1318
+	 * @throws EE_Error
1319
+	 * @throws InvalidArgumentException
1320
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1321
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1322
+	 */
1323
+	private function _get_selected_method_of_payment(
1324
+		$required = false,
1325
+		$request_param = 'selected_method_of_payment'
1326
+	) {
1327
+		// is selected_method_of_payment set in the request ?
1328
+		$selected_method_of_payment = EE_Registry::instance()->REQ->get($request_param, false);
1329
+		if ($selected_method_of_payment) {
1330
+			// sanitize it
1331
+			$selected_method_of_payment = is_array($selected_method_of_payment)
1332
+				? array_shift($selected_method_of_payment)
1333
+				: $selected_method_of_payment;
1334
+			$selected_method_of_payment = sanitize_text_field($selected_method_of_payment);
1335
+			// store it in the session so that it's available for all subsequent requests including AJAX
1336
+			$this->_save_selected_method_of_payment($selected_method_of_payment);
1337
+		} else {
1338
+			// or is is set in the session ?
1339
+			$selected_method_of_payment = EE_Registry::instance()->SSN->get_session_data(
1340
+				'selected_method_of_payment'
1341
+			);
1342
+		}
1343
+		// do ya really really gotta have it?
1344
+		if (empty($selected_method_of_payment) && $required) {
1345
+			EE_Error::add_error(
1346
+				sprintf(
1347
+					esc_html__(
1348
+						'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.',
1349
+						'event_espresso'
1350
+					),
1351
+					'<br/>',
1352
+					'<br/>',
1353
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
1354
+				),
1355
+				__FILE__,
1356
+				__FUNCTION__,
1357
+				__LINE__
1358
+			);
1359
+			return null;
1360
+		}
1361
+		return $selected_method_of_payment;
1362
+	}
1363
+
1364
+
1365
+
1366
+
1367
+
1368
+
1369
+	/********************************************************************************************************/
1370
+	/***********************************  SWITCH PAYMENT METHOD  ************************************/
1371
+	/********************************************************************************************************/
1372
+	/**
1373
+	 * switch_payment_method
1374
+	 *
1375
+	 * @access public
1376
+	 * @return string
1377
+	 * @throws EE_Error
1378
+	 * @throws InvalidArgumentException
1379
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1380
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1381
+	 */
1382
+	public function switch_payment_method()
1383
+	{
1384
+		if (! $this->_verify_payment_method_is_set()) {
1385
+			return false;
1386
+		}
1387
+		if (apply_filters(
1388
+			'FHEE__EE_SPCO_Reg_Step_Payment_Options__registration_checkout__selected_payment_method__display_success',
1389
+			false
1390
+		)) {
1391
+			EE_Error::add_success(
1392
+				apply_filters(
1393
+					'FHEE__Single_Page_Checkout__registration_checkout__selected_payment_method',
1394
+					sprintf(
1395
+						esc_html__(
1396
+							'You have selected "%s" as your method of payment. Please note the important payment information below.',
1397
+							'event_espresso'
1398
+						),
1399
+						$this->checkout->payment_method->name()
1400
+					)
1401
+				)
1402
+			);
1403
+		}
1404
+		// generate billing form for selected method of payment if it hasn't been done already
1405
+		if ($this->checkout->payment_method->type_obj()->has_billing_form()) {
1406
+			$this->checkout->billing_form = $this->_get_billing_form_for_payment_method(
1407
+				$this->checkout->payment_method
1408
+			);
1409
+		}
1410
+		// fill form with attendee info if applicable
1411
+		if (apply_filters(
1412
+			'FHEE__populate_billing_form_fields_from_attendee',
1413
+			(
1414
+				$this->checkout->billing_form instanceof EE_Billing_Attendee_Info_Form
1415
+				&& $this->checkout->transaction_has_primary_registrant()
1416
+			),
1417
+			$this->checkout->billing_form,
1418
+			$this->checkout->transaction
1419
+		)
1420
+		) {
1421
+			$this->checkout->billing_form->populate_from_attendee(
1422
+				$this->checkout->transaction->primary_registration()->attendee()
1423
+			);
1424
+		}
1425
+		// and debug content
1426
+		if ($this->checkout->billing_form instanceof EE_Billing_Info_Form
1427
+			&& $this->checkout->payment_method->type_obj() instanceof EE_PMT_Base
1428
+		) {
1429
+			$this->checkout->billing_form =
1430
+				$this->checkout->payment_method->type_obj()->apply_billing_form_debug_settings(
1431
+					$this->checkout->billing_form
1432
+				);
1433
+		}
1434
+		// get html and validation rules for form
1435
+		if ($this->checkout->billing_form instanceof EE_Form_Section_Proper) {
1436
+			$this->checkout->json_response->set_return_data(
1437
+				array('payment_method_info' => $this->checkout->billing_form->get_html())
1438
+			);
1439
+			// localize validation rules for main form
1440
+			$this->checkout->billing_form->localize_validation_rules(true);
1441
+			$this->checkout->json_response->add_validation_rules(EE_Form_Section_Proper::js_localization());
1442
+		} else {
1443
+			$this->checkout->json_response->set_return_data(array('payment_method_info' => ''));
1444
+		}
1445
+		// prevents advancement to next step
1446
+		$this->checkout->continue_reg = false;
1447
+		return true;
1448
+	}
1449
+
1450
+
1451
+	/**
1452
+	 * _verify_payment_method_is_set
1453
+	 *
1454
+	 * @return bool
1455
+	 * @throws EE_Error
1456
+	 * @throws InvalidArgumentException
1457
+	 * @throws ReflectionException
1458
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1459
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1460
+	 */
1461
+	protected function _verify_payment_method_is_set()
1462
+	{
1463
+		// generate billing form for selected method of payment if it hasn't been done already
1464
+		if (empty($this->checkout->selected_method_of_payment)) {
1465
+			// how have they chosen to pay?
1466
+			$this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
1467
+		} else {
1468
+			// choose your own adventure based on method_of_payment
1469
+			switch ($this->checkout->selected_method_of_payment) {
1470
+				case 'events_sold_out':
1471
+					EE_Error::add_attention(
1472
+						apply_filters(
1473
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___verify_payment_method_is_set__sold_out_events_msg',
1474
+							esc_html__(
1475
+								'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.',
1476
+								'event_espresso'
1477
+							)
1478
+						),
1479
+						__FILE__,
1480
+						__FUNCTION__,
1481
+						__LINE__
1482
+					);
1483
+					return false;
1484
+					break;
1485
+				case 'payments_closed':
1486
+					EE_Error::add_attention(
1487
+						apply_filters(
1488
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___verify_payment_method_is_set__payments_closed_msg',
1489
+							esc_html__(
1490
+								'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.',
1491
+								'event_espresso'
1492
+							)
1493
+						),
1494
+						__FILE__,
1495
+						__FUNCTION__,
1496
+						__LINE__
1497
+					);
1498
+					return false;
1499
+					break;
1500
+				case 'no_payment_required':
1501
+					EE_Error::add_attention(
1502
+						apply_filters(
1503
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___verify_payment_method_is_set__no_payment_required_msg',
1504
+							esc_html__(
1505
+								'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.',
1506
+								'event_espresso'
1507
+							)
1508
+						),
1509
+						__FILE__,
1510
+						__FUNCTION__,
1511
+						__LINE__
1512
+					);
1513
+					return false;
1514
+					break;
1515
+				default:
1516
+			}
1517
+		}
1518
+		// verify payment method
1519
+		if (! $this->checkout->payment_method instanceof EE_Payment_Method) {
1520
+			// get payment method for selected method of payment
1521
+			$this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment();
1522
+		}
1523
+		return $this->checkout->payment_method instanceof EE_Payment_Method ? true : false;
1524
+	}
1525
+
1526
+
1527
+
1528
+	/********************************************************************************************************/
1529
+	/***************************************  SAVE PAYER DETAILS  ****************************************/
1530
+	/********************************************************************************************************/
1531
+	/**
1532
+	 * save_payer_details_via_ajax
1533
+	 *
1534
+	 * @return void
1535
+	 * @throws EE_Error
1536
+	 * @throws InvalidArgumentException
1537
+	 * @throws ReflectionException
1538
+	 * @throws RuntimeException
1539
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1540
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1541
+	 */
1542
+	public function save_payer_details_via_ajax()
1543
+	{
1544
+		if (! $this->_verify_payment_method_is_set()) {
1545
+			return;
1546
+		}
1547
+		// generate billing form for selected method of payment if it hasn't been done already
1548
+		if ($this->checkout->payment_method->type_obj()->has_billing_form()) {
1549
+			$this->checkout->billing_form = $this->_get_billing_form_for_payment_method(
1550
+				$this->checkout->payment_method
1551
+			);
1552
+		}
1553
+		// generate primary attendee from payer info if applicable
1554
+		if (! $this->checkout->transaction_has_primary_registrant()) {
1555
+			$attendee = $this->_create_attendee_from_request_data();
1556
+			if ($attendee instanceof EE_Attendee) {
1557
+				foreach ($this->checkout->transaction->registrations() as $registration) {
1558
+					if ($registration->is_primary_registrant()) {
1559
+						$this->checkout->primary_attendee_obj = $attendee;
1560
+						$registration->_add_relation_to($attendee, 'Attendee');
1561
+						$registration->set_attendee_id($attendee->ID());
1562
+						$registration->update_cache_after_object_save('Attendee', $attendee);
1563
+					}
1564
+				}
1565
+			}
1566
+		}
1567
+	}
1568
+
1569
+
1570
+	/**
1571
+	 * create_attendee_from_request_data
1572
+	 * uses info from alternate GET or POST data (such as AJAX) to create a new attendee
1573
+	 *
1574
+	 * @return EE_Attendee
1575
+	 * @throws EE_Error
1576
+	 * @throws InvalidArgumentException
1577
+	 * @throws ReflectionException
1578
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1579
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1580
+	 */
1581
+	protected function _create_attendee_from_request_data()
1582
+	{
1583
+		// get State ID
1584
+		$STA_ID = ! empty($_REQUEST['state']) ? sanitize_text_field($_REQUEST['state']) : '';
1585
+		if (! empty($STA_ID)) {
1586
+			// can we get state object from name ?
1587
+			EE_Registry::instance()->load_model('State');
1588
+			$state = EEM_State::instance()->get_col(array(array('STA_name' => $STA_ID), 'limit' => 1), 'STA_ID');
1589
+			$STA_ID = is_array($state) && ! empty($state) ? reset($state) : $STA_ID;
1590
+		}
1591
+		// get Country ISO
1592
+		$CNT_ISO = ! empty($_REQUEST['country']) ? sanitize_text_field($_REQUEST['country']) : '';
1593
+		if (! empty($CNT_ISO)) {
1594
+			// can we get country object from name ?
1595
+			EE_Registry::instance()->load_model('Country');
1596
+			$country = EEM_Country::instance()->get_col(
1597
+				array(array('CNT_name' => $CNT_ISO), 'limit' => 1),
1598
+				'CNT_ISO'
1599
+			);
1600
+			$CNT_ISO = is_array($country) && ! empty($country) ? reset($country) : $CNT_ISO;
1601
+		}
1602
+		// grab attendee data
1603
+		$attendee_data = array(
1604
+			'ATT_fname'    => ! empty($_REQUEST['first_name']) ? sanitize_text_field($_REQUEST['first_name']) : '',
1605
+			'ATT_lname'    => ! empty($_REQUEST['last_name']) ? sanitize_text_field($_REQUEST['last_name']) : '',
1606
+			'ATT_email'    => ! empty($_REQUEST['email']) ? sanitize_email($_REQUEST['email']) : '',
1607
+			'ATT_address'  => ! empty($_REQUEST['address']) ? sanitize_text_field($_REQUEST['address']) : '',
1608
+			'ATT_address2' => ! empty($_REQUEST['address2']) ? sanitize_text_field($_REQUEST['address2']) : '',
1609
+			'ATT_city'     => ! empty($_REQUEST['city']) ? sanitize_text_field($_REQUEST['city']) : '',
1610
+			'STA_ID'       => $STA_ID,
1611
+			'CNT_ISO'      => $CNT_ISO,
1612
+			'ATT_zip'      => ! empty($_REQUEST['zip']) ? sanitize_text_field($_REQUEST['zip']) : '',
1613
+			'ATT_phone'    => ! empty($_REQUEST['phone']) ? sanitize_text_field($_REQUEST['phone']) : '',
1614
+		);
1615
+		// validate the email address since it is the most important piece of info
1616
+		if (empty($attendee_data['ATT_email']) || $attendee_data['ATT_email'] !== $_REQUEST['email']) {
1617
+			EE_Error::add_error(
1618
+				esc_html__('An invalid email address was submitted.', 'event_espresso'),
1619
+				__FILE__,
1620
+				__FUNCTION__,
1621
+				__LINE__
1622
+			);
1623
+		}
1624
+		// does this attendee already exist in the db ? we're searching using a combination of first name, last name,
1625
+		// AND email address
1626
+		if (! empty($attendee_data['ATT_fname'])
1627
+			&& ! empty($attendee_data['ATT_lname'])
1628
+			&& ! empty($attendee_data['ATT_email'])
1629
+		) {
1630
+			$existing_attendee = EE_Registry::instance()->LIB->EEM_Attendee->find_existing_attendee(
1631
+				array(
1632
+					'ATT_fname' => $attendee_data['ATT_fname'],
1633
+					'ATT_lname' => $attendee_data['ATT_lname'],
1634
+					'ATT_email' => $attendee_data['ATT_email'],
1635
+				)
1636
+			);
1637
+			if ($existing_attendee instanceof EE_Attendee) {
1638
+				return $existing_attendee;
1639
+			}
1640
+		}
1641
+		// no existing attendee? kk let's create a new one
1642
+		// kinda lame, but we need a first and last name to create an attendee, so use the email address if those
1643
+		// don't exist
1644
+		$attendee_data['ATT_fname'] = ! empty($attendee_data['ATT_fname'])
1645
+			? $attendee_data['ATT_fname']
1646
+			: $attendee_data['ATT_email'];
1647
+		$attendee_data['ATT_lname'] = ! empty($attendee_data['ATT_lname'])
1648
+			? $attendee_data['ATT_lname']
1649
+			: $attendee_data['ATT_email'];
1650
+		return EE_Attendee::new_instance($attendee_data);
1651
+	}
1652
+
1653
+
1654
+
1655
+	/********************************************************************************************************/
1656
+	/****************************************  PROCESS REG STEP  *****************************************/
1657
+	/********************************************************************************************************/
1658
+	/**
1659
+	 * process_reg_step
1660
+	 *
1661
+	 * @return bool
1662
+	 * @throws EE_Error
1663
+	 * @throws InvalidArgumentException
1664
+	 * @throws ReflectionException
1665
+	 * @throws \EventEspresso\core\exceptions\EntityNotFoundException
1666
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1667
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1668
+	 * @throws \EventEspresso\core\exceptions\InvalidStatusException
1669
+	 */
1670
+	public function process_reg_step()
1671
+	{
1672
+		// how have they chosen to pay?
1673
+		$this->checkout->selected_method_of_payment = $this->checkout->transaction->is_free()
1674
+			? 'no_payment_required'
1675
+			: $this->_get_selected_method_of_payment(true);
1676
+		// choose your own adventure based on method_of_payment
1677
+		switch ($this->checkout->selected_method_of_payment) {
1678
+			case 'events_sold_out':
1679
+				$this->checkout->redirect = true;
1680
+				$this->checkout->redirect_url = $this->checkout->cancel_page_url;
1681
+				$this->checkout->json_response->set_redirect_url($this->checkout->redirect_url);
1682
+				// mark this reg step as completed
1683
+				$this->set_completed();
1684
+				return false;
1685
+				break;
1686
+
1687
+			case 'payments_closed':
1688
+				if (apply_filters(
1689
+					'FHEE__EE_SPCO_Reg_Step_Payment_Options__process_reg_step__payments_closed__display_success',
1690
+					false
1691
+				)) {
1692
+					EE_Error::add_success(
1693
+						esc_html__('no payment required at this time.', 'event_espresso'),
1694
+						__FILE__,
1695
+						__FUNCTION__,
1696
+						__LINE__
1697
+					);
1698
+				}
1699
+				// mark this reg step as completed
1700
+				$this->set_completed();
1701
+				return true;
1702
+				break;
1703
+
1704
+			case 'no_payment_required':
1705
+				if (apply_filters(
1706
+					'FHEE__EE_SPCO_Reg_Step_Payment_Options__process_reg_step__no_payment_required__display_success',
1707
+					false
1708
+				)) {
1709
+					EE_Error::add_success(
1710
+						esc_html__('no payment required.', 'event_espresso'),
1711
+						__FILE__,
1712
+						__FUNCTION__,
1713
+						__LINE__
1714
+					);
1715
+				}
1716
+				// mark this reg step as completed
1717
+				$this->set_completed();
1718
+				return true;
1719
+				break;
1720
+
1721
+			default:
1722
+				$registrations = EE_Registry::instance()->SSN->checkout()->transaction->registrations(
1723
+					EE_Registry::instance()->SSN->checkout()->reg_cache_where_params
1724
+				);
1725
+				$ejected_registrations = EE_SPCO_Reg_Step_Payment_Options::find_registrations_that_lost_their_space(
1726
+					$registrations,
1727
+					EE_Registry::instance()->SSN->checkout()->revisit
1728
+				);
1729
+				// calculate difference between the two arrays
1730
+				$registrations = array_diff($registrations, $ejected_registrations);
1731
+				if (empty($registrations)) {
1732
+					$this->_redirect_because_event_sold_out();
1733
+					return false;
1734
+				}
1735
+				$payment_successful = $this->_process_payment();
1736
+				if ($payment_successful) {
1737
+					$this->checkout->continue_reg = true;
1738
+					$this->_maybe_set_completed($this->checkout->payment_method);
1739
+				} else {
1740
+					$this->checkout->continue_reg = false;
1741
+				}
1742
+				return $payment_successful;
1743
+		}
1744
+	}
1745
+
1746
+
1747
+	/**
1748
+	 * _redirect_because_event_sold_out
1749
+	 *
1750
+	 * @access protected
1751
+	 * @return void
1752
+	 */
1753
+	protected function _redirect_because_event_sold_out()
1754
+	{
1755
+		$this->checkout->continue_reg = false;
1756
+		// set redirect URL
1757
+		$this->checkout->redirect_url = add_query_arg(
1758
+			array('e_reg_url_link' => $this->checkout->reg_url_link),
1759
+			$this->checkout->current_step->reg_step_url()
1760
+		);
1761
+		$this->checkout->json_response->set_redirect_url($this->checkout->redirect_url);
1762
+	}
1763
+
1764
+
1765
+	/**
1766
+	 * _maybe_set_completed
1767
+	 *
1768
+	 * @access protected
1769
+	 * @param \EE_Payment_Method $payment_method
1770
+	 * @return void
1771
+	 * @throws \EE_Error
1772
+	 */
1773
+	protected function _maybe_set_completed(EE_Payment_Method $payment_method)
1774
+	{
1775
+		switch ($payment_method->type_obj()->payment_occurs()) {
1776
+			case EE_PMT_Base::offsite:
1777
+				break;
1778
+			case EE_PMT_Base::onsite:
1779
+			case EE_PMT_Base::offline:
1780
+				// mark this reg step as completed
1781
+				$this->set_completed();
1782
+				break;
1783
+		}
1784
+	}
1785
+
1786
+
1787
+	/**
1788
+	 *    update_reg_step
1789
+	 *    this is the final step after a user  revisits the site to retry a payment
1790
+	 *
1791
+	 * @return bool
1792
+	 * @throws EE_Error
1793
+	 * @throws InvalidArgumentException
1794
+	 * @throws ReflectionException
1795
+	 * @throws \EventEspresso\core\exceptions\EntityNotFoundException
1796
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1797
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1798
+	 * @throws \EventEspresso\core\exceptions\InvalidStatusException
1799
+	 */
1800
+	public function update_reg_step()
1801
+	{
1802
+		$success = true;
1803
+		// if payment required
1804
+		if ($this->checkout->transaction->total() > 0) {
1805
+			do_action(
1806
+				'AHEE__EE_Single_Page_Checkout__process_finalize_registration__before_gateway',
1807
+				$this->checkout->transaction
1808
+			);
1809
+			// attempt payment via payment method
1810
+			$success = $this->process_reg_step();
1811
+		}
1812
+		if ($success && ! $this->checkout->redirect) {
1813
+			$this->checkout->cart->get_grand_total()->save_this_and_descendants_to_txn(
1814
+				$this->checkout->transaction->ID()
1815
+			);
1816
+			// set return URL
1817
+			$this->checkout->redirect_url = add_query_arg(
1818
+				array('e_reg_url_link' => $this->checkout->reg_url_link),
1819
+				$this->checkout->thank_you_page_url
1820
+			);
1821
+		}
1822
+		return $success;
1823
+	}
1824
+
1825
+
1826
+	/**
1827
+	 *    _process_payment
1828
+	 *
1829
+	 * @access private
1830
+	 * @return bool
1831
+	 * @throws EE_Error
1832
+	 * @throws InvalidArgumentException
1833
+	 * @throws ReflectionException
1834
+	 * @throws RuntimeException
1835
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1836
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1837
+	 */
1838
+	private function _process_payment()
1839
+	{
1840
+		// basically confirm that the event hasn't sold out since they hit the page
1841
+		if (! $this->_last_second_ticket_verifications()) {
1842
+			return false;
1843
+		}
1844
+		// ya gotta make a choice man
1845
+		if (empty($this->checkout->selected_method_of_payment)) {
1846
+			$this->checkout->json_response->set_plz_select_method_of_payment(
1847
+				esc_html__('Please select a method of payment before proceeding.', 'event_espresso')
1848
+			);
1849
+			return false;
1850
+		}
1851
+		// get EE_Payment_Method object
1852
+		if (! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()) {
1853
+			return false;
1854
+		}
1855
+		// setup billing form
1856
+		if ($this->checkout->payment_method->is_on_site()) {
1857
+			$this->checkout->billing_form = $this->_get_billing_form_for_payment_method(
1858
+				$this->checkout->payment_method
1859
+			);
1860
+			// bad billing form ?
1861
+			if (! $this->_billing_form_is_valid()) {
1862
+				return false;
1863
+			}
1864
+		}
1865
+		// ensure primary registrant has been fully processed
1866
+		if (! $this->_setup_primary_registrant_prior_to_payment()) {
1867
+			return false;
1868
+		}
1869
+		// if session is close to expiring (under 10 minutes by default)
1870
+		if ((time() - EE_Registry::instance()->SSN->expiration()) < EE_Registry::instance()->SSN->extension()) {
1871
+			// add some time to session expiration so that payment can be completed
1872
+			EE_Registry::instance()->SSN->extend_expiration();
1873
+		}
1874
+		/** @type EE_Transaction_Processor $transaction_processor */
1875
+		// $transaction_processor = EE_Registry::instance()->load_class( 'Transaction_Processor' );
1876
+		// in case a registrant leaves to an Off-Site Gateway and never returns, we want to approve any registrations
1877
+		// for events with a default reg status of Approved
1878
+		// $transaction_processor->toggle_registration_statuses_for_default_approved_events(
1879
+		//      $this->checkout->transaction, $this->checkout->reg_cache_where_params
1880
+		// );
1881
+		// attempt payment
1882
+		$payment = $this->_attempt_payment($this->checkout->payment_method);
1883
+		// process results
1884
+		$payment = $this->_validate_payment($payment);
1885
+		$payment = $this->_post_payment_processing($payment);
1886
+		// verify payment
1887
+		if ($payment instanceof EE_Payment) {
1888
+			// store that for later
1889
+			$this->checkout->payment = $payment;
1890
+			// we can also consider the TXN to not have been failed, so temporarily upgrade it's status to abandoned
1891
+			$this->checkout->transaction->toggle_failed_transaction_status();
1892
+			$payment_status = $payment->status();
1893
+			if ($payment_status === EEM_Payment::status_id_approved
1894
+				|| $payment_status === EEM_Payment::status_id_pending
1895
+			) {
1896
+				return true;
1897
+			} else {
1898
+				return false;
1899
+			}
1900
+		} elseif ($payment === true) {
1901
+			// please note that offline payment methods will NOT make a payment,
1902
+			// but instead just mark themselves as the PMD_ID on the transaction, and return true
1903
+			$this->checkout->payment = $payment;
1904
+			return true;
1905
+		}
1906
+		// where's my money?
1907
+		return false;
1908
+	}
1909
+
1910
+
1911
+	/**
1912
+	 * _last_second_ticket_verifications
1913
+	 *
1914
+	 * @access public
1915
+	 * @return bool
1916
+	 * @throws EE_Error
1917
+	 */
1918
+	protected function _last_second_ticket_verifications()
1919
+	{
1920
+		// don't bother re-validating if not a return visit
1921
+		if (! $this->checkout->revisit) {
1922
+			return true;
1923
+		}
1924
+		$registrations = $this->checkout->transaction->registrations();
1925
+		if (empty($registrations)) {
1926
+			return false;
1927
+		}
1928
+		foreach ($registrations as $registration) {
1929
+			if ($registration instanceof EE_Registration && ! $registration->is_approved()) {
1930
+				$event = $registration->event_obj();
1931
+				if ($event instanceof EE_Event && $event->is_sold_out(true)) {
1932
+					EE_Error::add_error(
1933
+						apply_filters(
1934
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___last_second_ticket_verifications__sold_out_events_msg',
1935
+							sprintf(
1936
+								esc_html__(
1937
+									'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.',
1938
+									'event_espresso'
1939
+								),
1940
+								$event->name()
1941
+							)
1942
+						),
1943
+						__FILE__,
1944
+						__FUNCTION__,
1945
+						__LINE__
1946
+					);
1947
+					return false;
1948
+				}
1949
+			}
1950
+		}
1951
+		return true;
1952
+	}
1953
+
1954
+
1955
+	/**
1956
+	 * redirect_form
1957
+	 *
1958
+	 * @access public
1959
+	 * @return bool
1960
+	 * @throws EE_Error
1961
+	 * @throws InvalidArgumentException
1962
+	 * @throws ReflectionException
1963
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1964
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1965
+	 */
1966
+	public function redirect_form()
1967
+	{
1968
+		$payment_method_billing_info = $this->_payment_method_billing_info(
1969
+			$this->_get_payment_method_for_selected_method_of_payment()
1970
+		);
1971
+		$html = $payment_method_billing_info->get_html();
1972
+		$html .= $this->checkout->redirect_form;
1973
+		EE_Registry::instance()->REQ->add_output($html);
1974
+		return true;
1975
+	}
1976
+
1977
+
1978
+	/**
1979
+	 * _billing_form_is_valid
1980
+	 *
1981
+	 * @access private
1982
+	 * @return bool
1983
+	 * @throws \EE_Error
1984
+	 */
1985
+	private function _billing_form_is_valid()
1986
+	{
1987
+		if (! $this->checkout->payment_method->type_obj()->has_billing_form()) {
1988
+			return true;
1989
+		}
1990
+		if ($this->checkout->billing_form instanceof EE_Billing_Info_Form) {
1991
+			if ($this->checkout->billing_form->was_submitted()) {
1992
+				$this->checkout->billing_form->receive_form_submission();
1993
+				if ($this->checkout->billing_form->is_valid()) {
1994
+					return true;
1995
+				}
1996
+				$validation_errors = $this->checkout->billing_form->get_validation_errors_accumulated();
1997
+				$error_strings = array();
1998
+				foreach ($validation_errors as $validation_error) {
1999
+					if ($validation_error instanceof EE_Validation_Error) {
2000
+						$form_section = $validation_error->get_form_section();
2001
+						if ($form_section instanceof EE_Form_Input_Base) {
2002
+							$label = $form_section->html_label_text();
2003
+						} elseif ($form_section instanceof EE_Form_Section_Base) {
2004
+							$label = $form_section->name();
2005
+						} else {
2006
+							$label = esc_html__('Validation Error', 'event_espresso');
2007
+						}
2008
+						$error_strings[] = sprintf('%1$s: %2$s', $label, $validation_error->getMessage());
2009
+					}
2010
+				}
2011
+				EE_Error::add_error(
2012
+					sprintf(
2013
+						esc_html__(
2014
+							'One or more billing form inputs are invalid and require correction before proceeding. %1$s %2$s',
2015
+							'event_espresso'
2016
+						),
2017
+						'<br/>',
2018
+						implode('<br/>', $error_strings)
2019
+					),
2020
+					__FILE__,
2021
+					__FUNCTION__,
2022
+					__LINE__
2023
+				);
2024
+			} else {
2025
+				EE_Error::add_error(
2026
+					esc_html__(
2027
+						'The billing form was not submitted or something prevented it\'s submission.',
2028
+						'event_espresso'
2029
+					),
2030
+					__FILE__,
2031
+					__FUNCTION__,
2032
+					__LINE__
2033
+				);
2034
+			}
2035
+		} else {
2036
+			EE_Error::add_error(
2037
+				esc_html__(
2038
+					'The submitted billing form is invalid possibly due to a technical reason.',
2039
+					'event_espresso'
2040
+				),
2041
+				__FILE__,
2042
+				__FUNCTION__,
2043
+				__LINE__
2044
+			);
2045
+		}
2046
+		return false;
2047
+	}
2048
+
2049
+
2050
+	/**
2051
+	 * _setup_primary_registrant_prior_to_payment
2052
+	 * ensures that the primary registrant has a valid attendee object created with the critical details populated
2053
+	 * (first & last name & email) and that both the transaction object and primary registration object have been saved
2054
+	 * plz note that any other registrations will NOT be saved at this point (because they may not have any details
2055
+	 * yet)
2056
+	 *
2057
+	 * @access private
2058
+	 * @return bool
2059
+	 * @throws EE_Error
2060
+	 * @throws InvalidArgumentException
2061
+	 * @throws ReflectionException
2062
+	 * @throws RuntimeException
2063
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2064
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2065
+	 */
2066
+	private function _setup_primary_registrant_prior_to_payment()
2067
+	{
2068
+		// check if transaction has a primary registrant and that it has a related Attendee object
2069
+		// if not, then we need to at least gather some primary registrant data before attempting payment
2070
+		if ($this->checkout->billing_form instanceof EE_Billing_Attendee_Info_Form
2071
+			&& ! $this->checkout->transaction_has_primary_registrant()
2072
+			&& ! $this->_capture_primary_registration_data_from_billing_form()
2073
+		) {
2074
+			return false;
2075
+		}
2076
+		// because saving an object clears it's cache, we need to do the chevy shuffle
2077
+		// grab the primary_registration object
2078
+		$primary_registration = $this->checkout->transaction->primary_registration();
2079
+		// at this point we'll consider a TXN to not have been failed
2080
+		$this->checkout->transaction->toggle_failed_transaction_status();
2081
+		// save the TXN ( which clears cached copy of primary_registration)
2082
+		$this->checkout->transaction->save();
2083
+		// grab TXN ID and save it to the primary_registration
2084
+		$primary_registration->set_transaction_id($this->checkout->transaction->ID());
2085
+		// save what we have so far
2086
+		$primary_registration->save();
2087
+		return true;
2088
+	}
2089
+
2090
+
2091
+	/**
2092
+	 * _capture_primary_registration_data_from_billing_form
2093
+	 *
2094
+	 * @access private
2095
+	 * @return bool
2096
+	 * @throws EE_Error
2097
+	 * @throws InvalidArgumentException
2098
+	 * @throws ReflectionException
2099
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2100
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2101
+	 */
2102
+	private function _capture_primary_registration_data_from_billing_form()
2103
+	{
2104
+		// convert billing form data into an attendee
2105
+		$this->checkout->primary_attendee_obj = $this->checkout->billing_form->create_attendee_from_billing_form_data();
2106
+		if (! $this->checkout->primary_attendee_obj instanceof EE_Attendee) {
2107
+			EE_Error::add_error(
2108
+				sprintf(
2109
+					esc_html__(
2110
+						'The billing form details could not be used for attendee details due to a technical issue.%sPlease try again or contact %s for assistance.',
2111
+						'event_espresso'
2112
+					),
2113
+					'<br/>',
2114
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
2115
+				),
2116
+				__FILE__,
2117
+				__FUNCTION__,
2118
+				__LINE__
2119
+			);
2120
+			return false;
2121
+		}
2122
+		$primary_registration = $this->checkout->transaction->primary_registration();
2123
+		if (! $primary_registration instanceof EE_Registration) {
2124
+			EE_Error::add_error(
2125
+				sprintf(
2126
+					esc_html__(
2127
+						'The primary registrant for this transaction could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.',
2128
+						'event_espresso'
2129
+					),
2130
+					'<br/>',
2131
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
2132
+				),
2133
+				__FILE__,
2134
+				__FUNCTION__,
2135
+				__LINE__
2136
+			);
2137
+			return false;
2138
+		}
2139
+		if (! $primary_registration->_add_relation_to($this->checkout->primary_attendee_obj, 'Attendee')
2140
+			  instanceof
2141
+			  EE_Attendee
2142
+		) {
2143
+			EE_Error::add_error(
2144
+				sprintf(
2145
+					esc_html__(
2146
+						'The primary registrant could not be associated with this transaction due to a technical issue.%sPlease try again or contact %s for assistance.',
2147
+						'event_espresso'
2148
+					),
2149
+					'<br/>',
2150
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
2151
+				),
2152
+				__FILE__,
2153
+				__FUNCTION__,
2154
+				__LINE__
2155
+			);
2156
+			return false;
2157
+		}
2158
+		/** @type EE_Registration_Processor $registration_processor */
2159
+		$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
2160
+		// at this point, we should have enough details about the registrant to consider the registration NOT incomplete
2161
+		$registration_processor->toggle_incomplete_registration_status_to_default($primary_registration);
2162
+		return true;
2163
+	}
2164
+
2165
+
2166
+	/**
2167
+	 * _get_payment_method_for_selected_method_of_payment
2168
+	 * retrieves a valid payment method
2169
+	 *
2170
+	 * @access public
2171
+	 * @return EE_Payment_Method
2172
+	 * @throws EE_Error
2173
+	 * @throws InvalidArgumentException
2174
+	 * @throws ReflectionException
2175
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2176
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2177
+	 */
2178
+	private function _get_payment_method_for_selected_method_of_payment()
2179
+	{
2180
+		if ($this->checkout->selected_method_of_payment === 'events_sold_out') {
2181
+			$this->_redirect_because_event_sold_out();
2182
+			return null;
2183
+		}
2184
+		// get EE_Payment_Method object
2185
+		if (isset($this->checkout->available_payment_methods[ $this->checkout->selected_method_of_payment ])) {
2186
+			$payment_method = $this->checkout->available_payment_methods[ $this->checkout->selected_method_of_payment ];
2187
+		} else {
2188
+			// load EEM_Payment_Method
2189
+			EE_Registry::instance()->load_model('Payment_Method');
2190
+			/** @type EEM_Payment_Method $EEM_Payment_Method */
2191
+			$EEM_Payment_Method = EE_Registry::instance()->LIB->EEM_Payment_Method;
2192
+			$payment_method = $EEM_Payment_Method->get_one_by_slug($this->checkout->selected_method_of_payment);
2193
+		}
2194
+		// verify $payment_method
2195
+		if (! $payment_method instanceof EE_Payment_Method) {
2196
+			// not a payment
2197
+			EE_Error::add_error(
2198
+				sprintf(
2199
+					esc_html__(
2200
+						'The selected method of payment could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.',
2201
+						'event_espresso'
2202
+					),
2203
+					'<br/>',
2204
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
2205
+				),
2206
+				__FILE__,
2207
+				__FUNCTION__,
2208
+				__LINE__
2209
+			);
2210
+			return null;
2211
+		}
2212
+		// and verify it has a valid Payment_Method Type object
2213
+		if (! $payment_method->type_obj() instanceof EE_PMT_Base) {
2214
+			// not a payment
2215
+			EE_Error::add_error(
2216
+				sprintf(
2217
+					esc_html__(
2218
+						'A valid payment method could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.',
2219
+						'event_espresso'
2220
+					),
2221
+					'<br/>',
2222
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
2223
+				),
2224
+				__FILE__,
2225
+				__FUNCTION__,
2226
+				__LINE__
2227
+			);
2228
+			return null;
2229
+		}
2230
+		return $payment_method;
2231
+	}
2232
+
2233
+
2234
+	/**
2235
+	 *    _attempt_payment
2236
+	 *
2237
+	 * @access    private
2238
+	 * @type    EE_Payment_Method $payment_method
2239
+	 * @return mixed EE_Payment | boolean
2240
+	 * @throws EE_Error
2241
+	 * @throws InvalidArgumentException
2242
+	 * @throws ReflectionException
2243
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2244
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2245
+	 */
2246
+	private function _attempt_payment(EE_Payment_Method $payment_method)
2247
+	{
2248
+		$payment = null;
2249
+		$this->checkout->transaction->save();
2250
+		$payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2251
+		if (! $payment_processor instanceof EE_Payment_Processor) {
2252
+			return false;
2253
+		}
2254
+		try {
2255
+			$payment_processor->set_revisit($this->checkout->revisit);
2256
+			// generate payment object
2257
+			$payment = $payment_processor->process_payment(
2258
+				$payment_method,
2259
+				$this->checkout->transaction,
2260
+				$this->checkout->amount_owing,
2261
+				$this->checkout->billing_form,
2262
+				$this->_get_return_url($payment_method),
2263
+				'CART',
2264
+				$this->checkout->admin_request,
2265
+				true,
2266
+				$this->reg_step_url()
2267
+			);
2268
+		} catch (Exception $e) {
2269
+			$this->_handle_payment_processor_exception($e);
2270
+		}
2271
+		return $payment;
2272
+	}
2273
+
2274
+
2275
+	/**
2276
+	 * _handle_payment_processor_exception
2277
+	 *
2278
+	 * @access protected
2279
+	 * @param \Exception $e
2280
+	 * @return void
2281
+	 * @throws EE_Error
2282
+	 * @throws InvalidArgumentException
2283
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2284
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2285
+	 */
2286
+	protected function _handle_payment_processor_exception(Exception $e)
2287
+	{
2288
+		EE_Error::add_error(
2289
+			sprintf(
2290
+				esc_html__(
2291
+					'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',
2292
+					'event_espresso'
2293
+				),
2294
+				'<br/>',
2295
+				EE_Registry::instance()->CFG->organization->get_pretty('email'),
2296
+				$e->getMessage(),
2297
+				$e->getFile(),
2298
+				$e->getLine()
2299
+			),
2300
+			__FILE__,
2301
+			__FUNCTION__,
2302
+			__LINE__
2303
+		);
2304
+	}
2305
+
2306
+
2307
+	/**
2308
+	 * _get_return_url
2309
+	 *
2310
+	 * @access protected
2311
+	 * @param \EE_Payment_Method $payment_method
2312
+	 * @return string
2313
+	 * @throws \EE_Error
2314
+	 */
2315
+	protected function _get_return_url(EE_Payment_Method $payment_method)
2316
+	{
2317
+		$return_url = '';
2318
+		switch ($payment_method->type_obj()->payment_occurs()) {
2319
+			case EE_PMT_Base::offsite:
2320
+				$return_url = add_query_arg(
2321
+					array(
2322
+						'action'                     => 'process_gateway_response',
2323
+						'selected_method_of_payment' => $this->checkout->selected_method_of_payment,
2324
+						'spco_txn'                   => $this->checkout->transaction->ID(),
2325
+					),
2326
+					$this->reg_step_url()
2327
+				);
2328
+				break;
2329
+			case EE_PMT_Base::onsite:
2330
+			case EE_PMT_Base::offline:
2331
+				$return_url = $this->checkout->next_step->reg_step_url();
2332
+				break;
2333
+		}
2334
+		return $return_url;
2335
+	}
2336
+
2337
+
2338
+	/**
2339
+	 * _validate_payment
2340
+	 *
2341
+	 * @access private
2342
+	 * @param EE_Payment $payment
2343
+	 * @return EE_Payment|FALSE
2344
+	 * @throws EE_Error
2345
+	 * @throws InvalidArgumentException
2346
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2347
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2348
+	 */
2349
+	private function _validate_payment($payment = null)
2350
+	{
2351
+		if ($this->checkout->payment_method->is_off_line()) {
2352
+			return true;
2353
+		}
2354
+		// verify payment object
2355
+		if (! $payment instanceof EE_Payment) {
2356
+			// not a payment
2357
+			EE_Error::add_error(
2358
+				sprintf(
2359
+					esc_html__(
2360
+						'A valid payment was not generated due to a technical issue.%1$sPlease try again or contact %2$s for assistance.',
2361
+						'event_espresso'
2362
+					),
2363
+					'<br/>',
2364
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
2365
+				),
2366
+				__FILE__,
2367
+				__FUNCTION__,
2368
+				__LINE__
2369
+			);
2370
+			return false;
2371
+		}
2372
+		return $payment;
2373
+	}
2374
+
2375
+
2376
+	/**
2377
+	 * _post_payment_processing
2378
+	 *
2379
+	 * @access private
2380
+	 * @param EE_Payment|bool $payment
2381
+	 * @return bool
2382
+	 * @throws EE_Error
2383
+	 * @throws InvalidArgumentException
2384
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2385
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2386
+	 */
2387
+	private function _post_payment_processing($payment = null)
2388
+	{
2389
+		// Off-Line payment?
2390
+		if ($payment === true) {
2391
+			// $this->_setup_redirect_for_next_step();
2392
+			return true;
2393
+			// On-Site payment?
2394
+		} elseif ($this->checkout->payment_method->is_on_site()) {
2395
+			if (! $this->_process_payment_status($payment, EE_PMT_Base::onsite)) {
2396
+				// $this->_setup_redirect_for_next_step();
2397
+				$this->checkout->continue_reg = false;
2398
+			}
2399
+			// Off-Site payment?
2400
+		} elseif ($this->checkout->payment_method->is_off_site()) {
2401
+			// if a payment object was made and it specifies a redirect url, then we'll setup that redirect info
2402
+			if ($payment instanceof EE_Payment && $payment->redirect_url()) {
2403
+				do_action('AHEE_log', __CLASS__, __FUNCTION__, $payment->redirect_url(), '$payment->redirect_url()');
2404
+				$this->checkout->redirect = true;
2405
+				$this->checkout->redirect_form = $payment->redirect_form();
2406
+				$this->checkout->redirect_url = $this->reg_step_url('redirect_form');
2407
+				// set JSON response
2408
+				$this->checkout->json_response->set_redirect_form($this->checkout->redirect_form);
2409
+				// and lastly, let's bump the payment status to pending
2410
+				$payment->set_status(EEM_Payment::status_id_pending);
2411
+				$payment->save();
2412
+			} else {
2413
+				// not a payment
2414
+				$this->checkout->continue_reg = false;
2415
+				EE_Error::add_error(
2416
+					sprintf(
2417
+						esc_html__(
2418
+							'It appears the Off Site Payment Method was not configured properly.%sPlease try again or contact %s for assistance.',
2419
+							'event_espresso'
2420
+						),
2421
+						'<br/>',
2422
+						EE_Registry::instance()->CFG->organization->get_pretty('email')
2423
+					),
2424
+					__FILE__,
2425
+					__FUNCTION__,
2426
+					__LINE__
2427
+				);
2428
+			}
2429
+		} else {
2430
+			// ummm ya... not Off-Line, not On-Site, not off-Site ????
2431
+			$this->checkout->continue_reg = false;
2432
+			return false;
2433
+		}
2434
+		return $payment;
2435
+	}
2436
+
2437
+
2438
+	/**
2439
+	 *    _process_payment_status
2440
+	 *
2441
+	 * @access private
2442
+	 * @type    EE_Payment $payment
2443
+	 * @param string       $payment_occurs
2444
+	 * @return bool
2445
+	 * @throws EE_Error
2446
+	 * @throws InvalidArgumentException
2447
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2448
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2449
+	 */
2450
+	private function _process_payment_status($payment, $payment_occurs = EE_PMT_Base::offline)
2451
+	{
2452
+		// off-line payment? carry on
2453
+		if ($payment_occurs === EE_PMT_Base::offline) {
2454
+			return true;
2455
+		}
2456
+		// verify payment validity
2457
+		if ($payment instanceof EE_Payment) {
2458
+			do_action('AHEE_log', __CLASS__, __FUNCTION__, $payment->status(), '$payment->status()');
2459
+			$msg = $payment->gateway_response();
2460
+			// check results
2461
+			switch ($payment->status()) {
2462
+				// good payment
2463
+				case EEM_Payment::status_id_approved:
2464
+					EE_Error::add_success(
2465
+						esc_html__('Your payment was processed successfully.', 'event_espresso'),
2466
+						__FILE__,
2467
+						__FUNCTION__,
2468
+						__LINE__
2469
+					);
2470
+					return true;
2471
+					break;
2472
+				// slow payment
2473
+				case EEM_Payment::status_id_pending:
2474
+					if (empty($msg)) {
2475
+						$msg = esc_html__(
2476
+							'Your payment appears to have been processed successfully, but the Instant Payment Notification has not yet been received. It should arrive shortly.',
2477
+							'event_espresso'
2478
+						);
2479
+					}
2480
+					EE_Error::add_success($msg, __FILE__, __FUNCTION__, __LINE__);
2481
+					return true;
2482
+					break;
2483
+				// don't wanna payment
2484
+				case EEM_Payment::status_id_cancelled:
2485
+					if (empty($msg)) {
2486
+						$msg = _n(
2487
+							'Payment cancelled. Please try again.',
2488
+							'Payment cancelled. Please try again or select another method of payment.',
2489
+							count($this->checkout->available_payment_methods),
2490
+							'event_espresso'
2491
+						);
2492
+					}
2493
+					EE_Error::add_attention($msg, __FILE__, __FUNCTION__, __LINE__);
2494
+					return false;
2495
+					break;
2496
+				// not enough payment
2497
+				case EEM_Payment::status_id_declined:
2498
+					if (empty($msg)) {
2499
+						$msg = _n(
2500
+							'We\'re sorry but your payment was declined. Please try again.',
2501
+							'We\'re sorry but your payment was declined. Please try again or select another method of payment.',
2502
+							count($this->checkout->available_payment_methods),
2503
+							'event_espresso'
2504
+						);
2505
+					}
2506
+					EE_Error::add_attention($msg, __FILE__, __FUNCTION__, __LINE__);
2507
+					return false;
2508
+					break;
2509
+				// bad payment
2510
+				case EEM_Payment::status_id_failed:
2511
+					if (! empty($msg)) {
2512
+						EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2513
+						return false;
2514
+					}
2515
+					// default to error below
2516
+					break;
2517
+			}
2518
+		}
2519
+		// off-site payment gateway responses are too unreliable, so let's just assume that
2520
+		// the payment processing is just running slower than the registrant's request
2521
+		if ($payment_occurs === EE_PMT_Base::offsite) {
2522
+			return true;
2523
+		}
2524
+		EE_Error::add_error(
2525
+			sprintf(
2526
+				esc_html__(
2527
+					'Your payment could not be processed successfully due to a technical issue.%sPlease try again or contact %s for assistance.',
2528
+					'event_espresso'
2529
+				),
2530
+				'<br/>',
2531
+				EE_Registry::instance()->CFG->organization->get_pretty('email')
2532
+			),
2533
+			__FILE__,
2534
+			__FUNCTION__,
2535
+			__LINE__
2536
+		);
2537
+		return false;
2538
+	}
2539
+
2540
+
2541
+
2542
+
2543
+
2544
+
2545
+	/********************************************************************************************************/
2546
+	/**********************************  PROCESS GATEWAY RESPONSE  **********************************/
2547
+	/********************************************************************************************************/
2548
+	/**
2549
+	 * process_gateway_response
2550
+	 * this is the return point for Off-Site Payment Methods
2551
+	 * It will attempt to "handle the IPN" if it appears that this has not already occurred,
2552
+	 * otherwise, it will load up the last payment made for the TXN.
2553
+	 * If the payment retrieved looks good, it will then either:
2554
+	 *    complete the current step and allow advancement to the next reg step
2555
+	 *        or present the payment options again
2556
+	 *
2557
+	 * @access private
2558
+	 * @return EE_Payment|FALSE
2559
+	 * @throws EE_Error
2560
+	 * @throws InvalidArgumentException
2561
+	 * @throws ReflectionException
2562
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2563
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2564
+	 * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
2565
+	 */
2566
+	public function process_gateway_response()
2567
+	{
2568
+		$payment = null;
2569
+		// how have they chosen to pay?
2570
+		$this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
2571
+		// get EE_Payment_Method object
2572
+		if (! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()) {
2573
+			$this->checkout->continue_reg = false;
2574
+			return false;
2575
+		}
2576
+		if (! $this->checkout->payment_method->is_off_site()) {
2577
+			return false;
2578
+		}
2579
+		$this->_validate_offsite_return();
2580
+		// DEBUG LOG
2581
+		// $this->checkout->log(
2582
+		//     __CLASS__,
2583
+		//     __FUNCTION__,
2584
+		//     __LINE__,
2585
+		//     array(
2586
+		//         'selected_method_of_payment' => $this->checkout->selected_method_of_payment,
2587
+		//         'payment_method'             => $this->checkout->payment_method,
2588
+		//     ),
2589
+		//     true
2590
+		// );
2591
+		// verify TXN
2592
+		if ($this->checkout->transaction instanceof EE_Transaction) {
2593
+			$gateway = $this->checkout->payment_method->type_obj()->get_gateway();
2594
+			if (! $gateway instanceof EE_Offsite_Gateway) {
2595
+				$this->checkout->continue_reg = false;
2596
+				return false;
2597
+			}
2598
+			$payment = $this->_process_off_site_payment($gateway);
2599
+			$payment = $this->_process_cancelled_payments($payment);
2600
+			$payment = $this->_validate_payment($payment);
2601
+			// if payment was not declined by the payment gateway or cancelled by the registrant
2602
+			if ($this->_process_payment_status($payment, EE_PMT_Base::offsite)) {
2603
+				// $this->_setup_redirect_for_next_step();
2604
+				// store that for later
2605
+				$this->checkout->payment = $payment;
2606
+				// mark this reg step as completed, as long as gateway doesn't use a separate IPN request,
2607
+				// because we will complete this step during the IPN processing then
2608
+				if ($gateway instanceof EE_Offsite_Gateway && ! $this->handle_IPN_in_this_request()) {
2609
+					$this->set_completed();
2610
+				}
2611
+				return true;
2612
+			}
2613
+		}
2614
+		// DEBUG LOG
2615
+		// $this->checkout->log(
2616
+		//     __CLASS__,
2617
+		//     __FUNCTION__,
2618
+		//     __LINE__,
2619
+		//     array('payment' => $payment)
2620
+		// );
2621
+		$this->checkout->continue_reg = false;
2622
+		return false;
2623
+	}
2624
+
2625
+
2626
+	/**
2627
+	 * _validate_return
2628
+	 *
2629
+	 * @access private
2630
+	 * @return void
2631
+	 * @throws EE_Error
2632
+	 * @throws InvalidArgumentException
2633
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2634
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2635
+	 * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
2636
+	 */
2637
+	private function _validate_offsite_return()
2638
+	{
2639
+		$TXN_ID = (int) EE_Registry::instance()->REQ->get('spco_txn', 0);
2640
+		if ($TXN_ID !== $this->checkout->transaction->ID()) {
2641
+			// Houston... we might have a problem
2642
+			$invalid_TXN = false;
2643
+			// first gather some info
2644
+			$valid_TXN = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
2645
+			$primary_registrant = $valid_TXN instanceof EE_Transaction
2646
+				? $valid_TXN->primary_registration()
2647
+				: null;
2648
+			// let's start by retrieving the cart for this TXN
2649
+			$cart = $this->checkout->get_cart_for_transaction($this->checkout->transaction);
2650
+			if ($cart instanceof EE_Cart) {
2651
+				// verify that the current cart has tickets
2652
+				$tickets = $cart->get_tickets();
2653
+				if (empty($tickets)) {
2654
+					$invalid_TXN = true;
2655
+				}
2656
+			} else {
2657
+				$invalid_TXN = true;
2658
+			}
2659
+			$valid_TXN_SID = $primary_registrant instanceof EE_Registration
2660
+				? $primary_registrant->session_ID()
2661
+				: null;
2662
+			// validate current Session ID and compare against valid TXN session ID
2663
+			if ($invalid_TXN // if this is already true, then skip other checks
2664
+				|| EE_Session::instance()->id() === null
2665
+				|| (
2666
+					// WARNING !!!
2667
+					// this could be PayPal sending back duplicate requests (ya they do that)
2668
+					// or it **could** mean someone is simply registering AGAIN after having just done so
2669
+					// so now we need to determine if this current TXN looks valid or not
2670
+					// and whether this reg step has even been started ?
2671
+					EE_Session::instance()->id() === $valid_TXN_SID
2672
+					// really? you're half way through this reg step, but you never started it ?
2673
+					&& $this->checkout->transaction->reg_step_completed($this->slug()) === false
2674
+				)
2675
+			) {
2676
+				$invalid_TXN = true;
2677
+			}
2678
+			if ($invalid_TXN) {
2679
+				// is the valid TXN completed ?
2680
+				if ($valid_TXN instanceof EE_Transaction) {
2681
+					// has this step even been started ?
2682
+					$reg_step_completed = $valid_TXN->reg_step_completed($this->slug());
2683
+					if ($reg_step_completed !== false && $reg_step_completed !== true) {
2684
+						// so it **looks** like this is a double request from PayPal
2685
+						// so let's try to pick up where we left off
2686
+						$this->checkout->transaction = $valid_TXN;
2687
+						$this->checkout->refresh_all_entities(true);
2688
+						return;
2689
+					}
2690
+				}
2691
+				// you appear to be lost?
2692
+				$this->_redirect_wayward_request($primary_registrant);
2693
+			}
2694
+		}
2695
+	}
2696
+
2697
+
2698
+	/**
2699
+	 * _redirect_wayward_request
2700
+	 *
2701
+	 * @access private
2702
+	 * @param \EE_Registration|null $primary_registrant
2703
+	 * @return bool
2704
+	 * @throws EE_Error
2705
+	 * @throws InvalidArgumentException
2706
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2707
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2708
+	 */
2709
+	private function _redirect_wayward_request(EE_Registration $primary_registrant)
2710
+	{
2711
+		if (! $primary_registrant instanceof EE_Registration) {
2712
+			// try redirecting based on the current TXN
2713
+			$primary_registrant = $this->checkout->transaction instanceof EE_Transaction
2714
+				? $this->checkout->transaction->primary_registration()
2715
+				: null;
2716
+		}
2717
+		if (! $primary_registrant instanceof EE_Registration) {
2718
+			EE_Error::add_error(
2719
+				sprintf(
2720
+					esc_html__(
2721
+						'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.',
2722
+						'event_espresso'
2723
+					),
2724
+					'<br/>',
2725
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
2726
+				),
2727
+				__FILE__,
2728
+				__FUNCTION__,
2729
+				__LINE__
2730
+			);
2731
+			return false;
2732
+		}
2733
+		// make sure transaction is not locked
2734
+		$this->checkout->transaction->unlock();
2735
+		wp_safe_redirect(
2736
+			add_query_arg(
2737
+				array(
2738
+					'e_reg_url_link' => $primary_registrant->reg_url_link(),
2739
+				),
2740
+				$this->checkout->thank_you_page_url
2741
+			)
2742
+		);
2743
+		exit();
2744
+	}
2745
+
2746
+
2747
+	/**
2748
+	 * _process_off_site_payment
2749
+	 *
2750
+	 * @access private
2751
+	 * @param \EE_Offsite_Gateway $gateway
2752
+	 * @return EE_Payment
2753
+	 * @throws EE_Error
2754
+	 * @throws InvalidArgumentException
2755
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2756
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2757
+	 */
2758
+	private function _process_off_site_payment(EE_Offsite_Gateway $gateway)
2759
+	{
2760
+		try {
2761
+			$request_data = \EE_Registry::instance()->REQ->params();
2762
+			// if gateway uses_separate_IPN_request, then we don't have to process the IPN manually
2763
+			$this->set_handle_IPN_in_this_request(
2764
+				$gateway->handle_IPN_in_this_request($request_data, false)
2765
+			);
2766
+			if ($this->handle_IPN_in_this_request()) {
2767
+				// get payment details and process results
2768
+				/** @type EE_Payment_Processor $payment_processor */
2769
+				$payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2770
+				$payment = $payment_processor->process_ipn(
2771
+					$request_data,
2772
+					$this->checkout->transaction,
2773
+					$this->checkout->payment_method,
2774
+					true,
2775
+					false
2776
+				);
2777
+				// $payment_source = 'process_ipn';
2778
+			} else {
2779
+				$payment = $this->checkout->transaction->last_payment();
2780
+				// $payment_source = 'last_payment';
2781
+			}
2782
+		} catch (Exception $e) {
2783
+			// let's just eat the exception and try to move on using any previously set payment info
2784
+			$payment = $this->checkout->transaction->last_payment();
2785
+			// $payment_source = 'last_payment after Exception';
2786
+			// but if we STILL don't have a payment object
2787
+			if (! $payment instanceof EE_Payment) {
2788
+				// then we'll object ! ( not object like a thing... but object like what a lawyer says ! )
2789
+				$this->_handle_payment_processor_exception($e);
2790
+			}
2791
+		}
2792
+		// DEBUG LOG
2793
+		// $this->checkout->log(
2794
+		//     __CLASS__,
2795
+		//     __FUNCTION__,
2796
+		//     __LINE__,
2797
+		//     array(
2798
+		//         'process_ipn_payment' => $payment,
2799
+		//         'payment_source'      => $payment_source,
2800
+		//     )
2801
+		// );
2802
+		return $payment;
2803
+	}
2804
+
2805
+
2806
+	/**
2807
+	 * _process_cancelled_payments
2808
+	 * just makes sure that the payment status gets updated correctly
2809
+	 * so tha tan error isn't generated during payment validation
2810
+	 *
2811
+	 * @access private
2812
+	 * @param EE_Payment $payment
2813
+	 * @return EE_Payment | FALSE
2814
+	 * @throws \EE_Error
2815
+	 */
2816
+	private function _process_cancelled_payments($payment = null)
2817
+	{
2818
+		if ($payment instanceof EE_Payment
2819
+			&& isset($_REQUEST['ee_cancel_payment'])
2820
+			&& $payment->status() === EEM_Payment::status_id_failed
2821
+		) {
2822
+			$payment->set_status(EEM_Payment::status_id_cancelled);
2823
+		}
2824
+		return $payment;
2825
+	}
2826
+
2827
+
2828
+	/**
2829
+	 *    get_transaction_details_for_gateways
2830
+	 *
2831
+	 * @access    public
2832
+	 * @return int
2833
+	 * @throws EE_Error
2834
+	 * @throws InvalidArgumentException
2835
+	 * @throws ReflectionException
2836
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2837
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2838
+	 */
2839
+	public function get_transaction_details_for_gateways()
2840
+	{
2841
+		$txn_details = array();
2842
+		// ya gotta make a choice man
2843
+		if (empty($this->checkout->selected_method_of_payment)) {
2844
+			$txn_details = array(
2845
+				'error' => esc_html__('Please select a method of payment before proceeding.', 'event_espresso'),
2846
+			);
2847
+		}
2848
+		// get EE_Payment_Method object
2849
+		if (empty($txn_details)
2850
+			&&
2851
+			! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()
2852
+		) {
2853
+			$txn_details = array(
2854
+				'selected_method_of_payment' => $this->checkout->selected_method_of_payment,
2855
+				'error'                      => esc_html__(
2856
+					'A valid Payment Method could not be determined.',
2857
+					'event_espresso'
2858
+				),
2859
+			);
2860
+		}
2861
+		if (empty($txn_details) && $this->checkout->transaction instanceof EE_Transaction) {
2862
+			$return_url = $this->_get_return_url($this->checkout->payment_method);
2863
+			$txn_details = array(
2864
+				'TXN_ID'         => $this->checkout->transaction->ID(),
2865
+				'TXN_timestamp'  => $this->checkout->transaction->datetime(),
2866
+				'TXN_total'      => $this->checkout->transaction->total(),
2867
+				'TXN_paid'       => $this->checkout->transaction->paid(),
2868
+				'TXN_reg_steps'  => $this->checkout->transaction->reg_steps(),
2869
+				'STS_ID'         => $this->checkout->transaction->status_ID(),
2870
+				'PMD_ID'         => $this->checkout->transaction->payment_method_ID(),
2871
+				'payment_amount' => $this->checkout->amount_owing,
2872
+				'return_url'     => $return_url,
2873
+				'cancel_url'     => add_query_arg(array('ee_cancel_payment' => true), $return_url),
2874
+				'notify_url'     => EE_Config::instance()->core->txn_page_url(
2875
+					array(
2876
+						'e_reg_url_link'    => $this->checkout->transaction->primary_registration()->reg_url_link(),
2877
+						'ee_payment_method' => $this->checkout->payment_method->slug(),
2878
+					)
2879
+				),
2880
+			);
2881
+		}
2882
+		echo wp_json_encode($txn_details);
2883
+		exit();
2884
+	}
2885
+
2886
+
2887
+	/**
2888
+	 *    __sleep
2889
+	 * to conserve db space, let's remove the reg_form and the EE_Checkout object from EE_SPCO_Reg_Step objects upon
2890
+	 * serialization EE_Checkout will handle the reimplementation of itself upon waking, but we won't bother with the
2891
+	 * reg form, because if needed, it will be regenerated anyways
2892
+	 *
2893
+	 * @return array
2894
+	 */
2895
+	public function __sleep()
2896
+	{
2897
+		// remove the reg form and the checkout
2898
+		return array_diff(array_keys(get_object_vars($this)), array('reg_form', 'checkout', 'line_item_display'));
2899
+	}
2900 2900
 }
Please login to merge, or discard this patch.
Spacing   +76 added lines, -76 removed lines patch added patch discarded remove patch
@@ -129,7 +129,7 @@  discard block
 block discarded – undo
129 129
     {
130 130
         $this->_slug = 'payment_options';
131 131
         $this->_name = esc_html__('Payment Options', 'event_espresso');
132
-        $this->_template = SPCO_REG_STEPS_PATH . $this->_slug . DS . 'payment_options_main.template.php';
132
+        $this->_template = SPCO_REG_STEPS_PATH.$this->_slug.DS.'payment_options_main.template.php';
133 133
         $this->checkout = $checkout;
134 134
         $this->_reset_success_message();
135 135
         $this->set_instructions(
@@ -212,7 +212,7 @@  discard block
 block discarded – undo
212 212
     {
213 213
         $transaction = $this->checkout->transaction;
214 214
         // if the transaction isn't set or nothing is owed on it, don't enqueue any JS
215
-        if (! $transaction instanceof EE_Transaction || EEH_Money::compare_floats($transaction->remaining(), 0)) {
215
+        if ( ! $transaction instanceof EE_Transaction || EEH_Money::compare_floats($transaction->remaining(), 0)) {
216 216
             return;
217 217
         }
218 218
         foreach (EEM_Payment_Method::instance()->get_all_for_transaction(
@@ -304,18 +304,18 @@  discard block
 block discarded – undo
304 304
         foreach ($registrations as $REG_ID => $registration) {
305 305
             /** @var $registration EE_Registration */
306 306
             // has this registration lost it's space ?
307
-            if (isset($ejected_registrations[ $REG_ID ])) {
307
+            if (isset($ejected_registrations[$REG_ID])) {
308 308
                 if ($registration->event()->is_sold_out() || $registration->event()->is_sold_out(true)) {
309
-                    $sold_out_events[ $registration->event()->ID() ] = $registration->event();
309
+                    $sold_out_events[$registration->event()->ID()] = $registration->event();
310 310
                 } else {
311
-                    $insufficient_spaces_available[ $registration->event()->ID() ] = $registration->event();
311
+                    $insufficient_spaces_available[$registration->event()->ID()] = $registration->event();
312 312
                 }
313 313
                 continue;
314 314
             }
315 315
             // event requires admin approval
316 316
             if ($registration->status_ID() === EEM_Registration::status_id_not_approved) {
317 317
                 // add event to list of events with pre-approval reg status
318
-                $registrations_requiring_pre_approval[ $REG_ID ] = $registration;
318
+                $registrations_requiring_pre_approval[$REG_ID] = $registration;
319 319
                 do_action(
320 320
                     'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__event_requires_pre_approval',
321 321
                     $registration->event(),
@@ -331,7 +331,7 @@  discard block
 block discarded – undo
331 331
                 )
332 332
             ) {
333 333
                 // add event to list of events that are sold out
334
-                $sold_out_events[ $registration->event()->ID() ] = $registration->event();
334
+                $sold_out_events[$registration->event()->ID()] = $registration->event();
335 335
                 do_action(
336 336
                     'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__sold_out_event',
337 337
                     $registration->event(),
@@ -341,38 +341,38 @@  discard block
 block discarded – undo
341 341
             }
342 342
             // are they allowed to pay now and is there monies owing?
343 343
             if ($registration->owes_monies_and_can_pay()) {
344
-                $registrations_requiring_payment[ $REG_ID ] = $registration;
344
+                $registrations_requiring_payment[$REG_ID] = $registration;
345 345
                 do_action(
346 346
                     'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__event_requires_payment',
347 347
                     $registration->event(),
348 348
                     $this
349 349
                 );
350
-            } elseif (! $this->checkout->revisit
350
+            } elseif ( ! $this->checkout->revisit
351 351
                       && $registration->status_ID() !== EEM_Registration::status_id_not_approved
352 352
                       && $registration->ticket()->is_free()
353 353
             ) {
354
-                $registrations_for_free_events[ $registration->ticket()->ID() ] = $registration;
354
+                $registrations_for_free_events[$registration->ticket()->ID()] = $registration;
355 355
             }
356 356
         }
357 357
         $subsections = array();
358 358
         // now decide which template to load
359
-        if (! empty($sold_out_events)) {
359
+        if ( ! empty($sold_out_events)) {
360 360
             $subsections['sold_out_events'] = $this->_sold_out_events($sold_out_events);
361 361
         }
362
-        if (! empty($insufficient_spaces_available)) {
362
+        if ( ! empty($insufficient_spaces_available)) {
363 363
             $subsections['insufficient_space'] = $this->_insufficient_spaces_available(
364 364
                 $insufficient_spaces_available
365 365
             );
366 366
         }
367
-        if (! empty($registrations_requiring_pre_approval)) {
367
+        if ( ! empty($registrations_requiring_pre_approval)) {
368 368
             $subsections['registrations_requiring_pre_approval'] = $this->_registrations_requiring_pre_approval(
369 369
                 $registrations_requiring_pre_approval
370 370
             );
371 371
         }
372
-        if (! empty($registrations_for_free_events)) {
372
+        if ( ! empty($registrations_for_free_events)) {
373 373
             $subsections['no_payment_required'] = $this->_no_payment_required($registrations_for_free_events);
374 374
         }
375
-        if (! empty($registrations_requiring_payment)) {
375
+        if ( ! empty($registrations_requiring_payment)) {
376 376
             if ($this->checkout->amount_owing > 0) {
377 377
                 // autoload Line_Item_Display classes
378 378
                 EEH_Autoloader::register_line_item_filter_autoloaders();
@@ -437,13 +437,13 @@  discard block
 block discarded – undo
437 437
      */
438 438
     public static function add_spco_line_item_filters(EE_Line_Item_Filter_Collection $line_item_filter_collection)
439 439
     {
440
-        if (! EE_Registry::instance()->SSN instanceof EE_Session) {
440
+        if ( ! EE_Registry::instance()->SSN instanceof EE_Session) {
441 441
             return $line_item_filter_collection;
442 442
         }
443
-        if (! EE_Registry::instance()->SSN->checkout() instanceof EE_Checkout) {
443
+        if ( ! EE_Registry::instance()->SSN->checkout() instanceof EE_Checkout) {
444 444
             return $line_item_filter_collection;
445 445
         }
446
-        if (! EE_Registry::instance()->SSN->checkout()->transaction instanceof EE_Transaction) {
446
+        if ( ! EE_Registry::instance()->SSN->checkout()->transaction instanceof EE_Transaction) {
447 447
             return $line_item_filter_collection;
448 448
         }
449 449
         $line_item_filter_collection->add(
@@ -483,8 +483,8 @@  discard block
 block discarded – undo
483 483
         );
484 484
         foreach ($registrations as $REG_ID => $registration) {
485 485
             // has this registration lost it's space ?
486
-            if (isset($ejected_registrations[ $REG_ID ])) {
487
-                unset($registrations[ $REG_ID ]);
486
+            if (isset($ejected_registrations[$REG_ID])) {
487
+                unset($registrations[$REG_ID]);
488 488
                 continue;
489 489
             }
490 490
         }
@@ -534,24 +534,24 @@  discard block
 block discarded – undo
534 534
             }
535 535
             $EVT_ID = $registration->event_ID();
536 536
             $ticket = $registration->ticket();
537
-            if (! isset($tickets_remaining[ $ticket->ID() ])) {
538
-                $tickets_remaining[ $ticket->ID() ] = $ticket->remaining();
537
+            if ( ! isset($tickets_remaining[$ticket->ID()])) {
538
+                $tickets_remaining[$ticket->ID()] = $ticket->remaining();
539 539
             }
540
-            if ($tickets_remaining[ $ticket->ID() ] > 0) {
541
-                if (! isset($event_reg_count[ $EVT_ID ])) {
542
-                    $event_reg_count[ $EVT_ID ] = 0;
540
+            if ($tickets_remaining[$ticket->ID()] > 0) {
541
+                if ( ! isset($event_reg_count[$EVT_ID])) {
542
+                    $event_reg_count[$EVT_ID] = 0;
543 543
                 }
544
-                $event_reg_count[ $EVT_ID ]++;
545
-                if (! isset($event_spaces_remaining[ $EVT_ID ])) {
546
-                    $event_spaces_remaining[ $EVT_ID ] = $registration->event()->spaces_remaining_for_sale();
544
+                $event_reg_count[$EVT_ID]++;
545
+                if ( ! isset($event_spaces_remaining[$EVT_ID])) {
546
+                    $event_spaces_remaining[$EVT_ID] = $registration->event()->spaces_remaining_for_sale();
547 547
                 }
548 548
             }
549 549
             if ($revisit
550
-                && ($tickets_remaining[ $ticket->ID() ] === 0
551
-                    || $event_reg_count[ $EVT_ID ] > $event_spaces_remaining[ $EVT_ID ]
550
+                && ($tickets_remaining[$ticket->ID()] === 0
551
+                    || $event_reg_count[$EVT_ID] > $event_spaces_remaining[$EVT_ID]
552 552
                 )
553 553
             ) {
554
-                $ejected_registrations[ $REG_ID ] = $registration->event();
554
+                $ejected_registrations[$REG_ID] = $registration->event();
555 555
                 if ($registration->status_ID() !== EEM_Registration::status_id_wait_list) {
556 556
                     /** @type EE_Registration_Processor $registration_processor */
557 557
                     $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
@@ -611,7 +611,7 @@  discard block
 block discarded – undo
611 611
         foreach ($sold_out_events_array as $sold_out_event) {
612 612
             $sold_out_events .= EEH_HTML::li(
613 613
                 EEH_HTML::span(
614
-                    '  ' . $sold_out_event->name(),
614
+                    '  '.$sold_out_event->name(),
615 615
                     '',
616 616
                     'dashicons dashicons-marker ee-icon-size-16 pink-text'
617 617
                 )
@@ -667,7 +667,7 @@  discard block
 block discarded – undo
667 667
         foreach ($insufficient_spaces_events_array as $event) {
668 668
             if ($event instanceof EE_Event) {
669 669
                 $insufficient_space_events .= EEH_HTML::li(
670
-                    EEH_HTML::span(' ' . $event->name(), '', 'dashicons dashicons-marker ee-icon-size-16 pink-text')
670
+                    EEH_HTML::span(' '.$event->name(), '', 'dashicons dashicons-marker ee-icon-size-16 pink-text')
671 671
                 );
672 672
             }
673 673
         }
@@ -716,7 +716,7 @@  discard block
 block discarded – undo
716 716
         $events_requiring_pre_approval = '';
717 717
         foreach ($registrations_requiring_pre_approval as $registration) {
718 718
             if ($registration instanceof EE_Registration && $registration->event() instanceof EE_Event) {
719
-                $events_requiring_pre_approval[ $registration->event()->ID() ] = EEH_HTML::li(
719
+                $events_requiring_pre_approval[$registration->event()->ID()] = EEH_HTML::li(
720 720
                     EEH_HTML::span(
721 721
                         '',
722 722
                         '',
@@ -857,7 +857,7 @@  discard block
 block discarded – undo
857 857
     {
858 858
         return new EE_Form_Section_Proper(
859 859
             array(
860
-                'html_id'         => 'ee-' . $this->slug() . '-extra-hidden-inputs',
860
+                'html_id'         => 'ee-'.$this->slug().'-extra-hidden-inputs',
861 861
                 'layout_strategy' => new EE_Div_Per_Section_Layout(),
862 862
                 'subsections'     => array(
863 863
                     'spco_no_payment_required' => new EE_Hidden_Input(
@@ -897,7 +897,7 @@  discard block
 block discarded – undo
897 897
                 $payments += $registration->registration_payments();
898 898
             }
899 899
         }
900
-        if (! empty($payments)) {
900
+        if ( ! empty($payments)) {
901 901
             foreach ($payments as $payment) {
902 902
                 if ($payment instanceof EE_Registration_Payment) {
903 903
                     $this->checkout->amount_owing -= $payment->amount();
@@ -1017,23 +1017,23 @@  discard block
 block discarded – undo
1017 1017
                 $payment_method_button = EEH_HTML::img(
1018 1018
                     $payment_method->button_url(),
1019 1019
                     $payment_method->name(),
1020
-                    'spco-payment-method-' . $payment_method->slug() . '-btn-img',
1020
+                    'spco-payment-method-'.$payment_method->slug().'-btn-img',
1021 1021
                     'spco-payment-method-btn-img'
1022 1022
                 );
1023 1023
                 // check if any payment methods are set as default
1024 1024
                 // if payment method is already selected OR nothing is selected and this payment method should be
1025 1025
                 // open_by_default
1026 1026
                 if (($this->checkout->selected_method_of_payment === $payment_method->slug())
1027
-                    || (! $this->checkout->selected_method_of_payment && $payment_method->open_by_default())
1027
+                    || ( ! $this->checkout->selected_method_of_payment && $payment_method->open_by_default())
1028 1028
                 ) {
1029 1029
                     $this->checkout->selected_method_of_payment = $payment_method->slug();
1030 1030
                     $this->_save_selected_method_of_payment();
1031
-                    $default_payment_method_option[ $payment_method->slug() ] = $payment_method_button;
1031
+                    $default_payment_method_option[$payment_method->slug()] = $payment_method_button;
1032 1032
                 } else {
1033
-                    $available_payment_method_options[ $payment_method->slug() ] = $payment_method_button;
1033
+                    $available_payment_method_options[$payment_method->slug()] = $payment_method_button;
1034 1034
                 }
1035
-                $payment_methods_billing_info[ $payment_method->slug(
1036
-                ) . '-info' ] = $this->_payment_method_billing_info(
1035
+                $payment_methods_billing_info[$payment_method->slug(
1036
+                ).'-info'] = $this->_payment_method_billing_info(
1037 1037
                     $payment_method
1038 1038
                 );
1039 1039
             }
@@ -1069,7 +1069,7 @@  discard block
 block discarded – undo
1069 1069
      */
1070 1070
     protected function _get_available_payment_methods()
1071 1071
     {
1072
-        if (! empty($this->checkout->available_payment_methods)) {
1072
+        if ( ! empty($this->checkout->available_payment_methods)) {
1073 1073
             return $this->checkout->available_payment_methods;
1074 1074
         }
1075 1075
         $available_payment_methods = array();
@@ -1084,7 +1084,7 @@  discard block
 block discarded – undo
1084 1084
         );
1085 1085
         foreach ($payment_methods as $payment_method) {
1086 1086
             if ($payment_method instanceof EE_Payment_Method) {
1087
-                $available_payment_methods[ $payment_method->slug() ] = $payment_method;
1087
+                $available_payment_methods[$payment_method->slug()] = $payment_method;
1088 1088
             }
1089 1089
         }
1090 1090
         return $available_payment_methods;
@@ -1179,7 +1179,7 @@  discard block
 block discarded – undo
1179 1179
         );
1180 1180
         return new EE_Form_Section_Proper(
1181 1181
             array(
1182
-                'html_id'         => 'spco-payment-method-info-' . $payment_method->slug(),
1182
+                'html_id'         => 'spco-payment-method-info-'.$payment_method->slug(),
1183 1183
                 'html_class'      => 'spco-payment-method-info-dv',
1184 1184
                 // only display the selected or default PM
1185 1185
                 'html_style'      => $currently_selected ? '' : 'display:none;',
@@ -1209,7 +1209,7 @@  discard block
 block discarded – undo
1209 1209
         // how have they chosen to pay?
1210 1210
         $this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
1211 1211
         $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment();
1212
-        if (! $this->checkout->payment_method instanceof EE_Payment_Method) {
1212
+        if ( ! $this->checkout->payment_method instanceof EE_Payment_Method) {
1213 1213
             return false;
1214 1214
         }
1215 1215
         if (apply_filters(
@@ -1381,7 +1381,7 @@  discard block
 block discarded – undo
1381 1381
      */
1382 1382
     public function switch_payment_method()
1383 1383
     {
1384
-        if (! $this->_verify_payment_method_is_set()) {
1384
+        if ( ! $this->_verify_payment_method_is_set()) {
1385 1385
             return false;
1386 1386
         }
1387 1387
         if (apply_filters(
@@ -1516,7 +1516,7 @@  discard block
 block discarded – undo
1516 1516
             }
1517 1517
         }
1518 1518
         // verify payment method
1519
-        if (! $this->checkout->payment_method instanceof EE_Payment_Method) {
1519
+        if ( ! $this->checkout->payment_method instanceof EE_Payment_Method) {
1520 1520
             // get payment method for selected method of payment
1521 1521
             $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment();
1522 1522
         }
@@ -1541,7 +1541,7 @@  discard block
 block discarded – undo
1541 1541
      */
1542 1542
     public function save_payer_details_via_ajax()
1543 1543
     {
1544
-        if (! $this->_verify_payment_method_is_set()) {
1544
+        if ( ! $this->_verify_payment_method_is_set()) {
1545 1545
             return;
1546 1546
         }
1547 1547
         // generate billing form for selected method of payment if it hasn't been done already
@@ -1551,7 +1551,7 @@  discard block
 block discarded – undo
1551 1551
             );
1552 1552
         }
1553 1553
         // generate primary attendee from payer info if applicable
1554
-        if (! $this->checkout->transaction_has_primary_registrant()) {
1554
+        if ( ! $this->checkout->transaction_has_primary_registrant()) {
1555 1555
             $attendee = $this->_create_attendee_from_request_data();
1556 1556
             if ($attendee instanceof EE_Attendee) {
1557 1557
                 foreach ($this->checkout->transaction->registrations() as $registration) {
@@ -1582,7 +1582,7 @@  discard block
 block discarded – undo
1582 1582
     {
1583 1583
         // get State ID
1584 1584
         $STA_ID = ! empty($_REQUEST['state']) ? sanitize_text_field($_REQUEST['state']) : '';
1585
-        if (! empty($STA_ID)) {
1585
+        if ( ! empty($STA_ID)) {
1586 1586
             // can we get state object from name ?
1587 1587
             EE_Registry::instance()->load_model('State');
1588 1588
             $state = EEM_State::instance()->get_col(array(array('STA_name' => $STA_ID), 'limit' => 1), 'STA_ID');
@@ -1590,7 +1590,7 @@  discard block
 block discarded – undo
1590 1590
         }
1591 1591
         // get Country ISO
1592 1592
         $CNT_ISO = ! empty($_REQUEST['country']) ? sanitize_text_field($_REQUEST['country']) : '';
1593
-        if (! empty($CNT_ISO)) {
1593
+        if ( ! empty($CNT_ISO)) {
1594 1594
             // can we get country object from name ?
1595 1595
             EE_Registry::instance()->load_model('Country');
1596 1596
             $country = EEM_Country::instance()->get_col(
@@ -1623,7 +1623,7 @@  discard block
 block discarded – undo
1623 1623
         }
1624 1624
         // does this attendee already exist in the db ? we're searching using a combination of first name, last name,
1625 1625
         // AND email address
1626
-        if (! empty($attendee_data['ATT_fname'])
1626
+        if ( ! empty($attendee_data['ATT_fname'])
1627 1627
             && ! empty($attendee_data['ATT_lname'])
1628 1628
             && ! empty($attendee_data['ATT_email'])
1629 1629
         ) {
@@ -1838,7 +1838,7 @@  discard block
 block discarded – undo
1838 1838
     private function _process_payment()
1839 1839
     {
1840 1840
         // basically confirm that the event hasn't sold out since they hit the page
1841
-        if (! $this->_last_second_ticket_verifications()) {
1841
+        if ( ! $this->_last_second_ticket_verifications()) {
1842 1842
             return false;
1843 1843
         }
1844 1844
         // ya gotta make a choice man
@@ -1849,7 +1849,7 @@  discard block
 block discarded – undo
1849 1849
             return false;
1850 1850
         }
1851 1851
         // get EE_Payment_Method object
1852
-        if (! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()) {
1852
+        if ( ! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()) {
1853 1853
             return false;
1854 1854
         }
1855 1855
         // setup billing form
@@ -1858,12 +1858,12 @@  discard block
 block discarded – undo
1858 1858
                 $this->checkout->payment_method
1859 1859
             );
1860 1860
             // bad billing form ?
1861
-            if (! $this->_billing_form_is_valid()) {
1861
+            if ( ! $this->_billing_form_is_valid()) {
1862 1862
                 return false;
1863 1863
             }
1864 1864
         }
1865 1865
         // ensure primary registrant has been fully processed
1866
-        if (! $this->_setup_primary_registrant_prior_to_payment()) {
1866
+        if ( ! $this->_setup_primary_registrant_prior_to_payment()) {
1867 1867
             return false;
1868 1868
         }
1869 1869
         // if session is close to expiring (under 10 minutes by default)
@@ -1918,7 +1918,7 @@  discard block
 block discarded – undo
1918 1918
     protected function _last_second_ticket_verifications()
1919 1919
     {
1920 1920
         // don't bother re-validating if not a return visit
1921
-        if (! $this->checkout->revisit) {
1921
+        if ( ! $this->checkout->revisit) {
1922 1922
             return true;
1923 1923
         }
1924 1924
         $registrations = $this->checkout->transaction->registrations();
@@ -1984,7 +1984,7 @@  discard block
 block discarded – undo
1984 1984
      */
1985 1985
     private function _billing_form_is_valid()
1986 1986
     {
1987
-        if (! $this->checkout->payment_method->type_obj()->has_billing_form()) {
1987
+        if ( ! $this->checkout->payment_method->type_obj()->has_billing_form()) {
1988 1988
             return true;
1989 1989
         }
1990 1990
         if ($this->checkout->billing_form instanceof EE_Billing_Info_Form) {
@@ -2103,7 +2103,7 @@  discard block
 block discarded – undo
2103 2103
     {
2104 2104
         // convert billing form data into an attendee
2105 2105
         $this->checkout->primary_attendee_obj = $this->checkout->billing_form->create_attendee_from_billing_form_data();
2106
-        if (! $this->checkout->primary_attendee_obj instanceof EE_Attendee) {
2106
+        if ( ! $this->checkout->primary_attendee_obj instanceof EE_Attendee) {
2107 2107
             EE_Error::add_error(
2108 2108
                 sprintf(
2109 2109
                     esc_html__(
@@ -2120,7 +2120,7 @@  discard block
 block discarded – undo
2120 2120
             return false;
2121 2121
         }
2122 2122
         $primary_registration = $this->checkout->transaction->primary_registration();
2123
-        if (! $primary_registration instanceof EE_Registration) {
2123
+        if ( ! $primary_registration instanceof EE_Registration) {
2124 2124
             EE_Error::add_error(
2125 2125
                 sprintf(
2126 2126
                     esc_html__(
@@ -2136,7 +2136,7 @@  discard block
 block discarded – undo
2136 2136
             );
2137 2137
             return false;
2138 2138
         }
2139
-        if (! $primary_registration->_add_relation_to($this->checkout->primary_attendee_obj, 'Attendee')
2139
+        if ( ! $primary_registration->_add_relation_to($this->checkout->primary_attendee_obj, 'Attendee')
2140 2140
               instanceof
2141 2141
               EE_Attendee
2142 2142
         ) {
@@ -2182,8 +2182,8 @@  discard block
 block discarded – undo
2182 2182
             return null;
2183 2183
         }
2184 2184
         // get EE_Payment_Method object
2185
-        if (isset($this->checkout->available_payment_methods[ $this->checkout->selected_method_of_payment ])) {
2186
-            $payment_method = $this->checkout->available_payment_methods[ $this->checkout->selected_method_of_payment ];
2185
+        if (isset($this->checkout->available_payment_methods[$this->checkout->selected_method_of_payment])) {
2186
+            $payment_method = $this->checkout->available_payment_methods[$this->checkout->selected_method_of_payment];
2187 2187
         } else {
2188 2188
             // load EEM_Payment_Method
2189 2189
             EE_Registry::instance()->load_model('Payment_Method');
@@ -2192,7 +2192,7 @@  discard block
 block discarded – undo
2192 2192
             $payment_method = $EEM_Payment_Method->get_one_by_slug($this->checkout->selected_method_of_payment);
2193 2193
         }
2194 2194
         // verify $payment_method
2195
-        if (! $payment_method instanceof EE_Payment_Method) {
2195
+        if ( ! $payment_method instanceof EE_Payment_Method) {
2196 2196
             // not a payment
2197 2197
             EE_Error::add_error(
2198 2198
                 sprintf(
@@ -2210,7 +2210,7 @@  discard block
 block discarded – undo
2210 2210
             return null;
2211 2211
         }
2212 2212
         // and verify it has a valid Payment_Method Type object
2213
-        if (! $payment_method->type_obj() instanceof EE_PMT_Base) {
2213
+        if ( ! $payment_method->type_obj() instanceof EE_PMT_Base) {
2214 2214
             // not a payment
2215 2215
             EE_Error::add_error(
2216 2216
                 sprintf(
@@ -2248,7 +2248,7 @@  discard block
 block discarded – undo
2248 2248
         $payment = null;
2249 2249
         $this->checkout->transaction->save();
2250 2250
         $payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2251
-        if (! $payment_processor instanceof EE_Payment_Processor) {
2251
+        if ( ! $payment_processor instanceof EE_Payment_Processor) {
2252 2252
             return false;
2253 2253
         }
2254 2254
         try {
@@ -2352,7 +2352,7 @@  discard block
 block discarded – undo
2352 2352
             return true;
2353 2353
         }
2354 2354
         // verify payment object
2355
-        if (! $payment instanceof EE_Payment) {
2355
+        if ( ! $payment instanceof EE_Payment) {
2356 2356
             // not a payment
2357 2357
             EE_Error::add_error(
2358 2358
                 sprintf(
@@ -2392,7 +2392,7 @@  discard block
 block discarded – undo
2392 2392
             return true;
2393 2393
             // On-Site payment?
2394 2394
         } elseif ($this->checkout->payment_method->is_on_site()) {
2395
-            if (! $this->_process_payment_status($payment, EE_PMT_Base::onsite)) {
2395
+            if ( ! $this->_process_payment_status($payment, EE_PMT_Base::onsite)) {
2396 2396
                 // $this->_setup_redirect_for_next_step();
2397 2397
                 $this->checkout->continue_reg = false;
2398 2398
             }
@@ -2508,7 +2508,7 @@  discard block
 block discarded – undo
2508 2508
                     break;
2509 2509
                 // bad payment
2510 2510
                 case EEM_Payment::status_id_failed:
2511
-                    if (! empty($msg)) {
2511
+                    if ( ! empty($msg)) {
2512 2512
                         EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2513 2513
                         return false;
2514 2514
                     }
@@ -2569,11 +2569,11 @@  discard block
 block discarded – undo
2569 2569
         // how have they chosen to pay?
2570 2570
         $this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
2571 2571
         // get EE_Payment_Method object
2572
-        if (! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()) {
2572
+        if ( ! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()) {
2573 2573
             $this->checkout->continue_reg = false;
2574 2574
             return false;
2575 2575
         }
2576
-        if (! $this->checkout->payment_method->is_off_site()) {
2576
+        if ( ! $this->checkout->payment_method->is_off_site()) {
2577 2577
             return false;
2578 2578
         }
2579 2579
         $this->_validate_offsite_return();
@@ -2591,7 +2591,7 @@  discard block
 block discarded – undo
2591 2591
         // verify TXN
2592 2592
         if ($this->checkout->transaction instanceof EE_Transaction) {
2593 2593
             $gateway = $this->checkout->payment_method->type_obj()->get_gateway();
2594
-            if (! $gateway instanceof EE_Offsite_Gateway) {
2594
+            if ( ! $gateway instanceof EE_Offsite_Gateway) {
2595 2595
                 $this->checkout->continue_reg = false;
2596 2596
                 return false;
2597 2597
             }
@@ -2708,13 +2708,13 @@  discard block
 block discarded – undo
2708 2708
      */
2709 2709
     private function _redirect_wayward_request(EE_Registration $primary_registrant)
2710 2710
     {
2711
-        if (! $primary_registrant instanceof EE_Registration) {
2711
+        if ( ! $primary_registrant instanceof EE_Registration) {
2712 2712
             // try redirecting based on the current TXN
2713 2713
             $primary_registrant = $this->checkout->transaction instanceof EE_Transaction
2714 2714
                 ? $this->checkout->transaction->primary_registration()
2715 2715
                 : null;
2716 2716
         }
2717
-        if (! $primary_registrant instanceof EE_Registration) {
2717
+        if ( ! $primary_registrant instanceof EE_Registration) {
2718 2718
             EE_Error::add_error(
2719 2719
                 sprintf(
2720 2720
                     esc_html__(
@@ -2784,7 +2784,7 @@  discard block
 block discarded – undo
2784 2784
             $payment = $this->checkout->transaction->last_payment();
2785 2785
             // $payment_source = 'last_payment after Exception';
2786 2786
             // but if we STILL don't have a payment object
2787
-            if (! $payment instanceof EE_Payment) {
2787
+            if ( ! $payment instanceof EE_Payment) {
2788 2788
                 // then we'll object ! ( not object like a thing... but object like what a lawyer says ! )
2789 2789
                 $this->_handle_payment_processor_exception($e);
2790 2790
             }
Please login to merge, or discard this patch.
modules/batch/EED_Batch.module.php 2 patches
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -112,7 +112,7 @@  discard block
 block discarded – undo
112 112
      */
113 113
     protected function getLoader()
114 114
     {
115
-        if (!$this->loader instanceof LoaderInterface) {
115
+        if ( ! $this->loader instanceof LoaderInterface) {
116 116
             $this->loader = LoaderFactory::getLoader();
117 117
         }
118 118
         return $this->loader;
@@ -149,7 +149,7 @@  discard block
 block discarded – undo
149 149
         $job_response = $this->_enqueue_batch_job_scripts_and_styles_and_start_job();
150 150
         wp_enqueue_script(
151 151
             'batch_runner_init',
152
-            BATCH_URL . 'assets/batch_runner_init.js',
152
+            BATCH_URL.'assets/batch_runner_init.js',
153 153
             array('batch_runner'),
154 154
             EVENT_ESPRESSO_VERSION,
155 155
             true
@@ -173,7 +173,7 @@  discard block
 block discarded – undo
173 173
         $job_response = $this->_enqueue_batch_job_scripts_and_styles_and_start_job();
174 174
         wp_enqueue_script(
175 175
             'batch_file_runner_init',
176
-            BATCH_URL . 'assets/batch_file_runner_init.js',
176
+            BATCH_URL.'assets/batch_file_runner_init.js',
177 177
             array('batch_runner'),
178 178
             EVENT_ESPRESSO_VERSION,
179 179
             true
@@ -185,7 +185,7 @@  discard block
 block discarded – undo
185 185
             array(
186 186
                 'download_and_redirecting' => sprintf(
187 187
                     __('File Generation complete. Downloading, and %1$sredirecting%2$s...', 'event_espresso'),
188
-                    '<a href="' . $_REQUEST['return_url'] . '">',
188
+                    '<a href="'.$_REQUEST['return_url'].'">',
189 189
                     '</a>'
190 190
                 ),
191 191
                 'return_url'               => $_REQUEST['return_url'],
@@ -204,18 +204,18 @@  discard block
 block discarded – undo
204 204
     {
205 205
         wp_register_script(
206 206
             'progress_bar',
207
-            EE_PLUGIN_DIR_URL . 'core/libraries/batch/Assets/progress_bar.js',
207
+            EE_PLUGIN_DIR_URL.'core/libraries/batch/Assets/progress_bar.js',
208 208
             array('jquery')
209 209
         );
210 210
         wp_enqueue_style(
211 211
             'progress_bar',
212
-            EE_PLUGIN_DIR_URL . 'core/libraries/batch/Assets/progress_bar.css',
212
+            EE_PLUGIN_DIR_URL.'core/libraries/batch/Assets/progress_bar.css',
213 213
             array(),
214 214
             EVENT_ESPRESSO_VERSION
215 215
         );
216 216
         wp_enqueue_script(
217 217
             'batch_runner',
218
-            EE_PLUGIN_DIR_URL . 'core/libraries/batch/Assets/batch_runner.js',
218
+            EE_PLUGIN_DIR_URL.'core/libraries/batch/Assets/batch_runner.js',
219 219
             array('progress_bar')
220 220
         );
221 221
         // just copy the bits of EE admin's eei18n that we need in the JS
@@ -250,7 +250,7 @@  discard block
 block discarded – undo
250 250
     public function override_template($template)
251 251
     {
252 252
         if (isset($_REQUEST['espresso_batch']) && isset($_REQUEST['batch'])) {
253
-            return EE_MODULES . 'batch' . DS . 'templates' . DS . 'batch_frontend_wrapper.template.html';
253
+            return EE_MODULES.'batch'.DS.'templates'.DS.'batch_frontend_wrapper.template.html';
254 254
         }
255 255
         return $template;
256 256
     }
@@ -277,7 +277,7 @@  discard block
 block discarded – undo
277 277
     public function show_admin_page()
278 278
     {
279 279
         echo EEH_Template::locate_template(
280
-            EE_MODULES . 'batch' . DS . 'templates' . DS . 'batch_wrapper.template.html',
280
+            EE_MODULES.'batch'.DS.'templates'.DS.'batch_wrapper.template.html',
281 281
             array('batch_request_type' => $this->batch_request_type())
282 282
         );
283 283
     }
Please login to merge, or discard this patch.
Indentation   +328 added lines, -328 removed lines patch added patch discarded remove patch
@@ -28,356 +28,356 @@
 block discarded – undo
28 28
 class EED_Batch extends EED_Module
29 29
 {
30 30
 
31
-    /**
32
-     * Possibly value for $_REQUEST[ 'batch' ]. Indicates to run a job that
33
-     * processes data only
34
-     */
35
-    const batch_job = 'job';
36
-    /**
37
-     * Possibly value for $_REQUEST[ 'batch' ]. Indicates to run a job that
38
-     * produces a file for download
39
-     */
40
-    const batch_file_job = 'file';
41
-    /**
42
-     * Possibly value for $_REQUEST[ 'batch' ]. Indicates this request is NOT
43
-     * for a batch job. It's the same as not providing the $_REQUEST[ 'batch' ]
44
-     * at all
45
-     */
46
-    const batch_not_job = 'none';
31
+	/**
32
+	 * Possibly value for $_REQUEST[ 'batch' ]. Indicates to run a job that
33
+	 * processes data only
34
+	 */
35
+	const batch_job = 'job';
36
+	/**
37
+	 * Possibly value for $_REQUEST[ 'batch' ]. Indicates to run a job that
38
+	 * produces a file for download
39
+	 */
40
+	const batch_file_job = 'file';
41
+	/**
42
+	 * Possibly value for $_REQUEST[ 'batch' ]. Indicates this request is NOT
43
+	 * for a batch job. It's the same as not providing the $_REQUEST[ 'batch' ]
44
+	 * at all
45
+	 */
46
+	const batch_not_job = 'none';
47 47
 
48
-    /**
49
-     *
50
-     * @var string 'file', or 'job', or false to indicate its not a batch request at all
51
-     */
52
-    protected $_batch_request_type = null;
48
+	/**
49
+	 *
50
+	 * @var string 'file', or 'job', or false to indicate its not a batch request at all
51
+	 */
52
+	protected $_batch_request_type = null;
53 53
 
54
-    /**
55
-     * Because we want to use the response in both the localized JS and in the body
56
-     * we need to make this response available between method calls
57
-     *
58
-     * @var \EventEspressoBatchRequest\Helpers\JobStepResponse
59
-     */
60
-    protected $_job_step_response = null;
54
+	/**
55
+	 * Because we want to use the response in both the localized JS and in the body
56
+	 * we need to make this response available between method calls
57
+	 *
58
+	 * @var \EventEspressoBatchRequest\Helpers\JobStepResponse
59
+	 */
60
+	protected $_job_step_response = null;
61 61
 
62
-    /**
63
-     * @var LoaderInterface
64
-     */
65
-    protected $loader;
62
+	/**
63
+	 * @var LoaderInterface
64
+	 */
65
+	protected $loader;
66 66
 
67
-    /**
68
-     * Gets the batch instance
69
-     *
70
-     * @return EED_Batch
71
-     */
72
-    public static function instance()
73
-    {
74
-        return self::get_instance();
75
-    }
67
+	/**
68
+	 * Gets the batch instance
69
+	 *
70
+	 * @return EED_Batch
71
+	 */
72
+	public static function instance()
73
+	{
74
+		return self::get_instance();
75
+	}
76 76
 
77
-    /**
78
-     * Sets hooks to enable batch jobs on the frontend. Disabled by default
79
-     * because it's an attack vector and there are currently no implementations
80
-     */
81
-    public static function set_hooks()
82
-    {
83
-        // because this is a possibel attack vector, let's have this disabled until
84
-        // we at least have a real use for it on the frontend
85
-        if (apply_filters('FHEE__EED_Batch__set_hooks__enable_frontend_batch', false)) {
86
-            add_action('wp_enqueue_scripts', array(self::instance(), 'enqueue_scripts'));
87
-            add_filter('template_include', array(self::instance(), 'override_template'), 99);
88
-        }
89
-    }
77
+	/**
78
+	 * Sets hooks to enable batch jobs on the frontend. Disabled by default
79
+	 * because it's an attack vector and there are currently no implementations
80
+	 */
81
+	public static function set_hooks()
82
+	{
83
+		// because this is a possibel attack vector, let's have this disabled until
84
+		// we at least have a real use for it on the frontend
85
+		if (apply_filters('FHEE__EED_Batch__set_hooks__enable_frontend_batch', false)) {
86
+			add_action('wp_enqueue_scripts', array(self::instance(), 'enqueue_scripts'));
87
+			add_filter('template_include', array(self::instance(), 'override_template'), 99);
88
+		}
89
+	}
90 90
 
91
-    /**
92
-     * Initializes some hooks for the admin in order to run batch jobs
93
-     */
94
-    public static function set_hooks_admin()
95
-    {
96
-        add_action('admin_menu', array(self::instance(), 'register_admin_pages'));
97
-        add_action('admin_enqueue_scripts', array(self::instance(), 'enqueue_scripts'));
91
+	/**
92
+	 * Initializes some hooks for the admin in order to run batch jobs
93
+	 */
94
+	public static function set_hooks_admin()
95
+	{
96
+		add_action('admin_menu', array(self::instance(), 'register_admin_pages'));
97
+		add_action('admin_enqueue_scripts', array(self::instance(), 'enqueue_scripts'));
98 98
 
99
-        // ajax
100
-        add_action('wp_ajax_espresso_batch_continue', array(self::instance(), 'batch_continue'));
101
-        add_action('wp_ajax_espresso_batch_cleanup', array(self::instance(), 'batch_cleanup'));
102
-        add_action('wp_ajax_nopriv_espresso_batch_continue', array(self::instance(), 'batch_continue'));
103
-        add_action('wp_ajax_nopriv_espresso_batch_cleanup', array(self::instance(), 'batch_cleanup'));
104
-    }
99
+		// ajax
100
+		add_action('wp_ajax_espresso_batch_continue', array(self::instance(), 'batch_continue'));
101
+		add_action('wp_ajax_espresso_batch_cleanup', array(self::instance(), 'batch_cleanup'));
102
+		add_action('wp_ajax_nopriv_espresso_batch_continue', array(self::instance(), 'batch_continue'));
103
+		add_action('wp_ajax_nopriv_espresso_batch_cleanup', array(self::instance(), 'batch_cleanup'));
104
+	}
105 105
 
106
-    /**
107
-     * @since 4.9.80.p
108
-     * @return LoaderInterface
109
-     * @throws InvalidArgumentException
110
-     * @throws InvalidDataTypeException
111
-     * @throws InvalidInterfaceException
112
-     */
113
-    protected function getLoader()
114
-    {
115
-        if (!$this->loader instanceof LoaderInterface) {
116
-            $this->loader = LoaderFactory::getLoader();
117
-        }
118
-        return $this->loader;
119
-    }
106
+	/**
107
+	 * @since 4.9.80.p
108
+	 * @return LoaderInterface
109
+	 * @throws InvalidArgumentException
110
+	 * @throws InvalidDataTypeException
111
+	 * @throws InvalidInterfaceException
112
+	 */
113
+	protected function getLoader()
114
+	{
115
+		if (!$this->loader instanceof LoaderInterface) {
116
+			$this->loader = LoaderFactory::getLoader();
117
+		}
118
+		return $this->loader;
119
+	}
120 120
 
121
-    /**
122
-     * Enqueues batch scripts on the frontend or admin, and creates a job
123
-     */
124
-    public function enqueue_scripts()
125
-    {
126
-        if (isset($_REQUEST['espresso_batch'])
127
-            ||
128
-            (
129
-                isset($_REQUEST['page'])
130
-                && $_REQUEST['page'] == 'espresso_batch'
131
-            )
132
-        ) {
133
-            switch ($this->batch_request_type()) {
134
-                case self::batch_job:
135
-                    $this->enqueue_scripts_styles_batch_create();
136
-                    break;
137
-                case self::batch_file_job:
138
-                    $this->enqueue_scripts_styles_batch_file_create();
139
-                    break;
140
-            }
141
-        }
142
-    }
121
+	/**
122
+	 * Enqueues batch scripts on the frontend or admin, and creates a job
123
+	 */
124
+	public function enqueue_scripts()
125
+	{
126
+		if (isset($_REQUEST['espresso_batch'])
127
+			||
128
+			(
129
+				isset($_REQUEST['page'])
130
+				&& $_REQUEST['page'] == 'espresso_batch'
131
+			)
132
+		) {
133
+			switch ($this->batch_request_type()) {
134
+				case self::batch_job:
135
+					$this->enqueue_scripts_styles_batch_create();
136
+					break;
137
+				case self::batch_file_job:
138
+					$this->enqueue_scripts_styles_batch_file_create();
139
+					break;
140
+			}
141
+		}
142
+	}
143 143
 
144
-    /**
145
-     * Create a batch job, enqueues a script to run it, and localizes some data for it
146
-     */
147
-    public function enqueue_scripts_styles_batch_create()
148
-    {
149
-        $job_response = $this->_enqueue_batch_job_scripts_and_styles_and_start_job();
150
-        wp_enqueue_script(
151
-            'batch_runner_init',
152
-            BATCH_URL . 'assets/batch_runner_init.js',
153
-            array('batch_runner'),
154
-            EVENT_ESPRESSO_VERSION,
155
-            true
156
-        );
157
-        wp_localize_script('batch_runner_init', 'ee_job_response', $job_response->to_array());
158
-        wp_localize_script(
159
-            'batch_runner_init',
160
-            'ee_job_i18n',
161
-            array(
162
-                'return_url' => $_REQUEST['return_url'],
163
-            )
164
-        );
165
-    }
144
+	/**
145
+	 * Create a batch job, enqueues a script to run it, and localizes some data for it
146
+	 */
147
+	public function enqueue_scripts_styles_batch_create()
148
+	{
149
+		$job_response = $this->_enqueue_batch_job_scripts_and_styles_and_start_job();
150
+		wp_enqueue_script(
151
+			'batch_runner_init',
152
+			BATCH_URL . 'assets/batch_runner_init.js',
153
+			array('batch_runner'),
154
+			EVENT_ESPRESSO_VERSION,
155
+			true
156
+		);
157
+		wp_localize_script('batch_runner_init', 'ee_job_response', $job_response->to_array());
158
+		wp_localize_script(
159
+			'batch_runner_init',
160
+			'ee_job_i18n',
161
+			array(
162
+				'return_url' => $_REQUEST['return_url'],
163
+			)
164
+		);
165
+	}
166 166
 
167
-    /**
168
-     * Creates a batch job which will download a file, enqueues a script to run the job, and localizes some data for it
169
-     */
170
-    public function enqueue_scripts_styles_batch_file_create()
171
-    {
172
-        // creates a job based on the request variable
173
-        $job_response = $this->_enqueue_batch_job_scripts_and_styles_and_start_job();
174
-        wp_enqueue_script(
175
-            'batch_file_runner_init',
176
-            BATCH_URL . 'assets/batch_file_runner_init.js',
177
-            array('batch_runner'),
178
-            EVENT_ESPRESSO_VERSION,
179
-            true
180
-        );
181
-        wp_localize_script('batch_file_runner_init', 'ee_job_response', $job_response->to_array());
182
-        wp_localize_script(
183
-            'batch_file_runner_init',
184
-            'ee_job_i18n',
185
-            array(
186
-                'download_and_redirecting' => sprintf(
187
-                    __('File Generation complete. Downloading, and %1$sredirecting%2$s...', 'event_espresso'),
188
-                    '<a href="' . $_REQUEST['return_url'] . '">',
189
-                    '</a>'
190
-                ),
191
-                'return_url'               => $_REQUEST['return_url'],
192
-            )
193
-        );
194
-    }
167
+	/**
168
+	 * Creates a batch job which will download a file, enqueues a script to run the job, and localizes some data for it
169
+	 */
170
+	public function enqueue_scripts_styles_batch_file_create()
171
+	{
172
+		// creates a job based on the request variable
173
+		$job_response = $this->_enqueue_batch_job_scripts_and_styles_and_start_job();
174
+		wp_enqueue_script(
175
+			'batch_file_runner_init',
176
+			BATCH_URL . 'assets/batch_file_runner_init.js',
177
+			array('batch_runner'),
178
+			EVENT_ESPRESSO_VERSION,
179
+			true
180
+		);
181
+		wp_localize_script('batch_file_runner_init', 'ee_job_response', $job_response->to_array());
182
+		wp_localize_script(
183
+			'batch_file_runner_init',
184
+			'ee_job_i18n',
185
+			array(
186
+				'download_and_redirecting' => sprintf(
187
+					__('File Generation complete. Downloading, and %1$sredirecting%2$s...', 'event_espresso'),
188
+					'<a href="' . $_REQUEST['return_url'] . '">',
189
+					'</a>'
190
+				),
191
+				'return_url'               => $_REQUEST['return_url'],
192
+			)
193
+		);
194
+	}
195 195
 
196
-    /**
197
-     * Enqueues scripts and styles common to any batch job, and creates
198
-     * a job from the request data, and stores the response in the
199
-     * $this->_job_step_response property
200
-     *
201
-     * @return \EventEspressoBatchRequest\Helpers\JobStepResponse
202
-     */
203
-    protected function _enqueue_batch_job_scripts_and_styles_and_start_job()
204
-    {
205
-        wp_register_script(
206
-            'progress_bar',
207
-            EE_PLUGIN_DIR_URL . 'core/libraries/batch/Assets/progress_bar.js',
208
-            array('jquery')
209
-        );
210
-        wp_enqueue_style(
211
-            'progress_bar',
212
-            EE_PLUGIN_DIR_URL . 'core/libraries/batch/Assets/progress_bar.css',
213
-            array(),
214
-            EVENT_ESPRESSO_VERSION
215
-        );
216
-        wp_enqueue_script(
217
-            'batch_runner',
218
-            EE_PLUGIN_DIR_URL . 'core/libraries/batch/Assets/batch_runner.js',
219
-            array('progress_bar')
220
-        );
221
-        // just copy the bits of EE admin's eei18n that we need in the JS
222
-        wp_localize_script(
223
-            'batch_runner',
224
-            'eei18n',
225
-            array(
226
-                'ajax_url'      => WP_AJAX_URL,
227
-                'is_admin'      => (bool) is_admin(),
228
-                'error_message' => esc_html__('An error occurred and the job has been stopped. Please refresh the page to try again.', 'event_espresso'),
229
-            )
230
-        );
231
-        $job_handler_classname = stripslashes($_GET['job_handler']);
232
-        $request_data = array_diff_key(
233
-            $_REQUEST,
234
-            array_flip(array('action', 'page', 'ee', 'batch'))
235
-        );
236
-        $batch_runner = $this->getLoader()->getShared('EventEspressoBatchRequest\BatchRequestProcessor');
237
-        // eg 'EventEspressoBatchRequest\JobHandlers\RegistrationsReport'
238
-        $job_response = $batch_runner->create_job($job_handler_classname, $request_data);
239
-        // remember the response for later. We need it to display the page body
240
-        $this->_job_step_response = $job_response;
241
-        return $job_response;
242
-    }
196
+	/**
197
+	 * Enqueues scripts and styles common to any batch job, and creates
198
+	 * a job from the request data, and stores the response in the
199
+	 * $this->_job_step_response property
200
+	 *
201
+	 * @return \EventEspressoBatchRequest\Helpers\JobStepResponse
202
+	 */
203
+	protected function _enqueue_batch_job_scripts_and_styles_and_start_job()
204
+	{
205
+		wp_register_script(
206
+			'progress_bar',
207
+			EE_PLUGIN_DIR_URL . 'core/libraries/batch/Assets/progress_bar.js',
208
+			array('jquery')
209
+		);
210
+		wp_enqueue_style(
211
+			'progress_bar',
212
+			EE_PLUGIN_DIR_URL . 'core/libraries/batch/Assets/progress_bar.css',
213
+			array(),
214
+			EVENT_ESPRESSO_VERSION
215
+		);
216
+		wp_enqueue_script(
217
+			'batch_runner',
218
+			EE_PLUGIN_DIR_URL . 'core/libraries/batch/Assets/batch_runner.js',
219
+			array('progress_bar')
220
+		);
221
+		// just copy the bits of EE admin's eei18n that we need in the JS
222
+		wp_localize_script(
223
+			'batch_runner',
224
+			'eei18n',
225
+			array(
226
+				'ajax_url'      => WP_AJAX_URL,
227
+				'is_admin'      => (bool) is_admin(),
228
+				'error_message' => esc_html__('An error occurred and the job has been stopped. Please refresh the page to try again.', 'event_espresso'),
229
+			)
230
+		);
231
+		$job_handler_classname = stripslashes($_GET['job_handler']);
232
+		$request_data = array_diff_key(
233
+			$_REQUEST,
234
+			array_flip(array('action', 'page', 'ee', 'batch'))
235
+		);
236
+		$batch_runner = $this->getLoader()->getShared('EventEspressoBatchRequest\BatchRequestProcessor');
237
+		// eg 'EventEspressoBatchRequest\JobHandlers\RegistrationsReport'
238
+		$job_response = $batch_runner->create_job($job_handler_classname, $request_data);
239
+		// remember the response for later. We need it to display the page body
240
+		$this->_job_step_response = $job_response;
241
+		return $job_response;
242
+	}
243 243
 
244
-    /**
245
-     * If we are doing a frontend batch job, this makes it so WP shows our template's HTML
246
-     *
247
-     * @param string $template
248
-     * @return string
249
-     */
250
-    public function override_template($template)
251
-    {
252
-        if (isset($_REQUEST['espresso_batch']) && isset($_REQUEST['batch'])) {
253
-            return EE_MODULES . 'batch' . DS . 'templates' . DS . 'batch_frontend_wrapper.template.html';
254
-        }
255
-        return $template;
256
-    }
244
+	/**
245
+	 * If we are doing a frontend batch job, this makes it so WP shows our template's HTML
246
+	 *
247
+	 * @param string $template
248
+	 * @return string
249
+	 */
250
+	public function override_template($template)
251
+	{
252
+		if (isset($_REQUEST['espresso_batch']) && isset($_REQUEST['batch'])) {
253
+			return EE_MODULES . 'batch' . DS . 'templates' . DS . 'batch_frontend_wrapper.template.html';
254
+		}
255
+		return $template;
256
+	}
257 257
 
258
-    /**
259
-     * Adds an admin page which doesn't appear in the admin menu
260
-     */
261
-    public function register_admin_pages()
262
-    {
263
-        add_submenu_page(
264
-            '', // parent slug. we don't want this to actually appear in the menu
265
-            __('Batch Job', 'event_espresso'), // page title
266
-            'n/a', // menu title
267
-            'read', // we want this page to actually be accessible to anyone,
268
-            'espresso_batch', // menu slug
269
-            array(self::instance(), 'show_admin_page')
270
-        );
271
-    }
258
+	/**
259
+	 * Adds an admin page which doesn't appear in the admin menu
260
+	 */
261
+	public function register_admin_pages()
262
+	{
263
+		add_submenu_page(
264
+			'', // parent slug. we don't want this to actually appear in the menu
265
+			__('Batch Job', 'event_espresso'), // page title
266
+			'n/a', // menu title
267
+			'read', // we want this page to actually be accessible to anyone,
268
+			'espresso_batch', // menu slug
269
+			array(self::instance(), 'show_admin_page')
270
+		);
271
+	}
272 272
 
273
-    /**
274
-     * Renders the admin page, after most of the work was already done during enqueuing scripts
275
-     * of creating the job and localizing some data
276
-     */
277
-    public function show_admin_page()
278
-    {
279
-        echo EEH_Template::locate_template(
280
-            EE_MODULES . 'batch' . DS . 'templates' . DS . 'batch_wrapper.template.html',
281
-            array('batch_request_type' => $this->batch_request_type())
282
-        );
283
-    }
273
+	/**
274
+	 * Renders the admin page, after most of the work was already done during enqueuing scripts
275
+	 * of creating the job and localizing some data
276
+	 */
277
+	public function show_admin_page()
278
+	{
279
+		echo EEH_Template::locate_template(
280
+			EE_MODULES . 'batch' . DS . 'templates' . DS . 'batch_wrapper.template.html',
281
+			array('batch_request_type' => $this->batch_request_type())
282
+		);
283
+	}
284 284
 
285
-    /**
286
-     * Receives ajax calls for continuing a job
287
-     */
288
-    public function batch_continue()
289
-    {
290
-        $job_id = sanitize_text_field($_REQUEST['job_id']);
291
-        $batch_runner = $this->getLoader()->getShared('EventEspressoBatchRequest\BatchRequestProcessor');
292
-        $response_obj = $batch_runner->continue_job($job_id);
293
-        $this->_return_json($response_obj->to_array());
294
-    }
285
+	/**
286
+	 * Receives ajax calls for continuing a job
287
+	 */
288
+	public function batch_continue()
289
+	{
290
+		$job_id = sanitize_text_field($_REQUEST['job_id']);
291
+		$batch_runner = $this->getLoader()->getShared('EventEspressoBatchRequest\BatchRequestProcessor');
292
+		$response_obj = $batch_runner->continue_job($job_id);
293
+		$this->_return_json($response_obj->to_array());
294
+	}
295 295
 
296
-    /**
297
-     * Receives the ajax call to cleanup a job
298
-     *
299
-     * @return type
300
-     */
301
-    public function batch_cleanup()
302
-    {
303
-        $job_id = sanitize_text_field($_REQUEST['job_id']);
304
-        $batch_runner = $this->getLoader()->getShared('EventEspressoBatchRequest\BatchRequestProcessor');
305
-        $response_obj = $batch_runner->cleanup_job($job_id);
306
-        $this->_return_json($response_obj->to_array());
307
-    }
296
+	/**
297
+	 * Receives the ajax call to cleanup a job
298
+	 *
299
+	 * @return type
300
+	 */
301
+	public function batch_cleanup()
302
+	{
303
+		$job_id = sanitize_text_field($_REQUEST['job_id']);
304
+		$batch_runner = $this->getLoader()->getShared('EventEspressoBatchRequest\BatchRequestProcessor');
305
+		$response_obj = $batch_runner->cleanup_job($job_id);
306
+		$this->_return_json($response_obj->to_array());
307
+	}
308 308
 
309 309
 
310
-    /**
311
-     * Returns a json response
312
-     *
313
-     * @param array $data The data we want to send echo via in the JSON response's "data" element
314
-     *
315
-     * The returned json object is created from an array in the following format:
316
-     * array(
317
-     *    'notices' => '', // - contains any EE_Error formatted notices
318
-     *    'data' => array() //this can be any key/value pairs that a method returns for later json parsing by the js.
319
-     *    We're also going to include the template args with every package (so js can pick out any specific template
320
-     *    args that might be included in here)
321
-     *    'isEEajax' => true,//indicates this is a response from EE
322
-     * )
323
-     */
324
-    protected function _return_json($data)
325
-    {
326
-        $json = array(
327
-            'notices'  => EE_Error::get_notices(),
328
-            'data'     => $data,
329
-            'isEEajax' => true
330
-            // special flag so any ajax.Success methods in js can identify this return package as a EEajax package.
331
-        );
310
+	/**
311
+	 * Returns a json response
312
+	 *
313
+	 * @param array $data The data we want to send echo via in the JSON response's "data" element
314
+	 *
315
+	 * The returned json object is created from an array in the following format:
316
+	 * array(
317
+	 *    'notices' => '', // - contains any EE_Error formatted notices
318
+	 *    'data' => array() //this can be any key/value pairs that a method returns for later json parsing by the js.
319
+	 *    We're also going to include the template args with every package (so js can pick out any specific template
320
+	 *    args that might be included in here)
321
+	 *    'isEEajax' => true,//indicates this is a response from EE
322
+	 * )
323
+	 */
324
+	protected function _return_json($data)
325
+	{
326
+		$json = array(
327
+			'notices'  => EE_Error::get_notices(),
328
+			'data'     => $data,
329
+			'isEEajax' => true
330
+			// special flag so any ajax.Success methods in js can identify this return package as a EEajax package.
331
+		);
332 332
 
333 333
 
334
-        // make sure there are no php errors or headers_sent.  Then we can set correct json header.
335
-        if (null === error_get_last() || ! headers_sent()) {
336
-            header('Content-Type: application/json; charset=UTF-8');
337
-        }
338
-        echo wp_json_encode($json);
339
-        exit();
340
-    }
334
+		// make sure there are no php errors or headers_sent.  Then we can set correct json header.
335
+		if (null === error_get_last() || ! headers_sent()) {
336
+			header('Content-Type: application/json; charset=UTF-8');
337
+		}
338
+		echo wp_json_encode($json);
339
+		exit();
340
+	}
341 341
 
342
-    /**
343
-     * Gets the job step response which was done during the enqueuing of scripts
344
-     *
345
-     * @return \EventEspressoBatchRequest\Helpers\JobStepResponse
346
-     */
347
-    public function job_step_response()
348
-    {
349
-        return $this->_job_step_response;
350
-    }
342
+	/**
343
+	 * Gets the job step response which was done during the enqueuing of scripts
344
+	 *
345
+	 * @return \EventEspressoBatchRequest\Helpers\JobStepResponse
346
+	 */
347
+	public function job_step_response()
348
+	{
349
+		return $this->_job_step_response;
350
+	}
351 351
 
352
-    /**
353
-     * Gets the batch request type indicated in the $_REQUEST
354
-     *
355
-     * @return string: EED_Batch::batch_job, EED_Batch::batch_file_job, EED_Batch::batch_not_job
356
-     */
357
-    public function batch_request_type()
358
-    {
359
-        if ($this->_batch_request_type === null) {
360
-            if (isset($_GET['batch'])) {
361
-                if ($_GET['batch'] == self::batch_job) {
362
-                    $this->_batch_request_type = self::batch_job;
363
-                } elseif ($_GET['batch'] == self::batch_file_job) {
364
-                    $this->_batch_request_type = self::batch_file_job;
365
-                }
366
-            }
367
-            // if we didn't find that it was a batch request, indicate it wasn't
368
-            if ($this->_batch_request_type === null) {
369
-                $this->_batch_request_type = self::batch_not_job;
370
-            }
371
-        }
372
-        return $this->_batch_request_type;
373
-    }
352
+	/**
353
+	 * Gets the batch request type indicated in the $_REQUEST
354
+	 *
355
+	 * @return string: EED_Batch::batch_job, EED_Batch::batch_file_job, EED_Batch::batch_not_job
356
+	 */
357
+	public function batch_request_type()
358
+	{
359
+		if ($this->_batch_request_type === null) {
360
+			if (isset($_GET['batch'])) {
361
+				if ($_GET['batch'] == self::batch_job) {
362
+					$this->_batch_request_type = self::batch_job;
363
+				} elseif ($_GET['batch'] == self::batch_file_job) {
364
+					$this->_batch_request_type = self::batch_file_job;
365
+				}
366
+			}
367
+			// if we didn't find that it was a batch request, indicate it wasn't
368
+			if ($this->_batch_request_type === null) {
369
+				$this->_batch_request_type = self::batch_not_job;
370
+			}
371
+		}
372
+		return $this->_batch_request_type;
373
+	}
374 374
 
375
-    /**
376
-     * Unnecessary
377
-     *
378
-     * @param type $WP
379
-     */
380
-    public function run($WP)
381
-    {
382
-    }
375
+	/**
376
+	 * Unnecessary
377
+	 *
378
+	 * @param type $WP
379
+	 */
380
+	public function run($WP)
381
+	{
382
+	}
383 383
 }
Please login to merge, or discard this patch.
core/libraries/batch/BatchRequestProcessor.php 2 patches
Indentation   +201 added lines, -201 removed lines patch added patch discarded remove patch
@@ -25,215 +25,215 @@
 block discarded – undo
25 25
  */
26 26
 class BatchRequestProcessor
27 27
 {
28
-    // phpcs:disable PSR2.Classes.PropertyDeclaration.Underscore
29
-    // phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
30
-    /**
31
-     * Current job's ID (if assigned)
32
-     *
33
-     * @var string|null
34
-     */
35
-    protected $_job_id;
28
+	// phpcs:disable PSR2.Classes.PropertyDeclaration.Underscore
29
+	// phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
30
+	/**
31
+	 * Current job's ID (if assigned)
32
+	 *
33
+	 * @var string|null
34
+	 */
35
+	protected $_job_id;
36 36
 
37
-    /**
38
-     * Current job's parameters
39
-     *
40
-     * @var JobParameters|null
41
-     */
42
-    protected $_job_parameters;
43
-    /**
44
-     * @var LoaderInterface
45
-     */
46
-    private $loader;
37
+	/**
38
+	 * Current job's parameters
39
+	 *
40
+	 * @var JobParameters|null
41
+	 */
42
+	protected $_job_parameters;
43
+	/**
44
+	 * @var LoaderInterface
45
+	 */
46
+	private $loader;
47 47
 
48
-    /**
49
-     * BatchRequestProcessor constructor.
50
-     * @param LoaderInterface $loader
51
-     */
52
-    public function __construct(LoaderInterface $loader)
53
-    {
54
-        $this->loader = $loader;
55
-    }
56
-    // phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
57
-    /**
58
-     * Creates a job for the specified batch handler class (which should be autoloaded)
59
-     * and the specified request data
60
-     *
61
-     * @param string $batch_job_handler_class of an auto-loaded class implementing JobHandlerInterface
62
-     * @param array  $request_data            to be used by the batch job handler
63
-     * @return JobStepResponse
64
-     */
65
-    public function create_job($batch_job_handler_class, $request_data)
66
-    {
67
-        try {
68
-            $this->_job_id = wp_generate_password(15, false);
69
-            $obj = $this->instantiate_batch_job_handler_from_classname($batch_job_handler_class);
70
-            $this->_job_parameters = new JobParameters($this->_job_id, $batch_job_handler_class, $request_data);
71
-            $response = $obj->create_job($this->_job_parameters);
72
-            if (! $response instanceof JobStepResponse) {
73
-                throw new BatchRequestException(
74
-                    sprintf(
75
-                        __(
76
-                            'The class implementing JobHandlerInterface did not return a JobStepResponse when create_job was called with %1$s. It needs to return one or throw an Exception',
77
-                            'event_espresso'
78
-                        ),
79
-                        wp_json_encode($request_data)
80
-                    )
81
-                );
82
-            }
83
-            $success = $this->_job_parameters->save(true);
84
-            if (! $success) {
85
-                throw new BatchRequestException(
86
-                    sprintf(
87
-                        __(
88
-                            'Could not save job %1$s to the Wordpress Options table. These were the arguments used: %2$s',
89
-                            'event_espresso'
90
-                        ),
91
-                        $this->_job_id,
92
-                        wp_json_encode($request_data)
93
-                    )
94
-                );
95
-            }
96
-        } catch (\Exception $e) {
97
-            $response = $this->_get_error_response($e, 'create_job');
98
-        }
99
-        return $response;
100
-    }
48
+	/**
49
+	 * BatchRequestProcessor constructor.
50
+	 * @param LoaderInterface $loader
51
+	 */
52
+	public function __construct(LoaderInterface $loader)
53
+	{
54
+		$this->loader = $loader;
55
+	}
56
+	// phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
57
+	/**
58
+	 * Creates a job for the specified batch handler class (which should be autoloaded)
59
+	 * and the specified request data
60
+	 *
61
+	 * @param string $batch_job_handler_class of an auto-loaded class implementing JobHandlerInterface
62
+	 * @param array  $request_data            to be used by the batch job handler
63
+	 * @return JobStepResponse
64
+	 */
65
+	public function create_job($batch_job_handler_class, $request_data)
66
+	{
67
+		try {
68
+			$this->_job_id = wp_generate_password(15, false);
69
+			$obj = $this->instantiate_batch_job_handler_from_classname($batch_job_handler_class);
70
+			$this->_job_parameters = new JobParameters($this->_job_id, $batch_job_handler_class, $request_data);
71
+			$response = $obj->create_job($this->_job_parameters);
72
+			if (! $response instanceof JobStepResponse) {
73
+				throw new BatchRequestException(
74
+					sprintf(
75
+						__(
76
+							'The class implementing JobHandlerInterface did not return a JobStepResponse when create_job was called with %1$s. It needs to return one or throw an Exception',
77
+							'event_espresso'
78
+						),
79
+						wp_json_encode($request_data)
80
+					)
81
+				);
82
+			}
83
+			$success = $this->_job_parameters->save(true);
84
+			if (! $success) {
85
+				throw new BatchRequestException(
86
+					sprintf(
87
+						__(
88
+							'Could not save job %1$s to the Wordpress Options table. These were the arguments used: %2$s',
89
+							'event_espresso'
90
+						),
91
+						$this->_job_id,
92
+						wp_json_encode($request_data)
93
+					)
94
+				);
95
+			}
96
+		} catch (\Exception $e) {
97
+			$response = $this->_get_error_response($e, 'create_job');
98
+		}
99
+		return $response;
100
+	}
101 101
 
102 102
 
103
-    /**
104
-     * Retrieves the job's arguments
105
-     *
106
-     * @param string $job_id
107
-     * @param int    $batch_size
108
-     * @return JobStepResponse
109
-     */
110
-    public function continue_job($job_id, $batch_size = 50)
111
-    {
112
-        try {
113
-            $this->_job_id = $job_id;
114
-            $batch_size = defined('EE_BATCHRUNNER_BATCH_SIZE') ? EE_BATCHRUNNER_BATCH_SIZE : $batch_size;
115
-            // get the corresponding WordPress option for the job
116
-            $this->_job_parameters = JobParameters::load($this->_job_id);
117
-            $handler_obj = $this->instantiate_batch_job_handler_from_classname($this->_job_parameters->classname());
118
-            // continue it
119
-            $response = $handler_obj->continue_job($this->_job_parameters, $batch_size);
120
-            if (! $response instanceof JobStepResponse) {
121
-                throw new BatchRequestException(
122
-                    sprintf(
123
-                        __(
124
-                            'The class implementing JobHandlerInterface did not return a JobStepResponse when continue_job was called with job %1$s. It needs to return one or throw an Exception',
125
-                            'event_espresso'
126
-                        ),
127
-                        $this->_job_id
128
-                    )
129
-                );
130
-            }
131
-            $this->_job_parameters->save();
132
-        } catch (\Exception $e) {
133
-            $response = $this->_get_error_response($e, 'continue_job');
134
-        }
135
-        return $response;
136
-    }
103
+	/**
104
+	 * Retrieves the job's arguments
105
+	 *
106
+	 * @param string $job_id
107
+	 * @param int    $batch_size
108
+	 * @return JobStepResponse
109
+	 */
110
+	public function continue_job($job_id, $batch_size = 50)
111
+	{
112
+		try {
113
+			$this->_job_id = $job_id;
114
+			$batch_size = defined('EE_BATCHRUNNER_BATCH_SIZE') ? EE_BATCHRUNNER_BATCH_SIZE : $batch_size;
115
+			// get the corresponding WordPress option for the job
116
+			$this->_job_parameters = JobParameters::load($this->_job_id);
117
+			$handler_obj = $this->instantiate_batch_job_handler_from_classname($this->_job_parameters->classname());
118
+			// continue it
119
+			$response = $handler_obj->continue_job($this->_job_parameters, $batch_size);
120
+			if (! $response instanceof JobStepResponse) {
121
+				throw new BatchRequestException(
122
+					sprintf(
123
+						__(
124
+							'The class implementing JobHandlerInterface did not return a JobStepResponse when continue_job was called with job %1$s. It needs to return one or throw an Exception',
125
+							'event_espresso'
126
+						),
127
+						$this->_job_id
128
+					)
129
+				);
130
+			}
131
+			$this->_job_parameters->save();
132
+		} catch (\Exception $e) {
133
+			$response = $this->_get_error_response($e, 'continue_job');
134
+		}
135
+		return $response;
136
+	}
137 137
 
138 138
 
139
-    /**
140
-     * Instantiates an object of type $classname, which implements
141
-     * JobHandlerInterface
142
-     *
143
-     * @param string $classname
144
-     * @return JobHandlerInterface
145
-     * @throws BatchRequestException
146
-     */
147
-    public function instantiate_batch_job_handler_from_classname($classname)
148
-    {
149
-        if (! class_exists($classname)) {
150
-            throw new BatchRequestException(
151
-                sprintf(
152
-                    __(
153
-                        'The class %1$s does not exist, and so could not be used for running a job. It should implement JobHandlerInterface.',
154
-                        'event_espresso'
155
-                    ),
156
-                    $classname
157
-                )
158
-            );
159
-        }
160
-        $obj = $this->loader->getNew($classname);
161
-        if (! $obj instanceof JobHandlerInterface) {
162
-            throw new BatchRequestException(
163
-                sprintf(
164
-                    __(
165
-                        'The class %1$s does not implement JobHandlerInterface and so could not be used for running a job',
166
-                        'event_espresso'
167
-                    ),
168
-                    $classname
169
-                )
170
-            );
171
-        }
172
-        return $obj;
173
-    }
139
+	/**
140
+	 * Instantiates an object of type $classname, which implements
141
+	 * JobHandlerInterface
142
+	 *
143
+	 * @param string $classname
144
+	 * @return JobHandlerInterface
145
+	 * @throws BatchRequestException
146
+	 */
147
+	public function instantiate_batch_job_handler_from_classname($classname)
148
+	{
149
+		if (! class_exists($classname)) {
150
+			throw new BatchRequestException(
151
+				sprintf(
152
+					__(
153
+						'The class %1$s does not exist, and so could not be used for running a job. It should implement JobHandlerInterface.',
154
+						'event_espresso'
155
+					),
156
+					$classname
157
+				)
158
+			);
159
+		}
160
+		$obj = $this->loader->getNew($classname);
161
+		if (! $obj instanceof JobHandlerInterface) {
162
+			throw new BatchRequestException(
163
+				sprintf(
164
+					__(
165
+						'The class %1$s does not implement JobHandlerInterface and so could not be used for running a job',
166
+						'event_espresso'
167
+					),
168
+					$classname
169
+				)
170
+			);
171
+		}
172
+		return $obj;
173
+	}
174 174
 
175 175
 
176
-    /**
177
-     * Forces a job to be cleaned up
178
-     *
179
-     * @param string $job_id
180
-     * @return JobStepResponse
181
-     * @throws BatchRequestException
182
-     */
183
-    public function cleanup_job($job_id)
184
-    {
185
-        try {
186
-            $this->_job_id = $job_id;
187
-            $job_parameters = JobParameters::load($this->_job_id);
188
-            $handler_obj = $this->instantiate_batch_job_handler_from_classname($job_parameters->classname());
189
-            // continue it
190
-            $response = $handler_obj->cleanup_job($job_parameters);
191
-            if (! $response instanceof JobStepResponse) {
192
-                throw new BatchRequestException(
193
-                    sprintf(
194
-                        __(
195
-                            'The class implementing JobHandlerInterface did not return a JobStepResponse when cleanup_job was called with job %1$s. It needs to return one or throw an Exception',
196
-                            'event_espresso'
197
-                        ),
198
-                        $this->_job_id
199
-                    )
200
-                );
201
-            }
202
-            $job_parameters->set_status(JobParameters::status_cleaned_up);
203
-            $job_parameters->delete();
204
-            return $response;
205
-        } catch (\Exception $e) {
206
-            $response = $this->_get_error_response($e, 'cleanup_job');
207
-        }
208
-        return $response;
209
-    }
176
+	/**
177
+	 * Forces a job to be cleaned up
178
+	 *
179
+	 * @param string $job_id
180
+	 * @return JobStepResponse
181
+	 * @throws BatchRequestException
182
+	 */
183
+	public function cleanup_job($job_id)
184
+	{
185
+		try {
186
+			$this->_job_id = $job_id;
187
+			$job_parameters = JobParameters::load($this->_job_id);
188
+			$handler_obj = $this->instantiate_batch_job_handler_from_classname($job_parameters->classname());
189
+			// continue it
190
+			$response = $handler_obj->cleanup_job($job_parameters);
191
+			if (! $response instanceof JobStepResponse) {
192
+				throw new BatchRequestException(
193
+					sprintf(
194
+						__(
195
+							'The class implementing JobHandlerInterface did not return a JobStepResponse when cleanup_job was called with job %1$s. It needs to return one or throw an Exception',
196
+							'event_espresso'
197
+						),
198
+						$this->_job_id
199
+					)
200
+				);
201
+			}
202
+			$job_parameters->set_status(JobParameters::status_cleaned_up);
203
+			$job_parameters->delete();
204
+			return $response;
205
+		} catch (\Exception $e) {
206
+			$response = $this->_get_error_response($e, 'cleanup_job');
207
+		}
208
+		return $response;
209
+	}
210 210
 
211 211
 
212
-    /**
213
-     * Creates a valid JobStepResponse object from an exception and method name.
214
-     *
215
-     * @param \Exception $exception
216
-     * @param string     $method_name
217
-     * @return JobStepResponse
218
-     */
219
-    protected function _get_error_response(\Exception $exception, $method_name)
220
-    {
221
-        if (! $this->_job_parameters instanceof JobParameters) {
222
-            $this->_job_parameters = new JobParameters($this->_job_id, __('__Unknown__', 'event_espresso'), array());
223
-        }
224
-        $this->_job_parameters->set_status(JobParameters::status_error);
225
-        return new JobStepResponse(
226
-            $this->_job_parameters,
227
-            sprintf(
228
-                __(
229
-                    'An exception of type %1$s occurred while running %2$s. Its message was %3$s and had trace %4$s',
230
-                    'event_espresso'
231
-                ),
232
-                get_class($exception),
233
-                'BatchRunner::' . $method_name . '()',
234
-                $exception->getMessage(),
235
-                $exception->getTraceAsString()
236
-            )
237
-        );
238
-    }
212
+	/**
213
+	 * Creates a valid JobStepResponse object from an exception and method name.
214
+	 *
215
+	 * @param \Exception $exception
216
+	 * @param string     $method_name
217
+	 * @return JobStepResponse
218
+	 */
219
+	protected function _get_error_response(\Exception $exception, $method_name)
220
+	{
221
+		if (! $this->_job_parameters instanceof JobParameters) {
222
+			$this->_job_parameters = new JobParameters($this->_job_id, __('__Unknown__', 'event_espresso'), array());
223
+		}
224
+		$this->_job_parameters->set_status(JobParameters::status_error);
225
+		return new JobStepResponse(
226
+			$this->_job_parameters,
227
+			sprintf(
228
+				__(
229
+					'An exception of type %1$s occurred while running %2$s. Its message was %3$s and had trace %4$s',
230
+					'event_espresso'
231
+				),
232
+				get_class($exception),
233
+				'BatchRunner::' . $method_name . '()',
234
+				$exception->getMessage(),
235
+				$exception->getTraceAsString()
236
+			)
237
+		);
238
+	}
239 239
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -69,7 +69,7 @@  discard block
 block discarded – undo
69 69
             $obj = $this->instantiate_batch_job_handler_from_classname($batch_job_handler_class);
70 70
             $this->_job_parameters = new JobParameters($this->_job_id, $batch_job_handler_class, $request_data);
71 71
             $response = $obj->create_job($this->_job_parameters);
72
-            if (! $response instanceof JobStepResponse) {
72
+            if ( ! $response instanceof JobStepResponse) {
73 73
                 throw new BatchRequestException(
74 74
                     sprintf(
75 75
                         __(
@@ -81,7 +81,7 @@  discard block
 block discarded – undo
81 81
                 );
82 82
             }
83 83
             $success = $this->_job_parameters->save(true);
84
-            if (! $success) {
84
+            if ( ! $success) {
85 85
                 throw new BatchRequestException(
86 86
                     sprintf(
87 87
                         __(
@@ -117,7 +117,7 @@  discard block
 block discarded – undo
117 117
             $handler_obj = $this->instantiate_batch_job_handler_from_classname($this->_job_parameters->classname());
118 118
             // continue it
119 119
             $response = $handler_obj->continue_job($this->_job_parameters, $batch_size);
120
-            if (! $response instanceof JobStepResponse) {
120
+            if ( ! $response instanceof JobStepResponse) {
121 121
                 throw new BatchRequestException(
122 122
                     sprintf(
123 123
                         __(
@@ -146,7 +146,7 @@  discard block
 block discarded – undo
146 146
      */
147 147
     public function instantiate_batch_job_handler_from_classname($classname)
148 148
     {
149
-        if (! class_exists($classname)) {
149
+        if ( ! class_exists($classname)) {
150 150
             throw new BatchRequestException(
151 151
                 sprintf(
152 152
                     __(
@@ -158,7 +158,7 @@  discard block
 block discarded – undo
158 158
             );
159 159
         }
160 160
         $obj = $this->loader->getNew($classname);
161
-        if (! $obj instanceof JobHandlerInterface) {
161
+        if ( ! $obj instanceof JobHandlerInterface) {
162 162
             throw new BatchRequestException(
163 163
                 sprintf(
164 164
                     __(
@@ -188,7 +188,7 @@  discard block
 block discarded – undo
188 188
             $handler_obj = $this->instantiate_batch_job_handler_from_classname($job_parameters->classname());
189 189
             // continue it
190 190
             $response = $handler_obj->cleanup_job($job_parameters);
191
-            if (! $response instanceof JobStepResponse) {
191
+            if ( ! $response instanceof JobStepResponse) {
192 192
                 throw new BatchRequestException(
193 193
                     sprintf(
194 194
                         __(
@@ -218,7 +218,7 @@  discard block
 block discarded – undo
218 218
      */
219 219
     protected function _get_error_response(\Exception $exception, $method_name)
220 220
     {
221
-        if (! $this->_job_parameters instanceof JobParameters) {
221
+        if ( ! $this->_job_parameters instanceof JobParameters) {
222 222
             $this->_job_parameters = new JobParameters($this->_job_id, __('__Unknown__', 'event_espresso'), array());
223 223
         }
224 224
         $this->_job_parameters->set_status(JobParameters::status_error);
@@ -230,7 +230,7 @@  discard block
 block discarded – undo
230 230
                     'event_espresso'
231 231
                 ),
232 232
                 get_class($exception),
233
-                'BatchRunner::' . $method_name . '()',
233
+                'BatchRunner::'.$method_name.'()',
234 234
                 $exception->getMessage(),
235 235
                 $exception->getTraceAsString()
236 236
             )
Please login to merge, or discard this patch.
strategies/display/EE_File_Input_Display_Strategy.strategy.php 1 patch
Indentation   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -10,11 +10,11 @@
 block discarded – undo
10 10
  */
11 11
 class EE_File_Input_Display_Strategy extends EE_Text_Input_Display_Strategy
12 12
 {
13
-    /**
14
-     * Override's parent to just set the type. May someday support other arguments.
15
-     */
16
-    public function __construct()
17
-    {
18
-        parent::__construct('file');
19
-    }
13
+	/**
14
+	 * Override's parent to just set the type. May someday support other arguments.
15
+	 */
16
+	public function __construct()
17
+	{
18
+		parent::__construct('file');
19
+	}
20 20
 }
Please login to merge, or discard this patch.