Completed
Branch BUG/3575-event-deletion-previe... (bbeda1)
by
unknown
06:40 queued 04:49
created
core/EE_Front_Controller.core.php 2 patches
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -97,7 +97,7 @@  discard block
 block discarded – undo
97 97
      */
98 98
     public function Request_Handler()
99 99
     {
100
-        if (! $this->Request_Handler instanceof EE_Request_Handler) {
100
+        if ( ! $this->Request_Handler instanceof EE_Request_Handler) {
101 101
             $this->Request_Handler = LoaderFactory::getLoader()->getShared('EE_Request_Handler');
102 102
         }
103 103
         return $this->Request_Handler;
@@ -332,7 +332,7 @@  discard block
 block discarded – undo
332 332
         print(
333 333
         apply_filters(
334 334
             'FHEE__EE_Front_Controller__header_meta_tag',
335
-            '<meta name="generator" content="Event Espresso Version ' . EVENT_ESPRESSO_VERSION . "\" />\n"
335
+            '<meta name="generator" content="Event Espresso Version '.EVENT_ESPRESSO_VERSION."\" />\n"
336 336
         )
337 337
         );
338 338
 
@@ -349,7 +349,7 @@  discard block
 block discarded – undo
349 349
             print(
350 350
             apply_filters(
351 351
                 'FHEE__EE_Front_Controller__header_meta_tag__noindex_for_event_type',
352
-                '<meta name="robots" content="noindex,follow" />' . "\n"
352
+                '<meta name="robots" content="noindex,follow" />'."\n"
353 353
             )
354 354
             );
355 355
         }
@@ -415,7 +415,7 @@  discard block
 block discarded – undo
415 415
         ) {
416 416
             echo EE_Error::get_notices();
417 417
             $shown_already = true;
418
-            EEH_Template::display_template(EE_TEMPLATES . 'espresso-ajax-notices.template.php');
418
+            EEH_Template::display_template(EE_TEMPLATES.'espresso-ajax-notices.template.php');
419 419
         }
420 420
         do_action('AHEE__EE_Front_Controller__display_errors__end');
421 421
     }
Please login to merge, or discard this patch.
Indentation   +478 added lines, -478 removed lines patch added patch discarded remove patch
@@ -17,482 +17,482 @@
 block discarded – undo
17 17
 final class EE_Front_Controller
18 18
 {
19 19
 
20
-    /**
21
-     * @var string
22
-     */
23
-    private $_template_path;
24
-
25
-    /**
26
-     * @var string
27
-     */
28
-    private $_template;
29
-
30
-    /**
31
-     * @type EE_Registry
32
-     */
33
-    protected $Registry;
34
-
35
-    /**
36
-     * @type EE_Request_Handler
37
-     */
38
-    protected $Request_Handler;
39
-
40
-    /**
41
-     * @type EE_Module_Request_Router
42
-     */
43
-    protected $Module_Request_Router;
44
-
45
-    /**
46
-     * @type CurrentPage
47
-     */
48
-    protected $current_page;
49
-
50
-
51
-    /**
52
-     *    class constructor
53
-     *    should fire after shortcode, module, addon, or other plugin's default priority init phases have run
54
-     *
55
-     * @access    public
56
-     * @param EE_Registry              $Registry
57
-     * @param CurrentPage              $EspressoPage
58
-     * @param EE_Module_Request_Router $Module_Request_Router
59
-     */
60
-    public function __construct(
61
-        EE_Registry $Registry,
62
-        CurrentPage $EspressoPage,
63
-        EE_Module_Request_Router $Module_Request_Router
64
-    ) {
65
-        $this->Registry              = $Registry;
66
-        $this->current_page          = $EspressoPage;
67
-        $this->Module_Request_Router = $Module_Request_Router;
68
-        // load other resources and begin to actually run shortcodes and modules
69
-        // analyse the incoming WP request
70
-        add_action('parse_request', array($this, 'get_request'), 1, 1);
71
-        // process request with module factory
72
-        add_action('pre_get_posts', array($this, 'pre_get_posts'), 10, 1);
73
-        // before headers sent
74
-        add_action('wp', array($this, 'wp'), 5);
75
-        // primarily used to process any content shortcodes
76
-        add_action('template_redirect', array($this, 'templateRedirect'), 999);
77
-        // header
78
-        add_action('wp_head', array($this, 'header_meta_tag'), 5);
79
-        add_action('wp_print_scripts', array($this, 'wp_print_scripts'), 10);
80
-        add_filter('template_include', array($this, 'template_include'), 1);
81
-        // display errors
82
-        add_action('loop_start', array($this, 'display_errors'), 2);
83
-        // the content
84
-        // add_filter( 'the_content', array( $this, 'the_content' ), 5, 1 );
85
-        // exclude our private cpt comments
86
-        add_filter('comments_clauses', array($this, 'filter_wp_comments'), 10, 1);
87
-        // make sure any ajax requests will respect the url schema when requests are made against admin-ajax.php (http:// or https://)
88
-        add_filter('admin_url', array($this, 'maybe_force_admin_ajax_ssl'), 200, 1);
89
-        // action hook EE
90
-        do_action('AHEE__EE_Front_Controller__construct__done', $this);
91
-    }
92
-
93
-
94
-    /**
95
-     * @return EE_Request_Handler
96
-     * @deprecated 4.10.14.p
97
-     */
98
-    public function Request_Handler()
99
-    {
100
-        if (! $this->Request_Handler instanceof EE_Request_Handler) {
101
-            $this->Request_Handler = LoaderFactory::getLoader()->getShared('EE_Request_Handler');
102
-        }
103
-        return $this->Request_Handler;
104
-    }
105
-
106
-
107
-    /**
108
-     * @return EE_Module_Request_Router
109
-     */
110
-    public function Module_Request_Router()
111
-    {
112
-        return $this->Module_Request_Router;
113
-    }
114
-
115
-
116
-    /**
117
-     * @return LegacyShortcodesManager
118
-     * @deprecated 4.10.14.p
119
-     */
120
-    public function getLegacyShortcodesManager()
121
-    {
122
-        return EE_Config::getLegacyShortcodesManager();
123
-    }
124
-
125
-
126
-
127
-
128
-
129
-    /***********************************************        INIT ACTION HOOK         ***********************************************/
130
-    /**
131
-     * filter_wp_comments
132
-     * This simply makes sure that any "private" EE CPTs do not have their comments show up in any wp comment
133
-     * widgets/queries done on frontend
134
-     *
135
-     * @param  array $clauses array of comment clauses setup by WP_Comment_Query
136
-     * @return array array of comment clauses with modifications.
137
-     * @throws InvalidArgumentException
138
-     * @throws InvalidDataTypeException
139
-     * @throws InvalidInterfaceException
140
-     */
141
-    public function filter_wp_comments($clauses)
142
-    {
143
-        global $wpdb;
144
-        if (strpos($clauses['join'], $wpdb->posts) !== false) {
145
-            /** @var EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions $custom_post_types */
146
-            $custom_post_types = LoaderFactory::getLoader()->getShared(
147
-                'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions'
148
-            );
149
-            $cpts = $custom_post_types->getPrivateCustomPostTypes();
150
-            foreach ($cpts as $cpt => $details) {
151
-                $clauses['where'] .= $wpdb->prepare(" AND $wpdb->posts.post_type != %s", $cpt);
152
-            }
153
-        }
154
-        return $clauses;
155
-    }
156
-
157
-
158
-    /**
159
-     * this just makes sure that if the site is using ssl that we force that for any admin ajax calls from frontend
160
-     *
161
-     * @param  string $url incoming url
162
-     * @return string         final assembled url
163
-     */
164
-    public function maybe_force_admin_ajax_ssl($url)
165
-    {
166
-        if (is_ssl() && preg_match('/admin-ajax.php/', $url)) {
167
-            $url = str_replace('http://', 'https://', $url);
168
-        }
169
-        return $url;
170
-    }
171
-
172
-
173
-
174
-
175
-
176
-
177
-    /***********************************************        WP_LOADED ACTION HOOK         ***********************************************/
178
-
179
-
180
-    /**
181
-     *    wp_loaded - should fire after shortcode, module, addon, or other plugin's have been registered and their
182
-     *    default priority init phases have run
183
-     *
184
-     * @access    public
185
-     * @return    void
186
-     */
187
-    public function wp_loaded()
188
-    {
189
-    }
190
-
191
-
192
-
193
-
194
-
195
-    /***********************************************        PARSE_REQUEST HOOK         ***********************************************/
196
-    /**
197
-     *    _get_request
198
-     *
199
-     * @access public
200
-     * @param WP $WP
201
-     * @return void
202
-     */
203
-    public function get_request(WP $WP)
204
-    {
205
-        do_action('AHEE__EE_Front_Controller__get_request__start');
206
-        $this->current_page->parseQueryVars($WP);
207
-        do_action('AHEE__EE_Front_Controller__get_request__complete');
208
-        remove_action('parse_request', [$this, 'get_request'], 1);
209
-    }
210
-
211
-
212
-    /**
213
-     *    pre_get_posts - basically a module factory for instantiating modules and selecting the final view template
214
-     *
215
-     * @access    public
216
-     * @param WP_Query $WP_Query
217
-     * @return    void
218
-     * @throws EE_Error
219
-     * @throws ReflectionException
220
-     */
221
-    public function pre_get_posts($WP_Query)
222
-    {
223
-        // only load Module_Request_Router if this is the main query
224
-        if (
225
-            $this->Module_Request_Router instanceof EE_Module_Request_Router
226
-            && $WP_Query->is_main_query()
227
-        ) {
228
-            // cycle thru module routes
229
-            while ($route = $this->Module_Request_Router->get_route($WP_Query)) {
230
-                // determine module and method for route
231
-                $module = $this->Module_Request_Router->resolve_route($route[0], $route[1]);
232
-                if ($module instanceof EED_Module) {
233
-                    // get registered view for route
234
-                    $this->_template_path = $this->Module_Request_Router->get_view($route);
235
-                    // grab module name
236
-                    $module_name = $module->module_name();
237
-                    // map the module to the module objects
238
-                    $this->Registry->modules->{$module_name} = $module;
239
-                }
240
-            }
241
-        }
242
-    }
243
-
244
-
245
-
246
-
247
-
248
-    /***********************************************        WP HOOK         ***********************************************/
249
-
250
-
251
-    /**
252
-     *    wp - basically last chance to do stuff before headers sent
253
-     *
254
-     * @access    public
255
-     * @return    void
256
-     */
257
-    public function wp()
258
-    {
259
-    }
260
-
261
-
262
-
263
-    /***********************     GET_HEADER && WP_HEAD HOOK     ***********************/
264
-
265
-
266
-    /**
267
-     * callback for the "template_redirect" hook point
268
-     * checks sidebars for EE widgets
269
-     * loads resources and assets accordingly
270
-     *
271
-     * @return void
272
-     */
273
-    public function templateRedirect()
274
-    {
275
-        global $wp_query;
276
-        if (empty($wp_query->posts)) {
277
-            return;
278
-        }
279
-        // if we already know this is an espresso page, then load assets
280
-        $load_assets = $this->current_page->isEspressoPage();
281
-        // if we are already loading assets then just move along, otherwise check for widgets
282
-        $load_assets = $load_assets || $this->espresso_widgets_in_active_sidebars();
283
-        if ($load_assets) {
284
-            add_action('wp_enqueue_scripts', array($this, 'enqueueStyle'), 10);
285
-            add_action('wp_print_footer_scripts', array($this, 'enqueueScripts'), 10);
286
-        }
287
-    }
288
-
289
-
290
-    /**
291
-     * builds list of active widgets then scans active sidebars looking for them
292
-     * returns true is an EE widget is found in an active sidebar
293
-     * Please Note: this does NOT mean that the sidebar or widget
294
-     * is actually in use in a given template, as that is unfortunately not known
295
-     * until a sidebar and it's widgets are actually loaded
296
-     *
297
-     * @return boolean
298
-     */
299
-    private function espresso_widgets_in_active_sidebars()
300
-    {
301
-        $espresso_widgets = array();
302
-        foreach ($this->Registry->widgets as $widget_class => $widget) {
303
-            $id_base = EspressoWidget::getIdBase($widget_class);
304
-            if (is_active_widget(false, false, $id_base)) {
305
-                $espresso_widgets[] = $id_base;
306
-            }
307
-        }
308
-        $all_sidebar_widgets = wp_get_sidebars_widgets();
309
-        foreach ($all_sidebar_widgets as $sidebar_widgets) {
310
-            if (is_array($sidebar_widgets) && ! empty($sidebar_widgets)) {
311
-                foreach ($sidebar_widgets as $sidebar_widget) {
312
-                    foreach ($espresso_widgets as $espresso_widget) {
313
-                        if (strpos($sidebar_widget, $espresso_widget) !== false) {
314
-                            return true;
315
-                        }
316
-                    }
317
-                }
318
-            }
319
-        }
320
-        return false;
321
-    }
322
-
323
-
324
-    /**
325
-     *    header_meta_tag
326
-     *
327
-     * @access    public
328
-     * @return    void
329
-     */
330
-    public function header_meta_tag()
331
-    {
332
-        print(
333
-        apply_filters(
334
-            'FHEE__EE_Front_Controller__header_meta_tag',
335
-            '<meta name="generator" content="Event Espresso Version ' . EVENT_ESPRESSO_VERSION . "\" />\n"
336
-        )
337
-        );
338
-
339
-        // let's exclude all event type taxonomy term archive pages from search engine indexing
340
-        // @see https://events.codebasehq.com/projects/event-espresso/tickets/10249
341
-        // also exclude all critical pages from indexing
342
-        if (
343
-            (
344
-                is_tax('espresso_event_type')
345
-                && get_option('blog_public') !== '0'
346
-            )
347
-            || is_page(EE_Registry::instance()->CFG->core->get_critical_pages_array())
348
-        ) {
349
-            print(
350
-            apply_filters(
351
-                'FHEE__EE_Front_Controller__header_meta_tag__noindex_for_event_type',
352
-                '<meta name="robots" content="noindex,follow" />' . "\n"
353
-            )
354
-            );
355
-        }
356
-    }
357
-
358
-
359
-    /**
360
-     * wp_print_scripts
361
-     *
362
-     * @return void
363
-     * @throws EE_Error
364
-     */
365
-    public function wp_print_scripts()
366
-    {
367
-        global $post;
368
-        if (
369
-            isset($post->EE_Event)
370
-            && $post->EE_Event instanceof EE_Event
371
-            && get_post_type() === 'espresso_events'
372
-            && is_singular()
373
-        ) {
374
-            EEH_Schema::add_json_linked_data_for_event($post->EE_Event);
375
-        }
376
-    }
377
-
378
-
379
-    public function enqueueStyle()
380
-    {
381
-        wp_enqueue_style('espresso_default');
382
-        wp_enqueue_style('espresso_custom_css');
383
-    }
384
-
385
-
386
-
387
-    /***********************************************        WP_FOOTER         ***********************************************/
388
-
389
-
390
-    public function enqueueScripts()
391
-    {
392
-        wp_enqueue_script('espresso_core');
393
-    }
394
-
395
-
396
-    /**
397
-     * display_errors
398
-     *
399
-     * @access public
400
-     * @return void
401
-     * @throws DomainException
402
-     */
403
-    public function display_errors()
404
-    {
405
-        static $shown_already = false;
406
-        do_action('AHEE__EE_Front_Controller__display_errors__begin');
407
-        if (
408
-            ! $shown_already
409
-            && apply_filters('FHEE__EE_Front_Controller__display_errors', true)
410
-            && is_main_query()
411
-            && ! is_feed()
412
-            && in_the_loop()
413
-            && did_action('wp_head')
414
-            && $this->current_page->isEspressoPage()
415
-        ) {
416
-            echo EE_Error::get_notices();
417
-            $shown_already = true;
418
-            EEH_Template::display_template(EE_TEMPLATES . 'espresso-ajax-notices.template.php');
419
-        }
420
-        do_action('AHEE__EE_Front_Controller__display_errors__end');
421
-    }
422
-
423
-
424
-
425
-
426
-
427
-    /***********************************************        UTILITIES         ***********************************************/
428
-    /**
429
-     *    template_include
430
-     *
431
-     * @access    public
432
-     * @param   string $template_include_path
433
-     * @return    string
434
-     */
435
-    public function template_include($template_include_path = null)
436
-    {
437
-        if ($this->current_page->isEspressoPage()) {
438
-            $this->_template_path = ! empty($this->_template_path)
439
-                ? basename($this->_template_path)
440
-                : basename(
441
-                    $template_include_path
442
-                );
443
-            $template_path = EEH_Template::locate_template($this->_template_path, array(), false);
444
-            $this->_template_path = ! empty($template_path) ? $template_path : $template_include_path;
445
-            $this->_template = basename($this->_template_path);
446
-            return $this->_template_path;
447
-        }
448
-        return $template_include_path;
449
-    }
450
-
451
-
452
-    /**
453
-     * @param bool $with_path
454
-     * @return    string
455
-     */
456
-    public function get_selected_template($with_path = false)
457
-    {
458
-        return $with_path ? $this->_template_path : $this->_template;
459
-    }
460
-
461
-
462
-    /**
463
-     * @param string $shortcode_class
464
-     * @param WP     $wp
465
-     * @throws ReflectionException
466
-     * @deprecated 4.9.26
467
-     */
468
-    public function initialize_shortcode($shortcode_class = '', WP $wp = null)
469
-    {
470
-        EE_Error::doing_it_wrong(
471
-            __METHOD__,
472
-            esc_html__(
473
-                'Usage is deprecated. Please use \EventEspresso\core\services\shortcodes\LegacyShortcodesManager::initializeShortcode() instead.',
474
-                'event_espresso'
475
-            ),
476
-            '4.9.26'
477
-        );
478
-        $this->getLegacyShortcodesManager()->initializeShortcode($shortcode_class, $wp);
479
-    }
480
-
481
-
482
-    /**
483
-     * @return void
484
-     * @deprecated 4.9.57.p
485
-     */
486
-    public function loadPersistentAdminNoticeManager()
487
-    {
488
-    }
489
-
490
-
491
-    /**
492
-     * @return void
493
-     * @deprecated 4.9.64.p
494
-     */
495
-    public function employ_CPT_Strategy()
496
-    {
497
-    }
20
+	/**
21
+	 * @var string
22
+	 */
23
+	private $_template_path;
24
+
25
+	/**
26
+	 * @var string
27
+	 */
28
+	private $_template;
29
+
30
+	/**
31
+	 * @type EE_Registry
32
+	 */
33
+	protected $Registry;
34
+
35
+	/**
36
+	 * @type EE_Request_Handler
37
+	 */
38
+	protected $Request_Handler;
39
+
40
+	/**
41
+	 * @type EE_Module_Request_Router
42
+	 */
43
+	protected $Module_Request_Router;
44
+
45
+	/**
46
+	 * @type CurrentPage
47
+	 */
48
+	protected $current_page;
49
+
50
+
51
+	/**
52
+	 *    class constructor
53
+	 *    should fire after shortcode, module, addon, or other plugin's default priority init phases have run
54
+	 *
55
+	 * @access    public
56
+	 * @param EE_Registry              $Registry
57
+	 * @param CurrentPage              $EspressoPage
58
+	 * @param EE_Module_Request_Router $Module_Request_Router
59
+	 */
60
+	public function __construct(
61
+		EE_Registry $Registry,
62
+		CurrentPage $EspressoPage,
63
+		EE_Module_Request_Router $Module_Request_Router
64
+	) {
65
+		$this->Registry              = $Registry;
66
+		$this->current_page          = $EspressoPage;
67
+		$this->Module_Request_Router = $Module_Request_Router;
68
+		// load other resources and begin to actually run shortcodes and modules
69
+		// analyse the incoming WP request
70
+		add_action('parse_request', array($this, 'get_request'), 1, 1);
71
+		// process request with module factory
72
+		add_action('pre_get_posts', array($this, 'pre_get_posts'), 10, 1);
73
+		// before headers sent
74
+		add_action('wp', array($this, 'wp'), 5);
75
+		// primarily used to process any content shortcodes
76
+		add_action('template_redirect', array($this, 'templateRedirect'), 999);
77
+		// header
78
+		add_action('wp_head', array($this, 'header_meta_tag'), 5);
79
+		add_action('wp_print_scripts', array($this, 'wp_print_scripts'), 10);
80
+		add_filter('template_include', array($this, 'template_include'), 1);
81
+		// display errors
82
+		add_action('loop_start', array($this, 'display_errors'), 2);
83
+		// the content
84
+		// add_filter( 'the_content', array( $this, 'the_content' ), 5, 1 );
85
+		// exclude our private cpt comments
86
+		add_filter('comments_clauses', array($this, 'filter_wp_comments'), 10, 1);
87
+		// make sure any ajax requests will respect the url schema when requests are made against admin-ajax.php (http:// or https://)
88
+		add_filter('admin_url', array($this, 'maybe_force_admin_ajax_ssl'), 200, 1);
89
+		// action hook EE
90
+		do_action('AHEE__EE_Front_Controller__construct__done', $this);
91
+	}
92
+
93
+
94
+	/**
95
+	 * @return EE_Request_Handler
96
+	 * @deprecated 4.10.14.p
97
+	 */
98
+	public function Request_Handler()
99
+	{
100
+		if (! $this->Request_Handler instanceof EE_Request_Handler) {
101
+			$this->Request_Handler = LoaderFactory::getLoader()->getShared('EE_Request_Handler');
102
+		}
103
+		return $this->Request_Handler;
104
+	}
105
+
106
+
107
+	/**
108
+	 * @return EE_Module_Request_Router
109
+	 */
110
+	public function Module_Request_Router()
111
+	{
112
+		return $this->Module_Request_Router;
113
+	}
114
+
115
+
116
+	/**
117
+	 * @return LegacyShortcodesManager
118
+	 * @deprecated 4.10.14.p
119
+	 */
120
+	public function getLegacyShortcodesManager()
121
+	{
122
+		return EE_Config::getLegacyShortcodesManager();
123
+	}
124
+
125
+
126
+
127
+
128
+
129
+	/***********************************************        INIT ACTION HOOK         ***********************************************/
130
+	/**
131
+	 * filter_wp_comments
132
+	 * This simply makes sure that any "private" EE CPTs do not have their comments show up in any wp comment
133
+	 * widgets/queries done on frontend
134
+	 *
135
+	 * @param  array $clauses array of comment clauses setup by WP_Comment_Query
136
+	 * @return array array of comment clauses with modifications.
137
+	 * @throws InvalidArgumentException
138
+	 * @throws InvalidDataTypeException
139
+	 * @throws InvalidInterfaceException
140
+	 */
141
+	public function filter_wp_comments($clauses)
142
+	{
143
+		global $wpdb;
144
+		if (strpos($clauses['join'], $wpdb->posts) !== false) {
145
+			/** @var EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions $custom_post_types */
146
+			$custom_post_types = LoaderFactory::getLoader()->getShared(
147
+				'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions'
148
+			);
149
+			$cpts = $custom_post_types->getPrivateCustomPostTypes();
150
+			foreach ($cpts as $cpt => $details) {
151
+				$clauses['where'] .= $wpdb->prepare(" AND $wpdb->posts.post_type != %s", $cpt);
152
+			}
153
+		}
154
+		return $clauses;
155
+	}
156
+
157
+
158
+	/**
159
+	 * this just makes sure that if the site is using ssl that we force that for any admin ajax calls from frontend
160
+	 *
161
+	 * @param  string $url incoming url
162
+	 * @return string         final assembled url
163
+	 */
164
+	public function maybe_force_admin_ajax_ssl($url)
165
+	{
166
+		if (is_ssl() && preg_match('/admin-ajax.php/', $url)) {
167
+			$url = str_replace('http://', 'https://', $url);
168
+		}
169
+		return $url;
170
+	}
171
+
172
+
173
+
174
+
175
+
176
+
177
+	/***********************************************        WP_LOADED ACTION HOOK         ***********************************************/
178
+
179
+
180
+	/**
181
+	 *    wp_loaded - should fire after shortcode, module, addon, or other plugin's have been registered and their
182
+	 *    default priority init phases have run
183
+	 *
184
+	 * @access    public
185
+	 * @return    void
186
+	 */
187
+	public function wp_loaded()
188
+	{
189
+	}
190
+
191
+
192
+
193
+
194
+
195
+	/***********************************************        PARSE_REQUEST HOOK         ***********************************************/
196
+	/**
197
+	 *    _get_request
198
+	 *
199
+	 * @access public
200
+	 * @param WP $WP
201
+	 * @return void
202
+	 */
203
+	public function get_request(WP $WP)
204
+	{
205
+		do_action('AHEE__EE_Front_Controller__get_request__start');
206
+		$this->current_page->parseQueryVars($WP);
207
+		do_action('AHEE__EE_Front_Controller__get_request__complete');
208
+		remove_action('parse_request', [$this, 'get_request'], 1);
209
+	}
210
+
211
+
212
+	/**
213
+	 *    pre_get_posts - basically a module factory for instantiating modules and selecting the final view template
214
+	 *
215
+	 * @access    public
216
+	 * @param WP_Query $WP_Query
217
+	 * @return    void
218
+	 * @throws EE_Error
219
+	 * @throws ReflectionException
220
+	 */
221
+	public function pre_get_posts($WP_Query)
222
+	{
223
+		// only load Module_Request_Router if this is the main query
224
+		if (
225
+			$this->Module_Request_Router instanceof EE_Module_Request_Router
226
+			&& $WP_Query->is_main_query()
227
+		) {
228
+			// cycle thru module routes
229
+			while ($route = $this->Module_Request_Router->get_route($WP_Query)) {
230
+				// determine module and method for route
231
+				$module = $this->Module_Request_Router->resolve_route($route[0], $route[1]);
232
+				if ($module instanceof EED_Module) {
233
+					// get registered view for route
234
+					$this->_template_path = $this->Module_Request_Router->get_view($route);
235
+					// grab module name
236
+					$module_name = $module->module_name();
237
+					// map the module to the module objects
238
+					$this->Registry->modules->{$module_name} = $module;
239
+				}
240
+			}
241
+		}
242
+	}
243
+
244
+
245
+
246
+
247
+
248
+	/***********************************************        WP HOOK         ***********************************************/
249
+
250
+
251
+	/**
252
+	 *    wp - basically last chance to do stuff before headers sent
253
+	 *
254
+	 * @access    public
255
+	 * @return    void
256
+	 */
257
+	public function wp()
258
+	{
259
+	}
260
+
261
+
262
+
263
+	/***********************     GET_HEADER && WP_HEAD HOOK     ***********************/
264
+
265
+
266
+	/**
267
+	 * callback for the "template_redirect" hook point
268
+	 * checks sidebars for EE widgets
269
+	 * loads resources and assets accordingly
270
+	 *
271
+	 * @return void
272
+	 */
273
+	public function templateRedirect()
274
+	{
275
+		global $wp_query;
276
+		if (empty($wp_query->posts)) {
277
+			return;
278
+		}
279
+		// if we already know this is an espresso page, then load assets
280
+		$load_assets = $this->current_page->isEspressoPage();
281
+		// if we are already loading assets then just move along, otherwise check for widgets
282
+		$load_assets = $load_assets || $this->espresso_widgets_in_active_sidebars();
283
+		if ($load_assets) {
284
+			add_action('wp_enqueue_scripts', array($this, 'enqueueStyle'), 10);
285
+			add_action('wp_print_footer_scripts', array($this, 'enqueueScripts'), 10);
286
+		}
287
+	}
288
+
289
+
290
+	/**
291
+	 * builds list of active widgets then scans active sidebars looking for them
292
+	 * returns true is an EE widget is found in an active sidebar
293
+	 * Please Note: this does NOT mean that the sidebar or widget
294
+	 * is actually in use in a given template, as that is unfortunately not known
295
+	 * until a sidebar and it's widgets are actually loaded
296
+	 *
297
+	 * @return boolean
298
+	 */
299
+	private function espresso_widgets_in_active_sidebars()
300
+	{
301
+		$espresso_widgets = array();
302
+		foreach ($this->Registry->widgets as $widget_class => $widget) {
303
+			$id_base = EspressoWidget::getIdBase($widget_class);
304
+			if (is_active_widget(false, false, $id_base)) {
305
+				$espresso_widgets[] = $id_base;
306
+			}
307
+		}
308
+		$all_sidebar_widgets = wp_get_sidebars_widgets();
309
+		foreach ($all_sidebar_widgets as $sidebar_widgets) {
310
+			if (is_array($sidebar_widgets) && ! empty($sidebar_widgets)) {
311
+				foreach ($sidebar_widgets as $sidebar_widget) {
312
+					foreach ($espresso_widgets as $espresso_widget) {
313
+						if (strpos($sidebar_widget, $espresso_widget) !== false) {
314
+							return true;
315
+						}
316
+					}
317
+				}
318
+			}
319
+		}
320
+		return false;
321
+	}
322
+
323
+
324
+	/**
325
+	 *    header_meta_tag
326
+	 *
327
+	 * @access    public
328
+	 * @return    void
329
+	 */
330
+	public function header_meta_tag()
331
+	{
332
+		print(
333
+		apply_filters(
334
+			'FHEE__EE_Front_Controller__header_meta_tag',
335
+			'<meta name="generator" content="Event Espresso Version ' . EVENT_ESPRESSO_VERSION . "\" />\n"
336
+		)
337
+		);
338
+
339
+		// let's exclude all event type taxonomy term archive pages from search engine indexing
340
+		// @see https://events.codebasehq.com/projects/event-espresso/tickets/10249
341
+		// also exclude all critical pages from indexing
342
+		if (
343
+			(
344
+				is_tax('espresso_event_type')
345
+				&& get_option('blog_public') !== '0'
346
+			)
347
+			|| is_page(EE_Registry::instance()->CFG->core->get_critical_pages_array())
348
+		) {
349
+			print(
350
+			apply_filters(
351
+				'FHEE__EE_Front_Controller__header_meta_tag__noindex_for_event_type',
352
+				'<meta name="robots" content="noindex,follow" />' . "\n"
353
+			)
354
+			);
355
+		}
356
+	}
357
+
358
+
359
+	/**
360
+	 * wp_print_scripts
361
+	 *
362
+	 * @return void
363
+	 * @throws EE_Error
364
+	 */
365
+	public function wp_print_scripts()
366
+	{
367
+		global $post;
368
+		if (
369
+			isset($post->EE_Event)
370
+			&& $post->EE_Event instanceof EE_Event
371
+			&& get_post_type() === 'espresso_events'
372
+			&& is_singular()
373
+		) {
374
+			EEH_Schema::add_json_linked_data_for_event($post->EE_Event);
375
+		}
376
+	}
377
+
378
+
379
+	public function enqueueStyle()
380
+	{
381
+		wp_enqueue_style('espresso_default');
382
+		wp_enqueue_style('espresso_custom_css');
383
+	}
384
+
385
+
386
+
387
+	/***********************************************        WP_FOOTER         ***********************************************/
388
+
389
+
390
+	public function enqueueScripts()
391
+	{
392
+		wp_enqueue_script('espresso_core');
393
+	}
394
+
395
+
396
+	/**
397
+	 * display_errors
398
+	 *
399
+	 * @access public
400
+	 * @return void
401
+	 * @throws DomainException
402
+	 */
403
+	public function display_errors()
404
+	{
405
+		static $shown_already = false;
406
+		do_action('AHEE__EE_Front_Controller__display_errors__begin');
407
+		if (
408
+			! $shown_already
409
+			&& apply_filters('FHEE__EE_Front_Controller__display_errors', true)
410
+			&& is_main_query()
411
+			&& ! is_feed()
412
+			&& in_the_loop()
413
+			&& did_action('wp_head')
414
+			&& $this->current_page->isEspressoPage()
415
+		) {
416
+			echo EE_Error::get_notices();
417
+			$shown_already = true;
418
+			EEH_Template::display_template(EE_TEMPLATES . 'espresso-ajax-notices.template.php');
419
+		}
420
+		do_action('AHEE__EE_Front_Controller__display_errors__end');
421
+	}
422
+
423
+
424
+
425
+
426
+
427
+	/***********************************************        UTILITIES         ***********************************************/
428
+	/**
429
+	 *    template_include
430
+	 *
431
+	 * @access    public
432
+	 * @param   string $template_include_path
433
+	 * @return    string
434
+	 */
435
+	public function template_include($template_include_path = null)
436
+	{
437
+		if ($this->current_page->isEspressoPage()) {
438
+			$this->_template_path = ! empty($this->_template_path)
439
+				? basename($this->_template_path)
440
+				: basename(
441
+					$template_include_path
442
+				);
443
+			$template_path = EEH_Template::locate_template($this->_template_path, array(), false);
444
+			$this->_template_path = ! empty($template_path) ? $template_path : $template_include_path;
445
+			$this->_template = basename($this->_template_path);
446
+			return $this->_template_path;
447
+		}
448
+		return $template_include_path;
449
+	}
450
+
451
+
452
+	/**
453
+	 * @param bool $with_path
454
+	 * @return    string
455
+	 */
456
+	public function get_selected_template($with_path = false)
457
+	{
458
+		return $with_path ? $this->_template_path : $this->_template;
459
+	}
460
+
461
+
462
+	/**
463
+	 * @param string $shortcode_class
464
+	 * @param WP     $wp
465
+	 * @throws ReflectionException
466
+	 * @deprecated 4.9.26
467
+	 */
468
+	public function initialize_shortcode($shortcode_class = '', WP $wp = null)
469
+	{
470
+		EE_Error::doing_it_wrong(
471
+			__METHOD__,
472
+			esc_html__(
473
+				'Usage is deprecated. Please use \EventEspresso\core\services\shortcodes\LegacyShortcodesManager::initializeShortcode() instead.',
474
+				'event_espresso'
475
+			),
476
+			'4.9.26'
477
+		);
478
+		$this->getLegacyShortcodesManager()->initializeShortcode($shortcode_class, $wp);
479
+	}
480
+
481
+
482
+	/**
483
+	 * @return void
484
+	 * @deprecated 4.9.57.p
485
+	 */
486
+	public function loadPersistentAdminNoticeManager()
487
+	{
488
+	}
489
+
490
+
491
+	/**
492
+	 * @return void
493
+	 * @deprecated 4.9.64.p
494
+	 */
495
+	public function employ_CPT_Strategy()
496
+	{
497
+	}
498 498
 }
Please login to merge, or discard this patch.
modules/add_new_state/EED_Add_New_State.module.php 2 patches
Indentation   +810 added lines, -810 removed lines patch added patch discarded remove patch
@@ -17,814 +17,814 @@
 block discarded – undo
17 17
 {
18 18
 
19 19
 
20
-    /**
21
-     * @return EED_Add_New_State|EED_Module
22
-     * @throws EE_Error
23
-     * @throws ReflectionException
24
-     */
25
-    public static function instance()
26
-    {
27
-        return parent::get_instance(__CLASS__);
28
-    }
29
-
30
-
31
-    /**
32
-     * set_hooks - for hooking into EE Core, other modules, etc
33
-     *
34
-     * @return void
35
-     */
36
-    public static function set_hooks()
37
-    {
38
-        add_action('wp_loaded', ['EED_Add_New_State', 'set_definitions'], 2);
39
-        add_action('wp_enqueue_scripts', ['EED_Add_New_State', 'translate_js_strings'], 0);
40
-        add_action('wp_enqueue_scripts', ['EED_Add_New_State', 'wp_enqueue_scripts'], 10);
41
-        add_filter(
42
-            'FHEE__EE_SPCO_Reg_Step_Attendee_Information___question_group_reg_form__question_group_reg_form',
43
-            ['EED_Add_New_State', 'display_add_new_state_micro_form'],
44
-            1,
45
-            1
46
-        );
47
-        add_filter(
48
-            'FHEE__EE_SPCO_Reg_Step_Payment_Options___get_billing_form_for_payment_method__billing_form',
49
-            ['EED_Add_New_State', 'display_add_new_state_micro_form'],
50
-            1,
51
-            1
52
-        );
53
-        add_filter(
54
-            'FHEE__EE_Single_Page_Checkout__process_attendee_information__valid_data_line_item',
55
-            ['EED_Add_New_State', 'unset_new_state_request_params'],
56
-            10,
57
-            1
58
-        );
59
-        add_filter(
60
-            'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__state_options',
61
-            ['EED_Add_New_State', 'inject_new_reg_state_into_options'],
62
-            10,
63
-            5
64
-        );
65
-        add_filter(
66
-            'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__country_options',
67
-            ['EED_Add_New_State', 'inject_new_reg_country_into_options'],
68
-            10,
69
-            5
70
-        );
71
-        add_filter(
72
-            'FHEE__EE_State_Select_Input____construct__state_options',
73
-            ['EED_Add_New_State', 'state_options'],
74
-            10,
75
-            1
76
-        );
77
-        add_filter(
78
-            'FHEE__EE_Country_Select_Input____construct__country_options',
79
-            ['EED_Add_New_State', 'country_options'],
80
-            10,
81
-            1
82
-        );
83
-    }
84
-
85
-
86
-    /**
87
-     * set_hooks_admin - for hooking into EE Admin Core, other modules, etc
88
-     *
89
-     * @return void
90
-     */
91
-    public static function set_hooks_admin()
92
-    {
93
-        add_action('wp_loaded', ['EED_Add_New_State', 'set_definitions'], 2);
94
-        add_filter(
95
-            'FHEE__EE_SPCO_Reg_Step_Attendee_Information___question_group_reg_form__question_group_reg_form',
96
-            ['EED_Add_New_State', 'display_add_new_state_micro_form'],
97
-            1,
98
-            1
99
-        );
100
-        add_filter(
101
-            'FHEE__EE_SPCO_Reg_Step_Payment_Options___get_billing_form_for_payment_method__billing_form',
102
-            ['EED_Add_New_State', 'display_add_new_state_micro_form'],
103
-            1,
104
-            1
105
-        );
106
-        add_action('wp_ajax_espresso_add_new_state', ['EED_Add_New_State', 'add_new_state']);
107
-        add_action('wp_ajax_nopriv_espresso_add_new_state', ['EED_Add_New_State', 'add_new_state']);
108
-        add_filter(
109
-            'FHEE__EE_Single_Page_Checkout__process_attendee_information__valid_data_line_item',
110
-            ['EED_Add_New_State', 'unset_new_state_request_params'],
111
-            10,
112
-            1
113
-        );
114
-        add_action(
115
-            'AHEE__General_Settings_Admin_Page__update_country_settings__state_saved',
116
-            ['EED_Add_New_State', 'update_country_settings'],
117
-            10,
118
-            3
119
-        );
120
-        add_action(
121
-            'AHEE__General_Settings_Admin_Page__delete_state__state_deleted',
122
-            ['EED_Add_New_State', 'update_country_settings'],
123
-            10,
124
-            3
125
-        );
126
-        add_filter(
127
-            'FHEE__EE_State_Select_Input____construct__state_options',
128
-            ['EED_Add_New_State', 'state_options'],
129
-            10,
130
-            1
131
-        );
132
-        add_filter(
133
-            'FHEE__EE_Country_Select_Input____construct__country_options',
134
-            ['EED_Add_New_State', 'country_options'],
135
-            10,
136
-            1
137
-        );
138
-        add_filter(
139
-            'FHEE__EE_Form_Section_Proper__receive_form_submission__request_data',
140
-            ['EED_Add_New_State', 'filter_checkout_request_params'],
141
-            10,
142
-            1
143
-        );
144
-        add_filter(
145
-            'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__state_options',
146
-            ['EED_Add_New_State', 'inject_new_reg_state_into_options'],
147
-            10,
148
-            5
149
-        );
150
-        add_filter(
151
-            'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__country_options',
152
-            ['EED_Add_New_State', 'inject_new_reg_country_into_options'],
153
-            10,
154
-            5
155
-        );
156
-    }
157
-
158
-
159
-    /**
160
-     * @return void
161
-     */
162
-    public static function set_definitions()
163
-    {
164
-        define('ANS_ASSETS_URL', plugin_dir_url(__FILE__) . 'assets/');
165
-        define(
166
-            'ANS_TEMPLATES_PATH',
167
-            str_replace(
168
-                '\\',
169
-                '/',
170
-                plugin_dir_path(__FILE__)
171
-            ) . 'templates/'
172
-        );
173
-    }
174
-
175
-
176
-    /**
177
-     * @param WP $WP
178
-     * @return void
179
-     */
180
-    public function run($WP)
181
-    {
182
-    }
183
-
184
-
185
-    /**
186
-     * @return void
187
-     */
188
-    public static function translate_js_strings()
189
-    {
190
-        EE_Registry::$i18n_js_strings['ans_no_country']        = esc_html__(
191
-            'In order to proceed, you need to select the Country that your State/Province belongs to.',
192
-            'event_espresso'
193
-        );
194
-        EE_Registry::$i18n_js_strings['ans_no_name']           = esc_html__(
195
-            'In order to proceed, you need to enter the name of your State/Province.',
196
-            'event_espresso'
197
-        );
198
-        EE_Registry::$i18n_js_strings['ans_no_abbreviation']   = esc_html__(
199
-            'In order to proceed, you need to enter an abbreviation for the name of your State/Province.',
200
-            'event_espresso'
201
-        );
202
-        EE_Registry::$i18n_js_strings['ans_save_success']      = esc_html__(
203
-            'The new state was successfully saved to the database.',
204
-            'event_espresso'
205
-        );
206
-        EE_Registry::$i18n_js_strings['ans_server_save_error'] = esc_html__(
207
-            'An unknown error has occurred on the server while saving the new state to the database.',
208
-            'event_espresso'
209
-        );
210
-    }
211
-
212
-
213
-    /**
214
-     * @return void
215
-     */
216
-    public static function wp_enqueue_scripts()
217
-    {
218
-        if (apply_filters('EED_Single_Page_Checkout__SPCO_active', false)) {
219
-            wp_register_script(
220
-                'add_new_state',
221
-                ANS_ASSETS_URL . 'add_new_state.js',
222
-                ['espresso_core', 'single_page_checkout'],
223
-                EVENT_ESPRESSO_VERSION,
224
-                true
225
-            );
226
-            wp_enqueue_script('add_new_state');
227
-        }
228
-    }
229
-
230
-
231
-    /**
232
-     * display_add_new_state_micro_form
233
-     *
234
-     * @param EE_Form_Section_Proper $question_group_reg_form
235
-     * @return EE_Form_Section_Proper
236
-     * @throws EE_Error
237
-     * @throws ReflectionException
238
-     */
239
-    public static function display_add_new_state_micro_form(EE_Form_Section_Proper $question_group_reg_form)
240
-    {
241
-        $request = self::getRequest();
242
-        // only add the 'new_state_micro_form' when displaying reg forms,
243
-        // not during processing since we process the 'new_state_micro_form' in it's own AJAX request
244
-        $action = $request->getRequestParam('action');
245
-        // is the "state" question in this form section?
246
-        $input = $question_group_reg_form->get_subsection('state');
247
-        if ($action === 'process_reg_step' || $action === 'update_reg_step') {
248
-            // ok then all we need to do is make sure the input's HTML name is consistent
249
-            // by forcing it to set it now, like it did while getting the form for display
250
-            if ($input instanceof EE_State_Select_Input) {
251
-                $input->html_name();
252
-            }
253
-            return $question_group_reg_form;
254
-        }
255
-        // we're only doing this for state select inputs
256
-        if (
257
-            $input instanceof EE_State_Select_Input
258
-            && ! $input->get_display_strategy() instanceof EE_Hidden_Display_Strategy
259
-        ) {
260
-            // grab any set values from the request
261
-            $country_name        = str_replace('state', 'nsmf_new_state_country', $input->html_name());
262
-            $state_name          = str_replace('state', 'nsmf_new_state_name', $input->html_name());
263
-            $abbrv_name          = str_replace('state', 'nsmf_new_state_abbrv', $input->html_name());
264
-            $new_state_submit_id = str_replace('state', 'new_state', $input->html_id());
265
-            $country_options     = [];
266
-            $countries           = EEM_Country::instance()->get_all_countries();
267
-            if (! empty($countries)) {
268
-                foreach ($countries as $country) {
269
-                    if ($country instanceof EE_Country) {
270
-                        $country_options[ $country->ID() ] = $country->name();
271
-                    }
272
-                }
273
-            }
274
-            $new_state_micro_form = new EE_Form_Section_Proper(
275
-                [
276
-                    'name'            => 'new_state_micro_form',
277
-                    'html_id'         => 'new_state_micro_form',
278
-                    'layout_strategy' => new EE_Div_Per_Section_Layout(),
279
-                    'subsections'     => [
280
-                        // add hidden input to indicate that a new state is being added
281
-                        'add_new_state'               => new EE_Hidden_Input(
282
-                            [
283
-                                'html_name' => str_replace(
284
-                                    'state',
285
-                                    'nsmf_add_new_state',
286
-                                    $input->html_name()
287
-                                ),
288
-                                'html_id'   => str_replace(
289
-                                    'state',
290
-                                    'nsmf_add_new_state',
291
-                                    $input->html_id()
292
-                                ),
293
-                                'default'   => 0,
294
-                            ]
295
-                        ),
296
-                        // add link for displaying hidden container
297
-                        'click_here_link'             => new EE_Form_Section_HTML(
298
-                            apply_filters(
299
-                                'FHEE__EED_Add_New_State__display_add_new_state_micro_form__click_here_link',
300
-                                EEH_HTML::link(
301
-                                    '',
302
-                                    esc_html__('click here to add a new state/province', 'event_espresso'),
303
-                                    '',
304
-                                    'display-' . $input->html_id(),
305
-                                    'ee-form-add-new-state-lnk display-the-hidden smaller-text hide-if-no-js',
306
-                                    '',
307
-                                    'data-target="' . $input->html_id() . '"'
308
-                                )
309
-                            )
310
-                        ),
311
-                        // add initial html for hidden container
312
-                        'add_new_state_micro_form'    => new EE_Form_Section_HTML(
313
-                            apply_filters(
314
-                                'FHEE__EED_Add_New_State__display_add_new_state_micro_form__add_new_state_micro_form',
315
-                                EEH_HTML::div(
316
-                                    '',
317
-                                    $input->html_id() . '-dv',
318
-                                    'ee-form-add-new-state-dv',
319
-                                    'display: none;'
320
-                                ) .
321
-                                EEH_HTML::h6(
322
-                                    esc_html__(
323
-                                        'Is your state/province missing from the dropdown menu above? You can add it by completing the following steps:',
324
-                                        'event_espresso'
325
-                                    )
326
-                                ) .
327
-                                EEH_HTML::ul() .
328
-                                EEH_HTML::li(
329
-                                    esc_html__(
330
-                                        'first select the Country that your State/Province belongs to',
331
-                                        'event_espresso'
332
-                                    )
333
-                                ) .
334
-                                EEH_HTML::li(
335
-                                    esc_html__('enter the name of your State/Province', 'event_espresso')
336
-                                ) .
337
-                                EEH_HTML::li(
338
-                                    esc_html__(
339
-                                        'enter a two to six letter abbreviation for the name of your State/Province',
340
-                                        'event_espresso'
341
-                                    )
342
-                                ) .
343
-                                EEH_HTML::li(esc_html__('click the ADD button', 'event_espresso')) .
344
-                                EEH_HTML::ulx()
345
-                            )
346
-                        ),
347
-                        // NEW STATE COUNTRY
348
-                        'new_state_country'           => new EE_Country_Select_Input(
349
-                            $country_options,
350
-                            [
351
-                                'html_name'       => $country_name,
352
-                                'html_id'         => str_replace(
353
-                                    'state',
354
-                                    'nsmf_new_state_country',
355
-                                    $input->html_id()
356
-                                ),
357
-                                'html_class'      => $input->html_class() . ' new-state-country',
358
-                                'html_label_text' => esc_html__('New State/Province Country', 'event_espresso'),
359
-                                'default'         => $request->getRequestParam($country_name),
360
-                                'required'        => false,
361
-                            ]
362
-                        ),
363
-                        // NEW STATE NAME
364
-                        'new_state_name'              => new EE_Text_Input(
365
-                            [
366
-                                'html_name'       => $state_name,
367
-                                'html_id'         => str_replace(
368
-                                    'state',
369
-                                    'nsmf_new_state_name',
370
-                                    $input->html_id()
371
-                                ),
372
-                                'html_class'      => $input->html_class() . ' new-state-state',
373
-                                'html_label_text' => esc_html__(
374
-                                    'New State/Province Name',
375
-                                    'event_espresso'
376
-                                ),
377
-                                'default'         => $request->getRequestParam($state_name),
378
-                                'required'        => false,
379
-                            ]
380
-                        ),
381
-                        'spacer'                      => new EE_Form_Section_HTML(EEH_HTML::br()),
382
-                        // NEW STATE NAME
383
-                        'new_state_abbrv'             => new EE_Text_Input(
384
-                            [
385
-                                'html_name'             => $abbrv_name,
386
-                                'html_id'               => str_replace(
387
-                                    'state',
388
-                                    'nsmf_new_state_abbrv',
389
-                                    $input->html_id()
390
-                                ),
391
-                                'html_class'            => $input->html_class() . ' new-state-abbrv',
392
-                                'html_label_text'       => esc_html__(
393
-                                    'New State/Province Abbreviation',
394
-                                    'event_espresso'
395
-                                ) . ' *',
396
-                                'other_html_attributes' => 'size="24"',
397
-                                'default'               => $request->getRequestParam($abbrv_name),
398
-                                'required'              => false,
399
-                            ]
400
-                        ),
401
-                        // "submit" button
402
-                        'add_new_state_submit_button' => new EE_Form_Section_HTML(
403
-                            apply_filters(
404
-                                'FHEE__EED_Add_New_State__display_add_new_state_micro_form__add_new_state_submit_button',
405
-                                EEH_HTML::nbsp(3) .
406
-                                EEH_HTML::link(
407
-                                    '',
408
-                                    esc_html__('ADD', 'event_espresso'),
409
-                                    '',
410
-                                    'submit-' . $new_state_submit_id,
411
-                                    'ee-form-add-new-state-submit button button-secondary',
412
-                                    '',
413
-                                    'data-target="'
414
-                                    . $new_state_submit_id
415
-                                    . '" data-value-field-name="'
416
-                                    . $input->valueFieldName()
417
-                                    . '"'
418
-                                )
419
-                            )
420
-                        ),
421
-                        // extra info
422
-                        'add_new_state_extra'         => new EE_Form_Section_HTML(
423
-                            apply_filters(
424
-                                'FHEE__EED_Add_New_State__display_add_new_state_micro_form__add_new_state_extra',
425
-                                EEH_HTML::br(2)
426
-                                .
427
-                                EEH_HTML::div('', '', 'small-text')
428
-                                .
429
-                                EEH_HTML::strong(
430
-                                    '* ' .
431
-                                    esc_html__(
432
-                                        'Don\'t know your State/Province Abbreviation?',
433
-                                        'event_espresso'
434
-                                    )
435
-                                )
436
-                                .
437
-                                EEH_HTML::br()
438
-                                .
439
-                                sprintf(
440
-                                    esc_html__(
441
-                                        'You can look here: %s, for a list of Countries and links to their State/Province Abbreviations ("Subdivisions assigned codes" column).',
442
-                                        'event_espresso'
443
-                                    ),
444
-                                    EEH_HTML::link(
445
-                                        'https://en.wikipedia.org/wiki/ISO_3166-2',
446
-                                        'https://en.wikipedia.org/wiki/ISO_3166-2',
447
-                                        '',
448
-                                        '',
449
-                                        'ee-form-add-new-state-wiki-lnk',
450
-                                        '',
451
-                                        'target="_blank"'
452
-                                    )
453
-                                )
454
-                                .
455
-                                EEH_HTML::divx()
456
-                                .
457
-                                EEH_HTML::br()
458
-                                .
459
-                                EEH_HTML::link(
460
-                                    '',
461
-                                    esc_html__('cancel new State/Province', 'event_espresso'),
462
-                                    '',
463
-                                    'hide-' . $input->html_id(),
464
-                                    'ee-form-cancel-new-state-lnk smaller-text',
465
-                                    '',
466
-                                    'data-target="' . $input->html_id() . '"'
467
-                                )
468
-                                .
469
-                                EEH_HTML::divx()
470
-                                .
471
-                                EEH_HTML::br()
472
-                            )
473
-                        ),
474
-                    ],
475
-                ]
476
-            );
477
-            $question_group_reg_form->add_subsections(
478
-                ['new_state_micro_form' => $new_state_micro_form],
479
-                'state',
480
-                false
481
-            );
482
-        }
483
-        return $question_group_reg_form;
484
-    }
485
-
486
-
487
-    /**
488
-     * set_new_state_input_width
489
-     *
490
-     * @return int|string
491
-     * @throws EE_Error
492
-     * @throws InvalidArgumentException
493
-     * @throws InvalidDataTypeException
494
-     * @throws InvalidInterfaceException
495
-     * @throws ReflectionException
496
-     */
497
-    public static function add_new_state()
498
-    {
499
-        $request = self::getRequest();
500
-        if ($request->getRequestParam('nsmf_add_new_state', 0, 'int') === 1) {
501
-            EE_Registry::instance()->load_model('State');
502
-            // grab country ISO code, new state name, and new state abbreviation
503
-            $state_country = $request->getRequestParam('nsmf_new_state_country');
504
-            $state_name    = $request->getRequestParam('nsmf_new_state_name');
505
-            $state_abbr    = $request->getRequestParam('nsmf_new_state_abbrv');
506
-            if ($state_country && $state_name && $state_abbr) {
507
-                $new_state = EED_Add_New_State::save_new_state_to_db(
508
-                    [
509
-                        'CNT_ISO'    => strtoupper($state_country),
510
-                        'STA_abbrev' => strtoupper($state_abbr),
511
-                        'STA_name'   => ucwords($state_name),
512
-                        'STA_active' => false,
513
-                    ]
514
-                );
515
-                if ($new_state instanceof EE_State) {
516
-                    // clean house
517
-                    $request->unSetRequestParams(
518
-                        [
519
-                            'nsmf_add_new_state',
520
-                            'nsmf_new_state_country',
521
-                            'nsmf_new_state_name',
522
-                            'nsmf_new_state_abbrv',
523
-                        ]
524
-                    );
525
-                    // get any existing new states
526
-                    $new_states                     = EE_Registry::instance()->SSN->get_session_data('nsmf_new_states');
527
-                    $new_states[ $new_state->ID() ] = $new_state;
528
-                    EE_Registry::instance()->SSN->set_session_data(
529
-                        ['nsmf_new_states' => $new_states]
530
-                    );
531
-                    if ($request->isAjax()) {
532
-                        echo wp_json_encode(
533
-                            [
534
-                                'success'      => true,
535
-                                'id'           => $new_state->ID(),
536
-                                'name'         => $new_state->name(),
537
-                                'abbrev'       => $new_state->abbrev(),
538
-                                'country_iso'  => $new_state->country_iso(),
539
-                                'country_name' => $new_state->country()->name(),
540
-                            ]
541
-                        );
542
-                        exit();
543
-                    }
544
-                    return $new_state->ID();
545
-                }
546
-            } else {
547
-                $error = esc_html__(
548
-                    'A new State/Province could not be added because invalid or missing data was received.',
549
-                    'event_espresso'
550
-                );
551
-                if ($request->isAjax()) {
552
-                    echo wp_json_encode(['error' => $error]);
553
-                    exit();
554
-                }
555
-                EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
556
-            }
557
-        }
558
-        return false;
559
-    }
560
-
561
-
562
-    /**
563
-     * recursively drills down through request params to remove any that were added by this module
564
-     *
565
-     * @param array $request_params
566
-     * @return array
567
-     */
568
-    public static function filter_checkout_request_params($request_params)
569
-    {
570
-        foreach ($request_params as $form_section) {
571
-            if (is_array($form_section)) {
572
-                EED_Add_New_State::unset_new_state_request_params($form_section);
573
-                EED_Add_New_State::filter_checkout_request_params($form_section);
574
-            }
575
-        }
576
-        return $request_params;
577
-    }
578
-
579
-
580
-    /**
581
-     * @param array $request_params
582
-     * @return array
583
-     */
584
-    public static function unset_new_state_request_params($request_params)
585
-    {
586
-        unset(
587
-            $request_params['new_state_micro_form'],
588
-            $request_params['new_state_micro_add_new_state'],
589
-            $request_params['new_state_micro_new_state_country'],
590
-            $request_params['new_state_micro_new_state_name'],
591
-            $request_params['new_state_micro_new_state_abbrv']
592
-        );
593
-        return $request_params;
594
-    }
595
-
596
-
597
-    /**
598
-     * @param array $props_n_values
599
-     * @return EE_State|null
600
-     * @throws EE_Error
601
-     * @throws ReflectionException
602
-     */
603
-    public static function save_new_state_to_db($props_n_values = [])
604
-    {
605
-        /** @var EE_State[] $existing_state */
606
-        $existing_state = EEM_State::instance()->get_all([$props_n_values, 'limit' => 1]);
607
-        if (! empty($existing_state)) {
608
-            return array_pop($existing_state);
609
-        }
610
-        $new_state = EE_State::new_instance($props_n_values);
611
-        if ($new_state instanceof EE_State) {
612
-            $country_settings_url = add_query_arg(
613
-                [
614
-                    'page'    => 'espresso_general_settings',
615
-                    'action'  => 'country_settings',
616
-                    'country' => $new_state->country_iso(),
617
-                ],
618
-                admin_url('admin.php')
619
-            );
620
-            // if not non-ajax admin
621
-            new PersistentAdminNotice(
622
-                'new-state-added-' . $new_state->country_iso() . '-' . $new_state->abbrev(),
623
-                sprintf(
624
-                    esc_html__(
625
-                        'A new State named "%1$s (%2$s)" was dynamically added from an Event Espresso form for the Country of "%3$s".%5$sTo verify, edit, and/or delete this new State, please go to the %4$s and update the States / Provinces section.%5$sCheck "Yes" to have this new State added to dropdown select lists in forms.',
626
-                        'event_espresso'
627
-                    ),
628
-                    '<b>' . $new_state->name() . '</b>',
629
-                    '<b>' . $new_state->abbrev() . '</b>',
630
-                    '<b>' . $new_state->country()->name() . '</b>',
631
-                    '<a href="'
632
-                    . $country_settings_url
633
-                    . '">'
634
-                    . esc_html__(
635
-                        'Event Espresso - General Settings > Countries Tab',
636
-                        'event_espresso'
637
-                    )
638
-                    . '</a>',
639
-                    '<br />'
640
-                )
641
-            );
642
-            $new_state->save();
643
-            EEM_State::instance()->reset_cached_states();
644
-            return $new_state;
645
-        }
646
-        return null;
647
-    }
648
-
649
-
650
-    /**
651
-     * @param string $CNT_ISO
652
-     * @param string $STA_ID
653
-     * @param array  $cols_n_values
654
-     * @return void
655
-     * @throws DomainException
656
-     * @throws EE_Error
657
-     * @throws InvalidArgumentException
658
-     * @throws InvalidDataTypeException
659
-     * @throws InvalidInterfaceException
660
-     */
661
-    public static function update_country_settings($CNT_ISO = '', $STA_ID = '', $cols_n_values = [])
662
-    {
663
-        if (! $CNT_ISO) {
664
-            EE_Error::add_error(
665
-                esc_html__('An invalid or missing Country ISO Code was received.', 'event_espresso'),
666
-                __FILE__,
667
-                __FUNCTION__,
668
-                __LINE__
669
-            );
670
-        }
671
-        $STA_abbrev = is_array($cols_n_values) && isset($cols_n_values['STA_abbrev']) ? $cols_n_values['STA_abbrev']
672
-            : false;
673
-        if (! $STA_abbrev && ! empty($STA_ID)) {
674
-            $state = EEM_State::instance()->get_one_by_ID($STA_ID);
675
-            if ($state instanceof EE_State) {
676
-                $STA_abbrev = $state->abbrev();
677
-            }
678
-        }
679
-        if (! $STA_abbrev) {
680
-            EE_Error::add_error(
681
-                esc_html__('An invalid or missing State Abbreviation was received.', 'event_espresso'),
682
-                __FILE__,
683
-                __FUNCTION__,
684
-                __LINE__
685
-            );
686
-        }
687
-        /** @var PersistentAdminNoticeManager $persistent_admin_notice_manager */
688
-        $persistent_admin_notice_manager = LoaderFactory::getLoader()->getShared(
689
-            'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
690
-        );
691
-        $persistent_admin_notice_manager->dismissNotice($CNT_ISO . '-' . $STA_abbrev, true, true);
692
-    }
693
-
694
-
695
-    /**
696
-     * @param EE_State[]                            $state_options
697
-     * @param EE_SPCO_Reg_Step_Attendee_Information $reg_step
698
-     * @param EE_Registration                       $registration
699
-     * @param EE_Question                           $question
700
-     * @param                                       $answer
701
-     * @return array
702
-     * @throws EE_Error
703
-     * @throws ReflectionException
704
-     */
705
-    public static function inject_new_reg_state_into_options(
706
-        array $state_options,
707
-        EE_SPCO_Reg_Step_Attendee_Information $reg_step,
708
-        EE_Registration $registration,
709
-        EE_Question $question,
710
-        $answer
711
-    ) {
712
-        if (
713
-            $answer instanceof EE_Answer && $question instanceof EE_Question
714
-            && $question->type() === EEM_Question::QST_type_state
715
-        ) {
716
-            $STA_ID = $answer->value();
717
-            if (! empty($STA_ID)) {
718
-                $state = EEM_State::instance()->get_one_by_ID($STA_ID);
719
-                if ($state instanceof EE_State) {
720
-                    $country = $state->country();
721
-                    if ($country instanceof EE_Country) {
722
-                        if (! isset($state_options[ $country->name() ])) {
723
-                            $state_options[ $country->name() ] = [];
724
-                        }
725
-                        if (! isset($state_options[ $country->name() ][ $STA_ID ])) {
726
-                            $state_options[ $country->name() ][ $STA_ID ] = $state->name();
727
-                        }
728
-                    }
729
-                }
730
-            }
731
-        }
732
-        return $state_options;
733
-    }
734
-
735
-
736
-    /**
737
-     * @param EE_Country[]                          $country_options
738
-     * @param EE_SPCO_Reg_Step_Attendee_Information $reg_step
739
-     * @param EE_Registration                       $registration
740
-     * @param EE_Question                           $question
741
-     * @param                                       $answer
742
-     * @return array
743
-     * @throws EE_Error
744
-     * @throws ReflectionException
745
-     */
746
-    public static function inject_new_reg_country_into_options(
747
-        array $country_options,
748
-        EE_SPCO_Reg_Step_Attendee_Information $reg_step,
749
-        EE_Registration $registration,
750
-        EE_Question $question,
751
-        $answer
752
-    ) {
753
-        if (
754
-            $answer instanceof EE_Answer && $question instanceof EE_Question
755
-            && $question->type()
756
-               === EEM_Question::QST_type_country
757
-        ) {
758
-            $CNT_ISO = $answer->value();
759
-            if (! empty($CNT_ISO)) {
760
-                $country = EEM_Country::instance()->get_one_by_ID($CNT_ISO);
761
-                if ($country instanceof EE_Country) {
762
-                    if (! isset($country_options[ $CNT_ISO ])) {
763
-                        $country_options[ $CNT_ISO ] = $country->name();
764
-                    }
765
-                }
766
-            }
767
-        }
768
-        return $country_options;
769
-    }
770
-
771
-
772
-    /**
773
-     * @param EE_State[] $state_options
774
-     * @return array
775
-     * @throws EE_Error
776
-     * @throws ReflectionException
777
-     */
778
-    public static function state_options($state_options = [])
779
-    {
780
-        $new_states = EED_Add_New_State::_get_new_states();
781
-        foreach ($new_states as $new_state) {
782
-            if (
783
-                $new_state instanceof EE_State
784
-                && $new_state->country() instanceof EE_Country
785
-            ) {
786
-                $state_options[ $new_state->country()->name() ][ $new_state->ID() ] = $new_state->name();
787
-            }
788
-        }
789
-        return $state_options;
790
-    }
791
-
792
-
793
-    /**
794
-     * @return array
795
-     * @throws InvalidArgumentException
796
-     * @throws InvalidDataTypeException
797
-     * @throws InvalidInterfaceException
798
-     */
799
-    protected static function _get_new_states()
800
-    {
801
-        $new_states = [];
802
-        if (EE_Registry::instance()->SSN instanceof EE_Session) {
803
-            $new_states = EE_Registry::instance()->SSN->get_session_data(
804
-                'nsmf_new_states'
805
-            );
806
-        }
807
-        return is_array($new_states) ? $new_states : [];
808
-    }
809
-
810
-
811
-    /**
812
-     * @param EE_Country[] $country_options
813
-     * @return array
814
-     * @throws EE_Error
815
-     * @throws ReflectionException
816
-     */
817
-    public static function country_options($country_options = [])
818
-    {
819
-        $new_states = EED_Add_New_State::_get_new_states();
820
-        foreach ($new_states as $new_state) {
821
-            if (
822
-                $new_state instanceof EE_State
823
-                && $new_state->country() instanceof EE_Country
824
-            ) {
825
-                $country_options[ $new_state->country()->ID() ] = $new_state->country()->name();
826
-            }
827
-        }
828
-        return $country_options;
829
-    }
20
+	/**
21
+	 * @return EED_Add_New_State|EED_Module
22
+	 * @throws EE_Error
23
+	 * @throws ReflectionException
24
+	 */
25
+	public static function instance()
26
+	{
27
+		return parent::get_instance(__CLASS__);
28
+	}
29
+
30
+
31
+	/**
32
+	 * set_hooks - for hooking into EE Core, other modules, etc
33
+	 *
34
+	 * @return void
35
+	 */
36
+	public static function set_hooks()
37
+	{
38
+		add_action('wp_loaded', ['EED_Add_New_State', 'set_definitions'], 2);
39
+		add_action('wp_enqueue_scripts', ['EED_Add_New_State', 'translate_js_strings'], 0);
40
+		add_action('wp_enqueue_scripts', ['EED_Add_New_State', 'wp_enqueue_scripts'], 10);
41
+		add_filter(
42
+			'FHEE__EE_SPCO_Reg_Step_Attendee_Information___question_group_reg_form__question_group_reg_form',
43
+			['EED_Add_New_State', 'display_add_new_state_micro_form'],
44
+			1,
45
+			1
46
+		);
47
+		add_filter(
48
+			'FHEE__EE_SPCO_Reg_Step_Payment_Options___get_billing_form_for_payment_method__billing_form',
49
+			['EED_Add_New_State', 'display_add_new_state_micro_form'],
50
+			1,
51
+			1
52
+		);
53
+		add_filter(
54
+			'FHEE__EE_Single_Page_Checkout__process_attendee_information__valid_data_line_item',
55
+			['EED_Add_New_State', 'unset_new_state_request_params'],
56
+			10,
57
+			1
58
+		);
59
+		add_filter(
60
+			'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__state_options',
61
+			['EED_Add_New_State', 'inject_new_reg_state_into_options'],
62
+			10,
63
+			5
64
+		);
65
+		add_filter(
66
+			'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__country_options',
67
+			['EED_Add_New_State', 'inject_new_reg_country_into_options'],
68
+			10,
69
+			5
70
+		);
71
+		add_filter(
72
+			'FHEE__EE_State_Select_Input____construct__state_options',
73
+			['EED_Add_New_State', 'state_options'],
74
+			10,
75
+			1
76
+		);
77
+		add_filter(
78
+			'FHEE__EE_Country_Select_Input____construct__country_options',
79
+			['EED_Add_New_State', 'country_options'],
80
+			10,
81
+			1
82
+		);
83
+	}
84
+
85
+
86
+	/**
87
+	 * set_hooks_admin - for hooking into EE Admin Core, other modules, etc
88
+	 *
89
+	 * @return void
90
+	 */
91
+	public static function set_hooks_admin()
92
+	{
93
+		add_action('wp_loaded', ['EED_Add_New_State', 'set_definitions'], 2);
94
+		add_filter(
95
+			'FHEE__EE_SPCO_Reg_Step_Attendee_Information___question_group_reg_form__question_group_reg_form',
96
+			['EED_Add_New_State', 'display_add_new_state_micro_form'],
97
+			1,
98
+			1
99
+		);
100
+		add_filter(
101
+			'FHEE__EE_SPCO_Reg_Step_Payment_Options___get_billing_form_for_payment_method__billing_form',
102
+			['EED_Add_New_State', 'display_add_new_state_micro_form'],
103
+			1,
104
+			1
105
+		);
106
+		add_action('wp_ajax_espresso_add_new_state', ['EED_Add_New_State', 'add_new_state']);
107
+		add_action('wp_ajax_nopriv_espresso_add_new_state', ['EED_Add_New_State', 'add_new_state']);
108
+		add_filter(
109
+			'FHEE__EE_Single_Page_Checkout__process_attendee_information__valid_data_line_item',
110
+			['EED_Add_New_State', 'unset_new_state_request_params'],
111
+			10,
112
+			1
113
+		);
114
+		add_action(
115
+			'AHEE__General_Settings_Admin_Page__update_country_settings__state_saved',
116
+			['EED_Add_New_State', 'update_country_settings'],
117
+			10,
118
+			3
119
+		);
120
+		add_action(
121
+			'AHEE__General_Settings_Admin_Page__delete_state__state_deleted',
122
+			['EED_Add_New_State', 'update_country_settings'],
123
+			10,
124
+			3
125
+		);
126
+		add_filter(
127
+			'FHEE__EE_State_Select_Input____construct__state_options',
128
+			['EED_Add_New_State', 'state_options'],
129
+			10,
130
+			1
131
+		);
132
+		add_filter(
133
+			'FHEE__EE_Country_Select_Input____construct__country_options',
134
+			['EED_Add_New_State', 'country_options'],
135
+			10,
136
+			1
137
+		);
138
+		add_filter(
139
+			'FHEE__EE_Form_Section_Proper__receive_form_submission__request_data',
140
+			['EED_Add_New_State', 'filter_checkout_request_params'],
141
+			10,
142
+			1
143
+		);
144
+		add_filter(
145
+			'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__state_options',
146
+			['EED_Add_New_State', 'inject_new_reg_state_into_options'],
147
+			10,
148
+			5
149
+		);
150
+		add_filter(
151
+			'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__country_options',
152
+			['EED_Add_New_State', 'inject_new_reg_country_into_options'],
153
+			10,
154
+			5
155
+		);
156
+	}
157
+
158
+
159
+	/**
160
+	 * @return void
161
+	 */
162
+	public static function set_definitions()
163
+	{
164
+		define('ANS_ASSETS_URL', plugin_dir_url(__FILE__) . 'assets/');
165
+		define(
166
+			'ANS_TEMPLATES_PATH',
167
+			str_replace(
168
+				'\\',
169
+				'/',
170
+				plugin_dir_path(__FILE__)
171
+			) . 'templates/'
172
+		);
173
+	}
174
+
175
+
176
+	/**
177
+	 * @param WP $WP
178
+	 * @return void
179
+	 */
180
+	public function run($WP)
181
+	{
182
+	}
183
+
184
+
185
+	/**
186
+	 * @return void
187
+	 */
188
+	public static function translate_js_strings()
189
+	{
190
+		EE_Registry::$i18n_js_strings['ans_no_country']        = esc_html__(
191
+			'In order to proceed, you need to select the Country that your State/Province belongs to.',
192
+			'event_espresso'
193
+		);
194
+		EE_Registry::$i18n_js_strings['ans_no_name']           = esc_html__(
195
+			'In order to proceed, you need to enter the name of your State/Province.',
196
+			'event_espresso'
197
+		);
198
+		EE_Registry::$i18n_js_strings['ans_no_abbreviation']   = esc_html__(
199
+			'In order to proceed, you need to enter an abbreviation for the name of your State/Province.',
200
+			'event_espresso'
201
+		);
202
+		EE_Registry::$i18n_js_strings['ans_save_success']      = esc_html__(
203
+			'The new state was successfully saved to the database.',
204
+			'event_espresso'
205
+		);
206
+		EE_Registry::$i18n_js_strings['ans_server_save_error'] = esc_html__(
207
+			'An unknown error has occurred on the server while saving the new state to the database.',
208
+			'event_espresso'
209
+		);
210
+	}
211
+
212
+
213
+	/**
214
+	 * @return void
215
+	 */
216
+	public static function wp_enqueue_scripts()
217
+	{
218
+		if (apply_filters('EED_Single_Page_Checkout__SPCO_active', false)) {
219
+			wp_register_script(
220
+				'add_new_state',
221
+				ANS_ASSETS_URL . 'add_new_state.js',
222
+				['espresso_core', 'single_page_checkout'],
223
+				EVENT_ESPRESSO_VERSION,
224
+				true
225
+			);
226
+			wp_enqueue_script('add_new_state');
227
+		}
228
+	}
229
+
230
+
231
+	/**
232
+	 * display_add_new_state_micro_form
233
+	 *
234
+	 * @param EE_Form_Section_Proper $question_group_reg_form
235
+	 * @return EE_Form_Section_Proper
236
+	 * @throws EE_Error
237
+	 * @throws ReflectionException
238
+	 */
239
+	public static function display_add_new_state_micro_form(EE_Form_Section_Proper $question_group_reg_form)
240
+	{
241
+		$request = self::getRequest();
242
+		// only add the 'new_state_micro_form' when displaying reg forms,
243
+		// not during processing since we process the 'new_state_micro_form' in it's own AJAX request
244
+		$action = $request->getRequestParam('action');
245
+		// is the "state" question in this form section?
246
+		$input = $question_group_reg_form->get_subsection('state');
247
+		if ($action === 'process_reg_step' || $action === 'update_reg_step') {
248
+			// ok then all we need to do is make sure the input's HTML name is consistent
249
+			// by forcing it to set it now, like it did while getting the form for display
250
+			if ($input instanceof EE_State_Select_Input) {
251
+				$input->html_name();
252
+			}
253
+			return $question_group_reg_form;
254
+		}
255
+		// we're only doing this for state select inputs
256
+		if (
257
+			$input instanceof EE_State_Select_Input
258
+			&& ! $input->get_display_strategy() instanceof EE_Hidden_Display_Strategy
259
+		) {
260
+			// grab any set values from the request
261
+			$country_name        = str_replace('state', 'nsmf_new_state_country', $input->html_name());
262
+			$state_name          = str_replace('state', 'nsmf_new_state_name', $input->html_name());
263
+			$abbrv_name          = str_replace('state', 'nsmf_new_state_abbrv', $input->html_name());
264
+			$new_state_submit_id = str_replace('state', 'new_state', $input->html_id());
265
+			$country_options     = [];
266
+			$countries           = EEM_Country::instance()->get_all_countries();
267
+			if (! empty($countries)) {
268
+				foreach ($countries as $country) {
269
+					if ($country instanceof EE_Country) {
270
+						$country_options[ $country->ID() ] = $country->name();
271
+					}
272
+				}
273
+			}
274
+			$new_state_micro_form = new EE_Form_Section_Proper(
275
+				[
276
+					'name'            => 'new_state_micro_form',
277
+					'html_id'         => 'new_state_micro_form',
278
+					'layout_strategy' => new EE_Div_Per_Section_Layout(),
279
+					'subsections'     => [
280
+						// add hidden input to indicate that a new state is being added
281
+						'add_new_state'               => new EE_Hidden_Input(
282
+							[
283
+								'html_name' => str_replace(
284
+									'state',
285
+									'nsmf_add_new_state',
286
+									$input->html_name()
287
+								),
288
+								'html_id'   => str_replace(
289
+									'state',
290
+									'nsmf_add_new_state',
291
+									$input->html_id()
292
+								),
293
+								'default'   => 0,
294
+							]
295
+						),
296
+						// add link for displaying hidden container
297
+						'click_here_link'             => new EE_Form_Section_HTML(
298
+							apply_filters(
299
+								'FHEE__EED_Add_New_State__display_add_new_state_micro_form__click_here_link',
300
+								EEH_HTML::link(
301
+									'',
302
+									esc_html__('click here to add a new state/province', 'event_espresso'),
303
+									'',
304
+									'display-' . $input->html_id(),
305
+									'ee-form-add-new-state-lnk display-the-hidden smaller-text hide-if-no-js',
306
+									'',
307
+									'data-target="' . $input->html_id() . '"'
308
+								)
309
+							)
310
+						),
311
+						// add initial html for hidden container
312
+						'add_new_state_micro_form'    => new EE_Form_Section_HTML(
313
+							apply_filters(
314
+								'FHEE__EED_Add_New_State__display_add_new_state_micro_form__add_new_state_micro_form',
315
+								EEH_HTML::div(
316
+									'',
317
+									$input->html_id() . '-dv',
318
+									'ee-form-add-new-state-dv',
319
+									'display: none;'
320
+								) .
321
+								EEH_HTML::h6(
322
+									esc_html__(
323
+										'Is your state/province missing from the dropdown menu above? You can add it by completing the following steps:',
324
+										'event_espresso'
325
+									)
326
+								) .
327
+								EEH_HTML::ul() .
328
+								EEH_HTML::li(
329
+									esc_html__(
330
+										'first select the Country that your State/Province belongs to',
331
+										'event_espresso'
332
+									)
333
+								) .
334
+								EEH_HTML::li(
335
+									esc_html__('enter the name of your State/Province', 'event_espresso')
336
+								) .
337
+								EEH_HTML::li(
338
+									esc_html__(
339
+										'enter a two to six letter abbreviation for the name of your State/Province',
340
+										'event_espresso'
341
+									)
342
+								) .
343
+								EEH_HTML::li(esc_html__('click the ADD button', 'event_espresso')) .
344
+								EEH_HTML::ulx()
345
+							)
346
+						),
347
+						// NEW STATE COUNTRY
348
+						'new_state_country'           => new EE_Country_Select_Input(
349
+							$country_options,
350
+							[
351
+								'html_name'       => $country_name,
352
+								'html_id'         => str_replace(
353
+									'state',
354
+									'nsmf_new_state_country',
355
+									$input->html_id()
356
+								),
357
+								'html_class'      => $input->html_class() . ' new-state-country',
358
+								'html_label_text' => esc_html__('New State/Province Country', 'event_espresso'),
359
+								'default'         => $request->getRequestParam($country_name),
360
+								'required'        => false,
361
+							]
362
+						),
363
+						// NEW STATE NAME
364
+						'new_state_name'              => new EE_Text_Input(
365
+							[
366
+								'html_name'       => $state_name,
367
+								'html_id'         => str_replace(
368
+									'state',
369
+									'nsmf_new_state_name',
370
+									$input->html_id()
371
+								),
372
+								'html_class'      => $input->html_class() . ' new-state-state',
373
+								'html_label_text' => esc_html__(
374
+									'New State/Province Name',
375
+									'event_espresso'
376
+								),
377
+								'default'         => $request->getRequestParam($state_name),
378
+								'required'        => false,
379
+							]
380
+						),
381
+						'spacer'                      => new EE_Form_Section_HTML(EEH_HTML::br()),
382
+						// NEW STATE NAME
383
+						'new_state_abbrv'             => new EE_Text_Input(
384
+							[
385
+								'html_name'             => $abbrv_name,
386
+								'html_id'               => str_replace(
387
+									'state',
388
+									'nsmf_new_state_abbrv',
389
+									$input->html_id()
390
+								),
391
+								'html_class'            => $input->html_class() . ' new-state-abbrv',
392
+								'html_label_text'       => esc_html__(
393
+									'New State/Province Abbreviation',
394
+									'event_espresso'
395
+								) . ' *',
396
+								'other_html_attributes' => 'size="24"',
397
+								'default'               => $request->getRequestParam($abbrv_name),
398
+								'required'              => false,
399
+							]
400
+						),
401
+						// "submit" button
402
+						'add_new_state_submit_button' => new EE_Form_Section_HTML(
403
+							apply_filters(
404
+								'FHEE__EED_Add_New_State__display_add_new_state_micro_form__add_new_state_submit_button',
405
+								EEH_HTML::nbsp(3) .
406
+								EEH_HTML::link(
407
+									'',
408
+									esc_html__('ADD', 'event_espresso'),
409
+									'',
410
+									'submit-' . $new_state_submit_id,
411
+									'ee-form-add-new-state-submit button button-secondary',
412
+									'',
413
+									'data-target="'
414
+									. $new_state_submit_id
415
+									. '" data-value-field-name="'
416
+									. $input->valueFieldName()
417
+									. '"'
418
+								)
419
+							)
420
+						),
421
+						// extra info
422
+						'add_new_state_extra'         => new EE_Form_Section_HTML(
423
+							apply_filters(
424
+								'FHEE__EED_Add_New_State__display_add_new_state_micro_form__add_new_state_extra',
425
+								EEH_HTML::br(2)
426
+								.
427
+								EEH_HTML::div('', '', 'small-text')
428
+								.
429
+								EEH_HTML::strong(
430
+									'* ' .
431
+									esc_html__(
432
+										'Don\'t know your State/Province Abbreviation?',
433
+										'event_espresso'
434
+									)
435
+								)
436
+								.
437
+								EEH_HTML::br()
438
+								.
439
+								sprintf(
440
+									esc_html__(
441
+										'You can look here: %s, for a list of Countries and links to their State/Province Abbreviations ("Subdivisions assigned codes" column).',
442
+										'event_espresso'
443
+									),
444
+									EEH_HTML::link(
445
+										'https://en.wikipedia.org/wiki/ISO_3166-2',
446
+										'https://en.wikipedia.org/wiki/ISO_3166-2',
447
+										'',
448
+										'',
449
+										'ee-form-add-new-state-wiki-lnk',
450
+										'',
451
+										'target="_blank"'
452
+									)
453
+								)
454
+								.
455
+								EEH_HTML::divx()
456
+								.
457
+								EEH_HTML::br()
458
+								.
459
+								EEH_HTML::link(
460
+									'',
461
+									esc_html__('cancel new State/Province', 'event_espresso'),
462
+									'',
463
+									'hide-' . $input->html_id(),
464
+									'ee-form-cancel-new-state-lnk smaller-text',
465
+									'',
466
+									'data-target="' . $input->html_id() . '"'
467
+								)
468
+								.
469
+								EEH_HTML::divx()
470
+								.
471
+								EEH_HTML::br()
472
+							)
473
+						),
474
+					],
475
+				]
476
+			);
477
+			$question_group_reg_form->add_subsections(
478
+				['new_state_micro_form' => $new_state_micro_form],
479
+				'state',
480
+				false
481
+			);
482
+		}
483
+		return $question_group_reg_form;
484
+	}
485
+
486
+
487
+	/**
488
+	 * set_new_state_input_width
489
+	 *
490
+	 * @return int|string
491
+	 * @throws EE_Error
492
+	 * @throws InvalidArgumentException
493
+	 * @throws InvalidDataTypeException
494
+	 * @throws InvalidInterfaceException
495
+	 * @throws ReflectionException
496
+	 */
497
+	public static function add_new_state()
498
+	{
499
+		$request = self::getRequest();
500
+		if ($request->getRequestParam('nsmf_add_new_state', 0, 'int') === 1) {
501
+			EE_Registry::instance()->load_model('State');
502
+			// grab country ISO code, new state name, and new state abbreviation
503
+			$state_country = $request->getRequestParam('nsmf_new_state_country');
504
+			$state_name    = $request->getRequestParam('nsmf_new_state_name');
505
+			$state_abbr    = $request->getRequestParam('nsmf_new_state_abbrv');
506
+			if ($state_country && $state_name && $state_abbr) {
507
+				$new_state = EED_Add_New_State::save_new_state_to_db(
508
+					[
509
+						'CNT_ISO'    => strtoupper($state_country),
510
+						'STA_abbrev' => strtoupper($state_abbr),
511
+						'STA_name'   => ucwords($state_name),
512
+						'STA_active' => false,
513
+					]
514
+				);
515
+				if ($new_state instanceof EE_State) {
516
+					// clean house
517
+					$request->unSetRequestParams(
518
+						[
519
+							'nsmf_add_new_state',
520
+							'nsmf_new_state_country',
521
+							'nsmf_new_state_name',
522
+							'nsmf_new_state_abbrv',
523
+						]
524
+					);
525
+					// get any existing new states
526
+					$new_states                     = EE_Registry::instance()->SSN->get_session_data('nsmf_new_states');
527
+					$new_states[ $new_state->ID() ] = $new_state;
528
+					EE_Registry::instance()->SSN->set_session_data(
529
+						['nsmf_new_states' => $new_states]
530
+					);
531
+					if ($request->isAjax()) {
532
+						echo wp_json_encode(
533
+							[
534
+								'success'      => true,
535
+								'id'           => $new_state->ID(),
536
+								'name'         => $new_state->name(),
537
+								'abbrev'       => $new_state->abbrev(),
538
+								'country_iso'  => $new_state->country_iso(),
539
+								'country_name' => $new_state->country()->name(),
540
+							]
541
+						);
542
+						exit();
543
+					}
544
+					return $new_state->ID();
545
+				}
546
+			} else {
547
+				$error = esc_html__(
548
+					'A new State/Province could not be added because invalid or missing data was received.',
549
+					'event_espresso'
550
+				);
551
+				if ($request->isAjax()) {
552
+					echo wp_json_encode(['error' => $error]);
553
+					exit();
554
+				}
555
+				EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
556
+			}
557
+		}
558
+		return false;
559
+	}
560
+
561
+
562
+	/**
563
+	 * recursively drills down through request params to remove any that were added by this module
564
+	 *
565
+	 * @param array $request_params
566
+	 * @return array
567
+	 */
568
+	public static function filter_checkout_request_params($request_params)
569
+	{
570
+		foreach ($request_params as $form_section) {
571
+			if (is_array($form_section)) {
572
+				EED_Add_New_State::unset_new_state_request_params($form_section);
573
+				EED_Add_New_State::filter_checkout_request_params($form_section);
574
+			}
575
+		}
576
+		return $request_params;
577
+	}
578
+
579
+
580
+	/**
581
+	 * @param array $request_params
582
+	 * @return array
583
+	 */
584
+	public static function unset_new_state_request_params($request_params)
585
+	{
586
+		unset(
587
+			$request_params['new_state_micro_form'],
588
+			$request_params['new_state_micro_add_new_state'],
589
+			$request_params['new_state_micro_new_state_country'],
590
+			$request_params['new_state_micro_new_state_name'],
591
+			$request_params['new_state_micro_new_state_abbrv']
592
+		);
593
+		return $request_params;
594
+	}
595
+
596
+
597
+	/**
598
+	 * @param array $props_n_values
599
+	 * @return EE_State|null
600
+	 * @throws EE_Error
601
+	 * @throws ReflectionException
602
+	 */
603
+	public static function save_new_state_to_db($props_n_values = [])
604
+	{
605
+		/** @var EE_State[] $existing_state */
606
+		$existing_state = EEM_State::instance()->get_all([$props_n_values, 'limit' => 1]);
607
+		if (! empty($existing_state)) {
608
+			return array_pop($existing_state);
609
+		}
610
+		$new_state = EE_State::new_instance($props_n_values);
611
+		if ($new_state instanceof EE_State) {
612
+			$country_settings_url = add_query_arg(
613
+				[
614
+					'page'    => 'espresso_general_settings',
615
+					'action'  => 'country_settings',
616
+					'country' => $new_state->country_iso(),
617
+				],
618
+				admin_url('admin.php')
619
+			);
620
+			// if not non-ajax admin
621
+			new PersistentAdminNotice(
622
+				'new-state-added-' . $new_state->country_iso() . '-' . $new_state->abbrev(),
623
+				sprintf(
624
+					esc_html__(
625
+						'A new State named "%1$s (%2$s)" was dynamically added from an Event Espresso form for the Country of "%3$s".%5$sTo verify, edit, and/or delete this new State, please go to the %4$s and update the States / Provinces section.%5$sCheck "Yes" to have this new State added to dropdown select lists in forms.',
626
+						'event_espresso'
627
+					),
628
+					'<b>' . $new_state->name() . '</b>',
629
+					'<b>' . $new_state->abbrev() . '</b>',
630
+					'<b>' . $new_state->country()->name() . '</b>',
631
+					'<a href="'
632
+					. $country_settings_url
633
+					. '">'
634
+					. esc_html__(
635
+						'Event Espresso - General Settings > Countries Tab',
636
+						'event_espresso'
637
+					)
638
+					. '</a>',
639
+					'<br />'
640
+				)
641
+			);
642
+			$new_state->save();
643
+			EEM_State::instance()->reset_cached_states();
644
+			return $new_state;
645
+		}
646
+		return null;
647
+	}
648
+
649
+
650
+	/**
651
+	 * @param string $CNT_ISO
652
+	 * @param string $STA_ID
653
+	 * @param array  $cols_n_values
654
+	 * @return void
655
+	 * @throws DomainException
656
+	 * @throws EE_Error
657
+	 * @throws InvalidArgumentException
658
+	 * @throws InvalidDataTypeException
659
+	 * @throws InvalidInterfaceException
660
+	 */
661
+	public static function update_country_settings($CNT_ISO = '', $STA_ID = '', $cols_n_values = [])
662
+	{
663
+		if (! $CNT_ISO) {
664
+			EE_Error::add_error(
665
+				esc_html__('An invalid or missing Country ISO Code was received.', 'event_espresso'),
666
+				__FILE__,
667
+				__FUNCTION__,
668
+				__LINE__
669
+			);
670
+		}
671
+		$STA_abbrev = is_array($cols_n_values) && isset($cols_n_values['STA_abbrev']) ? $cols_n_values['STA_abbrev']
672
+			: false;
673
+		if (! $STA_abbrev && ! empty($STA_ID)) {
674
+			$state = EEM_State::instance()->get_one_by_ID($STA_ID);
675
+			if ($state instanceof EE_State) {
676
+				$STA_abbrev = $state->abbrev();
677
+			}
678
+		}
679
+		if (! $STA_abbrev) {
680
+			EE_Error::add_error(
681
+				esc_html__('An invalid or missing State Abbreviation was received.', 'event_espresso'),
682
+				__FILE__,
683
+				__FUNCTION__,
684
+				__LINE__
685
+			);
686
+		}
687
+		/** @var PersistentAdminNoticeManager $persistent_admin_notice_manager */
688
+		$persistent_admin_notice_manager = LoaderFactory::getLoader()->getShared(
689
+			'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
690
+		);
691
+		$persistent_admin_notice_manager->dismissNotice($CNT_ISO . '-' . $STA_abbrev, true, true);
692
+	}
693
+
694
+
695
+	/**
696
+	 * @param EE_State[]                            $state_options
697
+	 * @param EE_SPCO_Reg_Step_Attendee_Information $reg_step
698
+	 * @param EE_Registration                       $registration
699
+	 * @param EE_Question                           $question
700
+	 * @param                                       $answer
701
+	 * @return array
702
+	 * @throws EE_Error
703
+	 * @throws ReflectionException
704
+	 */
705
+	public static function inject_new_reg_state_into_options(
706
+		array $state_options,
707
+		EE_SPCO_Reg_Step_Attendee_Information $reg_step,
708
+		EE_Registration $registration,
709
+		EE_Question $question,
710
+		$answer
711
+	) {
712
+		if (
713
+			$answer instanceof EE_Answer && $question instanceof EE_Question
714
+			&& $question->type() === EEM_Question::QST_type_state
715
+		) {
716
+			$STA_ID = $answer->value();
717
+			if (! empty($STA_ID)) {
718
+				$state = EEM_State::instance()->get_one_by_ID($STA_ID);
719
+				if ($state instanceof EE_State) {
720
+					$country = $state->country();
721
+					if ($country instanceof EE_Country) {
722
+						if (! isset($state_options[ $country->name() ])) {
723
+							$state_options[ $country->name() ] = [];
724
+						}
725
+						if (! isset($state_options[ $country->name() ][ $STA_ID ])) {
726
+							$state_options[ $country->name() ][ $STA_ID ] = $state->name();
727
+						}
728
+					}
729
+				}
730
+			}
731
+		}
732
+		return $state_options;
733
+	}
734
+
735
+
736
+	/**
737
+	 * @param EE_Country[]                          $country_options
738
+	 * @param EE_SPCO_Reg_Step_Attendee_Information $reg_step
739
+	 * @param EE_Registration                       $registration
740
+	 * @param EE_Question                           $question
741
+	 * @param                                       $answer
742
+	 * @return array
743
+	 * @throws EE_Error
744
+	 * @throws ReflectionException
745
+	 */
746
+	public static function inject_new_reg_country_into_options(
747
+		array $country_options,
748
+		EE_SPCO_Reg_Step_Attendee_Information $reg_step,
749
+		EE_Registration $registration,
750
+		EE_Question $question,
751
+		$answer
752
+	) {
753
+		if (
754
+			$answer instanceof EE_Answer && $question instanceof EE_Question
755
+			&& $question->type()
756
+			   === EEM_Question::QST_type_country
757
+		) {
758
+			$CNT_ISO = $answer->value();
759
+			if (! empty($CNT_ISO)) {
760
+				$country = EEM_Country::instance()->get_one_by_ID($CNT_ISO);
761
+				if ($country instanceof EE_Country) {
762
+					if (! isset($country_options[ $CNT_ISO ])) {
763
+						$country_options[ $CNT_ISO ] = $country->name();
764
+					}
765
+				}
766
+			}
767
+		}
768
+		return $country_options;
769
+	}
770
+
771
+
772
+	/**
773
+	 * @param EE_State[] $state_options
774
+	 * @return array
775
+	 * @throws EE_Error
776
+	 * @throws ReflectionException
777
+	 */
778
+	public static function state_options($state_options = [])
779
+	{
780
+		$new_states = EED_Add_New_State::_get_new_states();
781
+		foreach ($new_states as $new_state) {
782
+			if (
783
+				$new_state instanceof EE_State
784
+				&& $new_state->country() instanceof EE_Country
785
+			) {
786
+				$state_options[ $new_state->country()->name() ][ $new_state->ID() ] = $new_state->name();
787
+			}
788
+		}
789
+		return $state_options;
790
+	}
791
+
792
+
793
+	/**
794
+	 * @return array
795
+	 * @throws InvalidArgumentException
796
+	 * @throws InvalidDataTypeException
797
+	 * @throws InvalidInterfaceException
798
+	 */
799
+	protected static function _get_new_states()
800
+	{
801
+		$new_states = [];
802
+		if (EE_Registry::instance()->SSN instanceof EE_Session) {
803
+			$new_states = EE_Registry::instance()->SSN->get_session_data(
804
+				'nsmf_new_states'
805
+			);
806
+		}
807
+		return is_array($new_states) ? $new_states : [];
808
+	}
809
+
810
+
811
+	/**
812
+	 * @param EE_Country[] $country_options
813
+	 * @return array
814
+	 * @throws EE_Error
815
+	 * @throws ReflectionException
816
+	 */
817
+	public static function country_options($country_options = [])
818
+	{
819
+		$new_states = EED_Add_New_State::_get_new_states();
820
+		foreach ($new_states as $new_state) {
821
+			if (
822
+				$new_state instanceof EE_State
823
+				&& $new_state->country() instanceof EE_Country
824
+			) {
825
+				$country_options[ $new_state->country()->ID() ] = $new_state->country()->name();
826
+			}
827
+		}
828
+		return $country_options;
829
+	}
830 830
 }
Please login to merge, or discard this patch.
Spacing   +48 added lines, -48 removed lines patch added patch discarded remove patch
@@ -161,14 +161,14 @@  discard block
 block discarded – undo
161 161
      */
162 162
     public static function set_definitions()
163 163
     {
164
-        define('ANS_ASSETS_URL', plugin_dir_url(__FILE__) . 'assets/');
164
+        define('ANS_ASSETS_URL', plugin_dir_url(__FILE__).'assets/');
165 165
         define(
166 166
             'ANS_TEMPLATES_PATH',
167 167
             str_replace(
168 168
                 '\\',
169 169
                 '/',
170 170
                 plugin_dir_path(__FILE__)
171
-            ) . 'templates/'
171
+            ).'templates/'
172 172
         );
173 173
     }
174 174
 
@@ -187,19 +187,19 @@  discard block
 block discarded – undo
187 187
      */
188 188
     public static function translate_js_strings()
189 189
     {
190
-        EE_Registry::$i18n_js_strings['ans_no_country']        = esc_html__(
190
+        EE_Registry::$i18n_js_strings['ans_no_country'] = esc_html__(
191 191
             'In order to proceed, you need to select the Country that your State/Province belongs to.',
192 192
             'event_espresso'
193 193
         );
194
-        EE_Registry::$i18n_js_strings['ans_no_name']           = esc_html__(
194
+        EE_Registry::$i18n_js_strings['ans_no_name'] = esc_html__(
195 195
             'In order to proceed, you need to enter the name of your State/Province.',
196 196
             'event_espresso'
197 197
         );
198
-        EE_Registry::$i18n_js_strings['ans_no_abbreviation']   = esc_html__(
198
+        EE_Registry::$i18n_js_strings['ans_no_abbreviation'] = esc_html__(
199 199
             'In order to proceed, you need to enter an abbreviation for the name of your State/Province.',
200 200
             'event_espresso'
201 201
         );
202
-        EE_Registry::$i18n_js_strings['ans_save_success']      = esc_html__(
202
+        EE_Registry::$i18n_js_strings['ans_save_success'] = esc_html__(
203 203
             'The new state was successfully saved to the database.',
204 204
             'event_espresso'
205 205
         );
@@ -218,7 +218,7 @@  discard block
 block discarded – undo
218 218
         if (apply_filters('EED_Single_Page_Checkout__SPCO_active', false)) {
219 219
             wp_register_script(
220 220
                 'add_new_state',
221
-                ANS_ASSETS_URL . 'add_new_state.js',
221
+                ANS_ASSETS_URL.'add_new_state.js',
222 222
                 ['espresso_core', 'single_page_checkout'],
223 223
                 EVENT_ESPRESSO_VERSION,
224 224
                 true
@@ -264,10 +264,10 @@  discard block
 block discarded – undo
264 264
             $new_state_submit_id = str_replace('state', 'new_state', $input->html_id());
265 265
             $country_options     = [];
266 266
             $countries           = EEM_Country::instance()->get_all_countries();
267
-            if (! empty($countries)) {
267
+            if ( ! empty($countries)) {
268 268
                 foreach ($countries as $country) {
269 269
                     if ($country instanceof EE_Country) {
270
-                        $country_options[ $country->ID() ] = $country->name();
270
+                        $country_options[$country->ID()] = $country->name();
271 271
                     }
272 272
                 }
273 273
             }
@@ -301,10 +301,10 @@  discard block
 block discarded – undo
301 301
                                     '',
302 302
                                     esc_html__('click here to add a new state/province', 'event_espresso'),
303 303
                                     '',
304
-                                    'display-' . $input->html_id(),
304
+                                    'display-'.$input->html_id(),
305 305
                                     'ee-form-add-new-state-lnk display-the-hidden smaller-text hide-if-no-js',
306 306
                                     '',
307
-                                    'data-target="' . $input->html_id() . '"'
307
+                                    'data-target="'.$input->html_id().'"'
308 308
                                 )
309 309
                             )
310 310
                         ),
@@ -314,33 +314,33 @@  discard block
 block discarded – undo
314 314
                                 'FHEE__EED_Add_New_State__display_add_new_state_micro_form__add_new_state_micro_form',
315 315
                                 EEH_HTML::div(
316 316
                                     '',
317
-                                    $input->html_id() . '-dv',
317
+                                    $input->html_id().'-dv',
318 318
                                     'ee-form-add-new-state-dv',
319 319
                                     'display: none;'
320
-                                ) .
320
+                                ).
321 321
                                 EEH_HTML::h6(
322 322
                                     esc_html__(
323 323
                                         'Is your state/province missing from the dropdown menu above? You can add it by completing the following steps:',
324 324
                                         'event_espresso'
325 325
                                     )
326
-                                ) .
327
-                                EEH_HTML::ul() .
326
+                                ).
327
+                                EEH_HTML::ul().
328 328
                                 EEH_HTML::li(
329 329
                                     esc_html__(
330 330
                                         'first select the Country that your State/Province belongs to',
331 331
                                         'event_espresso'
332 332
                                     )
333
-                                ) .
333
+                                ).
334 334
                                 EEH_HTML::li(
335 335
                                     esc_html__('enter the name of your State/Province', 'event_espresso')
336
-                                ) .
336
+                                ).
337 337
                                 EEH_HTML::li(
338 338
                                     esc_html__(
339 339
                                         'enter a two to six letter abbreviation for the name of your State/Province',
340 340
                                         'event_espresso'
341 341
                                     )
342
-                                ) .
343
-                                EEH_HTML::li(esc_html__('click the ADD button', 'event_espresso')) .
342
+                                ).
343
+                                EEH_HTML::li(esc_html__('click the ADD button', 'event_espresso')).
344 344
                                 EEH_HTML::ulx()
345 345
                             )
346 346
                         ),
@@ -354,7 +354,7 @@  discard block
 block discarded – undo
354 354
                                     'nsmf_new_state_country',
355 355
                                     $input->html_id()
356 356
                                 ),
357
-                                'html_class'      => $input->html_class() . ' new-state-country',
357
+                                'html_class'      => $input->html_class().' new-state-country',
358 358
                                 'html_label_text' => esc_html__('New State/Province Country', 'event_espresso'),
359 359
                                 'default'         => $request->getRequestParam($country_name),
360 360
                                 'required'        => false,
@@ -369,7 +369,7 @@  discard block
 block discarded – undo
369 369
                                     'nsmf_new_state_name',
370 370
                                     $input->html_id()
371 371
                                 ),
372
-                                'html_class'      => $input->html_class() . ' new-state-state',
372
+                                'html_class'      => $input->html_class().' new-state-state',
373 373
                                 'html_label_text' => esc_html__(
374 374
                                     'New State/Province Name',
375 375
                                     'event_espresso'
@@ -388,11 +388,11 @@  discard block
 block discarded – undo
388 388
                                     'nsmf_new_state_abbrv',
389 389
                                     $input->html_id()
390 390
                                 ),
391
-                                'html_class'            => $input->html_class() . ' new-state-abbrv',
391
+                                'html_class'            => $input->html_class().' new-state-abbrv',
392 392
                                 'html_label_text'       => esc_html__(
393 393
                                     'New State/Province Abbreviation',
394 394
                                     'event_espresso'
395
-                                ) . ' *',
395
+                                ).' *',
396 396
                                 'other_html_attributes' => 'size="24"',
397 397
                                 'default'               => $request->getRequestParam($abbrv_name),
398 398
                                 'required'              => false,
@@ -402,12 +402,12 @@  discard block
 block discarded – undo
402 402
                         'add_new_state_submit_button' => new EE_Form_Section_HTML(
403 403
                             apply_filters(
404 404
                                 'FHEE__EED_Add_New_State__display_add_new_state_micro_form__add_new_state_submit_button',
405
-                                EEH_HTML::nbsp(3) .
405
+                                EEH_HTML::nbsp(3).
406 406
                                 EEH_HTML::link(
407 407
                                     '',
408 408
                                     esc_html__('ADD', 'event_espresso'),
409 409
                                     '',
410
-                                    'submit-' . $new_state_submit_id,
410
+                                    'submit-'.$new_state_submit_id,
411 411
                                     'ee-form-add-new-state-submit button button-secondary',
412 412
                                     '',
413 413
                                     'data-target="'
@@ -427,7 +427,7 @@  discard block
 block discarded – undo
427 427
                                 EEH_HTML::div('', '', 'small-text')
428 428
                                 .
429 429
                                 EEH_HTML::strong(
430
-                                    '* ' .
430
+                                    '* '.
431 431
                                     esc_html__(
432 432
                                         'Don\'t know your State/Province Abbreviation?',
433 433
                                         'event_espresso'
@@ -460,10 +460,10 @@  discard block
 block discarded – undo
460 460
                                     '',
461 461
                                     esc_html__('cancel new State/Province', 'event_espresso'),
462 462
                                     '',
463
-                                    'hide-' . $input->html_id(),
463
+                                    'hide-'.$input->html_id(),
464 464
                                     'ee-form-cancel-new-state-lnk smaller-text',
465 465
                                     '',
466
-                                    'data-target="' . $input->html_id() . '"'
466
+                                    'data-target="'.$input->html_id().'"'
467 467
                                 )
468 468
                                 .
469 469
                                 EEH_HTML::divx()
@@ -524,7 +524,7 @@  discard block
 block discarded – undo
524 524
                     );
525 525
                     // get any existing new states
526 526
                     $new_states                     = EE_Registry::instance()->SSN->get_session_data('nsmf_new_states');
527
-                    $new_states[ $new_state->ID() ] = $new_state;
527
+                    $new_states[$new_state->ID()] = $new_state;
528 528
                     EE_Registry::instance()->SSN->set_session_data(
529 529
                         ['nsmf_new_states' => $new_states]
530 530
                     );
@@ -604,7 +604,7 @@  discard block
 block discarded – undo
604 604
     {
605 605
         /** @var EE_State[] $existing_state */
606 606
         $existing_state = EEM_State::instance()->get_all([$props_n_values, 'limit' => 1]);
607
-        if (! empty($existing_state)) {
607
+        if ( ! empty($existing_state)) {
608 608
             return array_pop($existing_state);
609 609
         }
610 610
         $new_state = EE_State::new_instance($props_n_values);
@@ -619,15 +619,15 @@  discard block
 block discarded – undo
619 619
             );
620 620
             // if not non-ajax admin
621 621
             new PersistentAdminNotice(
622
-                'new-state-added-' . $new_state->country_iso() . '-' . $new_state->abbrev(),
622
+                'new-state-added-'.$new_state->country_iso().'-'.$new_state->abbrev(),
623 623
                 sprintf(
624 624
                     esc_html__(
625 625
                         'A new State named "%1$s (%2$s)" was dynamically added from an Event Espresso form for the Country of "%3$s".%5$sTo verify, edit, and/or delete this new State, please go to the %4$s and update the States / Provinces section.%5$sCheck "Yes" to have this new State added to dropdown select lists in forms.',
626 626
                         'event_espresso'
627 627
                     ),
628
-                    '<b>' . $new_state->name() . '</b>',
629
-                    '<b>' . $new_state->abbrev() . '</b>',
630
-                    '<b>' . $new_state->country()->name() . '</b>',
628
+                    '<b>'.$new_state->name().'</b>',
629
+                    '<b>'.$new_state->abbrev().'</b>',
630
+                    '<b>'.$new_state->country()->name().'</b>',
631 631
                     '<a href="'
632 632
                     . $country_settings_url
633 633
                     . '">'
@@ -660,7 +660,7 @@  discard block
 block discarded – undo
660 660
      */
661 661
     public static function update_country_settings($CNT_ISO = '', $STA_ID = '', $cols_n_values = [])
662 662
     {
663
-        if (! $CNT_ISO) {
663
+        if ( ! $CNT_ISO) {
664 664
             EE_Error::add_error(
665 665
                 esc_html__('An invalid or missing Country ISO Code was received.', 'event_espresso'),
666 666
                 __FILE__,
@@ -670,13 +670,13 @@  discard block
 block discarded – undo
670 670
         }
671 671
         $STA_abbrev = is_array($cols_n_values) && isset($cols_n_values['STA_abbrev']) ? $cols_n_values['STA_abbrev']
672 672
             : false;
673
-        if (! $STA_abbrev && ! empty($STA_ID)) {
673
+        if ( ! $STA_abbrev && ! empty($STA_ID)) {
674 674
             $state = EEM_State::instance()->get_one_by_ID($STA_ID);
675 675
             if ($state instanceof EE_State) {
676 676
                 $STA_abbrev = $state->abbrev();
677 677
             }
678 678
         }
679
-        if (! $STA_abbrev) {
679
+        if ( ! $STA_abbrev) {
680 680
             EE_Error::add_error(
681 681
                 esc_html__('An invalid or missing State Abbreviation was received.', 'event_espresso'),
682 682
                 __FILE__,
@@ -688,7 +688,7 @@  discard block
 block discarded – undo
688 688
         $persistent_admin_notice_manager = LoaderFactory::getLoader()->getShared(
689 689
             'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
690 690
         );
691
-        $persistent_admin_notice_manager->dismissNotice($CNT_ISO . '-' . $STA_abbrev, true, true);
691
+        $persistent_admin_notice_manager->dismissNotice($CNT_ISO.'-'.$STA_abbrev, true, true);
692 692
     }
693 693
 
694 694
 
@@ -714,16 +714,16 @@  discard block
 block discarded – undo
714 714
             && $question->type() === EEM_Question::QST_type_state
715 715
         ) {
716 716
             $STA_ID = $answer->value();
717
-            if (! empty($STA_ID)) {
717
+            if ( ! empty($STA_ID)) {
718 718
                 $state = EEM_State::instance()->get_one_by_ID($STA_ID);
719 719
                 if ($state instanceof EE_State) {
720 720
                     $country = $state->country();
721 721
                     if ($country instanceof EE_Country) {
722
-                        if (! isset($state_options[ $country->name() ])) {
723
-                            $state_options[ $country->name() ] = [];
722
+                        if ( ! isset($state_options[$country->name()])) {
723
+                            $state_options[$country->name()] = [];
724 724
                         }
725
-                        if (! isset($state_options[ $country->name() ][ $STA_ID ])) {
726
-                            $state_options[ $country->name() ][ $STA_ID ] = $state->name();
725
+                        if ( ! isset($state_options[$country->name()][$STA_ID])) {
726
+                            $state_options[$country->name()][$STA_ID] = $state->name();
727 727
                         }
728 728
                     }
729 729
                 }
@@ -756,11 +756,11 @@  discard block
 block discarded – undo
756 756
                === EEM_Question::QST_type_country
757 757
         ) {
758 758
             $CNT_ISO = $answer->value();
759
-            if (! empty($CNT_ISO)) {
759
+            if ( ! empty($CNT_ISO)) {
760 760
                 $country = EEM_Country::instance()->get_one_by_ID($CNT_ISO);
761 761
                 if ($country instanceof EE_Country) {
762
-                    if (! isset($country_options[ $CNT_ISO ])) {
763
-                        $country_options[ $CNT_ISO ] = $country->name();
762
+                    if ( ! isset($country_options[$CNT_ISO])) {
763
+                        $country_options[$CNT_ISO] = $country->name();
764 764
                     }
765 765
                 }
766 766
             }
@@ -783,7 +783,7 @@  discard block
 block discarded – undo
783 783
                 $new_state instanceof EE_State
784 784
                 && $new_state->country() instanceof EE_Country
785 785
             ) {
786
-                $state_options[ $new_state->country()->name() ][ $new_state->ID() ] = $new_state->name();
786
+                $state_options[$new_state->country()->name()][$new_state->ID()] = $new_state->name();
787 787
             }
788 788
         }
789 789
         return $state_options;
@@ -822,7 +822,7 @@  discard block
 block discarded – undo
822 822
                 $new_state instanceof EE_State
823 823
                 && $new_state->country() instanceof EE_Country
824 824
             ) {
825
-                $country_options[ $new_state->country()->ID() ] = $new_state->country()->name();
825
+                $country_options[$new_state->country()->ID()] = $new_state->country()->name();
826 826
             }
827 827
         }
828 828
         return $country_options;
Please login to merge, or discard this patch.
modules/single_page_checkout/EED_Single_Page_Checkout.module.php 2 patches
Spacing   +43 added lines, -43 removed lines patch added patch discarded remove patch
@@ -115,7 +115,7 @@  discard block
 block discarded – undo
115 115
     public static function set_hooks_admin()
116 116
     {
117 117
         EED_Single_Page_Checkout::set_definitions();
118
-        if (! (defined('DOING_AJAX') && DOING_AJAX)) {
118
+        if ( ! (defined('DOING_AJAX') && DOING_AJAX)) {
119 119
             return;
120 120
         }
121 121
         // going to start an output buffer in case anything gets accidentally output
@@ -218,14 +218,14 @@  discard block
 block discarded – undo
218 218
         }
219 219
         define(
220 220
             'SPCO_BASE_PATH',
221
-            rtrim(str_replace(array('\\', '/'), '/', plugin_dir_path(__FILE__)), '/') . '/'
221
+            rtrim(str_replace(array('\\', '/'), '/', plugin_dir_path(__FILE__)), '/').'/'
222 222
         );
223
-        define('SPCO_CSS_URL', plugin_dir_url(__FILE__) . 'css/');
224
-        define('SPCO_IMG_URL', plugin_dir_url(__FILE__) . 'img/');
225
-        define('SPCO_JS_URL', plugin_dir_url(__FILE__) . 'js/');
226
-        define('SPCO_INC_PATH', SPCO_BASE_PATH . 'inc/');
227
-        define('SPCO_REG_STEPS_PATH', SPCO_BASE_PATH . 'reg_steps/');
228
-        define('SPCO_TEMPLATES_PATH', SPCO_BASE_PATH . 'templates/');
223
+        define('SPCO_CSS_URL', plugin_dir_url(__FILE__).'css/');
224
+        define('SPCO_IMG_URL', plugin_dir_url(__FILE__).'img/');
225
+        define('SPCO_JS_URL', plugin_dir_url(__FILE__).'js/');
226
+        define('SPCO_INC_PATH', SPCO_BASE_PATH.'inc/');
227
+        define('SPCO_REG_STEPS_PATH', SPCO_BASE_PATH.'reg_steps/');
228
+        define('SPCO_TEMPLATES_PATH', SPCO_BASE_PATH.'templates/');
229 229
         EEH_Autoloader::register_autoloaders_for_each_file_in_folder(SPCO_BASE_PATH, true);
230 230
         EE_Registry::$i18n_js_strings['registration_expiration_notice'] = EED_Single_Page_Checkout::getRegistrationExpirationNotice(
231 231
         );
@@ -256,7 +256,7 @@  discard block
 block discarded – undo
256 256
             // we need a
257 257
             if (isset($reg_step['file_path'], $reg_step['class_name'], $reg_step['slug'])) {
258 258
                 // copy over to the reg_steps_array
259
-                EED_Single_Page_Checkout::$_reg_steps_array[ $order ] = $reg_step;
259
+                EED_Single_Page_Checkout::$_reg_steps_array[$order] = $reg_step;
260 260
                 // register custom key route for each reg step
261 261
                 // ie: step=>"slug" - this is the entire reason we load the reg steps array now
262 262
                 EE_Config::register_route(
@@ -268,7 +268,7 @@  discard block
 block discarded – undo
268 268
                 // add AJAX or other hooks
269 269
                 if (isset($reg_step['has_hooks']) && $reg_step['has_hooks']) {
270 270
                     // setup autoloaders if necessary
271
-                    if (! class_exists($reg_step['class_name'])) {
271
+                    if ( ! class_exists($reg_step['class_name'])) {
272 272
                         EEH_Autoloader::register_autoloaders_for_each_file_in_folder(
273 273
                             $reg_step['file_path'],
274 274
                             true
@@ -295,19 +295,19 @@  discard block
 block discarded – undo
295 295
         if (empty($reg_steps)) {
296 296
             $reg_steps = array(
297 297
                 10  => array(
298
-                    'file_path'  => SPCO_REG_STEPS_PATH . 'attendee_information',
298
+                    'file_path'  => SPCO_REG_STEPS_PATH.'attendee_information',
299 299
                     'class_name' => 'EE_SPCO_Reg_Step_Attendee_Information',
300 300
                     'slug'       => 'attendee_information',
301 301
                     'has_hooks'  => false,
302 302
                 ),
303 303
                 30  => array(
304
-                    'file_path'  => SPCO_REG_STEPS_PATH . 'payment_options',
304
+                    'file_path'  => SPCO_REG_STEPS_PATH.'payment_options',
305 305
                     'class_name' => 'EE_SPCO_Reg_Step_Payment_Options',
306 306
                     'slug'       => 'payment_options',
307 307
                     'has_hooks'  => true,
308 308
                 ),
309 309
                 999 => array(
310
-                    'file_path'  => SPCO_REG_STEPS_PATH . 'finalize_registration',
310
+                    'file_path'  => SPCO_REG_STEPS_PATH.'finalize_registration',
311 311
                     'class_name' => 'EE_SPCO_Reg_Step_Finalize_Registration',
312 312
                     'slug'       => 'finalize_registration',
313 313
                     'has_hooks'  => false,
@@ -459,7 +459,7 @@  discard block
 block discarded – undo
459 459
                 $this->checkout
460 460
             );
461 461
             // load the reg steps array
462
-            if (! $this->_load_and_instantiate_reg_steps()) {
462
+            if ( ! $this->_load_and_instantiate_reg_steps()) {
463 463
                 EED_Single_Page_Checkout::$_initialized = true;
464 464
                 return;
465 465
             }
@@ -468,7 +468,7 @@  discard block
 block discarded – undo
468 468
             // and the next step
469 469
             $this->checkout->set_next_step();
470 470
             // verify that everything has been setup correctly
471
-            if (! ($this->_verify_transaction_and_get_registrations() && $this->_final_verifications())) {
471
+            if ( ! ($this->_verify_transaction_and_get_registrations() && $this->_final_verifications())) {
472 472
                 EED_Single_Page_Checkout::$_initialized = true;
473 473
                 return;
474 474
             }
@@ -483,7 +483,7 @@  discard block
 block discarded – undo
483 483
             // DEBUG LOG
484 484
             // $this->checkout->log( __CLASS__, __FUNCTION__, __LINE__ );
485 485
             // get reg form
486
-            if (! $this->_check_form_submission()) {
486
+            if ( ! $this->_check_form_submission()) {
487 487
                 EED_Single_Page_Checkout::$_initialized = true;
488 488
                 return;
489 489
             }
@@ -514,7 +514,7 @@  discard block
 block discarded – undo
514 514
      */
515 515
     private function _verify_session()
516 516
     {
517
-        if (! EE_Registry::instance()->SSN instanceof EE_Session) {
517
+        if ( ! EE_Registry::instance()->SSN instanceof EE_Session) {
518 518
             throw new EE_Error(esc_html__('The EE_Session class could not be loaded.', 'event_espresso'));
519 519
         }
520 520
         $clear_session_requested = $this->request->getRequestParam('clear_session', false, 'bool');
@@ -531,7 +531,7 @@  discard block
 block discarded – undo
531 531
             // EE_Registry::instance()->SSN->reset_cart();
532 532
             // EE_Registry::instance()->SSN->reset_checkout();
533 533
             // EE_Registry::instance()->SSN->reset_transaction();
534
-            if (! $clear_session_requested) {
534
+            if ( ! $clear_session_requested) {
535 535
                 EE_Error::add_attention(
536 536
                     EE_Registry::$i18n_js_strings['registration_expiration_notice'],
537 537
                     __FILE__,
@@ -558,7 +558,7 @@  discard block
 block discarded – undo
558 558
         /** @type EE_Checkout $checkout */
559 559
         $checkout = EE_Registry::instance()->SSN->checkout();
560 560
         // verify
561
-        if (! $checkout instanceof EE_Checkout) {
561
+        if ( ! $checkout instanceof EE_Checkout) {
562 562
             // instantiate EE_Checkout object for handling the properties of the current checkout process
563 563
             $checkout = EE_Registry::instance()->load_file(
564 564
                 SPCO_INC_PATH,
@@ -576,7 +576,7 @@  discard block
 block discarded – undo
576 576
         }
577 577
         $checkout = apply_filters('FHEE__EED_Single_Page_Checkout___initialize_checkout__checkout', $checkout);
578 578
         // verify again
579
-        if (! $checkout instanceof EE_Checkout) {
579
+        if ( ! $checkout instanceof EE_Checkout) {
580 580
             throw new EE_Error(esc_html__('The EE_Checkout class could not be loaded.', 'event_espresso'));
581 581
         }
582 582
         // reset anything that needs a clean slate for each request
@@ -637,7 +637,7 @@  discard block
 block discarded – undo
637 637
      */
638 638
     protected function _display_request_vars()
639 639
     {
640
-        if (! WP_DEBUG) {
640
+        if ( ! WP_DEBUG) {
641 641
             return;
642 642
         }
643 643
         EEH_Debug_Tools::printr($this->request->requestParams(), 'requestParams', __FILE__, __LINE__);
@@ -714,7 +714,7 @@  discard block
 block discarded – undo
714 714
         ) {
715 715
             // if not, then loop through raw reg steps array
716 716
             foreach (EED_Single_Page_Checkout::$_reg_steps_array as $order => $reg_step) {
717
-                if (! $this->_load_and_instantiate_reg_step($reg_step, $order)) {
717
+                if ( ! $this->_load_and_instantiate_reg_step($reg_step, $order)) {
718 718
                     return false;
719 719
                 }
720 720
             }
@@ -846,12 +846,12 @@  discard block
 block discarded – undo
846 846
     private function _verify_transaction_and_get_registrations()
847 847
     {
848 848
         // was there already a valid transaction in the checkout from the session ?
849
-        if (! $this->checkout->transaction instanceof EE_Transaction) {
849
+        if ( ! $this->checkout->transaction instanceof EE_Transaction) {
850 850
             // get transaction from db or session
851 851
             $this->checkout->transaction = $this->checkout->reg_url_link && ! is_admin()
852 852
                 ? $this->_get_transaction_and_cart_for_previous_visit()
853 853
                 : $this->_get_cart_for_current_session_and_setup_new_transaction();
854
-            if (! $this->checkout->transaction instanceof EE_Transaction) {
854
+            if ( ! $this->checkout->transaction instanceof EE_Transaction) {
855 855
                 EE_Error::add_error(
856 856
                     esc_html__(
857 857
                         'Your Registration and Transaction information could not be retrieved from the db.',
@@ -1077,16 +1077,16 @@  discard block
 block discarded – undo
1077 1077
                         )
1078 1078
                     );
1079 1079
                     // override capabilities for frontend registrations
1080
-                    if (! is_admin()) {
1080
+                    if ( ! is_admin()) {
1081 1081
                         $CreateRegistrationCommand->setCapCheck(
1082 1082
                             new PublicCapabilities('', 'create_new_registration')
1083 1083
                         );
1084 1084
                     }
1085 1085
                     $registration = EE_Registry::instance()->BUS->execute($CreateRegistrationCommand);
1086
-                    if (! $registration instanceof EE_Registration) {
1086
+                    if ( ! $registration instanceof EE_Registration) {
1087 1087
                         throw new InvalidEntityException($registration, 'EE_Registration');
1088 1088
                     }
1089
-                    $registrations[ $registration->ID() ] = $registration;
1089
+                    $registrations[$registration->ID()] = $registration;
1090 1090
                 }
1091 1091
             }
1092 1092
             $registration_processor->fix_reg_final_price_rounding_issue($transaction);
@@ -1128,7 +1128,7 @@  discard block
 block discarded – undo
1128 1128
             $this->checkout
1129 1129
         );
1130 1130
         // verify that current step is still set correctly
1131
-        if (! $this->checkout->current_step instanceof EE_SPCO_Reg_Step) {
1131
+        if ( ! $this->checkout->current_step instanceof EE_SPCO_Reg_Step) {
1132 1132
             EE_Error::add_error(
1133 1133
                 esc_html__(
1134 1134
                     'We\'re sorry but the registration process can not proceed because one or more registration steps were not setup correctly. Please refresh the page and try again or contact support.',
@@ -1141,9 +1141,9 @@  discard block
 block discarded – undo
1141 1141
             return false;
1142 1142
         }
1143 1143
         // if returning to SPCO, then verify that primary registrant is set
1144
-        if (! empty($this->checkout->reg_url_link)) {
1144
+        if ( ! empty($this->checkout->reg_url_link)) {
1145 1145
             $valid_registrant = $this->checkout->transaction->primary_registration();
1146
-            if (! $valid_registrant instanceof EE_Registration) {
1146
+            if ( ! $valid_registrant instanceof EE_Registration) {
1147 1147
                 EE_Error::add_error(
1148 1148
                     esc_html__(
1149 1149
                         'We\'re sorry but there appears to be an error with the "reg_url_link" or the primary registrant for this transaction. Please refresh the page and try again or contact support.',
@@ -1164,7 +1164,7 @@  discard block
 block discarded – undo
1164 1164
                     $valid_registrant = $registration;
1165 1165
                 }
1166 1166
             }
1167
-            if (! $valid_registrant instanceof EE_Registration) {
1167
+            if ( ! $valid_registrant instanceof EE_Registration) {
1168 1168
                 // hmmm... maybe we have the wrong session because the user is opening multiple tabs ?
1169 1169
                 if (EED_Single_Page_Checkout::$_checkout_verified) {
1170 1170
                     // clear the session, mark the checkout as unverified, and try again
@@ -1207,9 +1207,9 @@  discard block
 block discarded – undo
1207 1207
         $this->checkout->set_reg_step_initiated($this->checkout->current_step);
1208 1208
         // loop thru all steps to call their individual "initialize" methods and set i18n strings for JS
1209 1209
         foreach ($this->checkout->reg_steps as $reg_step) {
1210
-            if (! $reg_step->initialize_reg_step()) {
1210
+            if ( ! $reg_step->initialize_reg_step()) {
1211 1211
                 // if not initialized then maybe this step is being removed...
1212
-                if (! $reinitializing && $reg_step->is_current_step()) {
1212
+                if ( ! $reinitializing && $reg_step->is_current_step()) {
1213 1213
                     // if it was the current step, then we need to start over here
1214 1214
                     $this->_initialize_reg_steps(true);
1215 1215
                     return;
@@ -1262,7 +1262,7 @@  discard block
 block discarded – undo
1262 1262
                         )
1263 1263
                     );
1264 1264
                     // validate submitted form data
1265
-                    if (! $this->checkout->continue_reg || ! $this->checkout->current_step->reg_form->is_valid()) {
1265
+                    if ( ! $this->checkout->continue_reg || ! $this->checkout->current_step->reg_form->is_valid()) {
1266 1266
                         // thou shall not pass !!!
1267 1267
                         $this->checkout->continue_reg = false;
1268 1268
                         // any form validation errors?
@@ -1338,7 +1338,7 @@  discard block
 block discarded – undo
1338 1338
                         ) {
1339 1339
                             EE_Error::add_success(
1340 1340
                                 $this->checkout->current_step->success_message()
1341
-                                . '<br />' . $this->checkout->next_step->_instructions()
1341
+                                . '<br />'.$this->checkout->next_step->_instructions()
1342 1342
                             );
1343 1343
                         }
1344 1344
                         // pack it up, pack it in...
@@ -1476,7 +1476,7 @@  discard block
 block discarded – undo
1476 1476
         // load css
1477 1477
         wp_register_style(
1478 1478
             'single_page_checkout',
1479
-            SPCO_CSS_URL . 'single_page_checkout.css',
1479
+            SPCO_CSS_URL.'single_page_checkout.css',
1480 1480
             array('espresso_default'),
1481 1481
             EVENT_ESPRESSO_VERSION
1482 1482
         );
@@ -1484,21 +1484,21 @@  discard block
 block discarded – undo
1484 1484
         // load JS
1485 1485
         wp_register_script(
1486 1486
             'jquery_plugin',
1487
-            EE_THIRD_PARTY_URL . 'jquery	.plugin.min.js',
1487
+            EE_THIRD_PARTY_URL.'jquery	.plugin.min.js',
1488 1488
             array('jquery'),
1489 1489
             '1.0.1',
1490 1490
             true
1491 1491
         );
1492 1492
         wp_register_script(
1493 1493
             'jquery_countdown',
1494
-            EE_THIRD_PARTY_URL . 'jquery	.countdown.min.js',
1494
+            EE_THIRD_PARTY_URL.'jquery	.countdown.min.js',
1495 1495
             array('jquery_plugin'),
1496 1496
             '2.1.0',
1497 1497
             true
1498 1498
         );
1499 1499
         wp_register_script(
1500 1500
             'single_page_checkout',
1501
-            SPCO_JS_URL . 'single_page_checkout.js',
1501
+            SPCO_JS_URL.'single_page_checkout.js',
1502 1502
             array('espresso_core', 'underscore', 'ee_form_section_validation'),
1503 1503
             EVENT_ESPRESSO_VERSION,
1504 1504
             true
@@ -1524,7 +1524,7 @@  discard block
 block discarded – undo
1524 1524
          *      AHEE__EED_Single_Page_Checkout__enqueue_styles_and_scripts__attendee_information
1525 1525
          */
1526 1526
         do_action(
1527
-            'AHEE__EED_Single_Page_Checkout__enqueue_styles_and_scripts__' . $this->checkout->current_step->slug(),
1527
+            'AHEE__EED_Single_Page_Checkout__enqueue_styles_and_scripts__'.$this->checkout->current_step->slug(),
1528 1528
             $this
1529 1529
         );
1530 1530
     }
@@ -1576,7 +1576,7 @@  discard block
 block discarded – undo
1576 1576
                     'layout_strategy' =>
1577 1577
                         new EE_Template_Layout(
1578 1578
                             array(
1579
-                                'layout_template_file' => SPCO_TEMPLATES_PATH . 'registration_page_wrapper.template.php',
1579
+                                'layout_template_file' => SPCO_TEMPLATES_PATH.'registration_page_wrapper.template.php',
1580 1580
                                 'template_args'        => array(
1581 1581
                                     'empty_cart'              => $empty_cart,
1582 1582
                                     'revisit'                 => $this->checkout->revisit,
@@ -1646,7 +1646,7 @@  discard block
 block discarded – undo
1646 1646
         ) {
1647 1647
             add_filter(
1648 1648
                 'FHEE__EEH_Template__powered_by_event_espresso__url',
1649
-                function ($url) {
1649
+                function($url) {
1650 1650
                     return apply_filters('FHEE__EE_Front_Controller__registration_footer__url', $url);
1651 1651
                 }
1652 1652
             );
@@ -1799,7 +1799,7 @@  discard block
 block discarded – undo
1799 1799
             '</h4>',
1800 1800
             '<br />',
1801 1801
             '<p>',
1802
-            '<a href="' . get_post_type_archive_link('espresso_events') . '" title="',
1802
+            '<a href="'.get_post_type_archive_link('espresso_events').'" title="',
1803 1803
             '">',
1804 1804
             '</a>',
1805 1805
             '</p>'
Please login to merge, or discard this patch.
Indentation   +1788 added lines, -1788 removed lines patch added patch discarded remove patch
@@ -19,1792 +19,1792 @@
 block discarded – undo
19 19
 class EED_Single_Page_Checkout extends EED_Module
20 20
 {
21 21
 
22
-    /**
23
-     * $_initialized - has the SPCO controller already been initialized ?
24
-     *
25
-     * @var bool $_initialized
26
-     */
27
-    private static $_initialized = false;
28
-
29
-
30
-    /**
31
-     * $_checkout_verified - is the EE_Checkout verified as correct for this request ?
32
-     *
33
-     * @var bool $_valid_checkout
34
-     */
35
-    private static $_checkout_verified = true;
36
-
37
-    /**
38
-     *    $_reg_steps_array - holds initial array of reg steps
39
-     *
40
-     * @var array $_reg_steps_array
41
-     */
42
-    private static $_reg_steps_array = array();
43
-
44
-    /**
45
-     *    $checkout - EE_Checkout object for handling the properties of the current checkout process
46
-     *
47
-     * @var EE_Checkout $checkout
48
-     */
49
-    public $checkout;
50
-
51
-    /**
52
-     * @var RequestInterface $request
53
-     */
54
-    protected $request;
55
-
56
-
57
-    /**
58
-     * @return EED_Single_Page_Checkout|EED_Module
59
-     * @throws EE_Error
60
-     * @throws ReflectionException
61
-     */
62
-    public static function instance()
63
-    {
64
-        add_filter('EED_Single_Page_Checkout__SPCO_active', '__return_true');
65
-        return parent::get_instance(__CLASS__);
66
-    }
67
-
68
-
69
-    /**
70
-     * @return EE_CART
71
-     */
72
-    public function cart()
73
-    {
74
-        return $this->checkout->cart;
75
-    }
76
-
77
-
78
-    /**
79
-     * @return RequestInterface
80
-     * @since   4.10.14.p
81
-     */
82
-    public static function getRequest()
83
-    {
84
-        return LoaderFactory::getLoader()->getShared(RequestInterface::class);
85
-    }
86
-
87
-
88
-    /**
89
-     * @return EE_Transaction
90
-     */
91
-    public function transaction()
92
-    {
93
-        return $this->checkout->transaction;
94
-    }
95
-
96
-
97
-    /**
98
-     *    set_hooks - for hooking into EE Core, other modules, etc
99
-     *
100
-     * @return    void
101
-     * @throws EE_Error
102
-     */
103
-    public static function set_hooks()
104
-    {
105
-        EED_Single_Page_Checkout::set_definitions();
106
-    }
107
-
108
-
109
-    /**
110
-     *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
111
-     *
112
-     * @return    void
113
-     * @throws EE_Error
114
-     */
115
-    public static function set_hooks_admin()
116
-    {
117
-        EED_Single_Page_Checkout::set_definitions();
118
-        if (! (defined('DOING_AJAX') && DOING_AJAX)) {
119
-            return;
120
-        }
121
-        // going to start an output buffer in case anything gets accidentally output
122
-        // that might disrupt our JSON response
123
-        ob_start();
124
-        EED_Single_Page_Checkout::load_reg_steps();
125
-        // set ajax hooks
126
-        add_action('wp_ajax_process_reg_step', array('EED_Single_Page_Checkout', 'process_reg_step'));
127
-        add_action('wp_ajax_nopriv_process_reg_step', array('EED_Single_Page_Checkout', 'process_reg_step'));
128
-        add_action('wp_ajax_display_spco_reg_step', array('EED_Single_Page_Checkout', 'display_reg_step'));
129
-        add_action('wp_ajax_nopriv_display_spco_reg_step', array('EED_Single_Page_Checkout', 'display_reg_step'));
130
-        add_action('wp_ajax_update_reg_step', array('EED_Single_Page_Checkout', 'update_reg_step'));
131
-        add_action('wp_ajax_nopriv_update_reg_step', array('EED_Single_Page_Checkout', 'update_reg_step'));
132
-    }
133
-
134
-
135
-    /**
136
-     *    process ajax request
137
-     *
138
-     * @param string $ajax_action
139
-     * @throws EE_Error
140
-     * @throws ReflectionException
141
-     */
142
-    public static function process_ajax_request($ajax_action)
143
-    {
144
-        $request = EED_Single_Page_Checkout::getRequest();
145
-        $request->setRequestParam('action', $ajax_action);
146
-        EED_Single_Page_Checkout::instance()->_initialize();
147
-    }
148
-
149
-
150
-    /**
151
-     * ajax display registration step
152
-     *
153
-     * @throws EE_Error
154
-     * @throws ReflectionException
155
-     */
156
-    public static function display_reg_step()
157
-    {
158
-        EED_Single_Page_Checkout::process_ajax_request('display_spco_reg_step');
159
-    }
160
-
161
-
162
-    /**
163
-     * ajax process registration step
164
-     *
165
-     * @throws EE_Error
166
-     * @throws ReflectionException
167
-     */
168
-    public static function process_reg_step()
169
-    {
170
-        EED_Single_Page_Checkout::process_ajax_request('process_reg_step');
171
-    }
172
-
173
-
174
-    /**
175
-     * ajax process registration step
176
-     *
177
-     * @throws EE_Error
178
-     * @throws ReflectionException
179
-     */
180
-    public static function update_reg_step()
181
-    {
182
-        EED_Single_Page_Checkout::process_ajax_request('update_reg_step');
183
-    }
184
-
185
-
186
-    /**
187
-     * update_checkout
188
-     *
189
-     * @return void
190
-     * @throws ReflectionException
191
-     * @throws EE_Error
192
-     */
193
-    public static function update_checkout()
194
-    {
195
-        EED_Single_Page_Checkout::process_ajax_request('update_checkout');
196
-    }
197
-
198
-
199
-    /**
200
-     * @return void
201
-     * @deprecated 4.10.14.p
202
-     */
203
-    public static function load_request_handler()
204
-    {
205
-    }
206
-
207
-
208
-    /**
209
-     *    set_definitions
210
-     *
211
-     * @return    void
212
-     * @throws EE_Error
213
-     */
214
-    public static function set_definitions()
215
-    {
216
-        if (defined('SPCO_BASE_PATH')) {
217
-            return;
218
-        }
219
-        define(
220
-            'SPCO_BASE_PATH',
221
-            rtrim(str_replace(array('\\', '/'), '/', plugin_dir_path(__FILE__)), '/') . '/'
222
-        );
223
-        define('SPCO_CSS_URL', plugin_dir_url(__FILE__) . 'css/');
224
-        define('SPCO_IMG_URL', plugin_dir_url(__FILE__) . 'img/');
225
-        define('SPCO_JS_URL', plugin_dir_url(__FILE__) . 'js/');
226
-        define('SPCO_INC_PATH', SPCO_BASE_PATH . 'inc/');
227
-        define('SPCO_REG_STEPS_PATH', SPCO_BASE_PATH . 'reg_steps/');
228
-        define('SPCO_TEMPLATES_PATH', SPCO_BASE_PATH . 'templates/');
229
-        EEH_Autoloader::register_autoloaders_for_each_file_in_folder(SPCO_BASE_PATH, true);
230
-        EE_Registry::$i18n_js_strings['registration_expiration_notice'] = EED_Single_Page_Checkout::getRegistrationExpirationNotice(
231
-        );
232
-    }
233
-
234
-
235
-    /**
236
-     * load_reg_steps
237
-     * loads and instantiates each reg step based on the EE_Registry::instance()->CFG->registration->reg_steps array
238
-     *
239
-     * @throws EE_Error
240
-     */
241
-    public static function load_reg_steps()
242
-    {
243
-        static $reg_steps_loaded = false;
244
-        if ($reg_steps_loaded) {
245
-            return;
246
-        }
247
-        // filter list of reg_steps
248
-        $reg_steps_to_load = (array) apply_filters(
249
-            'AHEE__SPCO__load_reg_steps__reg_steps_to_load',
250
-            EED_Single_Page_Checkout::get_reg_steps()
251
-        );
252
-        // sort by key (order)
253
-        ksort($reg_steps_to_load);
254
-        // loop through folders
255
-        foreach ($reg_steps_to_load as $order => $reg_step) {
256
-            // we need a
257
-            if (isset($reg_step['file_path'], $reg_step['class_name'], $reg_step['slug'])) {
258
-                // copy over to the reg_steps_array
259
-                EED_Single_Page_Checkout::$_reg_steps_array[ $order ] = $reg_step;
260
-                // register custom key route for each reg step
261
-                // ie: step=>"slug" - this is the entire reason we load the reg steps array now
262
-                EE_Config::register_route(
263
-                    $reg_step['slug'],
264
-                    'EED_Single_Page_Checkout',
265
-                    'run',
266
-                    'step'
267
-                );
268
-                // add AJAX or other hooks
269
-                if (isset($reg_step['has_hooks']) && $reg_step['has_hooks']) {
270
-                    // setup autoloaders if necessary
271
-                    if (! class_exists($reg_step['class_name'])) {
272
-                        EEH_Autoloader::register_autoloaders_for_each_file_in_folder(
273
-                            $reg_step['file_path'],
274
-                            true
275
-                        );
276
-                    }
277
-                    if (is_callable($reg_step['class_name'], 'set_hooks')) {
278
-                        call_user_func(array($reg_step['class_name'], 'set_hooks'));
279
-                    }
280
-                }
281
-            }
282
-        }
283
-        $reg_steps_loaded = true;
284
-    }
285
-
286
-
287
-    /**
288
-     *    get_reg_steps
289
-     *
290
-     * @return    array
291
-     */
292
-    public static function get_reg_steps()
293
-    {
294
-        $reg_steps = EE_Registry::instance()->CFG->registration->reg_steps;
295
-        if (empty($reg_steps)) {
296
-            $reg_steps = array(
297
-                10  => array(
298
-                    'file_path'  => SPCO_REG_STEPS_PATH . 'attendee_information',
299
-                    'class_name' => 'EE_SPCO_Reg_Step_Attendee_Information',
300
-                    'slug'       => 'attendee_information',
301
-                    'has_hooks'  => false,
302
-                ),
303
-                30  => array(
304
-                    'file_path'  => SPCO_REG_STEPS_PATH . 'payment_options',
305
-                    'class_name' => 'EE_SPCO_Reg_Step_Payment_Options',
306
-                    'slug'       => 'payment_options',
307
-                    'has_hooks'  => true,
308
-                ),
309
-                999 => array(
310
-                    'file_path'  => SPCO_REG_STEPS_PATH . 'finalize_registration',
311
-                    'class_name' => 'EE_SPCO_Reg_Step_Finalize_Registration',
312
-                    'slug'       => 'finalize_registration',
313
-                    'has_hooks'  => false,
314
-                ),
315
-            );
316
-        }
317
-        return $reg_steps;
318
-    }
319
-
320
-
321
-    /**
322
-     *    registration_checkout_for_admin
323
-     *
324
-     * @return    string
325
-     * @throws EE_Error
326
-     * @throws ReflectionException
327
-     */
328
-    public static function registration_checkout_for_admin()
329
-    {
330
-        $request = EED_Single_Page_Checkout::getRequest();
331
-        $request->setRequestParam('step', 'attendee_information');
332
-        $request->setRequestParam('action', 'display_spco_reg_step');
333
-        $request->setRequestParam('process_form_submission', false);
334
-        EED_Single_Page_Checkout::instance()->_initialize();
335
-        EED_Single_Page_Checkout::instance()->_display_spco_reg_form();
336
-        return EED_Single_Page_Checkout::getResponse()->getOutput();
337
-    }
338
-
339
-
340
-    /**
341
-     * process_registration_from_admin
342
-     *
343
-     * @return EE_Transaction
344
-     * @throws EE_Error
345
-     * @throws ReflectionException
346
-     */
347
-    public static function process_registration_from_admin()
348
-    {
349
-        $request = EED_Single_Page_Checkout::getRequest();
350
-        $request->setRequestParam('step', 'attendee_information');
351
-        $request->setRequestParam('action', 'process_reg_step');
352
-        $request->setRequestParam('process_form_submission', true);
353
-        EED_Single_Page_Checkout::instance()->_initialize();
354
-        if (EED_Single_Page_Checkout::instance()->checkout->current_step->completed()) {
355
-            $final_reg_step = end(EED_Single_Page_Checkout::instance()->checkout->reg_steps);
356
-            if ($final_reg_step instanceof EE_SPCO_Reg_Step_Finalize_Registration) {
357
-                EED_Single_Page_Checkout::instance()->checkout->set_reg_step_initiated($final_reg_step);
358
-                if ($final_reg_step->process_reg_step()) {
359
-                    $final_reg_step->set_completed();
360
-                    EED_Single_Page_Checkout::instance()->checkout->update_txn_reg_steps_array();
361
-                    return EED_Single_Page_Checkout::instance()->checkout->transaction;
362
-                }
363
-            }
364
-        }
365
-        return null;
366
-    }
367
-
368
-
369
-    /**
370
-     *    run
371
-     *
372
-     * @param WP_Query $WP
373
-     * @return    void
374
-     */
375
-    public function run($WP)
376
-    {
377
-        if (
378
-            $WP instanceof WP_Query
379
-            && $WP->is_main_query()
380
-            && apply_filters('FHEE__EED_Single_Page_Checkout__run', true)
381
-            && $this->_is_reg_checkout()
382
-        ) {
383
-            $this->_initialize();
384
-        }
385
-    }
386
-
387
-
388
-    /**
389
-     * determines whether current url matches reg page url
390
-     *
391
-     * @return bool
392
-     */
393
-    protected function _is_reg_checkout()
394
-    {
395
-        // get current permalink for reg page without any extra query args
396
-        $reg_page_url = get_permalink(EE_Config::instance()->core->reg_page_id);
397
-        // get request URI for current request, but without the scheme or host
398
-        $current_request_uri = EEH_URL::filter_input_server_url();
399
-        $current_request_uri = html_entity_decode($current_request_uri);
400
-        // get array of query args from the current request URI
401
-        $query_args = EEH_URL::get_query_string($current_request_uri);
402
-        // grab page id if it is set
403
-        $page_id = isset($query_args['page_id']) ? absint($query_args['page_id']) : 0;
404
-        // and remove the page id from the query args (we will re-add it later)
405
-        unset($query_args['page_id']);
406
-        // now strip all query args from current request URI
407
-        $current_request_uri = remove_query_arg(array_keys($query_args), $current_request_uri);
408
-        // and re-add the page id if it was set
409
-        if ($page_id) {
410
-            $current_request_uri = add_query_arg('page_id', $page_id, $current_request_uri);
411
-        }
412
-        // remove slashes and ?
413
-        $current_request_uri = trim($current_request_uri, '?/');
414
-        // is current request URI part of the known full reg page URL ?
415
-        return ! empty($current_request_uri) && strpos($reg_page_url, $current_request_uri) !== false;
416
-    }
417
-
418
-
419
-    /**
420
-     * @param WP_Query $wp_query
421
-     * @return    void
422
-     * @throws EE_Error
423
-     * @throws ReflectionException
424
-     */
425
-    public static function init($wp_query)
426
-    {
427
-        EED_Single_Page_Checkout::instance()->run($wp_query);
428
-    }
429
-
430
-
431
-    /**
432
-     *    _initialize - initial module setup
433
-     *
434
-     * @return    void
435
-     */
436
-    private function _initialize()
437
-    {
438
-        // ensure SPCO doesn't run twice
439
-        if (EED_Single_Page_Checkout::$_initialized) {
440
-            return;
441
-        }
442
-        try {
443
-            $this->request = EED_Single_Page_Checkout::getRequest();
444
-            EED_Single_Page_Checkout::load_reg_steps();
445
-            $this->_verify_session();
446
-            // setup the EE_Checkout object
447
-            $this->checkout = $this->_initialize_checkout();
448
-            // filter checkout
449
-            $this->checkout = apply_filters('FHEE__EED_Single_Page_Checkout___initialize__checkout', $this->checkout);
450
-            // get the $_GET
451
-            $this->_get_request_vars();
452
-            if ($this->_block_bots()) {
453
-                return;
454
-            }
455
-            // filter continue_reg
456
-            $this->checkout->continue_reg = apply_filters(
457
-                'FHEE__EED_Single_Page_Checkout__init___continue_reg',
458
-                true,
459
-                $this->checkout
460
-            );
461
-            // load the reg steps array
462
-            if (! $this->_load_and_instantiate_reg_steps()) {
463
-                EED_Single_Page_Checkout::$_initialized = true;
464
-                return;
465
-            }
466
-            // set the current step
467
-            $this->checkout->set_current_step($this->checkout->step);
468
-            // and the next step
469
-            $this->checkout->set_next_step();
470
-            // verify that everything has been setup correctly
471
-            if (! ($this->_verify_transaction_and_get_registrations() && $this->_final_verifications())) {
472
-                EED_Single_Page_Checkout::$_initialized = true;
473
-                return;
474
-            }
475
-            // lock the transaction
476
-            $this->checkout->transaction->lock();
477
-            // make sure all of our cached objects are added to their respective model entity mappers
478
-            $this->checkout->refresh_all_entities();
479
-            // set amount owing
480
-            $this->checkout->amount_owing = $this->checkout->transaction->remaining();
481
-            // initialize each reg step, which gives them the chance to potentially alter the process
482
-            $this->_initialize_reg_steps();
483
-            // DEBUG LOG
484
-            // $this->checkout->log( __CLASS__, __FUNCTION__, __LINE__ );
485
-            // get reg form
486
-            if (! $this->_check_form_submission()) {
487
-                EED_Single_Page_Checkout::$_initialized = true;
488
-                return;
489
-            }
490
-            // checkout the action!!!
491
-            $this->_process_form_action();
492
-            // add some style and make it dance
493
-            $this->add_styles_and_scripts($this);
494
-            // kk... SPCO has successfully run
495
-            EED_Single_Page_Checkout::$_initialized = true;
496
-            // set no cache headers and constants
497
-            EE_System::do_not_cache();
498
-            // add anchor
499
-            add_action('loop_start', array($this, 'set_checkout_anchor'), 1);
500
-            // remove transaction lock
501
-            add_action('shutdown', array($this, 'unlock_transaction'), 1);
502
-        } catch (Exception $e) {
503
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
504
-        }
505
-    }
506
-
507
-
508
-    /**
509
-     *    _verify_session
510
-     * checks that the session is valid and not expired
511
-     *
512
-     * @throws EE_Error
513
-     * @throws ReflectionException
514
-     */
515
-    private function _verify_session()
516
-    {
517
-        if (! EE_Registry::instance()->SSN instanceof EE_Session) {
518
-            throw new EE_Error(esc_html__('The EE_Session class could not be loaded.', 'event_espresso'));
519
-        }
520
-        $clear_session_requested = $this->request->getRequestParam('clear_session', false, 'bool');
521
-        // is session still valid ?
522
-        if (
523
-            $clear_session_requested
524
-            || (
525
-                EE_Registry::instance()->SSN->expired()
526
-                && $this->request->getRequestParam('e_reg_url_link') === ''
527
-            )
528
-        ) {
529
-            $this->checkout = new EE_Checkout();
530
-            EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
531
-            // EE_Registry::instance()->SSN->reset_cart();
532
-            // EE_Registry::instance()->SSN->reset_checkout();
533
-            // EE_Registry::instance()->SSN->reset_transaction();
534
-            if (! $clear_session_requested) {
535
-                EE_Error::add_attention(
536
-                    EE_Registry::$i18n_js_strings['registration_expiration_notice'],
537
-                    __FILE__,
538
-                    __FUNCTION__,
539
-                    __LINE__
540
-                );
541
-            }
542
-            // EE_Registry::instance()->SSN->reset_expired();
543
-        }
544
-    }
545
-
546
-
547
-    /**
548
-     *    _initialize_checkout
549
-     * loads and instantiates EE_Checkout
550
-     *
551
-     * @return EE_Checkout
552
-     * @throws EE_Error
553
-     * @throws ReflectionException
554
-     */
555
-    private function _initialize_checkout()
556
-    {
557
-        // look in session for existing checkout
558
-        /** @type EE_Checkout $checkout */
559
-        $checkout = EE_Registry::instance()->SSN->checkout();
560
-        // verify
561
-        if (! $checkout instanceof EE_Checkout) {
562
-            // instantiate EE_Checkout object for handling the properties of the current checkout process
563
-            $checkout = EE_Registry::instance()->load_file(
564
-                SPCO_INC_PATH,
565
-                'EE_Checkout',
566
-                'class',
567
-                array(),
568
-                false
569
-            );
570
-        } else {
571
-            if ($checkout->current_step->is_final_step() && $checkout->exit_spco() === true) {
572
-                $this->unlock_transaction();
573
-                wp_safe_redirect($checkout->redirect_url);
574
-                exit();
575
-            }
576
-        }
577
-        $checkout = apply_filters('FHEE__EED_Single_Page_Checkout___initialize_checkout__checkout', $checkout);
578
-        // verify again
579
-        if (! $checkout instanceof EE_Checkout) {
580
-            throw new EE_Error(esc_html__('The EE_Checkout class could not be loaded.', 'event_espresso'));
581
-        }
582
-        // reset anything that needs a clean slate for each request
583
-        $checkout->reset_for_current_request();
584
-        return $checkout;
585
-    }
586
-
587
-
588
-    /**
589
-     *    _get_request_vars
590
-     *
591
-     * @return    void
592
-     */
593
-    private function _get_request_vars()
594
-    {
595
-        // make sure this request is marked as belonging to EE
596
-        /** @var CurrentPage $current_page */
597
-        $current_page = LoaderFactory::getLoader()->getShared(CurrentPage::class);
598
-        $current_page->setEspressoPage(true);
599
-        // which step is being requested ?
600
-        $this->checkout->step = $this->request->getRequestParam('step', $this->_get_first_step());
601
-        // which step is being edited ?
602
-        $this->checkout->edit_step = $this->request->getRequestParam('edit_step');
603
-        // and what we're doing on the current step
604
-        $this->checkout->action = $this->request->getRequestParam('action', 'display_spco_reg_step');
605
-        // timestamp
606
-        $this->checkout->uts = $this->request->getRequestParam('uts', 0, 'int');
607
-        // returning to edit ?
608
-        $this->checkout->reg_url_link = $this->request->getRequestParam('e_reg_url_link');
609
-        // add reg url link to registration query params
610
-        if ($this->checkout->reg_url_link && strpos($this->checkout->reg_url_link, '1-') !== 0) {
611
-            $this->checkout->reg_cache_where_params[0]['REG_url_link'] = $this->checkout->reg_url_link;
612
-        }
613
-        // or some other kind of revisit ?
614
-        $this->checkout->revisit = $this->request->getRequestParam('revisit', false, 'bool');
615
-        // and whether or not to generate a reg form for this request
616
-        $this->checkout->generate_reg_form = $this->request->getRequestParam('generate_reg_form', true, 'bool');
617
-        // and whether or not to process a reg form submission for this request
618
-        $this->checkout->process_form_submission = $this->request->getRequestParam(
619
-            'process_form_submission',
620
-            $this->checkout->action === 'process_reg_step',
621
-            'bool'
622
-        );
623
-        $this->checkout->process_form_submission = filter_var(
624
-            $this->checkout->action !== 'display_spco_reg_step'
625
-                ? $this->checkout->process_form_submission
626
-                : false,
627
-            FILTER_VALIDATE_BOOLEAN
628
-        );
629
-        // $this->_display_request_vars();
630
-    }
631
-
632
-
633
-    /**
634
-     *  _display_request_vars
635
-     *
636
-     * @return    void
637
-     */
638
-    protected function _display_request_vars()
639
-    {
640
-        if (! WP_DEBUG) {
641
-            return;
642
-        }
643
-        EEH_Debug_Tools::printr($this->request->requestParams(), 'requestParams', __FILE__, __LINE__);
644
-        EEH_Debug_Tools::printr($this->checkout->step, '$this->checkout->step', __FILE__, __LINE__);
645
-        EEH_Debug_Tools::printr($this->checkout->edit_step, '$this->checkout->edit_step', __FILE__, __LINE__);
646
-        EEH_Debug_Tools::printr($this->checkout->action, '$this->checkout->action', __FILE__, __LINE__);
647
-        EEH_Debug_Tools::printr($this->checkout->reg_url_link, '$this->checkout->reg_url_link', __FILE__, __LINE__);
648
-        EEH_Debug_Tools::printr($this->checkout->revisit, '$this->checkout->revisit', __FILE__, __LINE__);
649
-        EEH_Debug_Tools::printr(
650
-            $this->checkout->generate_reg_form,
651
-            '$this->checkout->generate_reg_form',
652
-            __FILE__,
653
-            __LINE__
654
-        );
655
-        EEH_Debug_Tools::printr(
656
-            $this->checkout->process_form_submission,
657
-            '$this->checkout->process_form_submission',
658
-            __FILE__,
659
-            __LINE__
660
-        );
661
-    }
662
-
663
-
664
-    /**
665
-     * _block_bots
666
-     * checks that the incoming request has either of the following set:
667
-     *  a uts (unix timestamp) which indicates that the request was redirected from the Ticket Selector
668
-     *  a REG URL Link, which indicates that the request is a return visit to SPCO for a valid TXN
669
-     * so if you're not coming from the Ticket Selector nor returning for a valid IP...
670
-     * then where you coming from man?
671
-     *
672
-     * @return boolean
673
-     */
674
-    private function _block_bots()
675
-    {
676
-        $invalid_checkout_access = EED_Invalid_Checkout_Access::getInvalidCheckoutAccess();
677
-        if ($invalid_checkout_access->checkoutAccessIsInvalid($this->checkout)) {
678
-            return true;
679
-        }
680
-        return false;
681
-    }
682
-
683
-
684
-    /**
685
-     *    _get_first_step
686
-     *  gets slug for first step in $_reg_steps_array
687
-     *
688
-     * @return    string
689
-     */
690
-    private function _get_first_step()
691
-    {
692
-        $first_step = reset(EED_Single_Page_Checkout::$_reg_steps_array);
693
-        return isset($first_step['slug']) ? $first_step['slug'] : 'attendee_information';
694
-    }
695
-
696
-
697
-    /**
698
-     * instantiates each reg step based on the loaded reg_steps array
699
-     *
700
-     * @return    bool
701
-     * @throws EE_Error
702
-     * @throws InvalidArgumentException
703
-     * @throws InvalidDataTypeException
704
-     * @throws InvalidInterfaceException
705
-     * @throws ReflectionException
706
-     */
707
-    private function _load_and_instantiate_reg_steps()
708
-    {
709
-        do_action('AHEE__Single_Page_Checkout___load_and_instantiate_reg_steps__start', $this->checkout);
710
-        // have reg_steps already been instantiated ?
711
-        if (
712
-            empty($this->checkout->reg_steps)
713
-            || apply_filters('FHEE__Single_Page_Checkout__load_reg_steps__reload_reg_steps', false, $this->checkout)
714
-        ) {
715
-            // if not, then loop through raw reg steps array
716
-            foreach (EED_Single_Page_Checkout::$_reg_steps_array as $order => $reg_step) {
717
-                if (! $this->_load_and_instantiate_reg_step($reg_step, $order)) {
718
-                    return false;
719
-                }
720
-            }
721
-            if (isset($this->checkout->reg_steps['registration_confirmation'])) {
722
-                // skip the registration_confirmation page ?
723
-                if (EE_Registry::instance()->CFG->registration->skip_reg_confirmation) {
724
-                    // just remove it from the reg steps array
725
-                    $this->checkout->remove_reg_step('registration_confirmation', false);
726
-                } elseif (
727
-                    EE_Registry::instance()->CFG->registration->reg_confirmation_last
728
-                ) {
729
-                    // set the order to something big like 100
730
-                    $this->checkout->set_reg_step_order('registration_confirmation');
731
-                }
732
-            }
733
-            // filter the array for good luck
734
-            $this->checkout->reg_steps = apply_filters(
735
-                'FHEE__Single_Page_Checkout__load_reg_steps__reg_steps',
736
-                $this->checkout->reg_steps
737
-            );
738
-            // finally re-sort based on the reg step class order properties
739
-            $this->checkout->sort_reg_steps();
740
-        } else {
741
-            foreach ($this->checkout->reg_steps as $reg_step) {
742
-                // set all current step stati to FALSE
743
-                $reg_step->set_is_current_step(false);
744
-            }
745
-        }
746
-        if (empty($this->checkout->reg_steps)) {
747
-            EE_Error::add_error(
748
-                esc_html__('No Reg Steps were loaded..', 'event_espresso'),
749
-                __FILE__,
750
-                __FUNCTION__,
751
-                __LINE__
752
-            );
753
-            return false;
754
-        }
755
-        // make reg step details available to JS
756
-        $this->checkout->set_reg_step_JSON_info();
757
-        return true;
758
-    }
759
-
760
-
761
-    /**
762
-     *     _load_and_instantiate_reg_step
763
-     *
764
-     * @param array $reg_step
765
-     * @param int   $order
766
-     * @return bool
767
-     * @throws EE_Error
768
-     * @throws ReflectionException
769
-     */
770
-    private function _load_and_instantiate_reg_step($reg_step = array(), $order = 0)
771
-    {
772
-        // we need a file_path, class_name, and slug to add a reg step
773
-        if (isset($reg_step['file_path'], $reg_step['class_name'], $reg_step['slug'])) {
774
-            // if editing a specific step, but this is NOT that step... (and it's not the 'finalize_registration' step)
775
-            if (
776
-                $this->checkout->reg_url_link
777
-                && $this->checkout->step !== $reg_step['slug']
778
-                && $reg_step['slug'] !== 'finalize_registration'
779
-                // normally at this point we would NOT load the reg step, but this filter can change that
780
-                && apply_filters(
781
-                    'FHEE__Single_Page_Checkout___load_and_instantiate_reg_step__bypass_reg_step',
782
-                    true,
783
-                    $reg_step,
784
-                    $this->checkout
785
-                )
786
-            ) {
787
-                return true;
788
-            }
789
-
790
-            // instantiate step class using file path and class name
791
-            $reg_step_obj = EE_Registry::instance()->load_file(
792
-                $reg_step['file_path'],
793
-                $reg_step['class_name'],
794
-                'class',
795
-                [$this->checkout],
796
-                false
797
-            );
798
-            // did we gets the goods ?
799
-            if ($reg_step_obj instanceof EE_SPCO_Reg_Step) {
800
-                // set reg step order based on config
801
-                $reg_step_obj->set_order($order);
802
-                // add instantiated reg step object to the master reg steps array
803
-                $this->checkout->add_reg_step($reg_step_obj);
804
-            } else {
805
-                EE_Error::add_error(
806
-                    esc_html__('The current step could not be set.', 'event_espresso'),
807
-                    __FILE__,
808
-                    __FUNCTION__,
809
-                    __LINE__
810
-                );
811
-                return false;
812
-            }
813
-        } else {
814
-            if (WP_DEBUG) {
815
-                EE_Error::add_error(
816
-                    sprintf(
817
-                        esc_html__(
818
-                            'A registration step could not be loaded. One or more of the following data points is invalid:%4$s%5$sFile Path: %1$s%6$s%5$sClass Name: %2$s%6$s%5$sSlug: %3$s%6$s%7$s',
819
-                            'event_espresso'
820
-                        ),
821
-                        isset($reg_step['file_path']) ? $reg_step['file_path'] : '',
822
-                        isset($reg_step['class_name']) ? $reg_step['class_name'] : '',
823
-                        isset($reg_step['slug']) ? $reg_step['slug'] : '',
824
-                        '<ul>',
825
-                        '<li>',
826
-                        '</li>',
827
-                        '</ul>'
828
-                    ),
829
-                    __FILE__,
830
-                    __FUNCTION__,
831
-                    __LINE__
832
-                );
833
-            }
834
-            return false;
835
-        }
836
-        return true;
837
-    }
838
-
839
-
840
-    /**
841
-     * _verify_transaction_and_get_registrations
842
-     *
843
-     * @return bool
844
-     * @throws EE_Error
845
-     * @throws ReflectionException
846
-     */
847
-    private function _verify_transaction_and_get_registrations()
848
-    {
849
-        // was there already a valid transaction in the checkout from the session ?
850
-        if (! $this->checkout->transaction instanceof EE_Transaction) {
851
-            // get transaction from db or session
852
-            $this->checkout->transaction = $this->checkout->reg_url_link && ! is_admin()
853
-                ? $this->_get_transaction_and_cart_for_previous_visit()
854
-                : $this->_get_cart_for_current_session_and_setup_new_transaction();
855
-            if (! $this->checkout->transaction instanceof EE_Transaction) {
856
-                EE_Error::add_error(
857
-                    esc_html__(
858
-                        'Your Registration and Transaction information could not be retrieved from the db.',
859
-                        'event_espresso'
860
-                    ),
861
-                    __FILE__,
862
-                    __FUNCTION__,
863
-                    __LINE__
864
-                );
865
-                $this->checkout->transaction = EE_Transaction::new_instance();
866
-                // add some style and make it dance
867
-                $this->add_styles_and_scripts($this);
868
-                EED_Single_Page_Checkout::$_initialized = true;
869
-                return false;
870
-            }
871
-            // and the registrations for the transaction
872
-            $this->_get_registrations($this->checkout->transaction);
873
-        }
874
-        return true;
875
-    }
876
-
877
-
878
-    /**
879
-     * _get_transaction_and_cart_for_previous_visit
880
-     *
881
-     * @return EE_Transaction|null
882
-     * @throws EE_Error
883
-     * @throws ReflectionException
884
-     */
885
-    private function _get_transaction_and_cart_for_previous_visit()
886
-    {
887
-        /** @var $TXN_model EEM_Transaction */
888
-        $TXN_model = EE_Registry::instance()->load_model('Transaction');
889
-        // because the reg_url_link is present in the request,
890
-        // this is a return visit to SPCO, so we'll get the transaction data from the db
891
-        $transaction = $TXN_model->get_transaction_from_reg_url_link($this->checkout->reg_url_link);
892
-        // verify transaction
893
-        if ($transaction instanceof EE_Transaction) {
894
-            // and get the cart that was used for that transaction
895
-            $this->checkout->cart = $this->_get_cart_for_transaction($transaction);
896
-            return $transaction;
897
-        }
898
-        EE_Error::add_error(
899
-            esc_html__('Your Registration and Transaction information could not be retrieved from the db.', 'event_espresso'),
900
-            __FILE__,
901
-            __FUNCTION__,
902
-            __LINE__
903
-        );
904
-        return null;
905
-    }
906
-
907
-
908
-    /**
909
-     * _get_cart_for_transaction
910
-     *
911
-     * @param EE_Transaction $transaction
912
-     * @return EE_Cart
913
-     */
914
-    private function _get_cart_for_transaction($transaction)
915
-    {
916
-        return $this->checkout->get_cart_for_transaction($transaction);
917
-    }
918
-
919
-
920
-    /**
921
-     * get_cart_for_transaction
922
-     *
923
-     * @param EE_Transaction $transaction
924
-     * @return EE_Cart
925
-     */
926
-    public function get_cart_for_transaction(EE_Transaction $transaction)
927
-    {
928
-        return $this->checkout->get_cart_for_transaction($transaction);
929
-    }
930
-
931
-
932
-    /**
933
-     * _get_transaction_and_cart_for_current_session
934
-     *    generates a new EE_Transaction object and adds it to the $_transaction property.
935
-     *
936
-     * @return EE_Transaction
937
-     * @throws EE_Error
938
-     * @throws ReflectionException
939
-     */
940
-    private function _get_cart_for_current_session_and_setup_new_transaction()
941
-    {
942
-        //  if there's no transaction, then this is the FIRST visit to SPCO
943
-        // so load up the cart ( passing nothing for the TXN because it doesn't exist yet )
944
-        $this->checkout->cart = $this->_get_cart_for_transaction(null);
945
-        // and then create a new transaction
946
-        $transaction = $this->_initialize_transaction();
947
-        // verify transaction
948
-        if ($transaction instanceof EE_Transaction) {
949
-            // save it so that we have an ID for other objects to use
950
-            $transaction->save();
951
-            // and save TXN data to the cart
952
-            $this->checkout->cart->get_grand_total()->save_this_and_descendants_to_txn($transaction->ID());
953
-        } else {
954
-            EE_Error::add_error(
955
-                esc_html__('A Valid Transaction could not be initialized.', 'event_espresso'),
956
-                __FILE__,
957
-                __FUNCTION__,
958
-                __LINE__
959
-            );
960
-        }
961
-        return $transaction;
962
-    }
963
-
964
-
965
-    /**
966
-     *    generates a new EE_Transaction object and adds it to the $_transaction property.
967
-     *
968
-     * @return EE_Transaction|null
969
-     */
970
-    private function _initialize_transaction()
971
-    {
972
-        try {
973
-            // ensure cart totals have been calculated
974
-            $this->checkout->cart->get_grand_total()->recalculate_total_including_taxes();
975
-            // grab the cart grand total
976
-            $cart_total = $this->checkout->cart->get_cart_grand_total();
977
-            // create new TXN
978
-            $transaction = EE_Transaction::new_instance(
979
-                array(
980
-                    'TXN_reg_steps' => $this->checkout->initialize_txn_reg_steps_array(),
981
-                    'TXN_total'     => $cart_total > 0 ? $cart_total : 0,
982
-                    'TXN_paid'      => 0,
983
-                    'STS_ID'        => EEM_Transaction::failed_status_code,
984
-                )
985
-            );
986
-            // save it so that we have an ID for other objects to use
987
-            $transaction->save();
988
-            // set cron job for following up on TXNs after their session has expired
989
-            EE_Cron_Tasks::schedule_expired_transaction_check(
990
-                EE_Registry::instance()->SSN->expiration() + 1,
991
-                $transaction->ID()
992
-            );
993
-            return $transaction;
994
-        } catch (Exception $e) {
995
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
996
-        }
997
-        return null;
998
-    }
999
-
1000
-
1001
-    /**
1002
-     * _get_registrations
1003
-     *
1004
-     * @param EE_Transaction $transaction
1005
-     * @return void
1006
-     * @throws EE_Error
1007
-     * @throws ReflectionException
1008
-     */
1009
-    private function _get_registrations(EE_Transaction $transaction)
1010
-    {
1011
-        // first step: grab the registrants  { : o
1012
-        $registrations = $transaction->registrations($this->checkout->reg_cache_where_params);
1013
-        $this->checkout->total_ticket_count = count($registrations);
1014
-        // verify registrations have been set
1015
-        if (empty($registrations)) {
1016
-            // if no cached registrations, then check the db
1017
-            $registrations = $transaction->registrations($this->checkout->reg_cache_where_params);
1018
-            // still nothing ? well as long as this isn't a revisit
1019
-            if (empty($registrations) && ! $this->checkout->revisit) {
1020
-                // generate new registrations from scratch
1021
-                $registrations = $this->_initialize_registrations($transaction);
1022
-            }
1023
-        }
1024
-        // sort by their original registration order
1025
-        usort($registrations, array('EED_Single_Page_Checkout', 'sort_registrations_by_REG_count'));
1026
-        // then loop thru the array
1027
-        foreach ($registrations as $registration) {
1028
-            // verify each registration
1029
-            if ($registration instanceof EE_Registration) {
1030
-                // we display all attendee info for the primary registrant
1031
-                if (
1032
-                    $this->checkout->reg_url_link === $registration->reg_url_link()
1033
-                    && $registration->is_primary_registrant()
1034
-                ) {
1035
-                    $this->checkout->primary_revisit = true;
1036
-                    break;
1037
-                }
1038
-                if ($this->checkout->revisit && $this->checkout->reg_url_link !== $registration->reg_url_link()) {
1039
-                    // but hide info if it doesn't belong to you
1040
-                    $transaction->clear_cache('Registration', $registration->ID());
1041
-                    $this->checkout->total_ticket_count--;
1042
-                }
1043
-                $this->checkout->set_reg_status_updated($registration->ID(), false);
1044
-            }
1045
-        }
1046
-    }
1047
-
1048
-
1049
-    /**
1050
-     *    adds related EE_Registration objects for each ticket in the cart to the current EE_Transaction object
1051
-     *
1052
-     * @param EE_Transaction $transaction
1053
-     * @return    array
1054
-     * @throws EE_Error
1055
-     * @throws ReflectionException
1056
-     */
1057
-    private function _initialize_registrations(EE_Transaction $transaction)
1058
-    {
1059
-        $att_nmbr = 0;
1060
-        $registrations = array();
1061
-        if ($transaction instanceof EE_Transaction) {
1062
-            /** @type EE_Registration_Processor $registration_processor */
1063
-            $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
1064
-            $this->checkout->total_ticket_count = $this->checkout->cart->all_ticket_quantity_count();
1065
-            // now let's add the cart items to the $transaction
1066
-            foreach ($this->checkout->cart->get_tickets() as $line_item) {
1067
-                // do the following for each ticket of this type they selected
1068
-                for ($x = 1; $x <= $line_item->quantity(); $x++) {
1069
-                    $att_nmbr++;
1070
-                    /** @var EventEspresso\core\services\commands\registration\CreateRegistrationCommand $CreateRegistrationCommand */
1071
-                    $CreateRegistrationCommand = EE_Registry::instance()->create(
1072
-                        'EventEspresso\core\services\commands\registration\CreateRegistrationCommand',
1073
-                        array(
1074
-                            $transaction,
1075
-                            $line_item,
1076
-                            $att_nmbr,
1077
-                            $this->checkout->total_ticket_count,
1078
-                        )
1079
-                    );
1080
-                    // override capabilities for frontend registrations
1081
-                    if (! is_admin()) {
1082
-                        $CreateRegistrationCommand->setCapCheck(
1083
-                            new PublicCapabilities('', 'create_new_registration')
1084
-                        );
1085
-                    }
1086
-                    $registration = EE_Registry::instance()->BUS->execute($CreateRegistrationCommand);
1087
-                    if (! $registration instanceof EE_Registration) {
1088
-                        throw new InvalidEntityException($registration, 'EE_Registration');
1089
-                    }
1090
-                    $registrations[ $registration->ID() ] = $registration;
1091
-                }
1092
-            }
1093
-            $registration_processor->fix_reg_final_price_rounding_issue($transaction);
1094
-        }
1095
-        return $registrations;
1096
-    }
1097
-
1098
-
1099
-    /**
1100
-     * sorts registrations by REG_count
1101
-     *
1102
-     * @param EE_Registration $reg_A
1103
-     * @param EE_Registration $reg_B
1104
-     * @return int
1105
-     */
1106
-    public static function sort_registrations_by_REG_count(EE_Registration $reg_A, EE_Registration $reg_B)
1107
-    {
1108
-        // this shouldn't ever happen within the same TXN, but oh well
1109
-        if ($reg_A->count() === $reg_B->count()) {
1110
-            return 0;
1111
-        }
1112
-        return ($reg_A->count() > $reg_B->count()) ? 1 : -1;
1113
-    }
1114
-
1115
-
1116
-    /**
1117
-     *    _final_verifications
1118
-     * just makes sure that everything is set up correctly before proceeding
1119
-     *
1120
-     * @return    bool
1121
-     * @throws EE_Error
1122
-     * @throws ReflectionException
1123
-     */
1124
-    private function _final_verifications()
1125
-    {
1126
-        // filter checkout
1127
-        $this->checkout = apply_filters(
1128
-            'FHEE__EED_Single_Page_Checkout___final_verifications__checkout',
1129
-            $this->checkout
1130
-        );
1131
-        // verify that current step is still set correctly
1132
-        if (! $this->checkout->current_step instanceof EE_SPCO_Reg_Step) {
1133
-            EE_Error::add_error(
1134
-                esc_html__(
1135
-                    'We\'re sorry but the registration process can not proceed because one or more registration steps were not setup correctly. Please refresh the page and try again or contact support.',
1136
-                    'event_espresso'
1137
-                ),
1138
-                __FILE__,
1139
-                __FUNCTION__,
1140
-                __LINE__
1141
-            );
1142
-            return false;
1143
-        }
1144
-        // if returning to SPCO, then verify that primary registrant is set
1145
-        if (! empty($this->checkout->reg_url_link)) {
1146
-            $valid_registrant = $this->checkout->transaction->primary_registration();
1147
-            if (! $valid_registrant instanceof EE_Registration) {
1148
-                EE_Error::add_error(
1149
-                    esc_html__(
1150
-                        'We\'re sorry but there appears to be an error with the "reg_url_link" or the primary registrant for this transaction. Please refresh the page and try again or contact support.',
1151
-                        'event_espresso'
1152
-                    ),
1153
-                    __FILE__,
1154
-                    __FUNCTION__,
1155
-                    __LINE__
1156
-                );
1157
-                return false;
1158
-            }
1159
-            $valid_registrant = null;
1160
-            foreach ($this->checkout->transaction->registrations($this->checkout->reg_cache_where_params) as $registration) {
1161
-                if (
1162
-                    $registration instanceof EE_Registration
1163
-                    && $registration->reg_url_link() === $this->checkout->reg_url_link
1164
-                ) {
1165
-                    $valid_registrant = $registration;
1166
-                }
1167
-            }
1168
-            if (! $valid_registrant instanceof EE_Registration) {
1169
-                // hmmm... maybe we have the wrong session because the user is opening multiple tabs ?
1170
-                if (EED_Single_Page_Checkout::$_checkout_verified) {
1171
-                    // clear the session, mark the checkout as unverified, and try again
1172
-                    EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
1173
-                    EED_Single_Page_Checkout::$_initialized = false;
1174
-                    EED_Single_Page_Checkout::$_checkout_verified = false;
1175
-                    $this->_initialize();
1176
-                    EE_Error::reset_notices();
1177
-                    return false;
1178
-                }
1179
-                EE_Error::add_error(
1180
-                    esc_html__(
1181
-                        'We\'re sorry but there appears to be an error with the "reg_url_link" or the transaction itself. Please refresh the page and try again or contact support.',
1182
-                        'event_espresso'
1183
-                    ),
1184
-                    __FILE__,
1185
-                    __FUNCTION__,
1186
-                    __LINE__
1187
-                );
1188
-                return false;
1189
-            }
1190
-        }
1191
-        // now that things have been kinda sufficiently verified,
1192
-        // let's add the checkout to the session so that it's available to other systems
1193
-        EE_Registry::instance()->SSN->set_checkout($this->checkout);
1194
-        return true;
1195
-    }
1196
-
1197
-
1198
-    /**
1199
-     *    _initialize_reg_steps
1200
-     * first makes sure that EE_Transaction_Processor::set_reg_step_initiated() is called as required
1201
-     * then loops thru all of the active reg steps and calls the initialize_reg_step() method
1202
-     *
1203
-     * @param bool $reinitializing
1204
-     * @throws EE_Error
1205
-     */
1206
-    private function _initialize_reg_steps($reinitializing = false)
1207
-    {
1208
-        $this->checkout->set_reg_step_initiated($this->checkout->current_step);
1209
-        // loop thru all steps to call their individual "initialize" methods and set i18n strings for JS
1210
-        foreach ($this->checkout->reg_steps as $reg_step) {
1211
-            if (! $reg_step->initialize_reg_step()) {
1212
-                // if not initialized then maybe this step is being removed...
1213
-                if (! $reinitializing && $reg_step->is_current_step()) {
1214
-                    // if it was the current step, then we need to start over here
1215
-                    $this->_initialize_reg_steps(true);
1216
-                    return;
1217
-                }
1218
-                continue;
1219
-            }
1220
-            // add css and JS for current step
1221
-            $this->add_styles_and_scripts($reg_step);
1222
-            if ($reg_step->is_current_step()) {
1223
-                // the text that appears on the reg step form submit button
1224
-                $reg_step->set_submit_button_text();
1225
-            }
1226
-        }
1227
-        // dynamically creates hook point like: AHEE__Single_Page_Checkout___initialize_reg_step__attendee_information
1228
-        do_action(
1229
-            "AHEE__Single_Page_Checkout___initialize_reg_step__{$this->checkout->current_step->slug()}",
1230
-            $this->checkout->current_step
1231
-        );
1232
-    }
1233
-
1234
-
1235
-    /**
1236
-     * _check_form_submission
1237
-     *
1238
-     * @return boolean
1239
-     * @throws EE_Error
1240
-     * @throws ReflectionException
1241
-     */
1242
-    private function _check_form_submission()
1243
-    {
1244
-        // does this request require the reg form to be generated ?
1245
-        if ($this->checkout->generate_reg_form) {
1246
-            // ever heard that song by Blue Rodeo ?
1247
-            try {
1248
-                $this->checkout->current_step->reg_form = $this->checkout->current_step->generate_reg_form();
1249
-                // if not displaying a form, then check for form submission
1250
-                if (
1251
-                    $this->checkout->process_form_submission
1252
-                    && $this->checkout->current_step->reg_form->was_submitted()
1253
-                ) {
1254
-                    // clear out any old data in case this step is being run again
1255
-                    $this->checkout->current_step->set_valid_data(array());
1256
-                    // capture submitted form data
1257
-                    $request_data = $this->request->requestParams();
1258
-                    $this->checkout->current_step->reg_form->receive_form_submission(
1259
-                        (array) apply_filters(
1260
-                            'FHEE__Single_Page_Checkout___check_form_submission__request_params',
1261
-                            $request_data,
1262
-                            $this->checkout
1263
-                        )
1264
-                    );
1265
-                    // validate submitted form data
1266
-                    if (! $this->checkout->continue_reg || ! $this->checkout->current_step->reg_form->is_valid()) {
1267
-                        // thou shall not pass !!!
1268
-                        $this->checkout->continue_reg = false;
1269
-                        // any form validation errors?
1270
-                        if ($this->checkout->current_step->reg_form->submission_error_message() !== '') {
1271
-                            EE_Error::add_error(
1272
-                                $this->checkout->current_step->reg_form->submission_error_message(),
1273
-                                __FILE__,
1274
-                                __FUNCTION__,
1275
-                                __LINE__
1276
-                            );
1277
-                        }
1278
-                        // well not really... what will happen is
1279
-                        // we'll just get redirected back to redo the current step
1280
-                        $this->go_to_next_step();
1281
-                        return false;
1282
-                    }
1283
-                }
1284
-            } catch (EE_Error $e) {
1285
-                $e->get_error();
1286
-            }
1287
-        }
1288
-        return true;
1289
-    }
1290
-
1291
-
1292
-    /**
1293
-     * _process_action
1294
-     *
1295
-     * @return void
1296
-     * @throws EE_Error
1297
-     * @throws ReflectionException
1298
-     */
1299
-    private function _process_form_action()
1300
-    {
1301
-        // what cha wanna do?
1302
-        switch ($this->checkout->action) {
1303
-            // AJAX next step reg form
1304
-            case 'display_spco_reg_step':
1305
-                $this->checkout->redirect = false;
1306
-                if ($this->request->isAjax()) {
1307
-                    $this->checkout->json_response->set_reg_step_html(
1308
-                        $this->checkout->current_step->display_reg_form()
1309
-                    );
1310
-                }
1311
-                break;
1312
-            default:
1313
-                // meh... do one of those other steps first
1314
-                if (
1315
-                    ! empty($this->checkout->action)
1316
-                    && is_callable(array($this->checkout->current_step, $this->checkout->action))
1317
-                ) {
1318
-                    // dynamically creates hook point like:
1319
-                    //   AHEE__Single_Page_Checkout__before_attendee_information__process_reg_step
1320
-                    do_action(
1321
-                        "AHEE__Single_Page_Checkout__before_{$this->checkout->current_step->slug()}__{$this->checkout->action}",
1322
-                        $this->checkout->current_step
1323
-                    );
1324
-                    $process_reg_step = apply_filters(
1325
-                        "AHEE__Single_Page_Checkout__process_reg_step__{$this->checkout->current_step->slug()}__{$this->checkout->action}",
1326
-                        true,
1327
-                        $this->checkout->current_step,
1328
-                        $this
1329
-                    );
1330
-                    // call action on current step
1331
-                    if ($process_reg_step && call_user_func([$this->checkout->current_step, $this->checkout->action])) {
1332
-                        // good registrant, you get to proceed
1333
-                        if (
1334
-                            $this->checkout->current_step->success_message() !== ''
1335
-                            && apply_filters(
1336
-                                'FHEE__Single_Page_Checkout___process_form_action__display_success',
1337
-                                false
1338
-                            )
1339
-                        ) {
1340
-                            EE_Error::add_success(
1341
-                                $this->checkout->current_step->success_message()
1342
-                                . '<br />' . $this->checkout->next_step->_instructions()
1343
-                            );
1344
-                        }
1345
-                        // pack it up, pack it in...
1346
-                        $this->_setup_redirect();
1347
-                    }
1348
-                    // dynamically creates hook point like:
1349
-                    //  AHEE__Single_Page_Checkout__after_payment_options__process_reg_step
1350
-                    do_action(
1351
-                        "AHEE__Single_Page_Checkout__after_{$this->checkout->current_step->slug()}__{$this->checkout->action}",
1352
-                        $this->checkout->current_step
1353
-                    );
1354
-                } else {
1355
-                    EE_Error::add_error(
1356
-                        sprintf(
1357
-                            esc_html__(
1358
-                                'The requested form action "%s" does not exist for the current "%s" registration step.',
1359
-                                'event_espresso'
1360
-                            ),
1361
-                            $this->checkout->action,
1362
-                            $this->checkout->current_step->name()
1363
-                        ),
1364
-                        __FILE__,
1365
-                        __FUNCTION__,
1366
-                        __LINE__
1367
-                    );
1368
-                }
1369
-            // end default
1370
-        }
1371
-        // store our progress so far
1372
-        $this->checkout->stash_transaction_and_checkout();
1373
-        // advance to the next step! If you pass GO, collect $200
1374
-        $this->go_to_next_step();
1375
-    }
1376
-
1377
-
1378
-    /**
1379
-     * @param EED_Single_Page_Checkout|EE_SPCO_Reg_Step $target an object with the method `translate_js_strings` and
1380
-     *                                                          `enqueue_styles_and_scripts`.
1381
-     * @return        void
1382
-     */
1383
-    public function add_styles_and_scripts($target)
1384
-    {
1385
-        // i18n
1386
-        $target->translate_js_strings();
1387
-        if ($this->checkout->admin_request) {
1388
-            add_action('admin_enqueue_scripts', array($target, 'enqueue_styles_and_scripts'), 10);
1389
-        } else {
1390
-            add_action('wp_enqueue_scripts', array($target, 'enqueue_styles_and_scripts'), 10);
1391
-        }
1392
-    }
1393
-
1394
-    /**
1395
-     *        translate_js_strings
1396
-     *
1397
-     * @return        void
1398
-     */
1399
-    public function translate_js_strings()
1400
-    {
1401
-        EE_Registry::$i18n_js_strings['revisit'] = $this->checkout->revisit;
1402
-        EE_Registry::$i18n_js_strings['e_reg_url_link'] = $this->checkout->reg_url_link;
1403
-        EE_Registry::$i18n_js_strings['server_error'] = esc_html__(
1404
-            'An unknown error occurred on the server while attempting to process your request. Please refresh the page and try again or contact support.',
1405
-            'event_espresso'
1406
-        );
1407
-        EE_Registry::$i18n_js_strings['invalid_json_response'] = esc_html__(
1408
-            'An invalid response was returned from the server while attempting to process your request. Please refresh the page and try again or contact support.',
1409
-            'event_espresso'
1410
-        );
1411
-        EE_Registry::$i18n_js_strings['validation_error'] = esc_html__(
1412
-            'There appears to be a problem with the form validation configuration! Please check the admin settings or contact support.',
1413
-            'event_espresso'
1414
-        );
1415
-        EE_Registry::$i18n_js_strings['invalid_payment_method'] = esc_html__(
1416
-            'There appears to be a problem with the payment method configuration! Please refresh the page and try again or contact support.',
1417
-            'event_espresso'
1418
-        );
1419
-        EE_Registry::$i18n_js_strings['reg_step_error'] = esc_html__(
1420
-            'This registration step could not be completed. Please refresh the page and try again.',
1421
-            'event_espresso'
1422
-        );
1423
-        EE_Registry::$i18n_js_strings['invalid_coupon'] = esc_html__(
1424
-            'We\'re sorry but that coupon code does not appear to be valid. If this is incorrect, please contact the site administrator.',
1425
-            'event_espresso'
1426
-        );
1427
-        EE_Registry::$i18n_js_strings['process_registration'] = sprintf(
1428
-            esc_html__(
1429
-                'Please wait while we process your registration.%sDo not refresh the page or navigate away while this is happening.%sThank you for your patience.',
1430
-                'event_espresso'
1431
-            ),
1432
-            '<br/>',
1433
-            '<br/>'
1434
-        );
1435
-        EE_Registry::$i18n_js_strings['language'] = get_bloginfo('language');
1436
-        EE_Registry::$i18n_js_strings['EESID'] = EE_Registry::instance()->SSN->id();
1437
-        EE_Registry::$i18n_js_strings['currency'] = EE_Registry::instance()->CFG->currency;
1438
-        EE_Registry::$i18n_js_strings['datepicker_yearRange'] = '-150:+20';
1439
-        EE_Registry::$i18n_js_strings['timer_years'] = esc_html__('years', 'event_espresso');
1440
-        EE_Registry::$i18n_js_strings['timer_months'] = esc_html__('months', 'event_espresso');
1441
-        EE_Registry::$i18n_js_strings['timer_weeks'] = esc_html__('weeks', 'event_espresso');
1442
-        EE_Registry::$i18n_js_strings['timer_days'] = esc_html__('days', 'event_espresso');
1443
-        EE_Registry::$i18n_js_strings['timer_hours'] = esc_html__('hours', 'event_espresso');
1444
-        EE_Registry::$i18n_js_strings['timer_minutes'] = esc_html__('minutes', 'event_espresso');
1445
-        EE_Registry::$i18n_js_strings['timer_seconds'] = esc_html__('seconds', 'event_espresso');
1446
-        EE_Registry::$i18n_js_strings['timer_year'] = esc_html__('year', 'event_espresso');
1447
-        EE_Registry::$i18n_js_strings['timer_month'] = esc_html__('month', 'event_espresso');
1448
-        EE_Registry::$i18n_js_strings['timer_week'] = esc_html__('week', 'event_espresso');
1449
-        EE_Registry::$i18n_js_strings['timer_day'] = esc_html__('day', 'event_espresso');
1450
-        EE_Registry::$i18n_js_strings['timer_hour'] = esc_html__('hour', 'event_espresso');
1451
-        EE_Registry::$i18n_js_strings['timer_minute'] = esc_html__('minute', 'event_espresso');
1452
-        EE_Registry::$i18n_js_strings['timer_second'] = esc_html__('second', 'event_espresso');
1453
-        EE_Registry::$i18n_js_strings['registration_expiration_notice'] = EED_Single_Page_Checkout::getRegistrationExpirationNotice(
1454
-        );
1455
-        EE_Registry::$i18n_js_strings['ajax_submit'] = apply_filters(
1456
-            'FHEE__Single_Page_Checkout__translate_js_strings__ajax_submit',
1457
-            true
1458
-        );
1459
-        EE_Registry::$i18n_js_strings['session_extension'] = absint(
1460
-            apply_filters('FHEE__EE_Session__extend_expiration__seconds_added', 10 * MINUTE_IN_SECONDS)
1461
-        );
1462
-        EE_Registry::$i18n_js_strings['session_expiration'] = gmdate(
1463
-            'M d, Y H:i:s',
1464
-            EE_Registry::instance()->SSN->expiration() + (get_option('gmt_offset') * HOUR_IN_SECONDS)
1465
-        );
1466
-    }
1467
-
1468
-
1469
-    /**
1470
-     *    enqueue_styles_and_scripts
1471
-     *
1472
-     * @return        void
1473
-     * @throws EE_Error
1474
-     */
1475
-    public function enqueue_styles_and_scripts()
1476
-    {
1477
-        // load css
1478
-        wp_register_style(
1479
-            'single_page_checkout',
1480
-            SPCO_CSS_URL . 'single_page_checkout.css',
1481
-            array('espresso_default'),
1482
-            EVENT_ESPRESSO_VERSION
1483
-        );
1484
-        wp_enqueue_style('single_page_checkout');
1485
-        // load JS
1486
-        wp_register_script(
1487
-            'jquery_plugin',
1488
-            EE_THIRD_PARTY_URL . 'jquery	.plugin.min.js',
1489
-            array('jquery'),
1490
-            '1.0.1',
1491
-            true
1492
-        );
1493
-        wp_register_script(
1494
-            'jquery_countdown',
1495
-            EE_THIRD_PARTY_URL . 'jquery	.countdown.min.js',
1496
-            array('jquery_plugin'),
1497
-            '2.1.0',
1498
-            true
1499
-        );
1500
-        wp_register_script(
1501
-            'single_page_checkout',
1502
-            SPCO_JS_URL . 'single_page_checkout.js',
1503
-            array('espresso_core', 'underscore', 'ee_form_section_validation'),
1504
-            EVENT_ESPRESSO_VERSION,
1505
-            true
1506
-        );
1507
-        if ($this->checkout->registration_form instanceof EE_Form_Section_Proper) {
1508
-            $this->checkout->registration_form->enqueue_js();
1509
-        }
1510
-        if ($this->checkout->current_step->reg_form instanceof EE_Form_Section_Proper) {
1511
-            $this->checkout->current_step->reg_form->enqueue_js();
1512
-        }
1513
-        wp_enqueue_script('single_page_checkout');
1514
-        if (apply_filters('FHEE__registration_page_wrapper_template__display_time_limit', false)) {
1515
-            wp_enqueue_script('jquery_countdown');
1516
-        }
1517
-        /**
1518
-         * global action hook for enqueueing styles and scripts with
1519
-         * spco calls.
1520
-         */
1521
-        do_action('AHEE__EED_Single_Page_Checkout__enqueue_styles_and_scripts', $this);
1522
-        /**
1523
-         * dynamic action hook for enqueueing styles and scripts with spco calls.
1524
-         * The hook will end up being something like:
1525
-         *      AHEE__EED_Single_Page_Checkout__enqueue_styles_and_scripts__attendee_information
1526
-         */
1527
-        do_action(
1528
-            'AHEE__EED_Single_Page_Checkout__enqueue_styles_and_scripts__' . $this->checkout->current_step->slug(),
1529
-            $this
1530
-        );
1531
-    }
1532
-
1533
-
1534
-    /**
1535
-     *    display the Registration Single Page Checkout Form
1536
-     *
1537
-     * @return    void
1538
-     * @throws EE_Error
1539
-     * @throws ReflectionException
1540
-     */
1541
-    private function _display_spco_reg_form()
1542
-    {
1543
-        // if registering via the admin, just display the reg form for the current step
1544
-        if ($this->checkout->admin_request) {
1545
-            EED_Single_Page_Checkout::getResponse()->addOutput($this->checkout->current_step->display_reg_form());
1546
-        } else {
1547
-            // add powered by EE msg
1548
-            add_action('AHEE__SPCO__reg_form_footer', array('EED_Single_Page_Checkout', 'display_registration_footer'));
1549
-            $empty_cart = count(
1550
-                $this->checkout->transaction->registrations($this->checkout->reg_cache_where_params)
1551
-            ) < 1;
1552
-            EE_Registry::$i18n_js_strings['empty_cart'] = $empty_cart;
1553
-            $cookies_not_set_msg = '';
1554
-            if ($empty_cart) {
1555
-                $cookies_not_set_msg = apply_filters(
1556
-                    'FHEE__Single_Page_Checkout__display_spco_reg_form__cookies_not_set_msg',
1557
-                    sprintf(
1558
-                        esc_html__(
1559
-                            '%1$s%3$sIt appears your browser is not currently set to accept Cookies%4$s%5$sIn order to register for events, you need to enable cookies.%7$sIf you require assistance, then click the following link to learn how to %8$senable cookies%9$s%6$s%2$s',
1560
-                            'event_espresso'
1561
-                        ),
1562
-                        '<div class="ee-attention hidden" id="ee-cookies-not-set-msg">',
1563
-                        '</div>',
1564
-                        '<h6 class="important-notice">',
1565
-                        '</h6>',
1566
-                        '<p>',
1567
-                        '</p>',
1568
-                        '<br />',
1569
-                        '<a href="https://www.whatismybrowser.com/guides/how-to-enable-cookies/" target="_blank" rel="noopener noreferrer">',
1570
-                        '</a>'
1571
-                    )
1572
-                );
1573
-            }
1574
-            $this->checkout->registration_form = new EE_Form_Section_Proper(
1575
-                array(
1576
-                    'name'            => 'single-page-checkout',
1577
-                    'html_id'         => 'ee-single-page-checkout-dv',
1578
-                    'layout_strategy' =>
1579
-                        new EE_Template_Layout(
1580
-                            array(
1581
-                                'layout_template_file' => SPCO_TEMPLATES_PATH . 'registration_page_wrapper.template.php',
1582
-                                'template_args'        => array(
1583
-                                    'empty_cart'              => $empty_cart,
1584
-                                    'revisit'                 => $this->checkout->revisit,
1585
-                                    'reg_steps'               => $this->checkout->reg_steps,
1586
-                                    'next_step'               => $this->checkout->next_step instanceof EE_SPCO_Reg_Step
1587
-                                        ? $this->checkout->next_step->slug()
1588
-                                        : '',
1589
-                                    'empty_msg'               => apply_filters(
1590
-                                        'FHEE__Single_Page_Checkout__display_spco_reg_form__empty_msg',
1591
-                                        sprintf(
1592
-                                            esc_html__(
1593
-                                                'You need to %1$sReturn to Events list%2$sselect at least one event%3$s before you can proceed with the registration process.',
1594
-                                                'event_espresso'
1595
-                                            ),
1596
-                                            '<a href="'
1597
-                                            . get_post_type_archive_link('espresso_events')
1598
-                                            . '" title="',
1599
-                                            '">',
1600
-                                            '</a>'
1601
-                                        )
1602
-                                    ),
1603
-                                    'cookies_not_set_msg'     => $cookies_not_set_msg,
1604
-                                    'registration_time_limit' => $this->checkout->get_registration_time_limit(),
1605
-                                    'session_expiration'      => gmdate(
1606
-                                        'M d, Y H:i:s',
1607
-                                        EE_Registry::instance()->SSN->expiration()
1608
-                                        + (get_option('gmt_offset') * HOUR_IN_SECONDS)
1609
-                                    ),
1610
-                                ),
1611
-                            )
1612
-                        ),
1613
-                )
1614
-            );
1615
-            // load template and add to output sent that gets filtered into the_content()
1616
-            EED_Single_Page_Checkout::getResponse()->addOutput($this->checkout->registration_form->get_html());
1617
-        }
1618
-    }
1619
-
1620
-
1621
-    /**
1622
-     *    add_extra_finalize_registration_inputs
1623
-     *
1624
-     * @param $next_step
1625
-     * @internal  param string $label
1626
-     * @return void
1627
-     */
1628
-    public function add_extra_finalize_registration_inputs($next_step)
1629
-    {
1630
-        if ($next_step === 'finalize_registration') {
1631
-            echo '<div id="spco-extra-finalize_registration-inputs-dv"></div>';
1632
-        }
1633
-    }
1634
-
1635
-
1636
-    /**
1637
-     *    display_registration_footer
1638
-     *
1639
-     * @return    string
1640
-     */
1641
-    public static function display_registration_footer()
1642
-    {
1643
-        if (
1644
-            apply_filters(
1645
-                'FHEE__EE_Front__Controller__show_reg_footer',
1646
-                EE_Registry::instance()->CFG->admin->show_reg_footer
1647
-            )
1648
-        ) {
1649
-            add_filter(
1650
-                'FHEE__EEH_Template__powered_by_event_espresso__url',
1651
-                function ($url) {
1652
-                    return apply_filters('FHEE__EE_Front_Controller__registration_footer__url', $url);
1653
-                }
1654
-            );
1655
-            echo apply_filters(
1656
-                'FHEE__EE_Front_Controller__display_registration_footer',
1657
-                EEH_Template::powered_by_event_espresso(
1658
-                    '',
1659
-                    'espresso-registration-footer-dv',
1660
-                    array('utm_content' => 'registration_checkout')
1661
-                )
1662
-            );
1663
-        }
1664
-        return '';
1665
-    }
1666
-
1667
-
1668
-    /**
1669
-     *    unlock_transaction
1670
-     *
1671
-     * @return    void
1672
-     * @throws EE_Error
1673
-     * @throws ReflectionException
1674
-     */
1675
-    public function unlock_transaction()
1676
-    {
1677
-        if ($this->checkout->transaction instanceof EE_Transaction) {
1678
-            $this->checkout->transaction->unlock();
1679
-        }
1680
-    }
1681
-
1682
-
1683
-    /**
1684
-     *        _setup_redirect
1685
-     *
1686
-     * @return void
1687
-     */
1688
-    private function _setup_redirect()
1689
-    {
1690
-        if ($this->checkout->continue_reg && $this->checkout->next_step instanceof EE_SPCO_Reg_Step) {
1691
-            $this->checkout->redirect = true;
1692
-            if (empty($this->checkout->redirect_url)) {
1693
-                $this->checkout->redirect_url = $this->checkout->next_step->reg_step_url();
1694
-            }
1695
-            $this->checkout->redirect_url = apply_filters(
1696
-                'FHEE__EED_Single_Page_Checkout___setup_redirect__checkout_redirect_url',
1697
-                $this->checkout->redirect_url,
1698
-                $this->checkout
1699
-            );
1700
-        }
1701
-    }
1702
-
1703
-
1704
-    /**
1705
-     *   handle ajax message responses and redirects
1706
-     *
1707
-     * @return void
1708
-     * @throws EE_Error
1709
-     * @throws ReflectionException
1710
-     */
1711
-    public function go_to_next_step()
1712
-    {
1713
-        if ($this->request->isAjax()) {
1714
-            // capture contents of output buffer we started earlier in the request, and insert into JSON response
1715
-            $this->checkout->json_response->set_unexpected_errors(ob_get_clean());
1716
-        }
1717
-        $this->unlock_transaction();
1718
-        // just return for these conditions
1719
-        if (
1720
-            $this->checkout->admin_request
1721
-            || $this->checkout->action === 'redirect_form'
1722
-            || $this->checkout->action === 'update_checkout'
1723
-        ) {
1724
-            return;
1725
-        }
1726
-        // AJAX response
1727
-        $this->_handle_json_response();
1728
-        // redirect to next step or the Thank You page
1729
-        $this->_handle_html_redirects();
1730
-        // hmmm... must be something wrong, so let's just display the form again !
1731
-        $this->_display_spco_reg_form();
1732
-    }
1733
-
1734
-
1735
-    /**
1736
-     *   _handle_json_response
1737
-     *
1738
-     * @return void
1739
-     * @throws EE_Error
1740
-     */
1741
-    protected function _handle_json_response()
1742
-    {
1743
-        // if this is an ajax request
1744
-        if ($this->request->isAjax()) {
1745
-            $this->checkout->json_response->set_registration_time_limit(
1746
-                $this->checkout->get_registration_time_limit()
1747
-            );
1748
-            $this->checkout->json_response->set_payment_amount($this->checkout->amount_owing);
1749
-            // just send the ajax (
1750
-            $json_response = apply_filters(
1751
-                'FHEE__EE_Single_Page_Checkout__JSON_response',
1752
-                $this->checkout->json_response
1753
-            );
1754
-            echo $json_response;
1755
-            exit();
1756
-        }
1757
-    }
1758
-
1759
-
1760
-    /**
1761
-     *   _handle_redirects
1762
-     *
1763
-     * @return void
1764
-     */
1765
-    protected function _handle_html_redirects()
1766
-    {
1767
-        // going somewhere ?
1768
-        if ($this->checkout->redirect && ! empty($this->checkout->redirect_url)) {
1769
-            // store notices in a transient
1770
-            EE_Error::get_notices(false, true);
1771
-            wp_safe_redirect($this->checkout->redirect_url);
1772
-            exit();
1773
-        }
1774
-    }
1775
-
1776
-
1777
-    /**
1778
-     *   set_checkout_anchor
1779
-     *
1780
-     * @return void
1781
-     */
1782
-    public function set_checkout_anchor()
1783
-    {
1784
-        echo '<a id="checkout" style="float: left; margin-left: -999em;"></a>';
1785
-    }
1786
-
1787
-    /**
1788
-     *    getRegistrationExpirationNotice
1789
-     *
1790
-     * @since     4.9.59.p
1791
-     * @return    string
1792
-     */
1793
-    public static function getRegistrationExpirationNotice()
1794
-    {
1795
-        return sprintf(
1796
-            esc_html__(
1797
-                '%1$sWe\'re sorry, but your registration time has expired.%2$s%3$s%4$sIf you still wish to complete your registration, please return to the %5$sEvent List%6$sEvent List%7$s and reselect your tickets if available. Please accept our apologies for any inconvenience this may have caused.%8$s',
1798
-                'event_espresso'
1799
-            ),
1800
-            '<h4 class="important-notice">',
1801
-            '</h4>',
1802
-            '<br />',
1803
-            '<p>',
1804
-            '<a href="' . get_post_type_archive_link('espresso_events') . '" title="',
1805
-            '">',
1806
-            '</a>',
1807
-            '</p>'
1808
-        );
1809
-    }
22
+	/**
23
+	 * $_initialized - has the SPCO controller already been initialized ?
24
+	 *
25
+	 * @var bool $_initialized
26
+	 */
27
+	private static $_initialized = false;
28
+
29
+
30
+	/**
31
+	 * $_checkout_verified - is the EE_Checkout verified as correct for this request ?
32
+	 *
33
+	 * @var bool $_valid_checkout
34
+	 */
35
+	private static $_checkout_verified = true;
36
+
37
+	/**
38
+	 *    $_reg_steps_array - holds initial array of reg steps
39
+	 *
40
+	 * @var array $_reg_steps_array
41
+	 */
42
+	private static $_reg_steps_array = array();
43
+
44
+	/**
45
+	 *    $checkout - EE_Checkout object for handling the properties of the current checkout process
46
+	 *
47
+	 * @var EE_Checkout $checkout
48
+	 */
49
+	public $checkout;
50
+
51
+	/**
52
+	 * @var RequestInterface $request
53
+	 */
54
+	protected $request;
55
+
56
+
57
+	/**
58
+	 * @return EED_Single_Page_Checkout|EED_Module
59
+	 * @throws EE_Error
60
+	 * @throws ReflectionException
61
+	 */
62
+	public static function instance()
63
+	{
64
+		add_filter('EED_Single_Page_Checkout__SPCO_active', '__return_true');
65
+		return parent::get_instance(__CLASS__);
66
+	}
67
+
68
+
69
+	/**
70
+	 * @return EE_CART
71
+	 */
72
+	public function cart()
73
+	{
74
+		return $this->checkout->cart;
75
+	}
76
+
77
+
78
+	/**
79
+	 * @return RequestInterface
80
+	 * @since   4.10.14.p
81
+	 */
82
+	public static function getRequest()
83
+	{
84
+		return LoaderFactory::getLoader()->getShared(RequestInterface::class);
85
+	}
86
+
87
+
88
+	/**
89
+	 * @return EE_Transaction
90
+	 */
91
+	public function transaction()
92
+	{
93
+		return $this->checkout->transaction;
94
+	}
95
+
96
+
97
+	/**
98
+	 *    set_hooks - for hooking into EE Core, other modules, etc
99
+	 *
100
+	 * @return    void
101
+	 * @throws EE_Error
102
+	 */
103
+	public static function set_hooks()
104
+	{
105
+		EED_Single_Page_Checkout::set_definitions();
106
+	}
107
+
108
+
109
+	/**
110
+	 *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
111
+	 *
112
+	 * @return    void
113
+	 * @throws EE_Error
114
+	 */
115
+	public static function set_hooks_admin()
116
+	{
117
+		EED_Single_Page_Checkout::set_definitions();
118
+		if (! (defined('DOING_AJAX') && DOING_AJAX)) {
119
+			return;
120
+		}
121
+		// going to start an output buffer in case anything gets accidentally output
122
+		// that might disrupt our JSON response
123
+		ob_start();
124
+		EED_Single_Page_Checkout::load_reg_steps();
125
+		// set ajax hooks
126
+		add_action('wp_ajax_process_reg_step', array('EED_Single_Page_Checkout', 'process_reg_step'));
127
+		add_action('wp_ajax_nopriv_process_reg_step', array('EED_Single_Page_Checkout', 'process_reg_step'));
128
+		add_action('wp_ajax_display_spco_reg_step', array('EED_Single_Page_Checkout', 'display_reg_step'));
129
+		add_action('wp_ajax_nopriv_display_spco_reg_step', array('EED_Single_Page_Checkout', 'display_reg_step'));
130
+		add_action('wp_ajax_update_reg_step', array('EED_Single_Page_Checkout', 'update_reg_step'));
131
+		add_action('wp_ajax_nopriv_update_reg_step', array('EED_Single_Page_Checkout', 'update_reg_step'));
132
+	}
133
+
134
+
135
+	/**
136
+	 *    process ajax request
137
+	 *
138
+	 * @param string $ajax_action
139
+	 * @throws EE_Error
140
+	 * @throws ReflectionException
141
+	 */
142
+	public static function process_ajax_request($ajax_action)
143
+	{
144
+		$request = EED_Single_Page_Checkout::getRequest();
145
+		$request->setRequestParam('action', $ajax_action);
146
+		EED_Single_Page_Checkout::instance()->_initialize();
147
+	}
148
+
149
+
150
+	/**
151
+	 * ajax display registration step
152
+	 *
153
+	 * @throws EE_Error
154
+	 * @throws ReflectionException
155
+	 */
156
+	public static function display_reg_step()
157
+	{
158
+		EED_Single_Page_Checkout::process_ajax_request('display_spco_reg_step');
159
+	}
160
+
161
+
162
+	/**
163
+	 * ajax process registration step
164
+	 *
165
+	 * @throws EE_Error
166
+	 * @throws ReflectionException
167
+	 */
168
+	public static function process_reg_step()
169
+	{
170
+		EED_Single_Page_Checkout::process_ajax_request('process_reg_step');
171
+	}
172
+
173
+
174
+	/**
175
+	 * ajax process registration step
176
+	 *
177
+	 * @throws EE_Error
178
+	 * @throws ReflectionException
179
+	 */
180
+	public static function update_reg_step()
181
+	{
182
+		EED_Single_Page_Checkout::process_ajax_request('update_reg_step');
183
+	}
184
+
185
+
186
+	/**
187
+	 * update_checkout
188
+	 *
189
+	 * @return void
190
+	 * @throws ReflectionException
191
+	 * @throws EE_Error
192
+	 */
193
+	public static function update_checkout()
194
+	{
195
+		EED_Single_Page_Checkout::process_ajax_request('update_checkout');
196
+	}
197
+
198
+
199
+	/**
200
+	 * @return void
201
+	 * @deprecated 4.10.14.p
202
+	 */
203
+	public static function load_request_handler()
204
+	{
205
+	}
206
+
207
+
208
+	/**
209
+	 *    set_definitions
210
+	 *
211
+	 * @return    void
212
+	 * @throws EE_Error
213
+	 */
214
+	public static function set_definitions()
215
+	{
216
+		if (defined('SPCO_BASE_PATH')) {
217
+			return;
218
+		}
219
+		define(
220
+			'SPCO_BASE_PATH',
221
+			rtrim(str_replace(array('\\', '/'), '/', plugin_dir_path(__FILE__)), '/') . '/'
222
+		);
223
+		define('SPCO_CSS_URL', plugin_dir_url(__FILE__) . 'css/');
224
+		define('SPCO_IMG_URL', plugin_dir_url(__FILE__) . 'img/');
225
+		define('SPCO_JS_URL', plugin_dir_url(__FILE__) . 'js/');
226
+		define('SPCO_INC_PATH', SPCO_BASE_PATH . 'inc/');
227
+		define('SPCO_REG_STEPS_PATH', SPCO_BASE_PATH . 'reg_steps/');
228
+		define('SPCO_TEMPLATES_PATH', SPCO_BASE_PATH . 'templates/');
229
+		EEH_Autoloader::register_autoloaders_for_each_file_in_folder(SPCO_BASE_PATH, true);
230
+		EE_Registry::$i18n_js_strings['registration_expiration_notice'] = EED_Single_Page_Checkout::getRegistrationExpirationNotice(
231
+		);
232
+	}
233
+
234
+
235
+	/**
236
+	 * load_reg_steps
237
+	 * loads and instantiates each reg step based on the EE_Registry::instance()->CFG->registration->reg_steps array
238
+	 *
239
+	 * @throws EE_Error
240
+	 */
241
+	public static function load_reg_steps()
242
+	{
243
+		static $reg_steps_loaded = false;
244
+		if ($reg_steps_loaded) {
245
+			return;
246
+		}
247
+		// filter list of reg_steps
248
+		$reg_steps_to_load = (array) apply_filters(
249
+			'AHEE__SPCO__load_reg_steps__reg_steps_to_load',
250
+			EED_Single_Page_Checkout::get_reg_steps()
251
+		);
252
+		// sort by key (order)
253
+		ksort($reg_steps_to_load);
254
+		// loop through folders
255
+		foreach ($reg_steps_to_load as $order => $reg_step) {
256
+			// we need a
257
+			if (isset($reg_step['file_path'], $reg_step['class_name'], $reg_step['slug'])) {
258
+				// copy over to the reg_steps_array
259
+				EED_Single_Page_Checkout::$_reg_steps_array[ $order ] = $reg_step;
260
+				// register custom key route for each reg step
261
+				// ie: step=>"slug" - this is the entire reason we load the reg steps array now
262
+				EE_Config::register_route(
263
+					$reg_step['slug'],
264
+					'EED_Single_Page_Checkout',
265
+					'run',
266
+					'step'
267
+				);
268
+				// add AJAX or other hooks
269
+				if (isset($reg_step['has_hooks']) && $reg_step['has_hooks']) {
270
+					// setup autoloaders if necessary
271
+					if (! class_exists($reg_step['class_name'])) {
272
+						EEH_Autoloader::register_autoloaders_for_each_file_in_folder(
273
+							$reg_step['file_path'],
274
+							true
275
+						);
276
+					}
277
+					if (is_callable($reg_step['class_name'], 'set_hooks')) {
278
+						call_user_func(array($reg_step['class_name'], 'set_hooks'));
279
+					}
280
+				}
281
+			}
282
+		}
283
+		$reg_steps_loaded = true;
284
+	}
285
+
286
+
287
+	/**
288
+	 *    get_reg_steps
289
+	 *
290
+	 * @return    array
291
+	 */
292
+	public static function get_reg_steps()
293
+	{
294
+		$reg_steps = EE_Registry::instance()->CFG->registration->reg_steps;
295
+		if (empty($reg_steps)) {
296
+			$reg_steps = array(
297
+				10  => array(
298
+					'file_path'  => SPCO_REG_STEPS_PATH . 'attendee_information',
299
+					'class_name' => 'EE_SPCO_Reg_Step_Attendee_Information',
300
+					'slug'       => 'attendee_information',
301
+					'has_hooks'  => false,
302
+				),
303
+				30  => array(
304
+					'file_path'  => SPCO_REG_STEPS_PATH . 'payment_options',
305
+					'class_name' => 'EE_SPCO_Reg_Step_Payment_Options',
306
+					'slug'       => 'payment_options',
307
+					'has_hooks'  => true,
308
+				),
309
+				999 => array(
310
+					'file_path'  => SPCO_REG_STEPS_PATH . 'finalize_registration',
311
+					'class_name' => 'EE_SPCO_Reg_Step_Finalize_Registration',
312
+					'slug'       => 'finalize_registration',
313
+					'has_hooks'  => false,
314
+				),
315
+			);
316
+		}
317
+		return $reg_steps;
318
+	}
319
+
320
+
321
+	/**
322
+	 *    registration_checkout_for_admin
323
+	 *
324
+	 * @return    string
325
+	 * @throws EE_Error
326
+	 * @throws ReflectionException
327
+	 */
328
+	public static function registration_checkout_for_admin()
329
+	{
330
+		$request = EED_Single_Page_Checkout::getRequest();
331
+		$request->setRequestParam('step', 'attendee_information');
332
+		$request->setRequestParam('action', 'display_spco_reg_step');
333
+		$request->setRequestParam('process_form_submission', false);
334
+		EED_Single_Page_Checkout::instance()->_initialize();
335
+		EED_Single_Page_Checkout::instance()->_display_spco_reg_form();
336
+		return EED_Single_Page_Checkout::getResponse()->getOutput();
337
+	}
338
+
339
+
340
+	/**
341
+	 * process_registration_from_admin
342
+	 *
343
+	 * @return EE_Transaction
344
+	 * @throws EE_Error
345
+	 * @throws ReflectionException
346
+	 */
347
+	public static function process_registration_from_admin()
348
+	{
349
+		$request = EED_Single_Page_Checkout::getRequest();
350
+		$request->setRequestParam('step', 'attendee_information');
351
+		$request->setRequestParam('action', 'process_reg_step');
352
+		$request->setRequestParam('process_form_submission', true);
353
+		EED_Single_Page_Checkout::instance()->_initialize();
354
+		if (EED_Single_Page_Checkout::instance()->checkout->current_step->completed()) {
355
+			$final_reg_step = end(EED_Single_Page_Checkout::instance()->checkout->reg_steps);
356
+			if ($final_reg_step instanceof EE_SPCO_Reg_Step_Finalize_Registration) {
357
+				EED_Single_Page_Checkout::instance()->checkout->set_reg_step_initiated($final_reg_step);
358
+				if ($final_reg_step->process_reg_step()) {
359
+					$final_reg_step->set_completed();
360
+					EED_Single_Page_Checkout::instance()->checkout->update_txn_reg_steps_array();
361
+					return EED_Single_Page_Checkout::instance()->checkout->transaction;
362
+				}
363
+			}
364
+		}
365
+		return null;
366
+	}
367
+
368
+
369
+	/**
370
+	 *    run
371
+	 *
372
+	 * @param WP_Query $WP
373
+	 * @return    void
374
+	 */
375
+	public function run($WP)
376
+	{
377
+		if (
378
+			$WP instanceof WP_Query
379
+			&& $WP->is_main_query()
380
+			&& apply_filters('FHEE__EED_Single_Page_Checkout__run', true)
381
+			&& $this->_is_reg_checkout()
382
+		) {
383
+			$this->_initialize();
384
+		}
385
+	}
386
+
387
+
388
+	/**
389
+	 * determines whether current url matches reg page url
390
+	 *
391
+	 * @return bool
392
+	 */
393
+	protected function _is_reg_checkout()
394
+	{
395
+		// get current permalink for reg page without any extra query args
396
+		$reg_page_url = get_permalink(EE_Config::instance()->core->reg_page_id);
397
+		// get request URI for current request, but without the scheme or host
398
+		$current_request_uri = EEH_URL::filter_input_server_url();
399
+		$current_request_uri = html_entity_decode($current_request_uri);
400
+		// get array of query args from the current request URI
401
+		$query_args = EEH_URL::get_query_string($current_request_uri);
402
+		// grab page id if it is set
403
+		$page_id = isset($query_args['page_id']) ? absint($query_args['page_id']) : 0;
404
+		// and remove the page id from the query args (we will re-add it later)
405
+		unset($query_args['page_id']);
406
+		// now strip all query args from current request URI
407
+		$current_request_uri = remove_query_arg(array_keys($query_args), $current_request_uri);
408
+		// and re-add the page id if it was set
409
+		if ($page_id) {
410
+			$current_request_uri = add_query_arg('page_id', $page_id, $current_request_uri);
411
+		}
412
+		// remove slashes and ?
413
+		$current_request_uri = trim($current_request_uri, '?/');
414
+		// is current request URI part of the known full reg page URL ?
415
+		return ! empty($current_request_uri) && strpos($reg_page_url, $current_request_uri) !== false;
416
+	}
417
+
418
+
419
+	/**
420
+	 * @param WP_Query $wp_query
421
+	 * @return    void
422
+	 * @throws EE_Error
423
+	 * @throws ReflectionException
424
+	 */
425
+	public static function init($wp_query)
426
+	{
427
+		EED_Single_Page_Checkout::instance()->run($wp_query);
428
+	}
429
+
430
+
431
+	/**
432
+	 *    _initialize - initial module setup
433
+	 *
434
+	 * @return    void
435
+	 */
436
+	private function _initialize()
437
+	{
438
+		// ensure SPCO doesn't run twice
439
+		if (EED_Single_Page_Checkout::$_initialized) {
440
+			return;
441
+		}
442
+		try {
443
+			$this->request = EED_Single_Page_Checkout::getRequest();
444
+			EED_Single_Page_Checkout::load_reg_steps();
445
+			$this->_verify_session();
446
+			// setup the EE_Checkout object
447
+			$this->checkout = $this->_initialize_checkout();
448
+			// filter checkout
449
+			$this->checkout = apply_filters('FHEE__EED_Single_Page_Checkout___initialize__checkout', $this->checkout);
450
+			// get the $_GET
451
+			$this->_get_request_vars();
452
+			if ($this->_block_bots()) {
453
+				return;
454
+			}
455
+			// filter continue_reg
456
+			$this->checkout->continue_reg = apply_filters(
457
+				'FHEE__EED_Single_Page_Checkout__init___continue_reg',
458
+				true,
459
+				$this->checkout
460
+			);
461
+			// load the reg steps array
462
+			if (! $this->_load_and_instantiate_reg_steps()) {
463
+				EED_Single_Page_Checkout::$_initialized = true;
464
+				return;
465
+			}
466
+			// set the current step
467
+			$this->checkout->set_current_step($this->checkout->step);
468
+			// and the next step
469
+			$this->checkout->set_next_step();
470
+			// verify that everything has been setup correctly
471
+			if (! ($this->_verify_transaction_and_get_registrations() && $this->_final_verifications())) {
472
+				EED_Single_Page_Checkout::$_initialized = true;
473
+				return;
474
+			}
475
+			// lock the transaction
476
+			$this->checkout->transaction->lock();
477
+			// make sure all of our cached objects are added to their respective model entity mappers
478
+			$this->checkout->refresh_all_entities();
479
+			// set amount owing
480
+			$this->checkout->amount_owing = $this->checkout->transaction->remaining();
481
+			// initialize each reg step, which gives them the chance to potentially alter the process
482
+			$this->_initialize_reg_steps();
483
+			// DEBUG LOG
484
+			// $this->checkout->log( __CLASS__, __FUNCTION__, __LINE__ );
485
+			// get reg form
486
+			if (! $this->_check_form_submission()) {
487
+				EED_Single_Page_Checkout::$_initialized = true;
488
+				return;
489
+			}
490
+			// checkout the action!!!
491
+			$this->_process_form_action();
492
+			// add some style and make it dance
493
+			$this->add_styles_and_scripts($this);
494
+			// kk... SPCO has successfully run
495
+			EED_Single_Page_Checkout::$_initialized = true;
496
+			// set no cache headers and constants
497
+			EE_System::do_not_cache();
498
+			// add anchor
499
+			add_action('loop_start', array($this, 'set_checkout_anchor'), 1);
500
+			// remove transaction lock
501
+			add_action('shutdown', array($this, 'unlock_transaction'), 1);
502
+		} catch (Exception $e) {
503
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
504
+		}
505
+	}
506
+
507
+
508
+	/**
509
+	 *    _verify_session
510
+	 * checks that the session is valid and not expired
511
+	 *
512
+	 * @throws EE_Error
513
+	 * @throws ReflectionException
514
+	 */
515
+	private function _verify_session()
516
+	{
517
+		if (! EE_Registry::instance()->SSN instanceof EE_Session) {
518
+			throw new EE_Error(esc_html__('The EE_Session class could not be loaded.', 'event_espresso'));
519
+		}
520
+		$clear_session_requested = $this->request->getRequestParam('clear_session', false, 'bool');
521
+		// is session still valid ?
522
+		if (
523
+			$clear_session_requested
524
+			|| (
525
+				EE_Registry::instance()->SSN->expired()
526
+				&& $this->request->getRequestParam('e_reg_url_link') === ''
527
+			)
528
+		) {
529
+			$this->checkout = new EE_Checkout();
530
+			EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
531
+			// EE_Registry::instance()->SSN->reset_cart();
532
+			// EE_Registry::instance()->SSN->reset_checkout();
533
+			// EE_Registry::instance()->SSN->reset_transaction();
534
+			if (! $clear_session_requested) {
535
+				EE_Error::add_attention(
536
+					EE_Registry::$i18n_js_strings['registration_expiration_notice'],
537
+					__FILE__,
538
+					__FUNCTION__,
539
+					__LINE__
540
+				);
541
+			}
542
+			// EE_Registry::instance()->SSN->reset_expired();
543
+		}
544
+	}
545
+
546
+
547
+	/**
548
+	 *    _initialize_checkout
549
+	 * loads and instantiates EE_Checkout
550
+	 *
551
+	 * @return EE_Checkout
552
+	 * @throws EE_Error
553
+	 * @throws ReflectionException
554
+	 */
555
+	private function _initialize_checkout()
556
+	{
557
+		// look in session for existing checkout
558
+		/** @type EE_Checkout $checkout */
559
+		$checkout = EE_Registry::instance()->SSN->checkout();
560
+		// verify
561
+		if (! $checkout instanceof EE_Checkout) {
562
+			// instantiate EE_Checkout object for handling the properties of the current checkout process
563
+			$checkout = EE_Registry::instance()->load_file(
564
+				SPCO_INC_PATH,
565
+				'EE_Checkout',
566
+				'class',
567
+				array(),
568
+				false
569
+			);
570
+		} else {
571
+			if ($checkout->current_step->is_final_step() && $checkout->exit_spco() === true) {
572
+				$this->unlock_transaction();
573
+				wp_safe_redirect($checkout->redirect_url);
574
+				exit();
575
+			}
576
+		}
577
+		$checkout = apply_filters('FHEE__EED_Single_Page_Checkout___initialize_checkout__checkout', $checkout);
578
+		// verify again
579
+		if (! $checkout instanceof EE_Checkout) {
580
+			throw new EE_Error(esc_html__('The EE_Checkout class could not be loaded.', 'event_espresso'));
581
+		}
582
+		// reset anything that needs a clean slate for each request
583
+		$checkout->reset_for_current_request();
584
+		return $checkout;
585
+	}
586
+
587
+
588
+	/**
589
+	 *    _get_request_vars
590
+	 *
591
+	 * @return    void
592
+	 */
593
+	private function _get_request_vars()
594
+	{
595
+		// make sure this request is marked as belonging to EE
596
+		/** @var CurrentPage $current_page */
597
+		$current_page = LoaderFactory::getLoader()->getShared(CurrentPage::class);
598
+		$current_page->setEspressoPage(true);
599
+		// which step is being requested ?
600
+		$this->checkout->step = $this->request->getRequestParam('step', $this->_get_first_step());
601
+		// which step is being edited ?
602
+		$this->checkout->edit_step = $this->request->getRequestParam('edit_step');
603
+		// and what we're doing on the current step
604
+		$this->checkout->action = $this->request->getRequestParam('action', 'display_spco_reg_step');
605
+		// timestamp
606
+		$this->checkout->uts = $this->request->getRequestParam('uts', 0, 'int');
607
+		// returning to edit ?
608
+		$this->checkout->reg_url_link = $this->request->getRequestParam('e_reg_url_link');
609
+		// add reg url link to registration query params
610
+		if ($this->checkout->reg_url_link && strpos($this->checkout->reg_url_link, '1-') !== 0) {
611
+			$this->checkout->reg_cache_where_params[0]['REG_url_link'] = $this->checkout->reg_url_link;
612
+		}
613
+		// or some other kind of revisit ?
614
+		$this->checkout->revisit = $this->request->getRequestParam('revisit', false, 'bool');
615
+		// and whether or not to generate a reg form for this request
616
+		$this->checkout->generate_reg_form = $this->request->getRequestParam('generate_reg_form', true, 'bool');
617
+		// and whether or not to process a reg form submission for this request
618
+		$this->checkout->process_form_submission = $this->request->getRequestParam(
619
+			'process_form_submission',
620
+			$this->checkout->action === 'process_reg_step',
621
+			'bool'
622
+		);
623
+		$this->checkout->process_form_submission = filter_var(
624
+			$this->checkout->action !== 'display_spco_reg_step'
625
+				? $this->checkout->process_form_submission
626
+				: false,
627
+			FILTER_VALIDATE_BOOLEAN
628
+		);
629
+		// $this->_display_request_vars();
630
+	}
631
+
632
+
633
+	/**
634
+	 *  _display_request_vars
635
+	 *
636
+	 * @return    void
637
+	 */
638
+	protected function _display_request_vars()
639
+	{
640
+		if (! WP_DEBUG) {
641
+			return;
642
+		}
643
+		EEH_Debug_Tools::printr($this->request->requestParams(), 'requestParams', __FILE__, __LINE__);
644
+		EEH_Debug_Tools::printr($this->checkout->step, '$this->checkout->step', __FILE__, __LINE__);
645
+		EEH_Debug_Tools::printr($this->checkout->edit_step, '$this->checkout->edit_step', __FILE__, __LINE__);
646
+		EEH_Debug_Tools::printr($this->checkout->action, '$this->checkout->action', __FILE__, __LINE__);
647
+		EEH_Debug_Tools::printr($this->checkout->reg_url_link, '$this->checkout->reg_url_link', __FILE__, __LINE__);
648
+		EEH_Debug_Tools::printr($this->checkout->revisit, '$this->checkout->revisit', __FILE__, __LINE__);
649
+		EEH_Debug_Tools::printr(
650
+			$this->checkout->generate_reg_form,
651
+			'$this->checkout->generate_reg_form',
652
+			__FILE__,
653
+			__LINE__
654
+		);
655
+		EEH_Debug_Tools::printr(
656
+			$this->checkout->process_form_submission,
657
+			'$this->checkout->process_form_submission',
658
+			__FILE__,
659
+			__LINE__
660
+		);
661
+	}
662
+
663
+
664
+	/**
665
+	 * _block_bots
666
+	 * checks that the incoming request has either of the following set:
667
+	 *  a uts (unix timestamp) which indicates that the request was redirected from the Ticket Selector
668
+	 *  a REG URL Link, which indicates that the request is a return visit to SPCO for a valid TXN
669
+	 * so if you're not coming from the Ticket Selector nor returning for a valid IP...
670
+	 * then where you coming from man?
671
+	 *
672
+	 * @return boolean
673
+	 */
674
+	private function _block_bots()
675
+	{
676
+		$invalid_checkout_access = EED_Invalid_Checkout_Access::getInvalidCheckoutAccess();
677
+		if ($invalid_checkout_access->checkoutAccessIsInvalid($this->checkout)) {
678
+			return true;
679
+		}
680
+		return false;
681
+	}
682
+
683
+
684
+	/**
685
+	 *    _get_first_step
686
+	 *  gets slug for first step in $_reg_steps_array
687
+	 *
688
+	 * @return    string
689
+	 */
690
+	private function _get_first_step()
691
+	{
692
+		$first_step = reset(EED_Single_Page_Checkout::$_reg_steps_array);
693
+		return isset($first_step['slug']) ? $first_step['slug'] : 'attendee_information';
694
+	}
695
+
696
+
697
+	/**
698
+	 * instantiates each reg step based on the loaded reg_steps array
699
+	 *
700
+	 * @return    bool
701
+	 * @throws EE_Error
702
+	 * @throws InvalidArgumentException
703
+	 * @throws InvalidDataTypeException
704
+	 * @throws InvalidInterfaceException
705
+	 * @throws ReflectionException
706
+	 */
707
+	private function _load_and_instantiate_reg_steps()
708
+	{
709
+		do_action('AHEE__Single_Page_Checkout___load_and_instantiate_reg_steps__start', $this->checkout);
710
+		// have reg_steps already been instantiated ?
711
+		if (
712
+			empty($this->checkout->reg_steps)
713
+			|| apply_filters('FHEE__Single_Page_Checkout__load_reg_steps__reload_reg_steps', false, $this->checkout)
714
+		) {
715
+			// if not, then loop through raw reg steps array
716
+			foreach (EED_Single_Page_Checkout::$_reg_steps_array as $order => $reg_step) {
717
+				if (! $this->_load_and_instantiate_reg_step($reg_step, $order)) {
718
+					return false;
719
+				}
720
+			}
721
+			if (isset($this->checkout->reg_steps['registration_confirmation'])) {
722
+				// skip the registration_confirmation page ?
723
+				if (EE_Registry::instance()->CFG->registration->skip_reg_confirmation) {
724
+					// just remove it from the reg steps array
725
+					$this->checkout->remove_reg_step('registration_confirmation', false);
726
+				} elseif (
727
+					EE_Registry::instance()->CFG->registration->reg_confirmation_last
728
+				) {
729
+					// set the order to something big like 100
730
+					$this->checkout->set_reg_step_order('registration_confirmation');
731
+				}
732
+			}
733
+			// filter the array for good luck
734
+			$this->checkout->reg_steps = apply_filters(
735
+				'FHEE__Single_Page_Checkout__load_reg_steps__reg_steps',
736
+				$this->checkout->reg_steps
737
+			);
738
+			// finally re-sort based on the reg step class order properties
739
+			$this->checkout->sort_reg_steps();
740
+		} else {
741
+			foreach ($this->checkout->reg_steps as $reg_step) {
742
+				// set all current step stati to FALSE
743
+				$reg_step->set_is_current_step(false);
744
+			}
745
+		}
746
+		if (empty($this->checkout->reg_steps)) {
747
+			EE_Error::add_error(
748
+				esc_html__('No Reg Steps were loaded..', 'event_espresso'),
749
+				__FILE__,
750
+				__FUNCTION__,
751
+				__LINE__
752
+			);
753
+			return false;
754
+		}
755
+		// make reg step details available to JS
756
+		$this->checkout->set_reg_step_JSON_info();
757
+		return true;
758
+	}
759
+
760
+
761
+	/**
762
+	 *     _load_and_instantiate_reg_step
763
+	 *
764
+	 * @param array $reg_step
765
+	 * @param int   $order
766
+	 * @return bool
767
+	 * @throws EE_Error
768
+	 * @throws ReflectionException
769
+	 */
770
+	private function _load_and_instantiate_reg_step($reg_step = array(), $order = 0)
771
+	{
772
+		// we need a file_path, class_name, and slug to add a reg step
773
+		if (isset($reg_step['file_path'], $reg_step['class_name'], $reg_step['slug'])) {
774
+			// if editing a specific step, but this is NOT that step... (and it's not the 'finalize_registration' step)
775
+			if (
776
+				$this->checkout->reg_url_link
777
+				&& $this->checkout->step !== $reg_step['slug']
778
+				&& $reg_step['slug'] !== 'finalize_registration'
779
+				// normally at this point we would NOT load the reg step, but this filter can change that
780
+				&& apply_filters(
781
+					'FHEE__Single_Page_Checkout___load_and_instantiate_reg_step__bypass_reg_step',
782
+					true,
783
+					$reg_step,
784
+					$this->checkout
785
+				)
786
+			) {
787
+				return true;
788
+			}
789
+
790
+			// instantiate step class using file path and class name
791
+			$reg_step_obj = EE_Registry::instance()->load_file(
792
+				$reg_step['file_path'],
793
+				$reg_step['class_name'],
794
+				'class',
795
+				[$this->checkout],
796
+				false
797
+			);
798
+			// did we gets the goods ?
799
+			if ($reg_step_obj instanceof EE_SPCO_Reg_Step) {
800
+				// set reg step order based on config
801
+				$reg_step_obj->set_order($order);
802
+				// add instantiated reg step object to the master reg steps array
803
+				$this->checkout->add_reg_step($reg_step_obj);
804
+			} else {
805
+				EE_Error::add_error(
806
+					esc_html__('The current step could not be set.', 'event_espresso'),
807
+					__FILE__,
808
+					__FUNCTION__,
809
+					__LINE__
810
+				);
811
+				return false;
812
+			}
813
+		} else {
814
+			if (WP_DEBUG) {
815
+				EE_Error::add_error(
816
+					sprintf(
817
+						esc_html__(
818
+							'A registration step could not be loaded. One or more of the following data points is invalid:%4$s%5$sFile Path: %1$s%6$s%5$sClass Name: %2$s%6$s%5$sSlug: %3$s%6$s%7$s',
819
+							'event_espresso'
820
+						),
821
+						isset($reg_step['file_path']) ? $reg_step['file_path'] : '',
822
+						isset($reg_step['class_name']) ? $reg_step['class_name'] : '',
823
+						isset($reg_step['slug']) ? $reg_step['slug'] : '',
824
+						'<ul>',
825
+						'<li>',
826
+						'</li>',
827
+						'</ul>'
828
+					),
829
+					__FILE__,
830
+					__FUNCTION__,
831
+					__LINE__
832
+				);
833
+			}
834
+			return false;
835
+		}
836
+		return true;
837
+	}
838
+
839
+
840
+	/**
841
+	 * _verify_transaction_and_get_registrations
842
+	 *
843
+	 * @return bool
844
+	 * @throws EE_Error
845
+	 * @throws ReflectionException
846
+	 */
847
+	private function _verify_transaction_and_get_registrations()
848
+	{
849
+		// was there already a valid transaction in the checkout from the session ?
850
+		if (! $this->checkout->transaction instanceof EE_Transaction) {
851
+			// get transaction from db or session
852
+			$this->checkout->transaction = $this->checkout->reg_url_link && ! is_admin()
853
+				? $this->_get_transaction_and_cart_for_previous_visit()
854
+				: $this->_get_cart_for_current_session_and_setup_new_transaction();
855
+			if (! $this->checkout->transaction instanceof EE_Transaction) {
856
+				EE_Error::add_error(
857
+					esc_html__(
858
+						'Your Registration and Transaction information could not be retrieved from the db.',
859
+						'event_espresso'
860
+					),
861
+					__FILE__,
862
+					__FUNCTION__,
863
+					__LINE__
864
+				);
865
+				$this->checkout->transaction = EE_Transaction::new_instance();
866
+				// add some style and make it dance
867
+				$this->add_styles_and_scripts($this);
868
+				EED_Single_Page_Checkout::$_initialized = true;
869
+				return false;
870
+			}
871
+			// and the registrations for the transaction
872
+			$this->_get_registrations($this->checkout->transaction);
873
+		}
874
+		return true;
875
+	}
876
+
877
+
878
+	/**
879
+	 * _get_transaction_and_cart_for_previous_visit
880
+	 *
881
+	 * @return EE_Transaction|null
882
+	 * @throws EE_Error
883
+	 * @throws ReflectionException
884
+	 */
885
+	private function _get_transaction_and_cart_for_previous_visit()
886
+	{
887
+		/** @var $TXN_model EEM_Transaction */
888
+		$TXN_model = EE_Registry::instance()->load_model('Transaction');
889
+		// because the reg_url_link is present in the request,
890
+		// this is a return visit to SPCO, so we'll get the transaction data from the db
891
+		$transaction = $TXN_model->get_transaction_from_reg_url_link($this->checkout->reg_url_link);
892
+		// verify transaction
893
+		if ($transaction instanceof EE_Transaction) {
894
+			// and get the cart that was used for that transaction
895
+			$this->checkout->cart = $this->_get_cart_for_transaction($transaction);
896
+			return $transaction;
897
+		}
898
+		EE_Error::add_error(
899
+			esc_html__('Your Registration and Transaction information could not be retrieved from the db.', 'event_espresso'),
900
+			__FILE__,
901
+			__FUNCTION__,
902
+			__LINE__
903
+		);
904
+		return null;
905
+	}
906
+
907
+
908
+	/**
909
+	 * _get_cart_for_transaction
910
+	 *
911
+	 * @param EE_Transaction $transaction
912
+	 * @return EE_Cart
913
+	 */
914
+	private function _get_cart_for_transaction($transaction)
915
+	{
916
+		return $this->checkout->get_cart_for_transaction($transaction);
917
+	}
918
+
919
+
920
+	/**
921
+	 * get_cart_for_transaction
922
+	 *
923
+	 * @param EE_Transaction $transaction
924
+	 * @return EE_Cart
925
+	 */
926
+	public function get_cart_for_transaction(EE_Transaction $transaction)
927
+	{
928
+		return $this->checkout->get_cart_for_transaction($transaction);
929
+	}
930
+
931
+
932
+	/**
933
+	 * _get_transaction_and_cart_for_current_session
934
+	 *    generates a new EE_Transaction object and adds it to the $_transaction property.
935
+	 *
936
+	 * @return EE_Transaction
937
+	 * @throws EE_Error
938
+	 * @throws ReflectionException
939
+	 */
940
+	private function _get_cart_for_current_session_and_setup_new_transaction()
941
+	{
942
+		//  if there's no transaction, then this is the FIRST visit to SPCO
943
+		// so load up the cart ( passing nothing for the TXN because it doesn't exist yet )
944
+		$this->checkout->cart = $this->_get_cart_for_transaction(null);
945
+		// and then create a new transaction
946
+		$transaction = $this->_initialize_transaction();
947
+		// verify transaction
948
+		if ($transaction instanceof EE_Transaction) {
949
+			// save it so that we have an ID for other objects to use
950
+			$transaction->save();
951
+			// and save TXN data to the cart
952
+			$this->checkout->cart->get_grand_total()->save_this_and_descendants_to_txn($transaction->ID());
953
+		} else {
954
+			EE_Error::add_error(
955
+				esc_html__('A Valid Transaction could not be initialized.', 'event_espresso'),
956
+				__FILE__,
957
+				__FUNCTION__,
958
+				__LINE__
959
+			);
960
+		}
961
+		return $transaction;
962
+	}
963
+
964
+
965
+	/**
966
+	 *    generates a new EE_Transaction object and adds it to the $_transaction property.
967
+	 *
968
+	 * @return EE_Transaction|null
969
+	 */
970
+	private function _initialize_transaction()
971
+	{
972
+		try {
973
+			// ensure cart totals have been calculated
974
+			$this->checkout->cart->get_grand_total()->recalculate_total_including_taxes();
975
+			// grab the cart grand total
976
+			$cart_total = $this->checkout->cart->get_cart_grand_total();
977
+			// create new TXN
978
+			$transaction = EE_Transaction::new_instance(
979
+				array(
980
+					'TXN_reg_steps' => $this->checkout->initialize_txn_reg_steps_array(),
981
+					'TXN_total'     => $cart_total > 0 ? $cart_total : 0,
982
+					'TXN_paid'      => 0,
983
+					'STS_ID'        => EEM_Transaction::failed_status_code,
984
+				)
985
+			);
986
+			// save it so that we have an ID for other objects to use
987
+			$transaction->save();
988
+			// set cron job for following up on TXNs after their session has expired
989
+			EE_Cron_Tasks::schedule_expired_transaction_check(
990
+				EE_Registry::instance()->SSN->expiration() + 1,
991
+				$transaction->ID()
992
+			);
993
+			return $transaction;
994
+		} catch (Exception $e) {
995
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
996
+		}
997
+		return null;
998
+	}
999
+
1000
+
1001
+	/**
1002
+	 * _get_registrations
1003
+	 *
1004
+	 * @param EE_Transaction $transaction
1005
+	 * @return void
1006
+	 * @throws EE_Error
1007
+	 * @throws ReflectionException
1008
+	 */
1009
+	private function _get_registrations(EE_Transaction $transaction)
1010
+	{
1011
+		// first step: grab the registrants  { : o
1012
+		$registrations = $transaction->registrations($this->checkout->reg_cache_where_params);
1013
+		$this->checkout->total_ticket_count = count($registrations);
1014
+		// verify registrations have been set
1015
+		if (empty($registrations)) {
1016
+			// if no cached registrations, then check the db
1017
+			$registrations = $transaction->registrations($this->checkout->reg_cache_where_params);
1018
+			// still nothing ? well as long as this isn't a revisit
1019
+			if (empty($registrations) && ! $this->checkout->revisit) {
1020
+				// generate new registrations from scratch
1021
+				$registrations = $this->_initialize_registrations($transaction);
1022
+			}
1023
+		}
1024
+		// sort by their original registration order
1025
+		usort($registrations, array('EED_Single_Page_Checkout', 'sort_registrations_by_REG_count'));
1026
+		// then loop thru the array
1027
+		foreach ($registrations as $registration) {
1028
+			// verify each registration
1029
+			if ($registration instanceof EE_Registration) {
1030
+				// we display all attendee info for the primary registrant
1031
+				if (
1032
+					$this->checkout->reg_url_link === $registration->reg_url_link()
1033
+					&& $registration->is_primary_registrant()
1034
+				) {
1035
+					$this->checkout->primary_revisit = true;
1036
+					break;
1037
+				}
1038
+				if ($this->checkout->revisit && $this->checkout->reg_url_link !== $registration->reg_url_link()) {
1039
+					// but hide info if it doesn't belong to you
1040
+					$transaction->clear_cache('Registration', $registration->ID());
1041
+					$this->checkout->total_ticket_count--;
1042
+				}
1043
+				$this->checkout->set_reg_status_updated($registration->ID(), false);
1044
+			}
1045
+		}
1046
+	}
1047
+
1048
+
1049
+	/**
1050
+	 *    adds related EE_Registration objects for each ticket in the cart to the current EE_Transaction object
1051
+	 *
1052
+	 * @param EE_Transaction $transaction
1053
+	 * @return    array
1054
+	 * @throws EE_Error
1055
+	 * @throws ReflectionException
1056
+	 */
1057
+	private function _initialize_registrations(EE_Transaction $transaction)
1058
+	{
1059
+		$att_nmbr = 0;
1060
+		$registrations = array();
1061
+		if ($transaction instanceof EE_Transaction) {
1062
+			/** @type EE_Registration_Processor $registration_processor */
1063
+			$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
1064
+			$this->checkout->total_ticket_count = $this->checkout->cart->all_ticket_quantity_count();
1065
+			// now let's add the cart items to the $transaction
1066
+			foreach ($this->checkout->cart->get_tickets() as $line_item) {
1067
+				// do the following for each ticket of this type they selected
1068
+				for ($x = 1; $x <= $line_item->quantity(); $x++) {
1069
+					$att_nmbr++;
1070
+					/** @var EventEspresso\core\services\commands\registration\CreateRegistrationCommand $CreateRegistrationCommand */
1071
+					$CreateRegistrationCommand = EE_Registry::instance()->create(
1072
+						'EventEspresso\core\services\commands\registration\CreateRegistrationCommand',
1073
+						array(
1074
+							$transaction,
1075
+							$line_item,
1076
+							$att_nmbr,
1077
+							$this->checkout->total_ticket_count,
1078
+						)
1079
+					);
1080
+					// override capabilities for frontend registrations
1081
+					if (! is_admin()) {
1082
+						$CreateRegistrationCommand->setCapCheck(
1083
+							new PublicCapabilities('', 'create_new_registration')
1084
+						);
1085
+					}
1086
+					$registration = EE_Registry::instance()->BUS->execute($CreateRegistrationCommand);
1087
+					if (! $registration instanceof EE_Registration) {
1088
+						throw new InvalidEntityException($registration, 'EE_Registration');
1089
+					}
1090
+					$registrations[ $registration->ID() ] = $registration;
1091
+				}
1092
+			}
1093
+			$registration_processor->fix_reg_final_price_rounding_issue($transaction);
1094
+		}
1095
+		return $registrations;
1096
+	}
1097
+
1098
+
1099
+	/**
1100
+	 * sorts registrations by REG_count
1101
+	 *
1102
+	 * @param EE_Registration $reg_A
1103
+	 * @param EE_Registration $reg_B
1104
+	 * @return int
1105
+	 */
1106
+	public static function sort_registrations_by_REG_count(EE_Registration $reg_A, EE_Registration $reg_B)
1107
+	{
1108
+		// this shouldn't ever happen within the same TXN, but oh well
1109
+		if ($reg_A->count() === $reg_B->count()) {
1110
+			return 0;
1111
+		}
1112
+		return ($reg_A->count() > $reg_B->count()) ? 1 : -1;
1113
+	}
1114
+
1115
+
1116
+	/**
1117
+	 *    _final_verifications
1118
+	 * just makes sure that everything is set up correctly before proceeding
1119
+	 *
1120
+	 * @return    bool
1121
+	 * @throws EE_Error
1122
+	 * @throws ReflectionException
1123
+	 */
1124
+	private function _final_verifications()
1125
+	{
1126
+		// filter checkout
1127
+		$this->checkout = apply_filters(
1128
+			'FHEE__EED_Single_Page_Checkout___final_verifications__checkout',
1129
+			$this->checkout
1130
+		);
1131
+		// verify that current step is still set correctly
1132
+		if (! $this->checkout->current_step instanceof EE_SPCO_Reg_Step) {
1133
+			EE_Error::add_error(
1134
+				esc_html__(
1135
+					'We\'re sorry but the registration process can not proceed because one or more registration steps were not setup correctly. Please refresh the page and try again or contact support.',
1136
+					'event_espresso'
1137
+				),
1138
+				__FILE__,
1139
+				__FUNCTION__,
1140
+				__LINE__
1141
+			);
1142
+			return false;
1143
+		}
1144
+		// if returning to SPCO, then verify that primary registrant is set
1145
+		if (! empty($this->checkout->reg_url_link)) {
1146
+			$valid_registrant = $this->checkout->transaction->primary_registration();
1147
+			if (! $valid_registrant instanceof EE_Registration) {
1148
+				EE_Error::add_error(
1149
+					esc_html__(
1150
+						'We\'re sorry but there appears to be an error with the "reg_url_link" or the primary registrant for this transaction. Please refresh the page and try again or contact support.',
1151
+						'event_espresso'
1152
+					),
1153
+					__FILE__,
1154
+					__FUNCTION__,
1155
+					__LINE__
1156
+				);
1157
+				return false;
1158
+			}
1159
+			$valid_registrant = null;
1160
+			foreach ($this->checkout->transaction->registrations($this->checkout->reg_cache_where_params) as $registration) {
1161
+				if (
1162
+					$registration instanceof EE_Registration
1163
+					&& $registration->reg_url_link() === $this->checkout->reg_url_link
1164
+				) {
1165
+					$valid_registrant = $registration;
1166
+				}
1167
+			}
1168
+			if (! $valid_registrant instanceof EE_Registration) {
1169
+				// hmmm... maybe we have the wrong session because the user is opening multiple tabs ?
1170
+				if (EED_Single_Page_Checkout::$_checkout_verified) {
1171
+					// clear the session, mark the checkout as unverified, and try again
1172
+					EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
1173
+					EED_Single_Page_Checkout::$_initialized = false;
1174
+					EED_Single_Page_Checkout::$_checkout_verified = false;
1175
+					$this->_initialize();
1176
+					EE_Error::reset_notices();
1177
+					return false;
1178
+				}
1179
+				EE_Error::add_error(
1180
+					esc_html__(
1181
+						'We\'re sorry but there appears to be an error with the "reg_url_link" or the transaction itself. Please refresh the page and try again or contact support.',
1182
+						'event_espresso'
1183
+					),
1184
+					__FILE__,
1185
+					__FUNCTION__,
1186
+					__LINE__
1187
+				);
1188
+				return false;
1189
+			}
1190
+		}
1191
+		// now that things have been kinda sufficiently verified,
1192
+		// let's add the checkout to the session so that it's available to other systems
1193
+		EE_Registry::instance()->SSN->set_checkout($this->checkout);
1194
+		return true;
1195
+	}
1196
+
1197
+
1198
+	/**
1199
+	 *    _initialize_reg_steps
1200
+	 * first makes sure that EE_Transaction_Processor::set_reg_step_initiated() is called as required
1201
+	 * then loops thru all of the active reg steps and calls the initialize_reg_step() method
1202
+	 *
1203
+	 * @param bool $reinitializing
1204
+	 * @throws EE_Error
1205
+	 */
1206
+	private function _initialize_reg_steps($reinitializing = false)
1207
+	{
1208
+		$this->checkout->set_reg_step_initiated($this->checkout->current_step);
1209
+		// loop thru all steps to call their individual "initialize" methods and set i18n strings for JS
1210
+		foreach ($this->checkout->reg_steps as $reg_step) {
1211
+			if (! $reg_step->initialize_reg_step()) {
1212
+				// if not initialized then maybe this step is being removed...
1213
+				if (! $reinitializing && $reg_step->is_current_step()) {
1214
+					// if it was the current step, then we need to start over here
1215
+					$this->_initialize_reg_steps(true);
1216
+					return;
1217
+				}
1218
+				continue;
1219
+			}
1220
+			// add css and JS for current step
1221
+			$this->add_styles_and_scripts($reg_step);
1222
+			if ($reg_step->is_current_step()) {
1223
+				// the text that appears on the reg step form submit button
1224
+				$reg_step->set_submit_button_text();
1225
+			}
1226
+		}
1227
+		// dynamically creates hook point like: AHEE__Single_Page_Checkout___initialize_reg_step__attendee_information
1228
+		do_action(
1229
+			"AHEE__Single_Page_Checkout___initialize_reg_step__{$this->checkout->current_step->slug()}",
1230
+			$this->checkout->current_step
1231
+		);
1232
+	}
1233
+
1234
+
1235
+	/**
1236
+	 * _check_form_submission
1237
+	 *
1238
+	 * @return boolean
1239
+	 * @throws EE_Error
1240
+	 * @throws ReflectionException
1241
+	 */
1242
+	private function _check_form_submission()
1243
+	{
1244
+		// does this request require the reg form to be generated ?
1245
+		if ($this->checkout->generate_reg_form) {
1246
+			// ever heard that song by Blue Rodeo ?
1247
+			try {
1248
+				$this->checkout->current_step->reg_form = $this->checkout->current_step->generate_reg_form();
1249
+				// if not displaying a form, then check for form submission
1250
+				if (
1251
+					$this->checkout->process_form_submission
1252
+					&& $this->checkout->current_step->reg_form->was_submitted()
1253
+				) {
1254
+					// clear out any old data in case this step is being run again
1255
+					$this->checkout->current_step->set_valid_data(array());
1256
+					// capture submitted form data
1257
+					$request_data = $this->request->requestParams();
1258
+					$this->checkout->current_step->reg_form->receive_form_submission(
1259
+						(array) apply_filters(
1260
+							'FHEE__Single_Page_Checkout___check_form_submission__request_params',
1261
+							$request_data,
1262
+							$this->checkout
1263
+						)
1264
+					);
1265
+					// validate submitted form data
1266
+					if (! $this->checkout->continue_reg || ! $this->checkout->current_step->reg_form->is_valid()) {
1267
+						// thou shall not pass !!!
1268
+						$this->checkout->continue_reg = false;
1269
+						// any form validation errors?
1270
+						if ($this->checkout->current_step->reg_form->submission_error_message() !== '') {
1271
+							EE_Error::add_error(
1272
+								$this->checkout->current_step->reg_form->submission_error_message(),
1273
+								__FILE__,
1274
+								__FUNCTION__,
1275
+								__LINE__
1276
+							);
1277
+						}
1278
+						// well not really... what will happen is
1279
+						// we'll just get redirected back to redo the current step
1280
+						$this->go_to_next_step();
1281
+						return false;
1282
+					}
1283
+				}
1284
+			} catch (EE_Error $e) {
1285
+				$e->get_error();
1286
+			}
1287
+		}
1288
+		return true;
1289
+	}
1290
+
1291
+
1292
+	/**
1293
+	 * _process_action
1294
+	 *
1295
+	 * @return void
1296
+	 * @throws EE_Error
1297
+	 * @throws ReflectionException
1298
+	 */
1299
+	private function _process_form_action()
1300
+	{
1301
+		// what cha wanna do?
1302
+		switch ($this->checkout->action) {
1303
+			// AJAX next step reg form
1304
+			case 'display_spco_reg_step':
1305
+				$this->checkout->redirect = false;
1306
+				if ($this->request->isAjax()) {
1307
+					$this->checkout->json_response->set_reg_step_html(
1308
+						$this->checkout->current_step->display_reg_form()
1309
+					);
1310
+				}
1311
+				break;
1312
+			default:
1313
+				// meh... do one of those other steps first
1314
+				if (
1315
+					! empty($this->checkout->action)
1316
+					&& is_callable(array($this->checkout->current_step, $this->checkout->action))
1317
+				) {
1318
+					// dynamically creates hook point like:
1319
+					//   AHEE__Single_Page_Checkout__before_attendee_information__process_reg_step
1320
+					do_action(
1321
+						"AHEE__Single_Page_Checkout__before_{$this->checkout->current_step->slug()}__{$this->checkout->action}",
1322
+						$this->checkout->current_step
1323
+					);
1324
+					$process_reg_step = apply_filters(
1325
+						"AHEE__Single_Page_Checkout__process_reg_step__{$this->checkout->current_step->slug()}__{$this->checkout->action}",
1326
+						true,
1327
+						$this->checkout->current_step,
1328
+						$this
1329
+					);
1330
+					// call action on current step
1331
+					if ($process_reg_step && call_user_func([$this->checkout->current_step, $this->checkout->action])) {
1332
+						// good registrant, you get to proceed
1333
+						if (
1334
+							$this->checkout->current_step->success_message() !== ''
1335
+							&& apply_filters(
1336
+								'FHEE__Single_Page_Checkout___process_form_action__display_success',
1337
+								false
1338
+							)
1339
+						) {
1340
+							EE_Error::add_success(
1341
+								$this->checkout->current_step->success_message()
1342
+								. '<br />' . $this->checkout->next_step->_instructions()
1343
+							);
1344
+						}
1345
+						// pack it up, pack it in...
1346
+						$this->_setup_redirect();
1347
+					}
1348
+					// dynamically creates hook point like:
1349
+					//  AHEE__Single_Page_Checkout__after_payment_options__process_reg_step
1350
+					do_action(
1351
+						"AHEE__Single_Page_Checkout__after_{$this->checkout->current_step->slug()}__{$this->checkout->action}",
1352
+						$this->checkout->current_step
1353
+					);
1354
+				} else {
1355
+					EE_Error::add_error(
1356
+						sprintf(
1357
+							esc_html__(
1358
+								'The requested form action "%s" does not exist for the current "%s" registration step.',
1359
+								'event_espresso'
1360
+							),
1361
+							$this->checkout->action,
1362
+							$this->checkout->current_step->name()
1363
+						),
1364
+						__FILE__,
1365
+						__FUNCTION__,
1366
+						__LINE__
1367
+					);
1368
+				}
1369
+			// end default
1370
+		}
1371
+		// store our progress so far
1372
+		$this->checkout->stash_transaction_and_checkout();
1373
+		// advance to the next step! If you pass GO, collect $200
1374
+		$this->go_to_next_step();
1375
+	}
1376
+
1377
+
1378
+	/**
1379
+	 * @param EED_Single_Page_Checkout|EE_SPCO_Reg_Step $target an object with the method `translate_js_strings` and
1380
+	 *                                                          `enqueue_styles_and_scripts`.
1381
+	 * @return        void
1382
+	 */
1383
+	public function add_styles_and_scripts($target)
1384
+	{
1385
+		// i18n
1386
+		$target->translate_js_strings();
1387
+		if ($this->checkout->admin_request) {
1388
+			add_action('admin_enqueue_scripts', array($target, 'enqueue_styles_and_scripts'), 10);
1389
+		} else {
1390
+			add_action('wp_enqueue_scripts', array($target, 'enqueue_styles_and_scripts'), 10);
1391
+		}
1392
+	}
1393
+
1394
+	/**
1395
+	 *        translate_js_strings
1396
+	 *
1397
+	 * @return        void
1398
+	 */
1399
+	public function translate_js_strings()
1400
+	{
1401
+		EE_Registry::$i18n_js_strings['revisit'] = $this->checkout->revisit;
1402
+		EE_Registry::$i18n_js_strings['e_reg_url_link'] = $this->checkout->reg_url_link;
1403
+		EE_Registry::$i18n_js_strings['server_error'] = esc_html__(
1404
+			'An unknown error occurred on the server while attempting to process your request. Please refresh the page and try again or contact support.',
1405
+			'event_espresso'
1406
+		);
1407
+		EE_Registry::$i18n_js_strings['invalid_json_response'] = esc_html__(
1408
+			'An invalid response was returned from the server while attempting to process your request. Please refresh the page and try again or contact support.',
1409
+			'event_espresso'
1410
+		);
1411
+		EE_Registry::$i18n_js_strings['validation_error'] = esc_html__(
1412
+			'There appears to be a problem with the form validation configuration! Please check the admin settings or contact support.',
1413
+			'event_espresso'
1414
+		);
1415
+		EE_Registry::$i18n_js_strings['invalid_payment_method'] = esc_html__(
1416
+			'There appears to be a problem with the payment method configuration! Please refresh the page and try again or contact support.',
1417
+			'event_espresso'
1418
+		);
1419
+		EE_Registry::$i18n_js_strings['reg_step_error'] = esc_html__(
1420
+			'This registration step could not be completed. Please refresh the page and try again.',
1421
+			'event_espresso'
1422
+		);
1423
+		EE_Registry::$i18n_js_strings['invalid_coupon'] = esc_html__(
1424
+			'We\'re sorry but that coupon code does not appear to be valid. If this is incorrect, please contact the site administrator.',
1425
+			'event_espresso'
1426
+		);
1427
+		EE_Registry::$i18n_js_strings['process_registration'] = sprintf(
1428
+			esc_html__(
1429
+				'Please wait while we process your registration.%sDo not refresh the page or navigate away while this is happening.%sThank you for your patience.',
1430
+				'event_espresso'
1431
+			),
1432
+			'<br/>',
1433
+			'<br/>'
1434
+		);
1435
+		EE_Registry::$i18n_js_strings['language'] = get_bloginfo('language');
1436
+		EE_Registry::$i18n_js_strings['EESID'] = EE_Registry::instance()->SSN->id();
1437
+		EE_Registry::$i18n_js_strings['currency'] = EE_Registry::instance()->CFG->currency;
1438
+		EE_Registry::$i18n_js_strings['datepicker_yearRange'] = '-150:+20';
1439
+		EE_Registry::$i18n_js_strings['timer_years'] = esc_html__('years', 'event_espresso');
1440
+		EE_Registry::$i18n_js_strings['timer_months'] = esc_html__('months', 'event_espresso');
1441
+		EE_Registry::$i18n_js_strings['timer_weeks'] = esc_html__('weeks', 'event_espresso');
1442
+		EE_Registry::$i18n_js_strings['timer_days'] = esc_html__('days', 'event_espresso');
1443
+		EE_Registry::$i18n_js_strings['timer_hours'] = esc_html__('hours', 'event_espresso');
1444
+		EE_Registry::$i18n_js_strings['timer_minutes'] = esc_html__('minutes', 'event_espresso');
1445
+		EE_Registry::$i18n_js_strings['timer_seconds'] = esc_html__('seconds', 'event_espresso');
1446
+		EE_Registry::$i18n_js_strings['timer_year'] = esc_html__('year', 'event_espresso');
1447
+		EE_Registry::$i18n_js_strings['timer_month'] = esc_html__('month', 'event_espresso');
1448
+		EE_Registry::$i18n_js_strings['timer_week'] = esc_html__('week', 'event_espresso');
1449
+		EE_Registry::$i18n_js_strings['timer_day'] = esc_html__('day', 'event_espresso');
1450
+		EE_Registry::$i18n_js_strings['timer_hour'] = esc_html__('hour', 'event_espresso');
1451
+		EE_Registry::$i18n_js_strings['timer_minute'] = esc_html__('minute', 'event_espresso');
1452
+		EE_Registry::$i18n_js_strings['timer_second'] = esc_html__('second', 'event_espresso');
1453
+		EE_Registry::$i18n_js_strings['registration_expiration_notice'] = EED_Single_Page_Checkout::getRegistrationExpirationNotice(
1454
+		);
1455
+		EE_Registry::$i18n_js_strings['ajax_submit'] = apply_filters(
1456
+			'FHEE__Single_Page_Checkout__translate_js_strings__ajax_submit',
1457
+			true
1458
+		);
1459
+		EE_Registry::$i18n_js_strings['session_extension'] = absint(
1460
+			apply_filters('FHEE__EE_Session__extend_expiration__seconds_added', 10 * MINUTE_IN_SECONDS)
1461
+		);
1462
+		EE_Registry::$i18n_js_strings['session_expiration'] = gmdate(
1463
+			'M d, Y H:i:s',
1464
+			EE_Registry::instance()->SSN->expiration() + (get_option('gmt_offset') * HOUR_IN_SECONDS)
1465
+		);
1466
+	}
1467
+
1468
+
1469
+	/**
1470
+	 *    enqueue_styles_and_scripts
1471
+	 *
1472
+	 * @return        void
1473
+	 * @throws EE_Error
1474
+	 */
1475
+	public function enqueue_styles_and_scripts()
1476
+	{
1477
+		// load css
1478
+		wp_register_style(
1479
+			'single_page_checkout',
1480
+			SPCO_CSS_URL . 'single_page_checkout.css',
1481
+			array('espresso_default'),
1482
+			EVENT_ESPRESSO_VERSION
1483
+		);
1484
+		wp_enqueue_style('single_page_checkout');
1485
+		// load JS
1486
+		wp_register_script(
1487
+			'jquery_plugin',
1488
+			EE_THIRD_PARTY_URL . 'jquery	.plugin.min.js',
1489
+			array('jquery'),
1490
+			'1.0.1',
1491
+			true
1492
+		);
1493
+		wp_register_script(
1494
+			'jquery_countdown',
1495
+			EE_THIRD_PARTY_URL . 'jquery	.countdown.min.js',
1496
+			array('jquery_plugin'),
1497
+			'2.1.0',
1498
+			true
1499
+		);
1500
+		wp_register_script(
1501
+			'single_page_checkout',
1502
+			SPCO_JS_URL . 'single_page_checkout.js',
1503
+			array('espresso_core', 'underscore', 'ee_form_section_validation'),
1504
+			EVENT_ESPRESSO_VERSION,
1505
+			true
1506
+		);
1507
+		if ($this->checkout->registration_form instanceof EE_Form_Section_Proper) {
1508
+			$this->checkout->registration_form->enqueue_js();
1509
+		}
1510
+		if ($this->checkout->current_step->reg_form instanceof EE_Form_Section_Proper) {
1511
+			$this->checkout->current_step->reg_form->enqueue_js();
1512
+		}
1513
+		wp_enqueue_script('single_page_checkout');
1514
+		if (apply_filters('FHEE__registration_page_wrapper_template__display_time_limit', false)) {
1515
+			wp_enqueue_script('jquery_countdown');
1516
+		}
1517
+		/**
1518
+		 * global action hook for enqueueing styles and scripts with
1519
+		 * spco calls.
1520
+		 */
1521
+		do_action('AHEE__EED_Single_Page_Checkout__enqueue_styles_and_scripts', $this);
1522
+		/**
1523
+		 * dynamic action hook for enqueueing styles and scripts with spco calls.
1524
+		 * The hook will end up being something like:
1525
+		 *      AHEE__EED_Single_Page_Checkout__enqueue_styles_and_scripts__attendee_information
1526
+		 */
1527
+		do_action(
1528
+			'AHEE__EED_Single_Page_Checkout__enqueue_styles_and_scripts__' . $this->checkout->current_step->slug(),
1529
+			$this
1530
+		);
1531
+	}
1532
+
1533
+
1534
+	/**
1535
+	 *    display the Registration Single Page Checkout Form
1536
+	 *
1537
+	 * @return    void
1538
+	 * @throws EE_Error
1539
+	 * @throws ReflectionException
1540
+	 */
1541
+	private function _display_spco_reg_form()
1542
+	{
1543
+		// if registering via the admin, just display the reg form for the current step
1544
+		if ($this->checkout->admin_request) {
1545
+			EED_Single_Page_Checkout::getResponse()->addOutput($this->checkout->current_step->display_reg_form());
1546
+		} else {
1547
+			// add powered by EE msg
1548
+			add_action('AHEE__SPCO__reg_form_footer', array('EED_Single_Page_Checkout', 'display_registration_footer'));
1549
+			$empty_cart = count(
1550
+				$this->checkout->transaction->registrations($this->checkout->reg_cache_where_params)
1551
+			) < 1;
1552
+			EE_Registry::$i18n_js_strings['empty_cart'] = $empty_cart;
1553
+			$cookies_not_set_msg = '';
1554
+			if ($empty_cart) {
1555
+				$cookies_not_set_msg = apply_filters(
1556
+					'FHEE__Single_Page_Checkout__display_spco_reg_form__cookies_not_set_msg',
1557
+					sprintf(
1558
+						esc_html__(
1559
+							'%1$s%3$sIt appears your browser is not currently set to accept Cookies%4$s%5$sIn order to register for events, you need to enable cookies.%7$sIf you require assistance, then click the following link to learn how to %8$senable cookies%9$s%6$s%2$s',
1560
+							'event_espresso'
1561
+						),
1562
+						'<div class="ee-attention hidden" id="ee-cookies-not-set-msg">',
1563
+						'</div>',
1564
+						'<h6 class="important-notice">',
1565
+						'</h6>',
1566
+						'<p>',
1567
+						'</p>',
1568
+						'<br />',
1569
+						'<a href="https://www.whatismybrowser.com/guides/how-to-enable-cookies/" target="_blank" rel="noopener noreferrer">',
1570
+						'</a>'
1571
+					)
1572
+				);
1573
+			}
1574
+			$this->checkout->registration_form = new EE_Form_Section_Proper(
1575
+				array(
1576
+					'name'            => 'single-page-checkout',
1577
+					'html_id'         => 'ee-single-page-checkout-dv',
1578
+					'layout_strategy' =>
1579
+						new EE_Template_Layout(
1580
+							array(
1581
+								'layout_template_file' => SPCO_TEMPLATES_PATH . 'registration_page_wrapper.template.php',
1582
+								'template_args'        => array(
1583
+									'empty_cart'              => $empty_cart,
1584
+									'revisit'                 => $this->checkout->revisit,
1585
+									'reg_steps'               => $this->checkout->reg_steps,
1586
+									'next_step'               => $this->checkout->next_step instanceof EE_SPCO_Reg_Step
1587
+										? $this->checkout->next_step->slug()
1588
+										: '',
1589
+									'empty_msg'               => apply_filters(
1590
+										'FHEE__Single_Page_Checkout__display_spco_reg_form__empty_msg',
1591
+										sprintf(
1592
+											esc_html__(
1593
+												'You need to %1$sReturn to Events list%2$sselect at least one event%3$s before you can proceed with the registration process.',
1594
+												'event_espresso'
1595
+											),
1596
+											'<a href="'
1597
+											. get_post_type_archive_link('espresso_events')
1598
+											. '" title="',
1599
+											'">',
1600
+											'</a>'
1601
+										)
1602
+									),
1603
+									'cookies_not_set_msg'     => $cookies_not_set_msg,
1604
+									'registration_time_limit' => $this->checkout->get_registration_time_limit(),
1605
+									'session_expiration'      => gmdate(
1606
+										'M d, Y H:i:s',
1607
+										EE_Registry::instance()->SSN->expiration()
1608
+										+ (get_option('gmt_offset') * HOUR_IN_SECONDS)
1609
+									),
1610
+								),
1611
+							)
1612
+						),
1613
+				)
1614
+			);
1615
+			// load template and add to output sent that gets filtered into the_content()
1616
+			EED_Single_Page_Checkout::getResponse()->addOutput($this->checkout->registration_form->get_html());
1617
+		}
1618
+	}
1619
+
1620
+
1621
+	/**
1622
+	 *    add_extra_finalize_registration_inputs
1623
+	 *
1624
+	 * @param $next_step
1625
+	 * @internal  param string $label
1626
+	 * @return void
1627
+	 */
1628
+	public function add_extra_finalize_registration_inputs($next_step)
1629
+	{
1630
+		if ($next_step === 'finalize_registration') {
1631
+			echo '<div id="spco-extra-finalize_registration-inputs-dv"></div>';
1632
+		}
1633
+	}
1634
+
1635
+
1636
+	/**
1637
+	 *    display_registration_footer
1638
+	 *
1639
+	 * @return    string
1640
+	 */
1641
+	public static function display_registration_footer()
1642
+	{
1643
+		if (
1644
+			apply_filters(
1645
+				'FHEE__EE_Front__Controller__show_reg_footer',
1646
+				EE_Registry::instance()->CFG->admin->show_reg_footer
1647
+			)
1648
+		) {
1649
+			add_filter(
1650
+				'FHEE__EEH_Template__powered_by_event_espresso__url',
1651
+				function ($url) {
1652
+					return apply_filters('FHEE__EE_Front_Controller__registration_footer__url', $url);
1653
+				}
1654
+			);
1655
+			echo apply_filters(
1656
+				'FHEE__EE_Front_Controller__display_registration_footer',
1657
+				EEH_Template::powered_by_event_espresso(
1658
+					'',
1659
+					'espresso-registration-footer-dv',
1660
+					array('utm_content' => 'registration_checkout')
1661
+				)
1662
+			);
1663
+		}
1664
+		return '';
1665
+	}
1666
+
1667
+
1668
+	/**
1669
+	 *    unlock_transaction
1670
+	 *
1671
+	 * @return    void
1672
+	 * @throws EE_Error
1673
+	 * @throws ReflectionException
1674
+	 */
1675
+	public function unlock_transaction()
1676
+	{
1677
+		if ($this->checkout->transaction instanceof EE_Transaction) {
1678
+			$this->checkout->transaction->unlock();
1679
+		}
1680
+	}
1681
+
1682
+
1683
+	/**
1684
+	 *        _setup_redirect
1685
+	 *
1686
+	 * @return void
1687
+	 */
1688
+	private function _setup_redirect()
1689
+	{
1690
+		if ($this->checkout->continue_reg && $this->checkout->next_step instanceof EE_SPCO_Reg_Step) {
1691
+			$this->checkout->redirect = true;
1692
+			if (empty($this->checkout->redirect_url)) {
1693
+				$this->checkout->redirect_url = $this->checkout->next_step->reg_step_url();
1694
+			}
1695
+			$this->checkout->redirect_url = apply_filters(
1696
+				'FHEE__EED_Single_Page_Checkout___setup_redirect__checkout_redirect_url',
1697
+				$this->checkout->redirect_url,
1698
+				$this->checkout
1699
+			);
1700
+		}
1701
+	}
1702
+
1703
+
1704
+	/**
1705
+	 *   handle ajax message responses and redirects
1706
+	 *
1707
+	 * @return void
1708
+	 * @throws EE_Error
1709
+	 * @throws ReflectionException
1710
+	 */
1711
+	public function go_to_next_step()
1712
+	{
1713
+		if ($this->request->isAjax()) {
1714
+			// capture contents of output buffer we started earlier in the request, and insert into JSON response
1715
+			$this->checkout->json_response->set_unexpected_errors(ob_get_clean());
1716
+		}
1717
+		$this->unlock_transaction();
1718
+		// just return for these conditions
1719
+		if (
1720
+			$this->checkout->admin_request
1721
+			|| $this->checkout->action === 'redirect_form'
1722
+			|| $this->checkout->action === 'update_checkout'
1723
+		) {
1724
+			return;
1725
+		}
1726
+		// AJAX response
1727
+		$this->_handle_json_response();
1728
+		// redirect to next step or the Thank You page
1729
+		$this->_handle_html_redirects();
1730
+		// hmmm... must be something wrong, so let's just display the form again !
1731
+		$this->_display_spco_reg_form();
1732
+	}
1733
+
1734
+
1735
+	/**
1736
+	 *   _handle_json_response
1737
+	 *
1738
+	 * @return void
1739
+	 * @throws EE_Error
1740
+	 */
1741
+	protected function _handle_json_response()
1742
+	{
1743
+		// if this is an ajax request
1744
+		if ($this->request->isAjax()) {
1745
+			$this->checkout->json_response->set_registration_time_limit(
1746
+				$this->checkout->get_registration_time_limit()
1747
+			);
1748
+			$this->checkout->json_response->set_payment_amount($this->checkout->amount_owing);
1749
+			// just send the ajax (
1750
+			$json_response = apply_filters(
1751
+				'FHEE__EE_Single_Page_Checkout__JSON_response',
1752
+				$this->checkout->json_response
1753
+			);
1754
+			echo $json_response;
1755
+			exit();
1756
+		}
1757
+	}
1758
+
1759
+
1760
+	/**
1761
+	 *   _handle_redirects
1762
+	 *
1763
+	 * @return void
1764
+	 */
1765
+	protected function _handle_html_redirects()
1766
+	{
1767
+		// going somewhere ?
1768
+		if ($this->checkout->redirect && ! empty($this->checkout->redirect_url)) {
1769
+			// store notices in a transient
1770
+			EE_Error::get_notices(false, true);
1771
+			wp_safe_redirect($this->checkout->redirect_url);
1772
+			exit();
1773
+		}
1774
+	}
1775
+
1776
+
1777
+	/**
1778
+	 *   set_checkout_anchor
1779
+	 *
1780
+	 * @return void
1781
+	 */
1782
+	public function set_checkout_anchor()
1783
+	{
1784
+		echo '<a id="checkout" style="float: left; margin-left: -999em;"></a>';
1785
+	}
1786
+
1787
+	/**
1788
+	 *    getRegistrationExpirationNotice
1789
+	 *
1790
+	 * @since     4.9.59.p
1791
+	 * @return    string
1792
+	 */
1793
+	public static function getRegistrationExpirationNotice()
1794
+	{
1795
+		return sprintf(
1796
+			esc_html__(
1797
+				'%1$sWe\'re sorry, but your registration time has expired.%2$s%3$s%4$sIf you still wish to complete your registration, please return to the %5$sEvent List%6$sEvent List%7$s and reselect your tickets if available. Please accept our apologies for any inconvenience this may have caused.%8$s',
1798
+				'event_espresso'
1799
+			),
1800
+			'<h4 class="important-notice">',
1801
+			'</h4>',
1802
+			'<br />',
1803
+			'<p>',
1804
+			'<a href="' . get_post_type_archive_link('espresso_events') . '" title="',
1805
+			'">',
1806
+			'</a>',
1807
+			'</p>'
1808
+		);
1809
+	}
1810 1810
 }
Please login to merge, or discard this patch.
reg_steps/payment_options/EE_SPCO_Reg_Step_Payment_Options.class.php 2 patches
Spacing   +80 added lines, -80 removed lines patch added patch discarded remove patch
@@ -133,7 +133,7 @@  discard block
 block discarded – undo
133 133
         $this->request   = EED_Single_Page_Checkout::getRequest();
134 134
         $this->_slug     = 'payment_options';
135 135
         $this->_name     = esc_html__('Payment Options', 'event_espresso');
136
-        $this->_template = SPCO_REG_STEPS_PATH . $this->_slug . '/payment_options_main.template.php';
136
+        $this->_template = SPCO_REG_STEPS_PATH.$this->_slug.'/payment_options_main.template.php';
137 137
         $this->checkout  = $checkout;
138 138
         $this->_reset_success_message();
139 139
         $this->set_instructions(
@@ -188,7 +188,7 @@  discard block
 block discarded – undo
188 188
      */
189 189
     public function translate_js_strings()
190 190
     {
191
-        EE_Registry::$i18n_js_strings['no_payment_method']      = esc_html__(
191
+        EE_Registry::$i18n_js_strings['no_payment_method'] = esc_html__(
192 192
             'Please select a method of payment in order to continue.',
193 193
             'event_espresso'
194 194
         );
@@ -196,7 +196,7 @@  discard block
 block discarded – undo
196 196
             'A valid method of payment could not be determined. Please refresh the page and try again.',
197 197
             'event_espresso'
198 198
         );
199
-        EE_Registry::$i18n_js_strings['forwarding_to_offsite']  = esc_html__(
199
+        EE_Registry::$i18n_js_strings['forwarding_to_offsite'] = esc_html__(
200 200
             'Forwarding to Secure Payment Provider.',
201 201
             'event_espresso'
202 202
         );
@@ -217,7 +217,7 @@  discard block
 block discarded – undo
217 217
     {
218 218
         $transaction = $this->checkout->transaction;
219 219
         // if the transaction isn't set or nothing is owed on it, don't enqueue any JS
220
-        if (! $transaction instanceof EE_Transaction || EEH_Money::compare_floats($transaction->remaining(), 0)) {
220
+        if ( ! $transaction instanceof EE_Transaction || EEH_Money::compare_floats($transaction->remaining(), 0)) {
221 221
             return;
222 222
         }
223 223
         foreach (
@@ -312,18 +312,18 @@  discard block
 block discarded – undo
312 312
         foreach ($registrations as $REG_ID => $registration) {
313 313
             /** @var $registration EE_Registration */
314 314
             // has this registration lost it's space ?
315
-            if (isset($ejected_registrations[ $REG_ID ])) {
315
+            if (isset($ejected_registrations[$REG_ID])) {
316 316
                 if ($registration->event()->is_sold_out() || $registration->event()->is_sold_out(true)) {
317
-                    $sold_out_events[ $registration->event()->ID() ] = $registration->event();
317
+                    $sold_out_events[$registration->event()->ID()] = $registration->event();
318 318
                 } else {
319
-                    $insufficient_spaces_available[ $registration->event()->ID() ] = $registration->event();
319
+                    $insufficient_spaces_available[$registration->event()->ID()] = $registration->event();
320 320
                 }
321 321
                 continue;
322 322
             }
323 323
             // event requires admin approval
324 324
             if ($registration->status_ID() === EEM_Registration::status_id_not_approved) {
325 325
                 // add event to list of events with pre-approval reg status
326
-                $registrations_requiring_pre_approval[ $REG_ID ] = $registration;
326
+                $registrations_requiring_pre_approval[$REG_ID] = $registration;
327 327
                 do_action(
328 328
                     'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__event_requires_pre_approval',
329 329
                     $registration->event(),
@@ -340,7 +340,7 @@  discard block
 block discarded – undo
340 340
                 )
341 341
             ) {
342 342
                 // add event to list of events that are sold out
343
-                $sold_out_events[ $registration->event()->ID() ] = $registration->event();
343
+                $sold_out_events[$registration->event()->ID()] = $registration->event();
344 344
                 do_action(
345 345
                     'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__sold_out_event',
346 346
                     $registration->event(),
@@ -350,7 +350,7 @@  discard block
 block discarded – undo
350 350
             }
351 351
             // are they allowed to pay now and is there monies owing?
352 352
             if ($registration->owes_monies_and_can_pay()) {
353
-                $registrations_requiring_payment[ $REG_ID ] = $registration;
353
+                $registrations_requiring_payment[$REG_ID] = $registration;
354 354
                 do_action(
355 355
                     'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__event_requires_payment',
356 356
                     $registration->event(),
@@ -361,28 +361,28 @@  discard block
 block discarded – undo
361 361
                       && $registration->status_ID() !== EEM_Registration::status_id_not_approved
362 362
                       && $registration->ticket()->is_free()
363 363
             ) {
364
-                $registrations_for_free_events[ $registration->ticket()->ID() ] = $registration;
364
+                $registrations_for_free_events[$registration->ticket()->ID()] = $registration;
365 365
             }
366 366
         }
367 367
         $subsections = [];
368 368
         // now decide which template to load
369
-        if (! empty($sold_out_events)) {
369
+        if ( ! empty($sold_out_events)) {
370 370
             $subsections['sold_out_events'] = $this->_sold_out_events($sold_out_events);
371 371
         }
372
-        if (! empty($insufficient_spaces_available)) {
372
+        if ( ! empty($insufficient_spaces_available)) {
373 373
             $subsections['insufficient_space'] = $this->_insufficient_spaces_available(
374 374
                 $insufficient_spaces_available
375 375
             );
376 376
         }
377
-        if (! empty($registrations_requiring_pre_approval)) {
377
+        if ( ! empty($registrations_requiring_pre_approval)) {
378 378
             $subsections['registrations_requiring_pre_approval'] = $this->_registrations_requiring_pre_approval(
379 379
                 $registrations_requiring_pre_approval
380 380
             );
381 381
         }
382
-        if (! empty($registrations_for_free_events)) {
382
+        if ( ! empty($registrations_for_free_events)) {
383 383
             $subsections['no_payment_required'] = $this->_no_payment_required($registrations_for_free_events);
384 384
         }
385
-        if (! empty($registrations_requiring_payment)) {
385
+        if ( ! empty($registrations_requiring_payment)) {
386 386
             if ($this->checkout->amount_owing > 0) {
387 387
                 // autoload Line_Item_Display classes
388 388
                 EEH_Autoloader::register_line_item_filter_autoloaders();
@@ -403,7 +403,7 @@  discard block
 block discarded – undo
403 403
                         ['registrations' => $registrations]
404 404
                     )
405 405
                 );
406
-                $this->checkout->amount_owing   = $filtered_line_item_tree->total();
406
+                $this->checkout->amount_owing = $filtered_line_item_tree->total();
407 407
                 $this->_apply_registration_payments_to_amount_owing($registrations);
408 408
             }
409 409
             $no_payment_required = false;
@@ -447,13 +447,13 @@  discard block
 block discarded – undo
447 447
      */
448 448
     public static function add_spco_line_item_filters(EE_Line_Item_Filter_Collection $line_item_filter_collection)
449 449
     {
450
-        if (! EE_Registry::instance()->SSN instanceof EE_Session) {
450
+        if ( ! EE_Registry::instance()->SSN instanceof EE_Session) {
451 451
             return $line_item_filter_collection;
452 452
         }
453
-        if (! EE_Registry::instance()->SSN->checkout() instanceof EE_Checkout) {
453
+        if ( ! EE_Registry::instance()->SSN->checkout() instanceof EE_Checkout) {
454 454
             return $line_item_filter_collection;
455 455
         }
456
-        if (! EE_Registry::instance()->SSN->checkout()->transaction instanceof EE_Transaction) {
456
+        if ( ! EE_Registry::instance()->SSN->checkout()->transaction instanceof EE_Transaction) {
457 457
             return $line_item_filter_collection;
458 458
         }
459 459
         $line_item_filter_collection->add(
@@ -493,8 +493,8 @@  discard block
 block discarded – undo
493 493
         );
494 494
         foreach ($registrations as $REG_ID => $registration) {
495 495
             // has this registration lost it's space ?
496
-            if (isset($ejected_registrations[ $REG_ID ])) {
497
-                unset($registrations[ $REG_ID ]);
496
+            if (isset($ejected_registrations[$REG_ID])) {
497
+                unset($registrations[$REG_ID]);
498 498
             }
499 499
         }
500 500
         return $registrations;
@@ -544,25 +544,25 @@  discard block
 block discarded – undo
544 544
             }
545 545
             $EVT_ID = $registration->event_ID();
546 546
             $ticket = $registration->ticket();
547
-            if (! isset($tickets_remaining[ $ticket->ID() ])) {
548
-                $tickets_remaining[ $ticket->ID() ] = $ticket->remaining();
547
+            if ( ! isset($tickets_remaining[$ticket->ID()])) {
548
+                $tickets_remaining[$ticket->ID()] = $ticket->remaining();
549 549
             }
550
-            if ($tickets_remaining[ $ticket->ID() ] > 0) {
551
-                if (! isset($event_reg_count[ $EVT_ID ])) {
552
-                    $event_reg_count[ $EVT_ID ] = 0;
550
+            if ($tickets_remaining[$ticket->ID()] > 0) {
551
+                if ( ! isset($event_reg_count[$EVT_ID])) {
552
+                    $event_reg_count[$EVT_ID] = 0;
553 553
                 }
554
-                $event_reg_count[ $EVT_ID ]++;
555
-                if (! isset($event_spaces_remaining[ $EVT_ID ])) {
556
-                    $event_spaces_remaining[ $EVT_ID ] = $registration->event()->spaces_remaining_for_sale();
554
+                $event_reg_count[$EVT_ID]++;
555
+                if ( ! isset($event_spaces_remaining[$EVT_ID])) {
556
+                    $event_spaces_remaining[$EVT_ID] = $registration->event()->spaces_remaining_for_sale();
557 557
                 }
558 558
             }
559 559
             if (
560 560
                 $revisit
561
-                && ($tickets_remaining[ $ticket->ID() ] === 0
562
-                    || $event_reg_count[ $EVT_ID ] > $event_spaces_remaining[ $EVT_ID ]
561
+                && ($tickets_remaining[$ticket->ID()] === 0
562
+                    || $event_reg_count[$EVT_ID] > $event_spaces_remaining[$EVT_ID]
563 563
                 )
564 564
             ) {
565
-                $ejected_registrations[ $REG_ID ] = $registration->event();
565
+                $ejected_registrations[$REG_ID] = $registration->event();
566 566
                 if ($registration->status_ID() !== EEM_Registration::status_id_wait_list) {
567 567
                     /** @type EE_Registration_Processor $registration_processor */
568 568
                     $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
@@ -622,7 +622,7 @@  discard block
 block discarded – undo
622 622
         foreach ($sold_out_events_array as $sold_out_event) {
623 623
             $sold_out_events .= EEH_HTML::li(
624 624
                 EEH_HTML::span(
625
-                    '  ' . $sold_out_event->name(),
625
+                    '  '.$sold_out_event->name(),
626 626
                     '',
627 627
                     'dashicons dashicons-marker ee-icon-size-16 pink-text'
628 628
                 )
@@ -678,7 +678,7 @@  discard block
 block discarded – undo
678 678
         foreach ($insufficient_spaces_events_array as $event) {
679 679
             if ($event instanceof EE_Event) {
680 680
                 $insufficient_space_events .= EEH_HTML::li(
681
-                    EEH_HTML::span(' ' . $event->name(), '', 'dashicons dashicons-marker ee-icon-size-16 pink-text')
681
+                    EEH_HTML::span(' '.$event->name(), '', 'dashicons dashicons-marker ee-icon-size-16 pink-text')
682 682
                 );
683 683
             }
684 684
         }
@@ -727,7 +727,7 @@  discard block
 block discarded – undo
727 727
         $events_requiring_pre_approval = [];
728 728
         foreach ($registrations_requiring_pre_approval as $registration) {
729 729
             if ($registration instanceof EE_Registration && $registration->event() instanceof EE_Event) {
730
-                $events_requiring_pre_approval[ $registration->event()->ID() ] = EEH_HTML::li(
730
+                $events_requiring_pre_approval[$registration->event()->ID()] = EEH_HTML::li(
731 731
                     EEH_HTML::span(
732 732
                         '',
733 733
                         '',
@@ -867,7 +867,7 @@  discard block
 block discarded – undo
867 867
     {
868 868
         return new EE_Form_Section_Proper(
869 869
             [
870
-                'html_id'         => 'ee-' . $this->slug() . '-extra-hidden-inputs',
870
+                'html_id'         => 'ee-'.$this->slug().'-extra-hidden-inputs',
871 871
                 'layout_strategy' => new EE_Div_Per_Section_Layout(),
872 872
                 'subsections'     => [
873 873
                     'spco_no_payment_required' => new EE_Hidden_Input(
@@ -906,7 +906,7 @@  discard block
 block discarded – undo
906 906
                 $payments += $registration->registration_payments();
907 907
             }
908 908
         }
909
-        if (! empty($payments)) {
909
+        if ( ! empty($payments)) {
910 910
             foreach ($payments as $payment) {
911 911
                 if ($payment instanceof EE_Registration_Payment) {
912 912
                     $this->checkout->amount_owing -= $payment->amount();
@@ -995,7 +995,7 @@  discard block
 block discarded – undo
995 995
             );
996 996
         }
997 997
         // switch up header depending on number of available payment methods
998
-        $payment_method_header     = count($this->checkout->available_payment_methods) > 1
998
+        $payment_method_header = count($this->checkout->available_payment_methods) > 1
999 999
             ? apply_filters(
1000 1000
                 'FHEE__registration_page_payment_options__method_of_payment_hdr',
1001 1001
                 esc_html__('Please Select Your Method of Payment', 'event_espresso')
@@ -1029,7 +1029,7 @@  discard block
 block discarded – undo
1029 1029
                 $payment_method_button = EEH_HTML::img(
1030 1030
                     $payment_method->button_url(),
1031 1031
                     $payment_method->name(),
1032
-                    'spco-payment-method-' . $payment_method->slug() . '-btn-img',
1032
+                    'spco-payment-method-'.$payment_method->slug().'-btn-img',
1033 1033
                     'spco-payment-method-btn-img'
1034 1034
                 );
1035 1035
                 // check if any payment methods are set as default
@@ -1037,15 +1037,15 @@  discard block
 block discarded – undo
1037 1037
                 // open_by_default
1038 1038
                 if (
1039 1039
                     ($this->checkout->selected_method_of_payment === $payment_method->slug())
1040
-                    || (! $this->checkout->selected_method_of_payment && $payment_method->open_by_default())
1040
+                    || ( ! $this->checkout->selected_method_of_payment && $payment_method->open_by_default())
1041 1041
                 ) {
1042 1042
                     $this->checkout->selected_method_of_payment = $payment_method->slug();
1043 1043
                     $this->_save_selected_method_of_payment();
1044
-                    $default_payment_method_option[ $payment_method->slug() ] = $payment_method_button;
1044
+                    $default_payment_method_option[$payment_method->slug()] = $payment_method_button;
1045 1045
                 } else {
1046
-                    $available_payment_method_options[ $payment_method->slug() ] = $payment_method_button;
1046
+                    $available_payment_method_options[$payment_method->slug()] = $payment_method_button;
1047 1047
                 }
1048
-                $payment_methods_billing_info[ $payment_method->slug() . '-info' ] =
1048
+                $payment_methods_billing_info[$payment_method->slug().'-info'] =
1049 1049
                     $this->_payment_method_billing_info(
1050 1050
                         $payment_method
1051 1051
                     );
@@ -1058,7 +1058,7 @@  discard block
 block discarded – undo
1058 1058
         $available_payment_methods['available_payment_methods'] = $this->_available_payment_method_inputs(
1059 1059
             $available_payment_method_options
1060 1060
         );
1061
-        $available_payment_methods                              += $payment_methods_billing_info;
1061
+        $available_payment_methods += $payment_methods_billing_info;
1062 1062
         // build the available payment methods form
1063 1063
         return new EE_Form_Section_Proper(
1064 1064
             [
@@ -1081,7 +1081,7 @@  discard block
 block discarded – undo
1081 1081
      */
1082 1082
     protected function _get_available_payment_methods()
1083 1083
     {
1084
-        if (! empty($this->checkout->available_payment_methods)) {
1084
+        if ( ! empty($this->checkout->available_payment_methods)) {
1085 1085
             return $this->checkout->available_payment_methods;
1086 1086
         }
1087 1087
         $available_payment_methods = [];
@@ -1093,7 +1093,7 @@  discard block
 block discarded – undo
1093 1093
         );
1094 1094
         foreach ($payment_methods as $payment_method) {
1095 1095
             if ($payment_method instanceof EE_Payment_Method) {
1096
-                $available_payment_methods[ $payment_method->slug() ] = $payment_method;
1096
+                $available_payment_methods[$payment_method->slug()] = $payment_method;
1097 1097
             }
1098 1098
         }
1099 1099
         return $available_payment_methods;
@@ -1188,7 +1188,7 @@  discard block
 block discarded – undo
1188 1188
         );
1189 1189
         return new EE_Form_Section_Proper(
1190 1190
             [
1191
-                'html_id'         => 'spco-payment-method-info-' . $payment_method->slug(),
1191
+                'html_id'         => 'spco-payment-method-info-'.$payment_method->slug(),
1192 1192
                 'html_class'      => 'spco-payment-method-info-dv',
1193 1193
                 // only display the selected or default PM
1194 1194
                 'html_style'      => $currently_selected ? '' : 'display:none;',
@@ -1217,7 +1217,7 @@  discard block
 block discarded – undo
1217 1217
         // how have they chosen to pay?
1218 1218
         $this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
1219 1219
         $this->checkout->payment_method             = $this->_get_payment_method_for_selected_method_of_payment();
1220
-        if (! $this->checkout->payment_method instanceof EE_Payment_Method) {
1220
+        if ( ! $this->checkout->payment_method instanceof EE_Payment_Method) {
1221 1221
             return false;
1222 1222
         }
1223 1223
         if (
@@ -1392,7 +1392,7 @@  discard block
 block discarded – undo
1392 1392
      */
1393 1393
     public function switch_payment_method()
1394 1394
     {
1395
-        if (! $this->_verify_payment_method_is_set()) {
1395
+        if ( ! $this->_verify_payment_method_is_set()) {
1396 1396
             return false;
1397 1397
         }
1398 1398
         if (
@@ -1528,7 +1528,7 @@  discard block
 block discarded – undo
1528 1528
             }
1529 1529
         }
1530 1530
         // verify payment method
1531
-        if (! $this->checkout->payment_method instanceof EE_Payment_Method) {
1531
+        if ( ! $this->checkout->payment_method instanceof EE_Payment_Method) {
1532 1532
             // get payment method for selected method of payment
1533 1533
             $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment();
1534 1534
         }
@@ -1553,7 +1553,7 @@  discard block
 block discarded – undo
1553 1553
      */
1554 1554
     public function save_payer_details_via_ajax()
1555 1555
     {
1556
-        if (! $this->_verify_payment_method_is_set()) {
1556
+        if ( ! $this->_verify_payment_method_is_set()) {
1557 1557
             return;
1558 1558
         }
1559 1559
         // generate billing form for selected method of payment if it hasn't been done already
@@ -1563,7 +1563,7 @@  discard block
 block discarded – undo
1563 1563
             );
1564 1564
         }
1565 1565
         // generate primary attendee from payer info if applicable
1566
-        if (! $this->checkout->transaction_has_primary_registrant()) {
1566
+        if ( ! $this->checkout->transaction_has_primary_registrant()) {
1567 1567
             $attendee = $this->_create_attendee_from_request_data();
1568 1568
             if ($attendee instanceof EE_Attendee) {
1569 1569
                 foreach ($this->checkout->transaction->registrations() as $registration) {
@@ -1594,7 +1594,7 @@  discard block
 block discarded – undo
1594 1594
     {
1595 1595
         // get State ID
1596 1596
         $STA_ID = $this->request->getRequestParam('state');
1597
-        if (! empty($STA_ID)) {
1597
+        if ( ! empty($STA_ID)) {
1598 1598
             // can we get state object from name ?
1599 1599
             EE_Registry::instance()->load_model('State');
1600 1600
             $state  = EEM_State::instance()->get_col([['STA_name' => $STA_ID], 'limit' => 1], 'STA_ID');
@@ -1602,7 +1602,7 @@  discard block
 block discarded – undo
1602 1602
         }
1603 1603
         // get Country ISO
1604 1604
         $CNT_ISO = $this->request->getRequestParam('country');
1605
-        if (! empty($CNT_ISO)) {
1605
+        if ( ! empty($CNT_ISO)) {
1606 1606
             // can we get country object from name ?
1607 1607
             EE_Registry::instance()->load_model('Country');
1608 1608
             $country = EEM_Country::instance()->get_col(
@@ -1849,7 +1849,7 @@  discard block
 block discarded – undo
1849 1849
     private function _process_payment()
1850 1850
     {
1851 1851
         // basically confirm that the event hasn't sold out since they hit the page
1852
-        if (! $this->_last_second_ticket_verifications()) {
1852
+        if ( ! $this->_last_second_ticket_verifications()) {
1853 1853
             return false;
1854 1854
         }
1855 1855
         // ya gotta make a choice man
@@ -1860,7 +1860,7 @@  discard block
 block discarded – undo
1860 1860
             return false;
1861 1861
         }
1862 1862
         // get EE_Payment_Method object
1863
-        if (! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()) {
1863
+        if ( ! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()) {
1864 1864
             return false;
1865 1865
         }
1866 1866
         // setup billing form
@@ -1869,12 +1869,12 @@  discard block
 block discarded – undo
1869 1869
                 $this->checkout->payment_method
1870 1870
             );
1871 1871
             // bad billing form ?
1872
-            if (! $this->_billing_form_is_valid()) {
1872
+            if ( ! $this->_billing_form_is_valid()) {
1873 1873
                 return false;
1874 1874
             }
1875 1875
         }
1876 1876
         // ensure primary registrant has been fully processed
1877
-        if (! $this->_setup_primary_registrant_prior_to_payment()) {
1877
+        if ( ! $this->_setup_primary_registrant_prior_to_payment()) {
1878 1878
             return false;
1879 1879
         }
1880 1880
         // if session is close to expiring (under 10 minutes by default)
@@ -1925,7 +1925,7 @@  discard block
 block discarded – undo
1925 1925
     protected function _last_second_ticket_verifications()
1926 1926
     {
1927 1927
         // don't bother re-validating if not a return visit
1928
-        if (! $this->checkout->revisit) {
1928
+        if ( ! $this->checkout->revisit) {
1929 1929
             return true;
1930 1930
         }
1931 1931
         $registrations = $this->checkout->transaction->registrations();
@@ -1975,7 +1975,7 @@  discard block
 block discarded – undo
1975 1975
             $this->_get_payment_method_for_selected_method_of_payment()
1976 1976
         );
1977 1977
         $html                        = $payment_method_billing_info->get_html();
1978
-        $html                        .= $this->checkout->redirect_form;
1978
+        $html .= $this->checkout->redirect_form;
1979 1979
         /** @var ResponseInterface $response */
1980 1980
         $response = LoaderFactory::getLoader()->getShared(ResponseInterface::class);
1981 1981
         $response->addOutput($html);
@@ -1991,7 +1991,7 @@  discard block
 block discarded – undo
1991 1991
      */
1992 1992
     private function _billing_form_is_valid()
1993 1993
     {
1994
-        if (! $this->checkout->payment_method->type_obj()->has_billing_form()) {
1994
+        if ( ! $this->checkout->payment_method->type_obj()->has_billing_form()) {
1995 1995
             return true;
1996 1996
         }
1997 1997
         if ($this->checkout->billing_form instanceof EE_Billing_Info_Form) {
@@ -2109,7 +2109,7 @@  discard block
 block discarded – undo
2109 2109
     {
2110 2110
         // convert billing form data into an attendee
2111 2111
         $this->checkout->primary_attendee_obj = $this->checkout->billing_form->create_attendee_from_billing_form_data();
2112
-        if (! $this->checkout->primary_attendee_obj instanceof EE_Attendee) {
2112
+        if ( ! $this->checkout->primary_attendee_obj instanceof EE_Attendee) {
2113 2113
             EE_Error::add_error(
2114 2114
                 sprintf(
2115 2115
                     esc_html__(
@@ -2126,7 +2126,7 @@  discard block
 block discarded – undo
2126 2126
             return false;
2127 2127
         }
2128 2128
         $primary_registration = $this->checkout->transaction->primary_registration();
2129
-        if (! $primary_registration instanceof EE_Registration) {
2129
+        if ( ! $primary_registration instanceof EE_Registration) {
2130 2130
             EE_Error::add_error(
2131 2131
                 sprintf(
2132 2132
                     esc_html__(
@@ -2188,8 +2188,8 @@  discard block
 block discarded – undo
2188 2188
             return null;
2189 2189
         }
2190 2190
         // get EE_Payment_Method object
2191
-        if (isset($this->checkout->available_payment_methods[ $this->checkout->selected_method_of_payment ])) {
2192
-            $payment_method = $this->checkout->available_payment_methods[ $this->checkout->selected_method_of_payment ];
2191
+        if (isset($this->checkout->available_payment_methods[$this->checkout->selected_method_of_payment])) {
2192
+            $payment_method = $this->checkout->available_payment_methods[$this->checkout->selected_method_of_payment];
2193 2193
         } else {
2194 2194
             // load EEM_Payment_Method
2195 2195
             EE_Registry::instance()->load_model('Payment_Method');
@@ -2197,7 +2197,7 @@  discard block
 block discarded – undo
2197 2197
             $payment_method     = $EEM_Payment_Method->get_one_by_slug($this->checkout->selected_method_of_payment);
2198 2198
         }
2199 2199
         // verify $payment_method
2200
-        if (! $payment_method instanceof EE_Payment_Method) {
2200
+        if ( ! $payment_method instanceof EE_Payment_Method) {
2201 2201
             // not a payment
2202 2202
             EE_Error::add_error(
2203 2203
                 sprintf(
@@ -2215,7 +2215,7 @@  discard block
 block discarded – undo
2215 2215
             return null;
2216 2216
         }
2217 2217
         // and verify it has a valid Payment_Method Type object
2218
-        if (! $payment_method->type_obj() instanceof EE_PMT_Base) {
2218
+        if ( ! $payment_method->type_obj() instanceof EE_PMT_Base) {
2219 2219
             // not a payment
2220 2220
             EE_Error::add_error(
2221 2221
                 sprintf(
@@ -2253,7 +2253,7 @@  discard block
 block discarded – undo
2253 2253
         $payment = null;
2254 2254
         $this->checkout->transaction->save();
2255 2255
         $payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2256
-        if (! $payment_processor instanceof EE_Payment_Processor) {
2256
+        if ( ! $payment_processor instanceof EE_Payment_Processor) {
2257 2257
             return false;
2258 2258
         }
2259 2259
         try {
@@ -2355,7 +2355,7 @@  discard block
 block discarded – undo
2355 2355
             return true;
2356 2356
         }
2357 2357
         // verify payment object
2358
-        if (! $payment instanceof EE_Payment) {
2358
+        if ( ! $payment instanceof EE_Payment) {
2359 2359
             // not a payment
2360 2360
             EE_Error::add_error(
2361 2361
                 sprintf(
@@ -2395,7 +2395,7 @@  discard block
 block discarded – undo
2395 2395
             return true;
2396 2396
             // On-Site payment?
2397 2397
         } elseif ($this->checkout->payment_method->is_on_site()) {
2398
-            if (! $this->_process_payment_status($payment, EE_PMT_Base::onsite)) {
2398
+            if ( ! $this->_process_payment_status($payment, EE_PMT_Base::onsite)) {
2399 2399
                 // $this->_setup_redirect_for_next_step();
2400 2400
                 $this->checkout->continue_reg = false;
2401 2401
             }
@@ -2423,7 +2423,7 @@  discard block
 block discarded – undo
2423 2423
                     EE_Registry::instance()->CFG->organization->get_pretty('email')
2424 2424
                 );
2425 2425
                 if ($payment instanceof EE_Payment && $payment->gateway_response()) {
2426
-                    $error_message = $error_message . '<br/>' . $payment->gateway_response();
2426
+                    $error_message = $error_message.'<br/>'.$payment->gateway_response();
2427 2427
                 }
2428 2428
                 $this->checkout->continue_reg = false;
2429 2429
                 EE_Error::add_error(
@@ -2510,7 +2510,7 @@  discard block
 block discarded – undo
2510 2510
                     return false;
2511 2511
                 // bad payment
2512 2512
                 case EEM_Payment::status_id_failed:
2513
-                    if (! empty($msg)) {
2513
+                    if ( ! empty($msg)) {
2514 2514
                         EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2515 2515
                         return false;
2516 2516
                     }
@@ -2568,18 +2568,18 @@  discard block
 block discarded – undo
2568 2568
         // how have they chosen to pay?
2569 2569
         $this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
2570 2570
         // get EE_Payment_Method object
2571
-        if (! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()) {
2571
+        if ( ! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()) {
2572 2572
             $this->checkout->continue_reg = false;
2573 2573
             return false;
2574 2574
         }
2575
-        if (! $this->checkout->payment_method->is_off_site()) {
2575
+        if ( ! $this->checkout->payment_method->is_off_site()) {
2576 2576
             return false;
2577 2577
         }
2578 2578
         $this->_validate_offsite_return();
2579 2579
         // verify TXN
2580 2580
         if ($this->checkout->transaction instanceof EE_Transaction) {
2581 2581
             $gateway = $this->checkout->payment_method->type_obj()->get_gateway();
2582
-            if (! $gateway instanceof EE_Offsite_Gateway) {
2582
+            if ( ! $gateway instanceof EE_Offsite_Gateway) {
2583 2583
                 $this->checkout->continue_reg = false;
2584 2584
                 return false;
2585 2585
             }
@@ -2593,7 +2593,7 @@  discard block
 block discarded – undo
2593 2593
                 $this->checkout->payment = $payment;
2594 2594
                 // mark this reg step as completed, as long as gateway doesn't use a separate IPN request,
2595 2595
                 // because we will complete this step during the IPN processing then
2596
-                if (! $this->handle_IPN_in_this_request()) {
2596
+                if ( ! $this->handle_IPN_in_this_request()) {
2597 2597
                     $this->set_completed();
2598 2598
                 }
2599 2599
                 return true;
@@ -2696,13 +2696,13 @@  discard block
 block discarded – undo
2696 2696
      */
2697 2697
     private function _redirect_wayward_request(EE_Registration $primary_registrant)
2698 2698
     {
2699
-        if (! $primary_registrant instanceof EE_Registration) {
2699
+        if ( ! $primary_registrant instanceof EE_Registration) {
2700 2700
             // try redirecting based on the current TXN
2701 2701
             $primary_registrant = $this->checkout->transaction instanceof EE_Transaction
2702 2702
                 ? $this->checkout->transaction->primary_registration()
2703 2703
                 : null;
2704 2704
         }
2705
-        if (! $primary_registrant instanceof EE_Registration) {
2705
+        if ( ! $primary_registrant instanceof EE_Registration) {
2706 2706
             EE_Error::add_error(
2707 2707
                 sprintf(
2708 2708
                     esc_html__(
@@ -2773,7 +2773,7 @@  discard block
 block discarded – undo
2773 2773
             $payment = $this->checkout->transaction->last_payment();
2774 2774
             // $payment_source = 'last_payment after Exception';
2775 2775
             // but if we STILL don't have a payment object
2776
-            if (! $payment instanceof EE_Payment) {
2776
+            if ( ! $payment instanceof EE_Payment) {
2777 2777
                 // then we'll object ! ( not object like a thing... but object like what a lawyer says ! )
2778 2778
                 $this->_handle_payment_processor_exception($e);
2779 2779
             }
Please login to merge, or discard this patch.
Indentation   +2856 added lines, -2856 removed lines patch added patch discarded remove patch
@@ -20,2860 +20,2860 @@
 block discarded – undo
20 20
 class EE_SPCO_Reg_Step_Payment_Options extends EE_SPCO_Reg_Step
21 21
 {
22 22
 
23
-    /**
24
-     * @var EE_Line_Item_Display $Line_Item_Display
25
-     */
26
-    protected $line_item_display;
27
-
28
-    /**
29
-     * @var boolean $handle_IPN_in_this_request
30
-     */
31
-    protected $handle_IPN_in_this_request = false;
32
-
33
-
34
-    /**
35
-     *    set_hooks - for hooking into EE Core, other modules, etc
36
-     *
37
-     * @access    public
38
-     * @return    void
39
-     */
40
-    public static function set_hooks()
41
-    {
42
-        add_filter(
43
-            'FHEE__SPCO__EE_Line_Item_Filter_Collection',
44
-            ['EE_SPCO_Reg_Step_Payment_Options', 'add_spco_line_item_filters']
45
-        );
46
-        add_action(
47
-            'wp_ajax_switch_spco_billing_form',
48
-            ['EE_SPCO_Reg_Step_Payment_Options', 'switch_spco_billing_form']
49
-        );
50
-        add_action(
51
-            'wp_ajax_nopriv_switch_spco_billing_form',
52
-            ['EE_SPCO_Reg_Step_Payment_Options', 'switch_spco_billing_form']
53
-        );
54
-        add_action('wp_ajax_save_payer_details', ['EE_SPCO_Reg_Step_Payment_Options', 'save_payer_details']);
55
-        add_action(
56
-            'wp_ajax_nopriv_save_payer_details',
57
-            ['EE_SPCO_Reg_Step_Payment_Options', 'save_payer_details']
58
-        );
59
-        add_action(
60
-            'wp_ajax_get_transaction_details_for_gateways',
61
-            ['EE_SPCO_Reg_Step_Payment_Options', 'get_transaction_details']
62
-        );
63
-        add_action(
64
-            'wp_ajax_nopriv_get_transaction_details_for_gateways',
65
-            ['EE_SPCO_Reg_Step_Payment_Options', 'get_transaction_details']
66
-        );
67
-        add_filter(
68
-            'FHEE__EED_Recaptcha___bypass_recaptcha__bypass_request_params_array',
69
-            ['EE_SPCO_Reg_Step_Payment_Options', 'bypass_recaptcha_for_load_payment_method'],
70
-            10,
71
-            1
72
-        );
73
-    }
74
-
75
-
76
-    /**
77
-     *    ajax switch_spco_billing_form
78
-     *
79
-     */
80
-    public static function switch_spco_billing_form()
81
-    {
82
-        EED_Single_Page_Checkout::process_ajax_request('switch_payment_method');
83
-    }
84
-
85
-
86
-    /**
87
-     *    ajax save_payer_details
88
-     *
89
-     */
90
-    public static function save_payer_details()
91
-    {
92
-        EED_Single_Page_Checkout::process_ajax_request('save_payer_details_via_ajax');
93
-    }
94
-
95
-
96
-    /**
97
-     *    ajax get_transaction_details
98
-     *
99
-     */
100
-    public static function get_transaction_details()
101
-    {
102
-        EED_Single_Page_Checkout::process_ajax_request('get_transaction_details_for_gateways');
103
-    }
104
-
105
-
106
-    /**
107
-     * bypass_recaptcha_for_load_payment_method
108
-     *
109
-     * @access public
110
-     * @return array
111
-     * @throws InvalidArgumentException
112
-     * @throws InvalidDataTypeException
113
-     * @throws InvalidInterfaceException
114
-     */
115
-    public static function bypass_recaptcha_for_load_payment_method()
116
-    {
117
-        return [
118
-            'EESID'  => EE_Registry::instance()->SSN->id(),
119
-            'step'   => 'payment_options',
120
-            'action' => 'spco_billing_form',
121
-        ];
122
-    }
123
-
124
-
125
-    /**
126
-     *    class constructor
127
-     *
128
-     * @access    public
129
-     * @param EE_Checkout $checkout
130
-     */
131
-    public function __construct(EE_Checkout $checkout)
132
-    {
133
-        $this->request   = EED_Single_Page_Checkout::getRequest();
134
-        $this->_slug     = 'payment_options';
135
-        $this->_name     = esc_html__('Payment Options', 'event_espresso');
136
-        $this->_template = SPCO_REG_STEPS_PATH . $this->_slug . '/payment_options_main.template.php';
137
-        $this->checkout  = $checkout;
138
-        $this->_reset_success_message();
139
-        $this->set_instructions(
140
-            esc_html__(
141
-                'Please select a method of payment and provide any necessary billing information before proceeding.',
142
-                'event_espresso'
143
-            )
144
-        );
145
-    }
146
-
147
-
148
-    /**
149
-     * @return null
150
-     */
151
-    public function line_item_display()
152
-    {
153
-        return $this->line_item_display;
154
-    }
155
-
156
-
157
-    /**
158
-     * @param null $line_item_display
159
-     */
160
-    public function set_line_item_display($line_item_display)
161
-    {
162
-        $this->line_item_display = $line_item_display;
163
-    }
164
-
165
-
166
-    /**
167
-     * @return boolean
168
-     */
169
-    public function handle_IPN_in_this_request()
170
-    {
171
-        return $this->handle_IPN_in_this_request;
172
-    }
173
-
174
-
175
-    /**
176
-     * @param boolean $handle_IPN_in_this_request
177
-     */
178
-    public function set_handle_IPN_in_this_request($handle_IPN_in_this_request)
179
-    {
180
-        $this->handle_IPN_in_this_request = filter_var($handle_IPN_in_this_request, FILTER_VALIDATE_BOOLEAN);
181
-    }
182
-
183
-
184
-    /**
185
-     * translate_js_strings
186
-     *
187
-     * @return void
188
-     */
189
-    public function translate_js_strings()
190
-    {
191
-        EE_Registry::$i18n_js_strings['no_payment_method']      = esc_html__(
192
-            'Please select a method of payment in order to continue.',
193
-            'event_espresso'
194
-        );
195
-        EE_Registry::$i18n_js_strings['invalid_payment_method'] = esc_html__(
196
-            'A valid method of payment could not be determined. Please refresh the page and try again.',
197
-            'event_espresso'
198
-        );
199
-        EE_Registry::$i18n_js_strings['forwarding_to_offsite']  = esc_html__(
200
-            'Forwarding to Secure Payment Provider.',
201
-            'event_espresso'
202
-        );
203
-    }
204
-
205
-
206
-    /**
207
-     * enqueue_styles_and_scripts
208
-     *
209
-     * @return void
210
-     * @throws EE_Error
211
-     * @throws InvalidArgumentException
212
-     * @throws InvalidDataTypeException
213
-     * @throws InvalidInterfaceException
214
-     * @throws ReflectionException
215
-     */
216
-    public function enqueue_styles_and_scripts()
217
-    {
218
-        $transaction = $this->checkout->transaction;
219
-        // if the transaction isn't set or nothing is owed on it, don't enqueue any JS
220
-        if (! $transaction instanceof EE_Transaction || EEH_Money::compare_floats($transaction->remaining(), 0)) {
221
-            return;
222
-        }
223
-        foreach (
224
-            EEM_Payment_Method::instance()->get_all_for_transaction(
225
-                $transaction,
226
-                EEM_Payment_Method::scope_cart
227
-            ) as $payment_method
228
-        ) {
229
-            $type_obj = $payment_method->type_obj();
230
-            if ($type_obj instanceof EE_PMT_Base) {
231
-                $billing_form = $type_obj->generate_new_billing_form($transaction);
232
-                if ($billing_form instanceof EE_Form_Section_Proper) {
233
-                    $billing_form->enqueue_js();
234
-                }
235
-            }
236
-        }
237
-    }
238
-
239
-
240
-    /**
241
-     * initialize_reg_step
242
-     *
243
-     * @return bool
244
-     * @throws EE_Error
245
-     * @throws InvalidArgumentException
246
-     * @throws ReflectionException
247
-     * @throws InvalidDataTypeException
248
-     * @throws InvalidInterfaceException
249
-     */
250
-    public function initialize_reg_step()
251
-    {
252
-        // TODO: if /when we implement donations, then this will need overriding
253
-        if (
254
-            // don't need payment options for:
255
-            // registrations made via the admin
256
-            // completed transactions
257
-            // overpaid transactions
258
-            // $ 0.00 transactions(no payment required)
259
-            ! $this->checkout->payment_required()
260
-            // but do NOT remove if current action being called belongs to this reg step
261
-            && ! is_callable([$this, $this->checkout->action])
262
-            && ! $this->completed()
263
-        ) {
264
-            // and if so, then we no longer need the Payment Options step
265
-            if ($this->is_current_step()) {
266
-                $this->checkout->generate_reg_form = false;
267
-            }
268
-            $this->checkout->remove_reg_step($this->_slug);
269
-            // DEBUG LOG
270
-            // $this->checkout->log( __CLASS__, __FUNCTION__, __LINE__ );
271
-            return false;
272
-        }
273
-        // load EEM_Payment_Method
274
-        EE_Registry::instance()->load_model('Payment_Method');
275
-        // get all active payment methods
276
-        $this->checkout->available_payment_methods = EEM_Payment_Method::instance()->get_all_for_transaction(
277
-            $this->checkout->transaction,
278
-            EEM_Payment_Method::scope_cart
279
-        );
280
-        return true;
281
-    }
282
-
283
-
284
-    /**
285
-     * @return EE_Form_Section_Proper
286
-     * @throws EE_Error
287
-     * @throws InvalidArgumentException
288
-     * @throws ReflectionException
289
-     * @throws EntityNotFoundException
290
-     * @throws InvalidDataTypeException
291
-     * @throws InvalidInterfaceException
292
-     * @throws InvalidStatusException
293
-     */
294
-    public function generate_reg_form()
295
-    {
296
-        // reset in case someone changes their mind
297
-        $this->_reset_selected_method_of_payment();
298
-        // set some defaults
299
-        $this->checkout->selected_method_of_payment = 'payments_closed';
300
-        $registrations_requiring_payment            = [];
301
-        $registrations_for_free_events              = [];
302
-        $registrations_requiring_pre_approval       = [];
303
-        $sold_out_events                            = [];
304
-        $insufficient_spaces_available              = [];
305
-        $no_payment_required                        = true;
306
-        // loop thru registrations to gather info
307
-        $registrations         = $this->checkout->transaction->registrations($this->checkout->reg_cache_where_params);
308
-        $ejected_registrations = EE_SPCO_Reg_Step_Payment_Options::find_registrations_that_lost_their_space(
309
-            $registrations,
310
-            $this->checkout->revisit
311
-        );
312
-        foreach ($registrations as $REG_ID => $registration) {
313
-            /** @var $registration EE_Registration */
314
-            // has this registration lost it's space ?
315
-            if (isset($ejected_registrations[ $REG_ID ])) {
316
-                if ($registration->event()->is_sold_out() || $registration->event()->is_sold_out(true)) {
317
-                    $sold_out_events[ $registration->event()->ID() ] = $registration->event();
318
-                } else {
319
-                    $insufficient_spaces_available[ $registration->event()->ID() ] = $registration->event();
320
-                }
321
-                continue;
322
-            }
323
-            // event requires admin approval
324
-            if ($registration->status_ID() === EEM_Registration::status_id_not_approved) {
325
-                // add event to list of events with pre-approval reg status
326
-                $registrations_requiring_pre_approval[ $REG_ID ] = $registration;
327
-                do_action(
328
-                    'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__event_requires_pre_approval',
329
-                    $registration->event(),
330
-                    $this
331
-                );
332
-                continue;
333
-            }
334
-            if (
335
-                $this->checkout->revisit
336
-                && $registration->status_ID() !== EEM_Registration::status_id_approved
337
-                && (
338
-                    $registration->event()->is_sold_out()
339
-                    || $registration->event()->is_sold_out(true)
340
-                )
341
-            ) {
342
-                // add event to list of events that are sold out
343
-                $sold_out_events[ $registration->event()->ID() ] = $registration->event();
344
-                do_action(
345
-                    'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__sold_out_event',
346
-                    $registration->event(),
347
-                    $this
348
-                );
349
-                continue;
350
-            }
351
-            // are they allowed to pay now and is there monies owing?
352
-            if ($registration->owes_monies_and_can_pay()) {
353
-                $registrations_requiring_payment[ $REG_ID ] = $registration;
354
-                do_action(
355
-                    'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__event_requires_payment',
356
-                    $registration->event(),
357
-                    $this
358
-                );
359
-            } elseif (
360
-                ! $this->checkout->revisit
361
-                      && $registration->status_ID() !== EEM_Registration::status_id_not_approved
362
-                      && $registration->ticket()->is_free()
363
-            ) {
364
-                $registrations_for_free_events[ $registration->ticket()->ID() ] = $registration;
365
-            }
366
-        }
367
-        $subsections = [];
368
-        // now decide which template to load
369
-        if (! empty($sold_out_events)) {
370
-            $subsections['sold_out_events'] = $this->_sold_out_events($sold_out_events);
371
-        }
372
-        if (! empty($insufficient_spaces_available)) {
373
-            $subsections['insufficient_space'] = $this->_insufficient_spaces_available(
374
-                $insufficient_spaces_available
375
-            );
376
-        }
377
-        if (! empty($registrations_requiring_pre_approval)) {
378
-            $subsections['registrations_requiring_pre_approval'] = $this->_registrations_requiring_pre_approval(
379
-                $registrations_requiring_pre_approval
380
-            );
381
-        }
382
-        if (! empty($registrations_for_free_events)) {
383
-            $subsections['no_payment_required'] = $this->_no_payment_required($registrations_for_free_events);
384
-        }
385
-        if (! empty($registrations_requiring_payment)) {
386
-            if ($this->checkout->amount_owing > 0) {
387
-                // autoload Line_Item_Display classes
388
-                EEH_Autoloader::register_line_item_filter_autoloaders();
389
-                $line_item_filter_processor = new EE_Line_Item_Filter_Processor(
390
-                    apply_filters(
391
-                        'FHEE__SPCO__EE_Line_Item_Filter_Collection',
392
-                        new EE_Line_Item_Filter_Collection()
393
-                    ),
394
-                    $this->checkout->cart->get_grand_total()
395
-                );
396
-                /** @var EE_Line_Item $filtered_line_item_tree */
397
-                $filtered_line_item_tree = $line_item_filter_processor->process();
398
-                EEH_Autoloader::register_line_item_display_autoloaders();
399
-                $this->set_line_item_display(new EE_Line_Item_Display('spco'));
400
-                $subsections['payment_options'] = $this->_display_payment_options(
401
-                    $this->line_item_display->display_line_item(
402
-                        $filtered_line_item_tree,
403
-                        ['registrations' => $registrations]
404
-                    )
405
-                );
406
-                $this->checkout->amount_owing   = $filtered_line_item_tree->total();
407
-                $this->_apply_registration_payments_to_amount_owing($registrations);
408
-            }
409
-            $no_payment_required = false;
410
-        } else {
411
-            $this->_hide_reg_step_submit_button_if_revisit();
412
-        }
413
-        $this->_save_selected_method_of_payment();
414
-
415
-        $subsections['default_hidden_inputs'] = $this->reg_step_hidden_inputs();
416
-        $subsections['extra_hidden_inputs']   = $this->_extra_hidden_inputs($no_payment_required);
417
-
418
-        return new EE_Form_Section_Proper(
419
-            [
420
-                'name'            => $this->reg_form_name(),
421
-                'html_id'         => $this->reg_form_name(),
422
-                'subsections'     => $subsections,
423
-                'layout_strategy' => new EE_No_Layout(),
424
-            ]
425
-        );
426
-    }
427
-
428
-
429
-    /**
430
-     * add line item filters required for this reg step
431
-     * these filters are applied via this line in EE_SPCO_Reg_Step_Payment_Options::set_hooks():
432
-     *        add_filter( 'FHEE__SPCO__EE_Line_Item_Filter_Collection', array( 'EE_SPCO_Reg_Step_Payment_Options',
433
-     *        'add_spco_line_item_filters' ) ); so any code that wants to use the same set of filters during the
434
-     *        payment options reg step, can apply these filters via the following: apply_filters(
435
-     *        'FHEE__SPCO__EE_Line_Item_Filter_Collection', new EE_Line_Item_Filter_Collection() ) or to an existing
436
-     *        filter collection by passing that instead of instantiating a new collection
437
-     *
438
-     * @param EE_Line_Item_Filter_Collection $line_item_filter_collection
439
-     * @return EE_Line_Item_Filter_Collection
440
-     * @throws EE_Error
441
-     * @throws InvalidArgumentException
442
-     * @throws ReflectionException
443
-     * @throws EntityNotFoundException
444
-     * @throws InvalidDataTypeException
445
-     * @throws InvalidInterfaceException
446
-     * @throws InvalidStatusException
447
-     */
448
-    public static function add_spco_line_item_filters(EE_Line_Item_Filter_Collection $line_item_filter_collection)
449
-    {
450
-        if (! EE_Registry::instance()->SSN instanceof EE_Session) {
451
-            return $line_item_filter_collection;
452
-        }
453
-        if (! EE_Registry::instance()->SSN->checkout() instanceof EE_Checkout) {
454
-            return $line_item_filter_collection;
455
-        }
456
-        if (! EE_Registry::instance()->SSN->checkout()->transaction instanceof EE_Transaction) {
457
-            return $line_item_filter_collection;
458
-        }
459
-        $line_item_filter_collection->add(
460
-            new EE_Billable_Line_Item_Filter(
461
-                EE_SPCO_Reg_Step_Payment_Options::remove_ejected_registrations(
462
-                    EE_Registry::instance()->SSN->checkout()->transaction->registrations(
463
-                        EE_Registry::instance()->SSN->checkout()->reg_cache_where_params
464
-                    )
465
-                )
466
-            )
467
-        );
468
-        $line_item_filter_collection->add(new EE_Non_Zero_Line_Item_Filter());
469
-        return $line_item_filter_collection;
470
-    }
471
-
472
-
473
-    /**
474
-     * remove_ejected_registrations
475
-     * if a registrant has lost their potential space at an event due to lack of payment,
476
-     * then this method removes them from the list of registrations being paid for during this request
477
-     *
478
-     * @param EE_Registration[] $registrations
479
-     * @return EE_Registration[]
480
-     * @throws EE_Error
481
-     * @throws InvalidArgumentException
482
-     * @throws ReflectionException
483
-     * @throws EntityNotFoundException
484
-     * @throws InvalidDataTypeException
485
-     * @throws InvalidInterfaceException
486
-     * @throws InvalidStatusException
487
-     */
488
-    public static function remove_ejected_registrations(array $registrations)
489
-    {
490
-        $ejected_registrations = EE_SPCO_Reg_Step_Payment_Options::find_registrations_that_lost_their_space(
491
-            $registrations,
492
-            EE_Registry::instance()->SSN->checkout()->revisit
493
-        );
494
-        foreach ($registrations as $REG_ID => $registration) {
495
-            // has this registration lost it's space ?
496
-            if (isset($ejected_registrations[ $REG_ID ])) {
497
-                unset($registrations[ $REG_ID ]);
498
-            }
499
-        }
500
-        return $registrations;
501
-    }
502
-
503
-
504
-    /**
505
-     * find_registrations_that_lost_their_space
506
-     * If a registrant chooses an offline payment method like Invoice,
507
-     * then no space is reserved for them at the event until they fully pay fo that site
508
-     * (unless the event's default reg status is set to APPROVED)
509
-     * if a registrant then later returns to pay, but the number of spaces available has been reduced due to sales,
510
-     * then this method will determine which registrations have lost the ability to complete the reg process.
511
-     *
512
-     * @param EE_Registration[] $registrations
513
-     * @param bool              $revisit
514
-     * @return array
515
-     * @throws EE_Error
516
-     * @throws InvalidArgumentException
517
-     * @throws ReflectionException
518
-     * @throws EntityNotFoundException
519
-     * @throws InvalidDataTypeException
520
-     * @throws InvalidInterfaceException
521
-     * @throws InvalidStatusException
522
-     */
523
-    public static function find_registrations_that_lost_their_space(array $registrations, $revisit = false)
524
-    {
525
-        // registrations per event
526
-        $event_reg_count = [];
527
-        // spaces left per event
528
-        $event_spaces_remaining = [];
529
-        // tickets left sorted by ID
530
-        $tickets_remaining = [];
531
-        // registrations that have lost their space
532
-        $ejected_registrations = [];
533
-        foreach ($registrations as $REG_ID => $registration) {
534
-            if (
535
-                $registration->status_ID() === EEM_Registration::status_id_approved
536
-                || apply_filters(
537
-                    'FHEE__EE_SPCO_Reg_Step_Payment_Options__find_registrations_that_lost_their_space__allow_reg_payment',
538
-                    false,
539
-                    $registration,
540
-                    $revisit
541
-                )
542
-            ) {
543
-                continue;
544
-            }
545
-            $EVT_ID = $registration->event_ID();
546
-            $ticket = $registration->ticket();
547
-            if (! isset($tickets_remaining[ $ticket->ID() ])) {
548
-                $tickets_remaining[ $ticket->ID() ] = $ticket->remaining();
549
-            }
550
-            if ($tickets_remaining[ $ticket->ID() ] > 0) {
551
-                if (! isset($event_reg_count[ $EVT_ID ])) {
552
-                    $event_reg_count[ $EVT_ID ] = 0;
553
-                }
554
-                $event_reg_count[ $EVT_ID ]++;
555
-                if (! isset($event_spaces_remaining[ $EVT_ID ])) {
556
-                    $event_spaces_remaining[ $EVT_ID ] = $registration->event()->spaces_remaining_for_sale();
557
-                }
558
-            }
559
-            if (
560
-                $revisit
561
-                && ($tickets_remaining[ $ticket->ID() ] === 0
562
-                    || $event_reg_count[ $EVT_ID ] > $event_spaces_remaining[ $EVT_ID ]
563
-                )
564
-            ) {
565
-                $ejected_registrations[ $REG_ID ] = $registration->event();
566
-                if ($registration->status_ID() !== EEM_Registration::status_id_wait_list) {
567
-                    /** @type EE_Registration_Processor $registration_processor */
568
-                    $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
569
-                    // at this point, we should have enough details about the registrant to consider the registration
570
-                    // NOT incomplete
571
-                    $registration_processor->manually_update_registration_status(
572
-                        $registration,
573
-                        EEM_Registration::status_id_wait_list
574
-                    );
575
-                }
576
-            }
577
-        }
578
-        return $ejected_registrations;
579
-    }
580
-
581
-
582
-    /**
583
-     * _hide_reg_step_submit_button
584
-     * removes the html for the reg step submit button
585
-     * by replacing it with an empty string via filter callback
586
-     *
587
-     * @return void
588
-     */
589
-    protected function _adjust_registration_status_if_event_old_sold()
590
-    {
591
-    }
592
-
593
-
594
-    /**
595
-     * _hide_reg_step_submit_button
596
-     * removes the html for the reg step submit button
597
-     * by replacing it with an empty string via filter callback
598
-     *
599
-     * @return void
600
-     */
601
-    protected function _hide_reg_step_submit_button_if_revisit()
602
-    {
603
-        if ($this->checkout->revisit) {
604
-            add_filter('FHEE__EE_SPCO_Reg_Step__reg_step_submit_button__sbmt_btn_html', '__return_empty_string');
605
-        }
606
-    }
607
-
608
-
609
-    /**
610
-     * sold_out_events
611
-     * displays notices regarding events that have sold out since hte registrant first signed up
612
-     *
613
-     * @param EE_Event[] $sold_out_events_array
614
-     * @return EE_Form_Section_Proper
615
-     * @throws EE_Error
616
-     */
617
-    private function _sold_out_events($sold_out_events_array = [])
618
-    {
619
-        // set some defaults
620
-        $this->checkout->selected_method_of_payment = 'events_sold_out';
621
-        $sold_out_events                            = '';
622
-        foreach ($sold_out_events_array as $sold_out_event) {
623
-            $sold_out_events .= EEH_HTML::li(
624
-                EEH_HTML::span(
625
-                    '  ' . $sold_out_event->name(),
626
-                    '',
627
-                    'dashicons dashicons-marker ee-icon-size-16 pink-text'
628
-                )
629
-            );
630
-        }
631
-        return new EE_Form_Section_Proper(
632
-            [
633
-                'layout_strategy' => new EE_Template_Layout(
634
-                    [
635
-                        'layout_template_file' => SPCO_REG_STEPS_PATH
636
-                                                  . $this->_slug
637
-                                                  . '/sold_out_events.template.php',
638
-                        'template_args'        => apply_filters(
639
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___sold_out_events__template_args',
640
-                            [
641
-                                'sold_out_events'     => $sold_out_events,
642
-                                'sold_out_events_msg' => apply_filters(
643
-                                    'FHEE__EE_SPCO_Reg_Step_Payment_Options___sold_out_events__sold_out_events_msg',
644
-                                    sprintf(
645
-                                        esc_html__(
646
-                                            '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',
647
-                                            'event_espresso'
648
-                                        ),
649
-                                        '<strong>',
650
-                                        '</strong>',
651
-                                        '<br />'
652
-                                    )
653
-                                ),
654
-                            ]
655
-                        ),
656
-                    ]
657
-                ),
658
-            ]
659
-        );
660
-    }
661
-
662
-
663
-    /**
664
-     * _insufficient_spaces_available
665
-     * displays notices regarding events that do not have enough remaining spaces
666
-     * to satisfy the current number of registrations looking to pay
667
-     *
668
-     * @param EE_Event[] $insufficient_spaces_events_array
669
-     * @return EE_Form_Section_Proper
670
-     * @throws EE_Error
671
-     * @throws ReflectionException
672
-     */
673
-    private function _insufficient_spaces_available($insufficient_spaces_events_array = [])
674
-    {
675
-        // set some defaults
676
-        $this->checkout->selected_method_of_payment = 'invoice';
677
-        $insufficient_space_events                  = '';
678
-        foreach ($insufficient_spaces_events_array as $event) {
679
-            if ($event instanceof EE_Event) {
680
-                $insufficient_space_events .= EEH_HTML::li(
681
-                    EEH_HTML::span(' ' . $event->name(), '', 'dashicons dashicons-marker ee-icon-size-16 pink-text')
682
-                );
683
-            }
684
-        }
685
-        return new EE_Form_Section_Proper(
686
-            [
687
-                'subsections'     => [
688
-                    'default_hidden_inputs' => $this->reg_step_hidden_inputs(),
689
-                    'extra_hidden_inputs'   => $this->_extra_hidden_inputs(),
690
-                ],
691
-                'layout_strategy' => new EE_Template_Layout(
692
-                    [
693
-                        'layout_template_file' => SPCO_REG_STEPS_PATH
694
-                                                  . $this->_slug
695
-                                                  . '/sold_out_events.template.php',
696
-                        'template_args'        => apply_filters(
697
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___insufficient_spaces_available__template_args',
698
-                            [
699
-                                'sold_out_events'     => $insufficient_space_events,
700
-                                'sold_out_events_msg' => apply_filters(
701
-                                    'FHEE__EE_SPCO_Reg_Step_Payment_Options___insufficient_spaces_available__insufficient_space_msg',
702
-                                    esc_html__(
703
-                                        '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.',
704
-                                        'event_espresso'
705
-                                    )
706
-                                ),
707
-                            ]
708
-                        ),
709
-                    ]
710
-                ),
711
-            ]
712
-        );
713
-    }
714
-
715
-
716
-    /**
717
-     * registrations_requiring_pre_approval
718
-     *
719
-     * @param array $registrations_requiring_pre_approval
720
-     * @return EE_Form_Section_Proper
721
-     * @throws EE_Error
722
-     * @throws EntityNotFoundException
723
-     * @throws ReflectionException
724
-     */
725
-    private function _registrations_requiring_pre_approval($registrations_requiring_pre_approval = [])
726
-    {
727
-        $events_requiring_pre_approval = [];
728
-        foreach ($registrations_requiring_pre_approval as $registration) {
729
-            if ($registration instanceof EE_Registration && $registration->event() instanceof EE_Event) {
730
-                $events_requiring_pre_approval[ $registration->event()->ID() ] = EEH_HTML::li(
731
-                    EEH_HTML::span(
732
-                        '',
733
-                        '',
734
-                        'dashicons dashicons-marker ee-icon-size-16 orange-text'
735
-                    )
736
-                    . EEH_HTML::span($registration->event()->name(), '', 'orange-text')
737
-                );
738
-            }
739
-        }
740
-        return new EE_Form_Section_Proper(
741
-            [
742
-                'layout_strategy' => new EE_Template_Layout(
743
-                    [
744
-                        'layout_template_file' => SPCO_REG_STEPS_PATH
745
-                                                  . $this->_slug
746
-                                                  . '/events_requiring_pre_approval.template.php', // layout_template
747
-                        'template_args'        => apply_filters(
748
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___sold_out_events__template_args',
749
-                            [
750
-                                'events_requiring_pre_approval'     => implode('', $events_requiring_pre_approval),
751
-                                'events_requiring_pre_approval_msg' => apply_filters(
752
-                                    'FHEE__EE_SPCO_Reg_Step_Payment_Options___events_requiring_pre_approval__events_requiring_pre_approval_msg',
753
-                                    esc_html__(
754
-                                        '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.',
755
-                                        'event_espresso'
756
-                                    )
757
-                                ),
758
-                            ]
759
-                        ),
760
-                    ]
761
-                ),
762
-            ]
763
-        );
764
-    }
765
-
766
-
767
-    /**
768
-     * _no_payment_required
769
-     *
770
-     * @param EE_Event[] $registrations_for_free_events
771
-     * @return EE_Form_Section_Proper
772
-     * @throws EE_Error
773
-     */
774
-    private function _no_payment_required($registrations_for_free_events = [])
775
-    {
776
-        // set some defaults
777
-        $this->checkout->selected_method_of_payment = 'no_payment_required';
778
-        // generate no_payment_required form
779
-        return new EE_Form_Section_Proper(
780
-            [
781
-                'layout_strategy' => new EE_Template_Layout(
782
-                    [
783
-                        'layout_template_file' => SPCO_REG_STEPS_PATH
784
-                                                  . $this->_slug
785
-                                                  . '/no_payment_required.template.php', // layout_template
786
-                        'template_args'        => apply_filters(
787
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___no_payment_required__template_args',
788
-                            [
789
-                                'revisit'                       => $this->checkout->revisit,
790
-                                'registrations'                 => [],
791
-                                'ticket_count'                  => [],
792
-                                'registrations_for_free_events' => $registrations_for_free_events,
793
-                                'no_payment_required_msg'       => EEH_HTML::p(
794
-                                    esc_html__('This is a free event, so no billing will occur.', 'event_espresso')
795
-                                ),
796
-                            ]
797
-                        ),
798
-                    ]
799
-                ),
800
-            ]
801
-        );
802
-    }
803
-
804
-
805
-    /**
806
-     * _display_payment_options
807
-     *
808
-     * @param string $transaction_details
809
-     * @return EE_Form_Section_Proper
810
-     * @throws EE_Error
811
-     * @throws InvalidArgumentException
812
-     * @throws InvalidDataTypeException
813
-     * @throws InvalidInterfaceException
814
-     */
815
-    private function _display_payment_options($transaction_details = '')
816
-    {
817
-        // has method_of_payment been set by no-js user?
818
-        $this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment();
819
-        // build payment options form
820
-        return apply_filters(
821
-            'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__payment_options_form',
822
-            new EE_Form_Section_Proper(
823
-                [
824
-                    'subsections'     => [
825
-                        'before_payment_options' => apply_filters(
826
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__before_payment_options',
827
-                            new EE_Form_Section_Proper(
828
-                                ['layout_strategy' => new EE_Div_Per_Section_Layout()]
829
-                            )
830
-                        ),
831
-                        'payment_options'        => $this->_setup_payment_options(),
832
-                        'after_payment_options'  => apply_filters(
833
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__after_payment_options',
834
-                            new EE_Form_Section_Proper(
835
-                                ['layout_strategy' => new EE_Div_Per_Section_Layout()]
836
-                            )
837
-                        ),
838
-                    ],
839
-                    'layout_strategy' => new EE_Template_Layout(
840
-                        [
841
-                            'layout_template_file' => $this->_template,
842
-                            'template_args'        => apply_filters(
843
-                                'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__template_args',
844
-                                [
845
-                                    'reg_count'                 => $this->line_item_display->total_items(),
846
-                                    'transaction_details'       => $transaction_details,
847
-                                    'available_payment_methods' => [],
848
-                                ]
849
-                            ),
850
-                        ]
851
-                    ),
852
-                ]
853
-            )
854
-        );
855
-    }
856
-
857
-
858
-    /**
859
-     * _extra_hidden_inputs
860
-     *
861
-     * @param bool $no_payment_required
862
-     * @return EE_Form_Section_Proper
863
-     * @throws EE_Error
864
-     * @throws ReflectionException
865
-     */
866
-    private function _extra_hidden_inputs($no_payment_required = true)
867
-    {
868
-        return new EE_Form_Section_Proper(
869
-            [
870
-                'html_id'         => 'ee-' . $this->slug() . '-extra-hidden-inputs',
871
-                'layout_strategy' => new EE_Div_Per_Section_Layout(),
872
-                'subsections'     => [
873
-                    'spco_no_payment_required' => new EE_Hidden_Input(
874
-                        [
875
-                            'normalization_strategy' => new EE_Boolean_Normalization(),
876
-                            'html_name'              => 'spco_no_payment_required',
877
-                            'html_id'                => 'spco-no-payment-required-payment_options',
878
-                            'default'                => $no_payment_required,
879
-                        ]
880
-                    ),
881
-                    'spco_transaction_id'      => new EE_Fixed_Hidden_Input(
882
-                        [
883
-                            'normalization_strategy' => new EE_Int_Normalization(),
884
-                            'html_name'              => 'spco_transaction_id',
885
-                            'html_id'                => 'spco-transaction-id',
886
-                            'default'                => $this->checkout->transaction->ID(),
887
-                        ]
888
-                    ),
889
-                ],
890
-            ]
891
-        );
892
-    }
893
-
894
-
895
-    /**
896
-     *    _apply_registration_payments_to_amount_owing
897
-     *
898
-     * @param array $registrations
899
-     * @throws EE_Error
900
-     */
901
-    protected function _apply_registration_payments_to_amount_owing(array $registrations)
902
-    {
903
-        $payments = [];
904
-        foreach ($registrations as $registration) {
905
-            if ($registration instanceof EE_Registration && $registration->owes_monies_and_can_pay()) {
906
-                $payments += $registration->registration_payments();
907
-            }
908
-        }
909
-        if (! empty($payments)) {
910
-            foreach ($payments as $payment) {
911
-                if ($payment instanceof EE_Registration_Payment) {
912
-                    $this->checkout->amount_owing -= $payment->amount();
913
-                }
914
-            }
915
-        }
916
-    }
917
-
918
-
919
-    /**
920
-     *    _reset_selected_method_of_payment
921
-     *
922
-     * @access    private
923
-     * @param bool $force_reset
924
-     * @return void
925
-     * @throws InvalidArgumentException
926
-     * @throws InvalidDataTypeException
927
-     * @throws InvalidInterfaceException
928
-     */
929
-    private function _reset_selected_method_of_payment($force_reset = false)
930
-    {
931
-        /** @var RequestInterface $request */
932
-        $request              = LoaderFactory::getLoader()->getShared(RequestInterface::class);
933
-        $reset_payment_method = $request->getRequestParam('reset_payment_method', $force_reset, 'bool');
934
-        if ($reset_payment_method) {
935
-            $this->checkout->selected_method_of_payment = null;
936
-            $this->checkout->payment_method             = null;
937
-            $this->checkout->billing_form               = null;
938
-            $this->_save_selected_method_of_payment();
939
-        }
940
-    }
941
-
942
-
943
-    /**
944
-     * _save_selected_method_of_payment
945
-     * stores the selected_method_of_payment in the session
946
-     * so that it's available for all subsequent requests including AJAX
947
-     *
948
-     * @access        private
949
-     * @param string $selected_method_of_payment
950
-     * @return void
951
-     * @throws InvalidArgumentException
952
-     * @throws InvalidDataTypeException
953
-     * @throws InvalidInterfaceException
954
-     */
955
-    private function _save_selected_method_of_payment($selected_method_of_payment = '')
956
-    {
957
-        $selected_method_of_payment = ! empty($selected_method_of_payment)
958
-            ? $selected_method_of_payment
959
-            : $this->checkout->selected_method_of_payment;
960
-        EE_Registry::instance()->SSN->set_session_data(
961
-            ['selected_method_of_payment' => $selected_method_of_payment]
962
-        );
963
-    }
964
-
965
-
966
-    /**
967
-     * _setup_payment_options
968
-     *
969
-     * @return EE_Form_Section_Proper
970
-     * @throws EE_Error
971
-     * @throws InvalidArgumentException
972
-     * @throws InvalidDataTypeException
973
-     * @throws InvalidInterfaceException
974
-     */
975
-    public function _setup_payment_options()
976
-    {
977
-        // load payment method classes
978
-        $this->checkout->available_payment_methods = $this->_get_available_payment_methods();
979
-        if (empty($this->checkout->available_payment_methods)) {
980
-            EE_Error::add_error(
981
-                apply_filters(
982
-                    'FHEE__EE_SPCO_Reg_Step_Payment_Options___setup_payment_options__error_message_no_payment_methods',
983
-                    sprintf(
984
-                        esc_html__(
985
-                            '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.',
986
-                            'event_espresso'
987
-                        ),
988
-                        '<br>',
989
-                        EE_Registry::instance()->CFG->organization->get_pretty('email')
990
-                    )
991
-                ),
992
-                __FILE__,
993
-                __FUNCTION__,
994
-                __LINE__
995
-            );
996
-        }
997
-        // switch up header depending on number of available payment methods
998
-        $payment_method_header     = count($this->checkout->available_payment_methods) > 1
999
-            ? apply_filters(
1000
-                'FHEE__registration_page_payment_options__method_of_payment_hdr',
1001
-                esc_html__('Please Select Your Method of Payment', 'event_espresso')
1002
-            )
1003
-            : apply_filters(
1004
-                'FHEE__registration_page_payment_options__method_of_payment_hdr',
1005
-                esc_html__('Method of Payment', 'event_espresso')
1006
-            );
1007
-        $available_payment_methods = [
1008
-            // display the "Payment Method" header
1009
-            'payment_method_header' => new EE_Form_Section_HTML(
1010
-                apply_filters(
1011
-                    'FHEE__EE_SPCO_Reg_Step_Payment_Options___setup_payment_options__payment_method_header',
1012
-                    EEH_HTML::h4($payment_method_header, 'method-of-payment-hdr'),
1013
-                    $payment_method_header
1014
-                )
1015
-            ),
1016
-        ];
1017
-        // the list of actual payment methods ( invoice, paypal, etc ) in a  ( slug => HTML )  format
1018
-        $available_payment_method_options = [];
1019
-        $default_payment_method_option    = [];
1020
-        // additional instructions to be displayed and hidden below payment methods (adding a clearing div to start)
1021
-        $payment_methods_billing_info = [
1022
-            new EE_Form_Section_HTML(
1023
-                EEH_HTML::div('<br />', '', '', 'clear:both;')
1024
-            ),
1025
-        ];
1026
-        // loop through payment methods
1027
-        foreach ($this->checkout->available_payment_methods as $payment_method) {
1028
-            if ($payment_method instanceof EE_Payment_Method) {
1029
-                $payment_method_button = EEH_HTML::img(
1030
-                    $payment_method->button_url(),
1031
-                    $payment_method->name(),
1032
-                    'spco-payment-method-' . $payment_method->slug() . '-btn-img',
1033
-                    'spco-payment-method-btn-img'
1034
-                );
1035
-                // check if any payment methods are set as default
1036
-                // if payment method is already selected OR nothing is selected and this payment method should be
1037
-                // open_by_default
1038
-                if (
1039
-                    ($this->checkout->selected_method_of_payment === $payment_method->slug())
1040
-                    || (! $this->checkout->selected_method_of_payment && $payment_method->open_by_default())
1041
-                ) {
1042
-                    $this->checkout->selected_method_of_payment = $payment_method->slug();
1043
-                    $this->_save_selected_method_of_payment();
1044
-                    $default_payment_method_option[ $payment_method->slug() ] = $payment_method_button;
1045
-                } else {
1046
-                    $available_payment_method_options[ $payment_method->slug() ] = $payment_method_button;
1047
-                }
1048
-                $payment_methods_billing_info[ $payment_method->slug() . '-info' ] =
1049
-                    $this->_payment_method_billing_info(
1050
-                        $payment_method
1051
-                    );
1052
-            }
1053
-        }
1054
-        // prepend available_payment_method_options with default_payment_method_option so that it appears first in list
1055
-        // of PMs
1056
-        $available_payment_method_options = $default_payment_method_option + $available_payment_method_options;
1057
-        // now generate the actual form  inputs
1058
-        $available_payment_methods['available_payment_methods'] = $this->_available_payment_method_inputs(
1059
-            $available_payment_method_options
1060
-        );
1061
-        $available_payment_methods                              += $payment_methods_billing_info;
1062
-        // build the available payment methods form
1063
-        return new EE_Form_Section_Proper(
1064
-            [
1065
-                'html_id'         => 'spco-available-methods-of-payment-dv',
1066
-                'subsections'     => $available_payment_methods,
1067
-                'layout_strategy' => new EE_Div_Per_Section_Layout(),
1068
-            ]
1069
-        );
1070
-    }
1071
-
1072
-
1073
-    /**
1074
-     * _get_available_payment_methods
1075
-     *
1076
-     * @return EE_Payment_Method[]
1077
-     * @throws EE_Error
1078
-     * @throws InvalidArgumentException
1079
-     * @throws InvalidDataTypeException
1080
-     * @throws InvalidInterfaceException
1081
-     */
1082
-    protected function _get_available_payment_methods()
1083
-    {
1084
-        if (! empty($this->checkout->available_payment_methods)) {
1085
-            return $this->checkout->available_payment_methods;
1086
-        }
1087
-        $available_payment_methods = [];
1088
-        $EEM_Payment_Method        = EEM_Payment_Method::instance();
1089
-        // get all active payment methods
1090
-        $payment_methods = $EEM_Payment_Method->get_all_for_transaction(
1091
-            $this->checkout->transaction,
1092
-            EEM_Payment_Method::scope_cart
1093
-        );
1094
-        foreach ($payment_methods as $payment_method) {
1095
-            if ($payment_method instanceof EE_Payment_Method) {
1096
-                $available_payment_methods[ $payment_method->slug() ] = $payment_method;
1097
-            }
1098
-        }
1099
-        return $available_payment_methods;
1100
-    }
1101
-
1102
-
1103
-    /**
1104
-     *    _available_payment_method_inputs
1105
-     *
1106
-     * @access    private
1107
-     * @param array $available_payment_method_options
1108
-     * @return    EE_Form_Section_Proper
1109
-     * @throws EE_Error
1110
-     * @throws EE_Error
1111
-     */
1112
-    private function _available_payment_method_inputs($available_payment_method_options = [])
1113
-    {
1114
-        // generate inputs
1115
-        return new EE_Form_Section_Proper(
1116
-            [
1117
-                'html_id'         => 'ee-available-payment-method-inputs',
1118
-                'layout_strategy' => new EE_Div_Per_Section_Layout(),
1119
-                'subsections'     => [
1120
-                    '' => new EE_Radio_Button_Input(
1121
-                        $available_payment_method_options,
1122
-                        [
1123
-                            'html_name'          => 'selected_method_of_payment',
1124
-                            'html_class'         => 'spco-payment-method',
1125
-                            'default'            => $this->checkout->selected_method_of_payment,
1126
-                            'label_size'         => 11,
1127
-                            'enforce_label_size' => true,
1128
-                        ]
1129
-                    ),
1130
-                ],
1131
-            ]
1132
-        );
1133
-    }
1134
-
1135
-
1136
-    /**
1137
-     *    _payment_method_billing_info
1138
-     *
1139
-     * @access    private
1140
-     * @param EE_Payment_Method $payment_method
1141
-     * @return EE_Form_Section_Proper
1142
-     * @throws EE_Error
1143
-     * @throws InvalidArgumentException
1144
-     * @throws InvalidDataTypeException
1145
-     * @throws InvalidInterfaceException
1146
-     */
1147
-    private function _payment_method_billing_info(EE_Payment_Method $payment_method)
1148
-    {
1149
-        $currently_selected = $this->checkout->selected_method_of_payment === $payment_method->slug();
1150
-        // generate the billing form for payment method
1151
-        $billing_form                 = $currently_selected
1152
-            ? $this->_get_billing_form_for_payment_method($payment_method)
1153
-            : new EE_Form_Section_HTML();
1154
-        $this->checkout->billing_form = $currently_selected
1155
-            ? $billing_form
1156
-            : $this->checkout->billing_form;
1157
-        // it's all in the details
1158
-        $info_html = EEH_HTML::h3(
1159
-            esc_html__('Important information regarding your payment', 'event_espresso'),
1160
-            '',
1161
-            'spco-payment-method-hdr'
1162
-        );
1163
-        // add some info regarding the step, either from what's saved in the admin,
1164
-        // or a default string depending on whether the PM has a billing form or not
1165
-        if ($payment_method->description()) {
1166
-            $payment_method_info = $payment_method->description();
1167
-        } elseif ($billing_form instanceof EE_Billing_Info_Form) {
1168
-            $payment_method_info = sprintf(
1169
-                esc_html__(
1170
-                    'Please provide the following billing information, then click the "%1$s" button below in order to proceed.',
1171
-                    'event_espresso'
1172
-                ),
1173
-                $this->submit_button_text()
1174
-            );
1175
-        } else {
1176
-            $payment_method_info = sprintf(
1177
-                esc_html__('Please click the "%1$s" button below in order to proceed.', 'event_espresso'),
1178
-                $this->submit_button_text()
1179
-            );
1180
-        }
1181
-        $info_html .= EEH_HTML::div(
1182
-            apply_filters(
1183
-                'FHEE__EE_SPCO_Reg_Step_Payment_Options___payment_method_billing_info__payment_method_info',
1184
-                $payment_method_info
1185
-            ),
1186
-            '',
1187
-            'spco-payment-method-desc ee-attention'
1188
-        );
1189
-        return new EE_Form_Section_Proper(
1190
-            [
1191
-                'html_id'         => 'spco-payment-method-info-' . $payment_method->slug(),
1192
-                'html_class'      => 'spco-payment-method-info-dv',
1193
-                // only display the selected or default PM
1194
-                'html_style'      => $currently_selected ? '' : 'display:none;',
1195
-                'layout_strategy' => new EE_Div_Per_Section_Layout(),
1196
-                'subsections'     => [
1197
-                    'info'         => new EE_Form_Section_HTML($info_html),
1198
-                    'billing_form' => $currently_selected ? $billing_form : new EE_Form_Section_HTML(),
1199
-                ],
1200
-            ]
1201
-        );
1202
-    }
1203
-
1204
-
1205
-    /**
1206
-     * get_billing_form_html_for_payment_method
1207
-     *
1208
-     * @return bool
1209
-     * @throws EE_Error
1210
-     * @throws InvalidArgumentException
1211
-     * @throws ReflectionException
1212
-     * @throws InvalidDataTypeException
1213
-     * @throws InvalidInterfaceException
1214
-     */
1215
-    public function get_billing_form_html_for_payment_method()
1216
-    {
1217
-        // how have they chosen to pay?
1218
-        $this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
1219
-        $this->checkout->payment_method             = $this->_get_payment_method_for_selected_method_of_payment();
1220
-        if (! $this->checkout->payment_method instanceof EE_Payment_Method) {
1221
-            return false;
1222
-        }
1223
-        if (
1224
-            apply_filters(
1225
-                'FHEE__EE_SPCO_Reg_Step_Payment_Options__registration_checkout__selected_payment_method__display_success',
1226
-                false
1227
-            )
1228
-        ) {
1229
-            EE_Error::add_success(
1230
-                apply_filters(
1231
-                    'FHEE__Single_Page_Checkout__registration_checkout__selected_payment_method',
1232
-                    sprintf(
1233
-                        esc_html__(
1234
-                            'You have selected "%s" as your method of payment. Please note the important payment information below.',
1235
-                            'event_espresso'
1236
-                        ),
1237
-                        $this->checkout->payment_method->name()
1238
-                    )
1239
-                )
1240
-            );
1241
-        }
1242
-        // now generate billing form for selected method of payment
1243
-        $payment_method_billing_form = $this->_get_billing_form_for_payment_method($this->checkout->payment_method);
1244
-        // fill form with attendee info if applicable
1245
-        if (
1246
-            $payment_method_billing_form instanceof EE_Billing_Attendee_Info_Form
1247
-            && $this->checkout->transaction_has_primary_registrant()
1248
-        ) {
1249
-            $payment_method_billing_form->populate_from_attendee(
1250
-                $this->checkout->transaction->primary_registration()->attendee()
1251
-            );
1252
-        }
1253
-        // and debug content
1254
-        if (
1255
-            $payment_method_billing_form instanceof EE_Billing_Info_Form
1256
-            && $this->checkout->payment_method->type_obj() instanceof EE_PMT_Base
1257
-        ) {
1258
-            $payment_method_billing_form =
1259
-                $this->checkout->payment_method->type_obj()->apply_billing_form_debug_settings(
1260
-                    $payment_method_billing_form
1261
-                );
1262
-        }
1263
-        $billing_info = $payment_method_billing_form instanceof EE_Form_Section_Proper
1264
-            ? $payment_method_billing_form->get_html()
1265
-            : '';
1266
-        $this->checkout->json_response->set_return_data(['payment_method_info' => $billing_info]);
1267
-        // localize validation rules for main form
1268
-        $this->checkout->current_step->reg_form->localize_validation_rules();
1269
-        $this->checkout->json_response->add_validation_rules(EE_Form_Section_Proper::js_localization());
1270
-        return true;
1271
-    }
1272
-
1273
-
1274
-    /**
1275
-     * _get_billing_form_for_payment_method
1276
-     *
1277
-     * @param EE_Payment_Method $payment_method
1278
-     * @return EE_Billing_Info_Form|EE_Form_Section_HTML
1279
-     * @throws EE_Error
1280
-     * @throws InvalidArgumentException
1281
-     * @throws InvalidDataTypeException
1282
-     * @throws InvalidInterfaceException
1283
-     */
1284
-    private function _get_billing_form_for_payment_method(EE_Payment_Method $payment_method)
1285
-    {
1286
-        $billing_form = $payment_method->type_obj()->billing_form(
1287
-            $this->checkout->transaction,
1288
-            ['amount_owing' => $this->checkout->amount_owing]
1289
-        );
1290
-        if ($billing_form instanceof EE_Billing_Info_Form) {
1291
-            if (
1292
-                apply_filters(
1293
-                    'FHEE__EE_SPCO_Reg_Step_Payment_Options__registration_checkout__selected_payment_method__display_success',
1294
-                    false
1295
-                )
1296
-                && $this->request->requestParamIsSet('payment_method')
1297
-            ) {
1298
-                EE_Error::add_success(
1299
-                    apply_filters(
1300
-                        'FHEE__Single_Page_Checkout__registration_checkout__selected_payment_method',
1301
-                        sprintf(
1302
-                            esc_html__(
1303
-                                'You have selected "%s" as your method of payment. Please note the important payment information below.',
1304
-                                'event_espresso'
1305
-                            ),
1306
-                            $payment_method->name()
1307
-                        )
1308
-                    )
1309
-                );
1310
-            }
1311
-            return apply_filters(
1312
-                'FHEE__EE_SPCO_Reg_Step_Payment_Options___get_billing_form_for_payment_method__billing_form',
1313
-                $billing_form,
1314
-                $payment_method
1315
-            );
1316
-        }
1317
-        // no actual billing form, so return empty HTML form section
1318
-        return new EE_Form_Section_HTML();
1319
-    }
1320
-
1321
-
1322
-    /**
1323
-     * _get_selected_method_of_payment
1324
-     *
1325
-     * @param boolean $required whether to throw an error if the "selected_method_of_payment"
1326
-     *                          is not found in the incoming request
1327
-     * @param string  $request_param
1328
-     * @return NULL|string
1329
-     * @throws EE_Error
1330
-     * @throws InvalidArgumentException
1331
-     * @throws InvalidDataTypeException
1332
-     * @throws InvalidInterfaceException
1333
-     */
1334
-    private function _get_selected_method_of_payment(
1335
-        $required = false,
1336
-        $request_param = 'selected_method_of_payment'
1337
-    ) {
1338
-        // is selected_method_of_payment set in the request ?
1339
-        $selected_method_of_payment = $this->request->getRequestParam($request_param);
1340
-        if ($selected_method_of_payment) {
1341
-            // sanitize it
1342
-            $selected_method_of_payment = is_array($selected_method_of_payment)
1343
-                ? array_shift($selected_method_of_payment)
1344
-                : $selected_method_of_payment;
1345
-            $selected_method_of_payment = sanitize_text_field($selected_method_of_payment);
1346
-            // store it in the session so that it's available for all subsequent requests including AJAX
1347
-            $this->_save_selected_method_of_payment($selected_method_of_payment);
1348
-        } else {
1349
-            // or is is set in the session ?
1350
-            $selected_method_of_payment = EE_Registry::instance()->SSN->get_session_data(
1351
-                'selected_method_of_payment'
1352
-            );
1353
-        }
1354
-        // do ya really really gotta have it?
1355
-        if (empty($selected_method_of_payment) && $required) {
1356
-            EE_Error::add_error(
1357
-                sprintf(
1358
-                    esc_html__(
1359
-                        '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.',
1360
-                        'event_espresso'
1361
-                    ),
1362
-                    '<br/>',
1363
-                    '<br/>',
1364
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
1365
-                ),
1366
-                __FILE__,
1367
-                __FUNCTION__,
1368
-                __LINE__
1369
-            );
1370
-            return null;
1371
-        }
1372
-        return $selected_method_of_payment;
1373
-    }
1374
-
1375
-
1376
-
1377
-
1378
-
1379
-
1380
-    /********************************************************************************************************/
1381
-    /***********************************  SWITCH PAYMENT METHOD  ************************************/
1382
-    /********************************************************************************************************/
1383
-    /**
1384
-     * switch_payment_method
1385
-     *
1386
-     * @return bool
1387
-     * @throws EE_Error
1388
-     * @throws InvalidArgumentException
1389
-     * @throws InvalidDataTypeException
1390
-     * @throws InvalidInterfaceException
1391
-     * @throws ReflectionException
1392
-     */
1393
-    public function switch_payment_method()
1394
-    {
1395
-        if (! $this->_verify_payment_method_is_set()) {
1396
-            return false;
1397
-        }
1398
-        if (
1399
-            apply_filters(
1400
-                'FHEE__EE_SPCO_Reg_Step_Payment_Options__registration_checkout__selected_payment_method__display_success',
1401
-                false
1402
-            )
1403
-        ) {
1404
-            EE_Error::add_success(
1405
-                apply_filters(
1406
-                    'FHEE__Single_Page_Checkout__registration_checkout__selected_payment_method',
1407
-                    sprintf(
1408
-                        esc_html__(
1409
-                            'You have selected "%s" as your method of payment. Please note the important payment information below.',
1410
-                            'event_espresso'
1411
-                        ),
1412
-                        $this->checkout->payment_method->name()
1413
-                    )
1414
-                )
1415
-            );
1416
-        }
1417
-        // generate billing form for selected method of payment if it hasn't been done already
1418
-        if ($this->checkout->payment_method->type_obj()->has_billing_form()) {
1419
-            $this->checkout->billing_form = $this->_get_billing_form_for_payment_method(
1420
-                $this->checkout->payment_method
1421
-            );
1422
-        }
1423
-        // fill form with attendee info if applicable
1424
-        if (
1425
-            apply_filters(
1426
-                'FHEE__populate_billing_form_fields_from_attendee',
1427
-                (
1428
-                $this->checkout->billing_form instanceof EE_Billing_Attendee_Info_Form
1429
-                && $this->checkout->transaction_has_primary_registrant()
1430
-                ),
1431
-                $this->checkout->billing_form,
1432
-                $this->checkout->transaction
1433
-            )
1434
-        ) {
1435
-            $this->checkout->billing_form->populate_from_attendee(
1436
-                $this->checkout->transaction->primary_registration()->attendee()
1437
-            );
1438
-        }
1439
-        // and debug content
1440
-        if (
1441
-            $this->checkout->billing_form instanceof EE_Billing_Info_Form
1442
-            && $this->checkout->payment_method->type_obj() instanceof EE_PMT_Base
1443
-        ) {
1444
-            $this->checkout->billing_form =
1445
-                $this->checkout->payment_method->type_obj()->apply_billing_form_debug_settings(
1446
-                    $this->checkout->billing_form
1447
-                );
1448
-        }
1449
-        // get html and validation rules for form
1450
-        if ($this->checkout->billing_form instanceof EE_Form_Section_Proper) {
1451
-            $this->checkout->json_response->set_return_data(
1452
-                ['payment_method_info' => $this->checkout->billing_form->get_html()]
1453
-            );
1454
-            // localize validation rules for main form
1455
-            $this->checkout->billing_form->localize_validation_rules(true);
1456
-            $this->checkout->json_response->add_validation_rules(EE_Form_Section_Proper::js_localization());
1457
-        } else {
1458
-            $this->checkout->json_response->set_return_data(['payment_method_info' => '']);
1459
-        }
1460
-        // prevents advancement to next step
1461
-        $this->checkout->continue_reg = false;
1462
-        return true;
1463
-    }
1464
-
1465
-
1466
-    /**
1467
-     * _verify_payment_method_is_set
1468
-     *
1469
-     * @return bool
1470
-     * @throws EE_Error
1471
-     * @throws InvalidArgumentException
1472
-     * @throws ReflectionException
1473
-     * @throws InvalidDataTypeException
1474
-     * @throws InvalidInterfaceException
1475
-     */
1476
-    protected function _verify_payment_method_is_set()
1477
-    {
1478
-        // generate billing form for selected method of payment if it hasn't been done already
1479
-        if (empty($this->checkout->selected_method_of_payment)) {
1480
-            // how have they chosen to pay?
1481
-            $this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
1482
-        } else {
1483
-            // choose your own adventure based on method_of_payment
1484
-            switch ($this->checkout->selected_method_of_payment) {
1485
-                case 'events_sold_out':
1486
-                    EE_Error::add_attention(
1487
-                        apply_filters(
1488
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___verify_payment_method_is_set__sold_out_events_msg',
1489
-                            esc_html__(
1490
-                                '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.',
1491
-                                'event_espresso'
1492
-                            )
1493
-                        ),
1494
-                        __FILE__,
1495
-                        __FUNCTION__,
1496
-                        __LINE__
1497
-                    );
1498
-                    return false;
1499
-                case 'payments_closed':
1500
-                    EE_Error::add_attention(
1501
-                        apply_filters(
1502
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___verify_payment_method_is_set__payments_closed_msg',
1503
-                            esc_html__(
1504
-                                '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.',
1505
-                                'event_espresso'
1506
-                            )
1507
-                        ),
1508
-                        __FILE__,
1509
-                        __FUNCTION__,
1510
-                        __LINE__
1511
-                    );
1512
-                    return false;
1513
-                case 'no_payment_required':
1514
-                    EE_Error::add_attention(
1515
-                        apply_filters(
1516
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___verify_payment_method_is_set__no_payment_required_msg',
1517
-                            esc_html__(
1518
-                                '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.',
1519
-                                'event_espresso'
1520
-                            )
1521
-                        ),
1522
-                        __FILE__,
1523
-                        __FUNCTION__,
1524
-                        __LINE__
1525
-                    );
1526
-                    return false;
1527
-                default:
1528
-            }
1529
-        }
1530
-        // verify payment method
1531
-        if (! $this->checkout->payment_method instanceof EE_Payment_Method) {
1532
-            // get payment method for selected method of payment
1533
-            $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment();
1534
-        }
1535
-        return $this->checkout->payment_method instanceof EE_Payment_Method;
1536
-    }
1537
-
1538
-
1539
-
1540
-    /********************************************************************************************************/
1541
-    /***************************************  SAVE PAYER DETAILS  ****************************************/
1542
-    /********************************************************************************************************/
1543
-    /**
1544
-     * save_payer_details_via_ajax
1545
-     *
1546
-     * @return void
1547
-     * @throws EE_Error
1548
-     * @throws InvalidArgumentException
1549
-     * @throws ReflectionException
1550
-     * @throws RuntimeException
1551
-     * @throws InvalidDataTypeException
1552
-     * @throws InvalidInterfaceException
1553
-     */
1554
-    public function save_payer_details_via_ajax()
1555
-    {
1556
-        if (! $this->_verify_payment_method_is_set()) {
1557
-            return;
1558
-        }
1559
-        // generate billing form for selected method of payment if it hasn't been done already
1560
-        if ($this->checkout->payment_method->type_obj()->has_billing_form()) {
1561
-            $this->checkout->billing_form = $this->_get_billing_form_for_payment_method(
1562
-                $this->checkout->payment_method
1563
-            );
1564
-        }
1565
-        // generate primary attendee from payer info if applicable
1566
-        if (! $this->checkout->transaction_has_primary_registrant()) {
1567
-            $attendee = $this->_create_attendee_from_request_data();
1568
-            if ($attendee instanceof EE_Attendee) {
1569
-                foreach ($this->checkout->transaction->registrations() as $registration) {
1570
-                    if ($registration->is_primary_registrant()) {
1571
-                        $this->checkout->primary_attendee_obj = $attendee;
1572
-                        $registration->_add_relation_to($attendee, 'Attendee');
1573
-                        $registration->set_attendee_id($attendee->ID());
1574
-                        $registration->update_cache_after_object_save('Attendee', $attendee);
1575
-                    }
1576
-                }
1577
-            }
1578
-        }
1579
-    }
1580
-
1581
-
1582
-    /**
1583
-     * create_attendee_from_request_data
1584
-     * uses info from alternate GET or POST data (such as AJAX) to create a new attendee
1585
-     *
1586
-     * @return EE_Attendee
1587
-     * @throws EE_Error
1588
-     * @throws InvalidArgumentException
1589
-     * @throws ReflectionException
1590
-     * @throws InvalidDataTypeException
1591
-     * @throws InvalidInterfaceException
1592
-     */
1593
-    protected function _create_attendee_from_request_data()
1594
-    {
1595
-        // get State ID
1596
-        $STA_ID = $this->request->getRequestParam('state');
1597
-        if (! empty($STA_ID)) {
1598
-            // can we get state object from name ?
1599
-            EE_Registry::instance()->load_model('State');
1600
-            $state  = EEM_State::instance()->get_col([['STA_name' => $STA_ID], 'limit' => 1], 'STA_ID');
1601
-            $STA_ID = is_array($state) && ! empty($state) ? reset($state) : $STA_ID;
1602
-        }
1603
-        // get Country ISO
1604
-        $CNT_ISO = $this->request->getRequestParam('country');
1605
-        if (! empty($CNT_ISO)) {
1606
-            // can we get country object from name ?
1607
-            EE_Registry::instance()->load_model('Country');
1608
-            $country = EEM_Country::instance()->get_col(
1609
-                [['CNT_name' => $CNT_ISO], 'limit' => 1],
1610
-                'CNT_ISO'
1611
-            );
1612
-            $CNT_ISO = is_array($country) && ! empty($country) ? reset($country) : $CNT_ISO;
1613
-        }
1614
-        // grab attendee data
1615
-        $attendee_data = [
1616
-            'ATT_fname'    => $this->request->getRequestParam('first_name'),
1617
-            'ATT_lname'    => $this->request->getRequestParam('last_name'),
1618
-            'ATT_email'    => $this->request->getRequestParam('email'),
1619
-            'ATT_address'  => $this->request->getRequestParam('address'),
1620
-            'ATT_address2' => $this->request->getRequestParam('address2'),
1621
-            'ATT_city'     => $this->request->getRequestParam('city'),
1622
-            'STA_ID'       => $STA_ID,
1623
-            'CNT_ISO'      => $CNT_ISO,
1624
-            'ATT_zip'      => $this->request->getRequestParam('zip'),
1625
-            'ATT_phone'    => $this->request->getRequestParam('phone'),
1626
-        ];
1627
-        // validate the email address since it is the most important piece of info
1628
-        if (empty($attendee_data['ATT_email'])) {
1629
-            EE_Error::add_error(
1630
-                esc_html__('An invalid email address was submitted.', 'event_espresso'),
1631
-                __FILE__,
1632
-                __FUNCTION__,
1633
-                __LINE__
1634
-            );
1635
-        }
1636
-        // does this attendee already exist in the db ? we're searching using a combination of first name, last name,
1637
-        // AND email address
1638
-        if (
1639
-            ! empty($attendee_data['ATT_fname'])
1640
-            && ! empty($attendee_data['ATT_lname'])
1641
-            && ! empty($attendee_data['ATT_email'])
1642
-        ) {
1643
-            $existing_attendee = EEM_Attendee::instance()->find_existing_attendee(
1644
-                [
1645
-                    'ATT_fname' => $attendee_data['ATT_fname'],
1646
-                    'ATT_lname' => $attendee_data['ATT_lname'],
1647
-                    'ATT_email' => $attendee_data['ATT_email'],
1648
-                ]
1649
-            );
1650
-            if ($existing_attendee instanceof EE_Attendee) {
1651
-                return $existing_attendee;
1652
-            }
1653
-        }
1654
-        // no existing attendee? kk let's create a new one
1655
-        // kinda lame, but we need a first and last name to create an attendee, so use the email address if those
1656
-        // don't exist
1657
-        $attendee_data['ATT_fname'] = ! empty($attendee_data['ATT_fname'])
1658
-            ? $attendee_data['ATT_fname']
1659
-            : $attendee_data['ATT_email'];
1660
-        $attendee_data['ATT_lname'] = ! empty($attendee_data['ATT_lname'])
1661
-            ? $attendee_data['ATT_lname']
1662
-            : $attendee_data['ATT_email'];
1663
-        return EE_Attendee::new_instance($attendee_data);
1664
-    }
1665
-
1666
-
1667
-
1668
-    /********************************************************************************************************/
1669
-    /****************************************  PROCESS REG STEP  *****************************************/
1670
-    /********************************************************************************************************/
1671
-    /**
1672
-     * process_reg_step
1673
-     *
1674
-     * @return bool
1675
-     * @throws EE_Error
1676
-     * @throws InvalidArgumentException
1677
-     * @throws ReflectionException
1678
-     * @throws EntityNotFoundException
1679
-     * @throws InvalidDataTypeException
1680
-     * @throws InvalidInterfaceException
1681
-     * @throws InvalidStatusException
1682
-     */
1683
-    public function process_reg_step()
1684
-    {
1685
-        // how have they chosen to pay?
1686
-        $this->checkout->selected_method_of_payment = $this->checkout->transaction->is_free()
1687
-            ? 'no_payment_required'
1688
-            : $this->_get_selected_method_of_payment(true);
1689
-        // choose your own adventure based on method_of_payment
1690
-        switch ($this->checkout->selected_method_of_payment) {
1691
-            case 'events_sold_out':
1692
-                $this->checkout->redirect     = true;
1693
-                $this->checkout->redirect_url = $this->checkout->cancel_page_url;
1694
-                $this->checkout->json_response->set_redirect_url($this->checkout->redirect_url);
1695
-                // mark this reg step as completed
1696
-                $this->set_completed();
1697
-                return false;
1698
-
1699
-            case 'payments_closed':
1700
-                if (
1701
-                    apply_filters(
1702
-                        'FHEE__EE_SPCO_Reg_Step_Payment_Options__process_reg_step__payments_closed__display_success',
1703
-                        false
1704
-                    )
1705
-                ) {
1706
-                    EE_Error::add_success(
1707
-                        esc_html__('no payment required at this time.', 'event_espresso'),
1708
-                        __FILE__,
1709
-                        __FUNCTION__,
1710
-                        __LINE__
1711
-                    );
1712
-                }
1713
-                // mark this reg step as completed
1714
-                $this->set_completed();
1715
-                return true;
1716
-
1717
-            case 'no_payment_required':
1718
-                if (
1719
-                    apply_filters(
1720
-                        'FHEE__EE_SPCO_Reg_Step_Payment_Options__process_reg_step__no_payment_required__display_success',
1721
-                        false
1722
-                    )
1723
-                ) {
1724
-                    EE_Error::add_success(
1725
-                        esc_html__('no payment required.', 'event_espresso'),
1726
-                        __FILE__,
1727
-                        __FUNCTION__,
1728
-                        __LINE__
1729
-                    );
1730
-                }
1731
-                // mark this reg step as completed
1732
-                $this->set_completed();
1733
-                return true;
1734
-
1735
-            default:
1736
-                $registrations         = EE_Registry::instance()->SSN->checkout()->transaction->registrations(
1737
-                    EE_Registry::instance()->SSN->checkout()->reg_cache_where_params
1738
-                );
1739
-                $ejected_registrations = EE_SPCO_Reg_Step_Payment_Options::find_registrations_that_lost_their_space(
1740
-                    $registrations,
1741
-                    EE_Registry::instance()->SSN->checkout()->revisit
1742
-                );
1743
-                // calculate difference between the two arrays
1744
-                $registrations = array_diff($registrations, $ejected_registrations);
1745
-                if (empty($registrations)) {
1746
-                    $this->_redirect_because_event_sold_out();
1747
-                    return false;
1748
-                }
1749
-                $payment_successful = $this->_process_payment();
1750
-                if ($payment_successful) {
1751
-                    $this->checkout->continue_reg = true;
1752
-                    $this->_maybe_set_completed($this->checkout->payment_method);
1753
-                } else {
1754
-                    $this->checkout->continue_reg = false;
1755
-                }
1756
-                return $payment_successful;
1757
-        }
1758
-    }
1759
-
1760
-
1761
-    /**
1762
-     * _redirect_because_event_sold_out
1763
-     *
1764
-     * @return void
1765
-     */
1766
-    protected function _redirect_because_event_sold_out()
1767
-    {
1768
-        $this->checkout->continue_reg = false;
1769
-        // set redirect URL
1770
-        $this->checkout->redirect_url = add_query_arg(
1771
-            ['e_reg_url_link' => $this->checkout->reg_url_link],
1772
-            $this->checkout->current_step->reg_step_url()
1773
-        );
1774
-        $this->checkout->json_response->set_redirect_url($this->checkout->redirect_url);
1775
-    }
1776
-
1777
-
1778
-    /**
1779
-     * _maybe_set_completed
1780
-     *
1781
-     * @param EE_Payment_Method $payment_method
1782
-     * @return void
1783
-     * @throws EE_Error
1784
-     */
1785
-    protected function _maybe_set_completed(EE_Payment_Method $payment_method)
1786
-    {
1787
-        switch ($payment_method->type_obj()->payment_occurs()) {
1788
-            case EE_PMT_Base::offsite:
1789
-                break;
1790
-            case EE_PMT_Base::onsite:
1791
-            case EE_PMT_Base::offline:
1792
-                // mark this reg step as completed
1793
-                $this->set_completed();
1794
-                break;
1795
-        }
1796
-    }
1797
-
1798
-
1799
-    /**
1800
-     *    update_reg_step
1801
-     *    this is the final step after a user  revisits the site to retry a payment
1802
-     *
1803
-     * @return bool
1804
-     * @throws EE_Error
1805
-     * @throws InvalidArgumentException
1806
-     * @throws ReflectionException
1807
-     * @throws EntityNotFoundException
1808
-     * @throws InvalidDataTypeException
1809
-     * @throws InvalidInterfaceException
1810
-     * @throws InvalidStatusException
1811
-     */
1812
-    public function update_reg_step()
1813
-    {
1814
-        $success = true;
1815
-        // if payment required
1816
-        if ($this->checkout->transaction->total() > 0) {
1817
-            do_action(
1818
-                'AHEE__EE_Single_Page_Checkout__process_finalize_registration__before_gateway',
1819
-                $this->checkout->transaction
1820
-            );
1821
-            // attempt payment via payment method
1822
-            $success = $this->process_reg_step();
1823
-        }
1824
-        if ($success && ! $this->checkout->redirect) {
1825
-            $this->checkout->cart->get_grand_total()->save_this_and_descendants_to_txn(
1826
-                $this->checkout->transaction->ID()
1827
-            );
1828
-            // set return URL
1829
-            $this->checkout->redirect_url = add_query_arg(
1830
-                ['e_reg_url_link' => $this->checkout->reg_url_link],
1831
-                $this->checkout->thank_you_page_url
1832
-            );
1833
-        }
1834
-        return $success;
1835
-    }
1836
-
1837
-
1838
-    /**
1839
-     *    _process_payment
1840
-     *
1841
-     * @return bool
1842
-     * @throws EE_Error
1843
-     * @throws InvalidArgumentException
1844
-     * @throws ReflectionException
1845
-     * @throws RuntimeException
1846
-     * @throws InvalidDataTypeException
1847
-     * @throws InvalidInterfaceException
1848
-     */
1849
-    private function _process_payment()
1850
-    {
1851
-        // basically confirm that the event hasn't sold out since they hit the page
1852
-        if (! $this->_last_second_ticket_verifications()) {
1853
-            return false;
1854
-        }
1855
-        // ya gotta make a choice man
1856
-        if (empty($this->checkout->selected_method_of_payment)) {
1857
-            $this->checkout->json_response->set_plz_select_method_of_payment(
1858
-                esc_html__('Please select a method of payment before proceeding.', 'event_espresso')
1859
-            );
1860
-            return false;
1861
-        }
1862
-        // get EE_Payment_Method object
1863
-        if (! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()) {
1864
-            return false;
1865
-        }
1866
-        // setup billing form
1867
-        if ($this->checkout->payment_method->is_on_site()) {
1868
-            $this->checkout->billing_form = $this->_get_billing_form_for_payment_method(
1869
-                $this->checkout->payment_method
1870
-            );
1871
-            // bad billing form ?
1872
-            if (! $this->_billing_form_is_valid()) {
1873
-                return false;
1874
-            }
1875
-        }
1876
-        // ensure primary registrant has been fully processed
1877
-        if (! $this->_setup_primary_registrant_prior_to_payment()) {
1878
-            return false;
1879
-        }
1880
-        // if session is close to expiring (under 10 minutes by default)
1881
-        if ((time() - EE_Registry::instance()->SSN->expiration()) < EE_Registry::instance()->SSN->extension()) {
1882
-            // add some time to session expiration so that payment can be completed
1883
-            EE_Registry::instance()->SSN->extend_expiration();
1884
-        }
1885
-        /** @type EE_Transaction_Processor $transaction_processor */
1886
-        // $transaction_processor = EE_Registry::instance()->load_class( 'Transaction_Processor' );
1887
-        // in case a registrant leaves to an Off-Site Gateway and never returns, we want to approve any registrations
1888
-        // for events with a default reg status of Approved
1889
-        // $transaction_processor->toggle_registration_statuses_for_default_approved_events(
1890
-        //      $this->checkout->transaction, $this->checkout->reg_cache_where_params
1891
-        // );
1892
-        // attempt payment
1893
-        $payment = $this->_attempt_payment($this->checkout->payment_method);
1894
-        // process results
1895
-        $payment = $this->_validate_payment($payment);
1896
-        $payment = $this->_post_payment_processing($payment);
1897
-        // verify payment
1898
-        if ($payment instanceof EE_Payment) {
1899
-            // store that for later
1900
-            $this->checkout->payment = $payment;
1901
-            // we can also consider the TXN to not have been failed, so temporarily upgrade it's status to abandoned
1902
-            $this->checkout->transaction->toggle_failed_transaction_status();
1903
-            $payment_status = $payment->status();
1904
-            return $payment_status === EEM_Payment::status_id_approved
1905
-                   || $payment_status === EEM_Payment::status_id_pending;
1906
-        }
1907
-        if ($payment === true) {
1908
-            // please note that offline payment methods will NOT make a payment,
1909
-            // but instead just mark themselves as the PMD_ID on the transaction, and return true
1910
-            $this->checkout->payment = $payment;
1911
-            return true;
1912
-        }
1913
-        // where's my money?
1914
-        return false;
1915
-    }
1916
-
1917
-
1918
-    /**
1919
-     * _last_second_ticket_verifications
1920
-     *
1921
-     * @return bool
1922
-     * @throws EE_Error
1923
-     * @throws ReflectionException
1924
-     */
1925
-    protected function _last_second_ticket_verifications()
1926
-    {
1927
-        // don't bother re-validating if not a return visit
1928
-        if (! $this->checkout->revisit) {
1929
-            return true;
1930
-        }
1931
-        $registrations = $this->checkout->transaction->registrations();
1932
-        if (empty($registrations)) {
1933
-            return false;
1934
-        }
1935
-        foreach ($registrations as $registration) {
1936
-            if ($registration instanceof EE_Registration && ! $registration->is_approved()) {
1937
-                $event = $registration->event_obj();
1938
-                if ($event instanceof EE_Event && $event->is_sold_out(true)) {
1939
-                    EE_Error::add_error(
1940
-                        apply_filters(
1941
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___last_second_ticket_verifications__sold_out_events_msg',
1942
-                            sprintf(
1943
-                                esc_html__(
1944
-                                    '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.',
1945
-                                    'event_espresso'
1946
-                                ),
1947
-                                $event->name()
1948
-                            )
1949
-                        ),
1950
-                        __FILE__,
1951
-                        __FUNCTION__,
1952
-                        __LINE__
1953
-                    );
1954
-                    return false;
1955
-                }
1956
-            }
1957
-        }
1958
-        return true;
1959
-    }
1960
-
1961
-
1962
-    /**
1963
-     * redirect_form
1964
-     *
1965
-     * @return bool
1966
-     * @throws EE_Error
1967
-     * @throws InvalidArgumentException
1968
-     * @throws ReflectionException
1969
-     * @throws InvalidDataTypeException
1970
-     * @throws InvalidInterfaceException
1971
-     */
1972
-    public function redirect_form()
1973
-    {
1974
-        $payment_method_billing_info = $this->_payment_method_billing_info(
1975
-            $this->_get_payment_method_for_selected_method_of_payment()
1976
-        );
1977
-        $html                        = $payment_method_billing_info->get_html();
1978
-        $html                        .= $this->checkout->redirect_form;
1979
-        /** @var ResponseInterface $response */
1980
-        $response = LoaderFactory::getLoader()->getShared(ResponseInterface::class);
1981
-        $response->addOutput($html);
1982
-        return true;
1983
-    }
1984
-
1985
-
1986
-    /**
1987
-     * _billing_form_is_valid
1988
-     *
1989
-     * @return bool
1990
-     * @throws EE_Error
1991
-     */
1992
-    private function _billing_form_is_valid()
1993
-    {
1994
-        if (! $this->checkout->payment_method->type_obj()->has_billing_form()) {
1995
-            return true;
1996
-        }
1997
-        if ($this->checkout->billing_form instanceof EE_Billing_Info_Form) {
1998
-            if ($this->checkout->billing_form->was_submitted()) {
1999
-                $this->checkout->billing_form->receive_form_submission();
2000
-                if ($this->checkout->billing_form->is_valid()) {
2001
-                    return true;
2002
-                }
2003
-                $validation_errors = $this->checkout->billing_form->get_validation_errors_accumulated();
2004
-                $error_strings     = [];
2005
-                foreach ($validation_errors as $validation_error) {
2006
-                    if ($validation_error instanceof EE_Validation_Error) {
2007
-                        $form_section = $validation_error->get_form_section();
2008
-                        if ($form_section instanceof EE_Form_Input_Base) {
2009
-                            $label = $form_section->html_label_text();
2010
-                        } elseif ($form_section instanceof EE_Form_Section_Base) {
2011
-                            $label = $form_section->name();
2012
-                        } else {
2013
-                            $label = esc_html__('Validation Error', 'event_espresso');
2014
-                        }
2015
-                        $error_strings[] = sprintf('%1$s: %2$s', $label, $validation_error->getMessage());
2016
-                    }
2017
-                }
2018
-                EE_Error::add_error(
2019
-                    sprintf(
2020
-                        esc_html__(
2021
-                            'One or more billing form inputs are invalid and require correction before proceeding. %1$s %2$s',
2022
-                            'event_espresso'
2023
-                        ),
2024
-                        '<br/>',
2025
-                        implode('<br/>', $error_strings)
2026
-                    ),
2027
-                    __FILE__,
2028
-                    __FUNCTION__,
2029
-                    __LINE__
2030
-                );
2031
-            } else {
2032
-                EE_Error::add_error(
2033
-                    esc_html__(
2034
-                        'The billing form was not submitted or something prevented it\'s submission.',
2035
-                        'event_espresso'
2036
-                    ),
2037
-                    __FILE__,
2038
-                    __FUNCTION__,
2039
-                    __LINE__
2040
-                );
2041
-            }
2042
-        } else {
2043
-            EE_Error::add_error(
2044
-                esc_html__(
2045
-                    'The submitted billing form is invalid possibly due to a technical reason.',
2046
-                    'event_espresso'
2047
-                ),
2048
-                __FILE__,
2049
-                __FUNCTION__,
2050
-                __LINE__
2051
-            );
2052
-        }
2053
-        return false;
2054
-    }
2055
-
2056
-
2057
-    /**
2058
-     * _setup_primary_registrant_prior_to_payment
2059
-     * ensures that the primary registrant has a valid attendee object created with the critical details populated
2060
-     * (first & last name & email) and that both the transaction object and primary registration object have been saved
2061
-     * plz note that any other registrations will NOT be saved at this point (because they may not have any details
2062
-     * yet)
2063
-     *
2064
-     * @return bool
2065
-     * @throws EE_Error
2066
-     * @throws InvalidArgumentException
2067
-     * @throws ReflectionException
2068
-     * @throws RuntimeException
2069
-     * @throws InvalidDataTypeException
2070
-     * @throws InvalidInterfaceException
2071
-     */
2072
-    private function _setup_primary_registrant_prior_to_payment()
2073
-    {
2074
-        // check if transaction has a primary registrant and that it has a related Attendee object
2075
-        // if not, then we need to at least gather some primary registrant data before attempting payment
2076
-        if (
2077
-            $this->checkout->billing_form instanceof EE_Billing_Attendee_Info_Form
2078
-            && ! $this->checkout->transaction_has_primary_registrant()
2079
-            && ! $this->_capture_primary_registration_data_from_billing_form()
2080
-        ) {
2081
-            return false;
2082
-        }
2083
-        // because saving an object clears it's cache, we need to do the chevy shuffle
2084
-        // grab the primary_registration object
2085
-        $primary_registration = $this->checkout->transaction->primary_registration();
2086
-        // at this point we'll consider a TXN to not have been failed
2087
-        $this->checkout->transaction->toggle_failed_transaction_status();
2088
-        // save the TXN ( which clears cached copy of primary_registration)
2089
-        $this->checkout->transaction->save();
2090
-        // grab TXN ID and save it to the primary_registration
2091
-        $primary_registration->set_transaction_id($this->checkout->transaction->ID());
2092
-        // save what we have so far
2093
-        $primary_registration->save();
2094
-        return true;
2095
-    }
2096
-
2097
-
2098
-    /**
2099
-     * _capture_primary_registration_data_from_billing_form
2100
-     *
2101
-     * @return bool
2102
-     * @throws EE_Error
2103
-     * @throws InvalidArgumentException
2104
-     * @throws ReflectionException
2105
-     * @throws InvalidDataTypeException
2106
-     * @throws InvalidInterfaceException
2107
-     */
2108
-    private function _capture_primary_registration_data_from_billing_form()
2109
-    {
2110
-        // convert billing form data into an attendee
2111
-        $this->checkout->primary_attendee_obj = $this->checkout->billing_form->create_attendee_from_billing_form_data();
2112
-        if (! $this->checkout->primary_attendee_obj instanceof EE_Attendee) {
2113
-            EE_Error::add_error(
2114
-                sprintf(
2115
-                    esc_html__(
2116
-                        'The billing form details could not be used for attendee details due to a technical issue.%sPlease try again or contact %s for assistance.',
2117
-                        'event_espresso'
2118
-                    ),
2119
-                    '<br/>',
2120
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
2121
-                ),
2122
-                __FILE__,
2123
-                __FUNCTION__,
2124
-                __LINE__
2125
-            );
2126
-            return false;
2127
-        }
2128
-        $primary_registration = $this->checkout->transaction->primary_registration();
2129
-        if (! $primary_registration instanceof EE_Registration) {
2130
-            EE_Error::add_error(
2131
-                sprintf(
2132
-                    esc_html__(
2133
-                        'The primary registrant for this transaction could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.',
2134
-                        'event_espresso'
2135
-                    ),
2136
-                    '<br/>',
2137
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
2138
-                ),
2139
-                __FILE__,
2140
-                __FUNCTION__,
2141
-                __LINE__
2142
-            );
2143
-            return false;
2144
-        }
2145
-        if (
2146
-            ! $primary_registration->_add_relation_to($this->checkout->primary_attendee_obj, 'Attendee')
2147
-              instanceof
2148
-              EE_Attendee
2149
-        ) {
2150
-            EE_Error::add_error(
2151
-                sprintf(
2152
-                    esc_html__(
2153
-                        'The primary registrant could not be associated with this transaction due to a technical issue.%sPlease try again or contact %s for assistance.',
2154
-                        'event_espresso'
2155
-                    ),
2156
-                    '<br/>',
2157
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
2158
-                ),
2159
-                __FILE__,
2160
-                __FUNCTION__,
2161
-                __LINE__
2162
-            );
2163
-            return false;
2164
-        }
2165
-        /** @type EE_Registration_Processor $registration_processor */
2166
-        $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
2167
-        // at this point, we should have enough details about the registrant to consider the registration NOT incomplete
2168
-        $registration_processor->toggle_incomplete_registration_status_to_default($primary_registration);
2169
-        return true;
2170
-    }
2171
-
2172
-
2173
-    /**
2174
-     * _get_payment_method_for_selected_method_of_payment
2175
-     * retrieves a valid payment method
2176
-     *
2177
-     * @return EE_Payment_Method
2178
-     * @throws EE_Error
2179
-     * @throws InvalidArgumentException
2180
-     * @throws ReflectionException
2181
-     * @throws InvalidDataTypeException
2182
-     * @throws InvalidInterfaceException
2183
-     */
2184
-    private function _get_payment_method_for_selected_method_of_payment()
2185
-    {
2186
-        if ($this->checkout->selected_method_of_payment === 'events_sold_out') {
2187
-            $this->_redirect_because_event_sold_out();
2188
-            return null;
2189
-        }
2190
-        // get EE_Payment_Method object
2191
-        if (isset($this->checkout->available_payment_methods[ $this->checkout->selected_method_of_payment ])) {
2192
-            $payment_method = $this->checkout->available_payment_methods[ $this->checkout->selected_method_of_payment ];
2193
-        } else {
2194
-            // load EEM_Payment_Method
2195
-            EE_Registry::instance()->load_model('Payment_Method');
2196
-            $EEM_Payment_Method = EEM_Payment_Method::instance();
2197
-            $payment_method     = $EEM_Payment_Method->get_one_by_slug($this->checkout->selected_method_of_payment);
2198
-        }
2199
-        // verify $payment_method
2200
-        if (! $payment_method instanceof EE_Payment_Method) {
2201
-            // not a payment
2202
-            EE_Error::add_error(
2203
-                sprintf(
2204
-                    esc_html__(
2205
-                        'The selected method of payment could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.',
2206
-                        'event_espresso'
2207
-                    ),
2208
-                    '<br/>',
2209
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
2210
-                ),
2211
-                __FILE__,
2212
-                __FUNCTION__,
2213
-                __LINE__
2214
-            );
2215
-            return null;
2216
-        }
2217
-        // and verify it has a valid Payment_Method Type object
2218
-        if (! $payment_method->type_obj() instanceof EE_PMT_Base) {
2219
-            // not a payment
2220
-            EE_Error::add_error(
2221
-                sprintf(
2222
-                    esc_html__(
2223
-                        'A valid payment method could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.',
2224
-                        'event_espresso'
2225
-                    ),
2226
-                    '<br/>',
2227
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
2228
-                ),
2229
-                __FILE__,
2230
-                __FUNCTION__,
2231
-                __LINE__
2232
-            );
2233
-            return null;
2234
-        }
2235
-        return $payment_method;
2236
-    }
2237
-
2238
-
2239
-    /**
2240
-     *    _attempt_payment
2241
-     *
2242
-     * @access    private
2243
-     * @type    EE_Payment_Method $payment_method
2244
-     * @return mixed EE_Payment | boolean
2245
-     * @throws EE_Error
2246
-     * @throws InvalidArgumentException
2247
-     * @throws ReflectionException
2248
-     * @throws InvalidDataTypeException
2249
-     * @throws InvalidInterfaceException
2250
-     */
2251
-    private function _attempt_payment(EE_Payment_Method $payment_method)
2252
-    {
2253
-        $payment = null;
2254
-        $this->checkout->transaction->save();
2255
-        $payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2256
-        if (! $payment_processor instanceof EE_Payment_Processor) {
2257
-            return false;
2258
-        }
2259
-        try {
2260
-            $payment_processor->set_revisit($this->checkout->revisit);
2261
-            // generate payment object
2262
-            $payment = $payment_processor->process_payment(
2263
-                $payment_method,
2264
-                $this->checkout->transaction,
2265
-                $this->checkout->amount_owing,
2266
-                $this->checkout->billing_form,
2267
-                $this->_get_return_url($payment_method),
2268
-                'CART',
2269
-                $this->checkout->admin_request,
2270
-                true,
2271
-                $this->reg_step_url()
2272
-            );
2273
-        } catch (Exception $e) {
2274
-            $this->_handle_payment_processor_exception($e);
2275
-        }
2276
-        return $payment;
2277
-    }
2278
-
2279
-
2280
-    /**
2281
-     * _handle_payment_processor_exception
2282
-     *
2283
-     * @param Exception $e
2284
-     * @return void
2285
-     * @throws EE_Error
2286
-     * @throws InvalidArgumentException
2287
-     * @throws InvalidDataTypeException
2288
-     * @throws InvalidInterfaceException
2289
-     */
2290
-    protected function _handle_payment_processor_exception(Exception $e)
2291
-    {
2292
-        EE_Error::add_error(
2293
-            sprintf(
2294
-                esc_html__(
2295
-                    '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',
2296
-                    'event_espresso'
2297
-                ),
2298
-                '<br/>',
2299
-                EE_Registry::instance()->CFG->organization->get_pretty('email'),
2300
-                $e->getMessage(),
2301
-                $e->getFile(),
2302
-                $e->getLine()
2303
-            ),
2304
-            __FILE__,
2305
-            __FUNCTION__,
2306
-            __LINE__
2307
-        );
2308
-    }
2309
-
2310
-
2311
-    /**
2312
-     * _get_return_url
2313
-     *
2314
-     * @param EE_Payment_Method $payment_method
2315
-     * @return string
2316
-     * @throws EE_Error
2317
-     * @throws ReflectionException
2318
-     */
2319
-    protected function _get_return_url(EE_Payment_Method $payment_method)
2320
-    {
2321
-        $return_url = '';
2322
-        switch ($payment_method->type_obj()->payment_occurs()) {
2323
-            case EE_PMT_Base::offsite:
2324
-                $return_url = add_query_arg(
2325
-                    [
2326
-                        'action'                     => 'process_gateway_response',
2327
-                        'selected_method_of_payment' => $this->checkout->selected_method_of_payment,
2328
-                        'spco_txn'                   => $this->checkout->transaction->ID(),
2329
-                    ],
2330
-                    $this->reg_step_url()
2331
-                );
2332
-                break;
2333
-            case EE_PMT_Base::onsite:
2334
-            case EE_PMT_Base::offline:
2335
-                $return_url = $this->checkout->next_step->reg_step_url();
2336
-                break;
2337
-        }
2338
-        return $return_url;
2339
-    }
2340
-
2341
-
2342
-    /**
2343
-     * _validate_payment
2344
-     *
2345
-     * @param EE_Payment $payment
2346
-     * @return EE_Payment|FALSE
2347
-     * @throws EE_Error
2348
-     * @throws InvalidArgumentException
2349
-     * @throws InvalidDataTypeException
2350
-     * @throws InvalidInterfaceException
2351
-     */
2352
-    private function _validate_payment($payment = null)
2353
-    {
2354
-        if ($this->checkout->payment_method->is_off_line()) {
2355
-            return true;
2356
-        }
2357
-        // verify payment object
2358
-        if (! $payment instanceof EE_Payment) {
2359
-            // not a payment
2360
-            EE_Error::add_error(
2361
-                sprintf(
2362
-                    esc_html__(
2363
-                        'A valid payment was not generated due to a technical issue.%1$sPlease try again or contact %2$s for assistance.',
2364
-                        'event_espresso'
2365
-                    ),
2366
-                    '<br/>',
2367
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
2368
-                ),
2369
-                __FILE__,
2370
-                __FUNCTION__,
2371
-                __LINE__
2372
-            );
2373
-            return false;
2374
-        }
2375
-        return $payment;
2376
-    }
2377
-
2378
-
2379
-    /**
2380
-     * _post_payment_processing
2381
-     *
2382
-     * @param EE_Payment|bool $payment
2383
-     * @return bool
2384
-     * @throws EE_Error
2385
-     * @throws InvalidArgumentException
2386
-     * @throws InvalidDataTypeException
2387
-     * @throws InvalidInterfaceException
2388
-     * @throws ReflectionException
2389
-     */
2390
-    private function _post_payment_processing($payment = null)
2391
-    {
2392
-        // Off-Line payment?
2393
-        if ($payment === true) {
2394
-            // $this->_setup_redirect_for_next_step();
2395
-            return true;
2396
-            // On-Site payment?
2397
-        } elseif ($this->checkout->payment_method->is_on_site()) {
2398
-            if (! $this->_process_payment_status($payment, EE_PMT_Base::onsite)) {
2399
-                // $this->_setup_redirect_for_next_step();
2400
-                $this->checkout->continue_reg = false;
2401
-            }
2402
-            // Off-Site payment?
2403
-        } elseif ($this->checkout->payment_method->is_off_site()) {
2404
-            // if a payment object was made and it specifies a redirect url, then we'll setup that redirect info
2405
-            if ($payment instanceof EE_Payment && $payment->redirect_url()) {
2406
-                do_action('AHEE_log', __CLASS__, __FUNCTION__, $payment->redirect_url(), '$payment->redirect_url()');
2407
-                $this->checkout->redirect      = true;
2408
-                $this->checkout->redirect_form = $payment->redirect_form();
2409
-                $this->checkout->redirect_url  = $this->reg_step_url('redirect_form');
2410
-                // set JSON response
2411
-                $this->checkout->json_response->set_redirect_form($this->checkout->redirect_form);
2412
-                // and lastly, let's bump the payment status to pending
2413
-                $payment->set_status(EEM_Payment::status_id_pending);
2414
-                $payment->save();
2415
-            } else {
2416
-                // we couldn't redirect the user. Let's tell them why.
2417
-                $error_message = sprintf(
2418
-                    esc_html__(
2419
-                        'It appears the Off Site Payment Method was not configured properly.%sPlease try again or contact %s for assistance.',
2420
-                        'event_espresso'
2421
-                    ),
2422
-                    '<br/>',
2423
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
2424
-                );
2425
-                if ($payment instanceof EE_Payment && $payment->gateway_response()) {
2426
-                    $error_message = $error_message . '<br/>' . $payment->gateway_response();
2427
-                }
2428
-                $this->checkout->continue_reg = false;
2429
-                EE_Error::add_error(
2430
-                    $error_message,
2431
-                    __FILE__,
2432
-                    __FUNCTION__,
2433
-                    __LINE__
2434
-                );
2435
-            }
2436
-        } else {
2437
-            // ummm ya... not Off-Line, not On-Site, not off-Site ????
2438
-            $this->checkout->continue_reg = false;
2439
-            return false;
2440
-        }
2441
-        return $payment;
2442
-    }
2443
-
2444
-
2445
-    /**
2446
-     *    _process_payment_status
2447
-     *
2448
-     * @type    EE_Payment $payment
2449
-     * @param string       $payment_occurs
2450
-     * @return bool
2451
-     * @throws EE_Error
2452
-     * @throws InvalidArgumentException
2453
-     * @throws InvalidDataTypeException
2454
-     * @throws InvalidInterfaceException
2455
-     */
2456
-    private function _process_payment_status($payment, $payment_occurs = EE_PMT_Base::offline)
2457
-    {
2458
-        // off-line payment? carry on
2459
-        if ($payment_occurs === EE_PMT_Base::offline) {
2460
-            return true;
2461
-        }
2462
-        // verify payment validity
2463
-        if ($payment instanceof EE_Payment) {
2464
-            do_action('AHEE_log', __CLASS__, __FUNCTION__, $payment->status(), '$payment->status()');
2465
-            $msg = $payment->gateway_response();
2466
-            // check results
2467
-            switch ($payment->status()) {
2468
-                // good payment
2469
-                case EEM_Payment::status_id_approved:
2470
-                    EE_Error::add_success(
2471
-                        esc_html__('Your payment was processed successfully.', 'event_espresso'),
2472
-                        __FILE__,
2473
-                        __FUNCTION__,
2474
-                        __LINE__
2475
-                    );
2476
-                    return true;
2477
-                // slow payment
2478
-                case EEM_Payment::status_id_pending:
2479
-                    if (empty($msg)) {
2480
-                        $msg = esc_html__(
2481
-                            'Your payment appears to have been processed successfully, but the Instant Payment Notification has not yet been received. It should arrive shortly.',
2482
-                            'event_espresso'
2483
-                        );
2484
-                    }
2485
-                    EE_Error::add_success($msg, __FILE__, __FUNCTION__, __LINE__);
2486
-                    return true;
2487
-                // don't wanna payment
2488
-                case EEM_Payment::status_id_cancelled:
2489
-                    if (empty($msg)) {
2490
-                        $msg = _n(
2491
-                            'Payment cancelled. Please try again.',
2492
-                            'Payment cancelled. Please try again or select another method of payment.',
2493
-                            count($this->checkout->available_payment_methods),
2494
-                            'event_espresso'
2495
-                        );
2496
-                    }
2497
-                    EE_Error::add_attention($msg, __FILE__, __FUNCTION__, __LINE__);
2498
-                    return false;
2499
-                // not enough payment
2500
-                case EEM_Payment::status_id_declined:
2501
-                    if (empty($msg)) {
2502
-                        $msg = _n(
2503
-                            'We\'re sorry but your payment was declined. Please try again.',
2504
-                            'We\'re sorry but your payment was declined. Please try again or select another method of payment.',
2505
-                            count($this->checkout->available_payment_methods),
2506
-                            'event_espresso'
2507
-                        );
2508
-                    }
2509
-                    EE_Error::add_attention($msg, __FILE__, __FUNCTION__, __LINE__);
2510
-                    return false;
2511
-                // bad payment
2512
-                case EEM_Payment::status_id_failed:
2513
-                    if (! empty($msg)) {
2514
-                        EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2515
-                        return false;
2516
-                    }
2517
-                    // default to error below
2518
-                    break;
2519
-            }
2520
-        }
2521
-        // off-site payment gateway responses are too unreliable, so let's just assume that
2522
-        // the payment processing is just running slower than the registrant's request
2523
-        if ($payment_occurs === EE_PMT_Base::offsite) {
2524
-            return true;
2525
-        }
2526
-        EE_Error::add_error(
2527
-            sprintf(
2528
-                esc_html__(
2529
-                    'Your payment could not be processed successfully due to a technical issue.%sPlease try again or contact %s for assistance.',
2530
-                    'event_espresso'
2531
-                ),
2532
-                '<br/>',
2533
-                EE_Registry::instance()->CFG->organization->get_pretty('email')
2534
-            ),
2535
-            __FILE__,
2536
-            __FUNCTION__,
2537
-            __LINE__
2538
-        );
2539
-        return false;
2540
-    }
2541
-
2542
-
2543
-
2544
-
2545
-
2546
-
2547
-    /********************************************************************************************************/
2548
-    /**********************************  PROCESS GATEWAY RESPONSE  **********************************/
2549
-    /********************************************************************************************************/
2550
-    /**
2551
-     * process_gateway_response
2552
-     * this is the return point for Off-Site Payment Methods
2553
-     * It will attempt to "handle the IPN" if it appears that this has not already occurred,
2554
-     * otherwise, it will load up the last payment made for the TXN.
2555
-     * If the payment retrieved looks good, it will then either:
2556
-     *    complete the current step and allow advancement to the next reg step
2557
-     *        or present the payment options again
2558
-     *
2559
-     * @return bool
2560
-     * @throws EE_Error
2561
-     * @throws InvalidArgumentException
2562
-     * @throws ReflectionException
2563
-     * @throws InvalidDataTypeException
2564
-     * @throws InvalidInterfaceException
2565
-     */
2566
-    public function process_gateway_response()
2567
-    {
2568
-        // how have they chosen to pay?
2569
-        $this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
2570
-        // get EE_Payment_Method object
2571
-        if (! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()) {
2572
-            $this->checkout->continue_reg = false;
2573
-            return false;
2574
-        }
2575
-        if (! $this->checkout->payment_method->is_off_site()) {
2576
-            return false;
2577
-        }
2578
-        $this->_validate_offsite_return();
2579
-        // verify TXN
2580
-        if ($this->checkout->transaction instanceof EE_Transaction) {
2581
-            $gateway = $this->checkout->payment_method->type_obj()->get_gateway();
2582
-            if (! $gateway instanceof EE_Offsite_Gateway) {
2583
-                $this->checkout->continue_reg = false;
2584
-                return false;
2585
-            }
2586
-            $payment = $this->_process_off_site_payment($gateway);
2587
-            $payment = $this->_process_cancelled_payments($payment);
2588
-            $payment = $this->_validate_payment($payment);
2589
-            // if payment was not declined by the payment gateway or cancelled by the registrant
2590
-            if ($this->_process_payment_status($payment, EE_PMT_Base::offsite)) {
2591
-                // $this->_setup_redirect_for_next_step();
2592
-                // store that for later
2593
-                $this->checkout->payment = $payment;
2594
-                // mark this reg step as completed, as long as gateway doesn't use a separate IPN request,
2595
-                // because we will complete this step during the IPN processing then
2596
-                if (! $this->handle_IPN_in_this_request()) {
2597
-                    $this->set_completed();
2598
-                }
2599
-                return true;
2600
-            }
2601
-        }
2602
-        // DEBUG LOG
2603
-        // $this->checkout->log(
2604
-        //     __CLASS__,
2605
-        //     __FUNCTION__,
2606
-        //     __LINE__,
2607
-        //     array('payment' => $payment)
2608
-        // );
2609
-        $this->checkout->continue_reg = false;
2610
-        return false;
2611
-    }
2612
-
2613
-
2614
-    /**
2615
-     * _validate_return
2616
-     *
2617
-     * @return void
2618
-     * @throws EE_Error
2619
-     * @throws InvalidArgumentException
2620
-     * @throws InvalidDataTypeException
2621
-     * @throws InvalidInterfaceException
2622
-     * @throws ReflectionException
2623
-     */
2624
-    private function _validate_offsite_return()
2625
-    {
2626
-        $TXN_ID = $this->request->getRequestParam('spco_txn', 0, 'int');
2627
-        if ($TXN_ID !== $this->checkout->transaction->ID()) {
2628
-            // Houston... we might have a problem
2629
-            $invalid_TXN = false;
2630
-            // first gather some info
2631
-            $valid_TXN          = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
2632
-            $primary_registrant = $valid_TXN instanceof EE_Transaction
2633
-                ? $valid_TXN->primary_registration()
2634
-                : null;
2635
-            // let's start by retrieving the cart for this TXN
2636
-            $cart = $this->checkout->get_cart_for_transaction($this->checkout->transaction);
2637
-            if ($cart instanceof EE_Cart) {
2638
-                // verify that the current cart has tickets
2639
-                $tickets = $cart->get_tickets();
2640
-                if (empty($tickets)) {
2641
-                    $invalid_TXN = true;
2642
-                }
2643
-            } else {
2644
-                $invalid_TXN = true;
2645
-            }
2646
-            $valid_TXN_SID = $primary_registrant instanceof EE_Registration
2647
-                ? $primary_registrant->session_ID()
2648
-                : null;
2649
-            // validate current Session ID and compare against valid TXN session ID
2650
-            if (
2651
-                $invalid_TXN // if this is already true, then skip other checks
2652
-                || EE_Session::instance()->id() === null
2653
-                || (
2654
-                    // WARNING !!!
2655
-                    // this could be PayPal sending back duplicate requests (ya they do that)
2656
-                    // or it **could** mean someone is simply registering AGAIN after having just done so
2657
-                    // so now we need to determine if this current TXN looks valid or not
2658
-                    // and whether this reg step has even been started ?
2659
-                    EE_Session::instance()->id() === $valid_TXN_SID
2660
-                    // really? you're half way through this reg step, but you never started it ?
2661
-                    && $this->checkout->transaction->reg_step_completed($this->slug()) === false
2662
-                )
2663
-            ) {
2664
-                $invalid_TXN = true;
2665
-            }
2666
-            if ($invalid_TXN) {
2667
-                // is the valid TXN completed ?
2668
-                if ($valid_TXN instanceof EE_Transaction) {
2669
-                    // has this step even been started ?
2670
-                    $reg_step_completed = $valid_TXN->reg_step_completed($this->slug());
2671
-                    if ($reg_step_completed !== false && $reg_step_completed !== true) {
2672
-                        // so it **looks** like this is a double request from PayPal
2673
-                        // so let's try to pick up where we left off
2674
-                        $this->checkout->transaction = $valid_TXN;
2675
-                        $this->checkout->refresh_all_entities(true);
2676
-                        return;
2677
-                    }
2678
-                }
2679
-                // you appear to be lost?
2680
-                $this->_redirect_wayward_request($primary_registrant);
2681
-            }
2682
-        }
2683
-    }
2684
-
2685
-
2686
-    /**
2687
-     * _redirect_wayward_request
2688
-     *
2689
-     * @param EE_Registration|null $primary_registrant
2690
-     * @return void
2691
-     * @throws EE_Error
2692
-     * @throws InvalidArgumentException
2693
-     * @throws InvalidDataTypeException
2694
-     * @throws InvalidInterfaceException
2695
-     * @throws ReflectionException
2696
-     */
2697
-    private function _redirect_wayward_request(EE_Registration $primary_registrant)
2698
-    {
2699
-        if (! $primary_registrant instanceof EE_Registration) {
2700
-            // try redirecting based on the current TXN
2701
-            $primary_registrant = $this->checkout->transaction instanceof EE_Transaction
2702
-                ? $this->checkout->transaction->primary_registration()
2703
-                : null;
2704
-        }
2705
-        if (! $primary_registrant instanceof EE_Registration) {
2706
-            EE_Error::add_error(
2707
-                sprintf(
2708
-                    esc_html__(
2709
-                        '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.',
2710
-                        'event_espresso'
2711
-                    ),
2712
-                    '<br/>',
2713
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
2714
-                ),
2715
-                __FILE__,
2716
-                __FUNCTION__,
2717
-                __LINE__
2718
-            );
2719
-            return;
2720
-        }
2721
-        // make sure transaction is not locked
2722
-        $this->checkout->transaction->unlock();
2723
-        wp_safe_redirect(
2724
-            add_query_arg(
2725
-                [
2726
-                    'e_reg_url_link' => $primary_registrant->reg_url_link(),
2727
-                ],
2728
-                $this->checkout->thank_you_page_url
2729
-            )
2730
-        );
2731
-        exit();
2732
-    }
2733
-
2734
-
2735
-    /**
2736
-     * _process_off_site_payment
2737
-     *
2738
-     * @param EE_Offsite_Gateway $gateway
2739
-     * @return EE_Payment
2740
-     * @throws EE_Error
2741
-     * @throws InvalidArgumentException
2742
-     * @throws InvalidDataTypeException
2743
-     * @throws InvalidInterfaceException
2744
-     * @throws ReflectionException
2745
-     */
2746
-    private function _process_off_site_payment(EE_Offsite_Gateway $gateway)
2747
-    {
2748
-        try {
2749
-            $request      = LoaderFactory::getLoader()->getShared(RequestInterface::class);
2750
-            $request_data = $request->requestParams();
2751
-            // if gateway uses_separate_IPN_request, then we don't have to process the IPN manually
2752
-            $this->set_handle_IPN_in_this_request(
2753
-                $gateway->handle_IPN_in_this_request($request_data, false)
2754
-            );
2755
-            if ($this->handle_IPN_in_this_request()) {
2756
-                // get payment details and process results
2757
-                /** @type EE_Payment_Processor $payment_processor */
2758
-                $payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2759
-                $payment           = $payment_processor->process_ipn(
2760
-                    $request_data,
2761
-                    $this->checkout->transaction,
2762
-                    $this->checkout->payment_method,
2763
-                    true,
2764
-                    false
2765
-                );
2766
-                // $payment_source = 'process_ipn';
2767
-            } else {
2768
-                $payment = $this->checkout->transaction->last_payment();
2769
-                // $payment_source = 'last_payment';
2770
-            }
2771
-        } catch (Exception $e) {
2772
-            // let's just eat the exception and try to move on using any previously set payment info
2773
-            $payment = $this->checkout->transaction->last_payment();
2774
-            // $payment_source = 'last_payment after Exception';
2775
-            // but if we STILL don't have a payment object
2776
-            if (! $payment instanceof EE_Payment) {
2777
-                // then we'll object ! ( not object like a thing... but object like what a lawyer says ! )
2778
-                $this->_handle_payment_processor_exception($e);
2779
-            }
2780
-        }
2781
-        return $payment;
2782
-    }
2783
-
2784
-
2785
-    /**
2786
-     * _process_cancelled_payments
2787
-     * just makes sure that the payment status gets updated correctly
2788
-     * so tha tan error isn't generated during payment validation
2789
-     *
2790
-     * @param EE_Payment $payment
2791
-     * @return EE_Payment|null
2792
-     * @throws EE_Error
2793
-     */
2794
-    private function _process_cancelled_payments($payment = null)
2795
-    {
2796
-        if (
2797
-            $payment instanceof EE_Payment
2798
-            && $this->request->requestParamIsSet('ee_cancel_payment')
2799
-            && $payment->status() === EEM_Payment::status_id_failed
2800
-        ) {
2801
-            $payment->set_status(EEM_Payment::status_id_cancelled);
2802
-        }
2803
-        return $payment;
2804
-    }
2805
-
2806
-
2807
-    /**
2808
-     *    get_transaction_details_for_gateways
2809
-     *
2810
-     * @access    public
2811
-     * @return void
2812
-     * @throws EE_Error
2813
-     * @throws InvalidArgumentException
2814
-     * @throws ReflectionException
2815
-     * @throws InvalidDataTypeException
2816
-     * @throws InvalidInterfaceException
2817
-     */
2818
-    public function get_transaction_details_for_gateways()
2819
-    {
2820
-        $txn_details = [];
2821
-        // ya gotta make a choice man
2822
-        if (empty($this->checkout->selected_method_of_payment)) {
2823
-            $txn_details = [
2824
-                'error' => esc_html__('Please select a method of payment before proceeding.', 'event_espresso'),
2825
-            ];
2826
-        }
2827
-        // get EE_Payment_Method object
2828
-        if (
2829
-            empty($txn_details)
2830
-            && ! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()
2831
-        ) {
2832
-            $txn_details = [
2833
-                'selected_method_of_payment' => $this->checkout->selected_method_of_payment,
2834
-                'error'                      => esc_html__(
2835
-                    'A valid Payment Method could not be determined.',
2836
-                    'event_espresso'
2837
-                ),
2838
-            ];
2839
-        }
2840
-        if (empty($txn_details) && $this->checkout->transaction instanceof EE_Transaction) {
2841
-            $return_url  = $this->_get_return_url($this->checkout->payment_method);
2842
-            $txn_details = [
2843
-                'TXN_ID'         => $this->checkout->transaction->ID(),
2844
-                'TXN_timestamp'  => $this->checkout->transaction->datetime(),
2845
-                'TXN_total'      => $this->checkout->transaction->total(),
2846
-                'TXN_paid'       => $this->checkout->transaction->paid(),
2847
-                'TXN_reg_steps'  => $this->checkout->transaction->reg_steps(),
2848
-                'STS_ID'         => $this->checkout->transaction->status_ID(),
2849
-                'PMD_ID'         => $this->checkout->transaction->payment_method_ID(),
2850
-                'payment_amount' => $this->checkout->amount_owing,
2851
-                'return_url'     => $return_url,
2852
-                'cancel_url'     => add_query_arg(['ee_cancel_payment' => true], $return_url),
2853
-                'notify_url'     => EE_Config::instance()->core->txn_page_url(
2854
-                    [
2855
-                        'e_reg_url_link'    => $this->checkout->transaction->primary_registration()->reg_url_link(),
2856
-                        'ee_payment_method' => $this->checkout->payment_method->slug(),
2857
-                    ]
2858
-                ),
2859
-            ];
2860
-        }
2861
-        echo wp_json_encode($txn_details);
2862
-        exit();
2863
-    }
2864
-
2865
-
2866
-    /**
2867
-     *    __sleep
2868
-     * to conserve db space, let's remove the reg_form and the EE_Checkout object from EE_SPCO_Reg_Step objects upon
2869
-     * serialization EE_Checkout will handle the reimplementation of itself upon waking, but we won't bother with the
2870
-     * reg form, because if needed, it will be regenerated anyways
2871
-     *
2872
-     * @return array
2873
-     */
2874
-    public function __sleep()
2875
-    {
2876
-        // remove the reg form and the checkout
2877
-        return array_diff(array_keys(get_object_vars($this)), ['reg_form', 'checkout', 'line_item_display']);
2878
-    }
23
+	/**
24
+	 * @var EE_Line_Item_Display $Line_Item_Display
25
+	 */
26
+	protected $line_item_display;
27
+
28
+	/**
29
+	 * @var boolean $handle_IPN_in_this_request
30
+	 */
31
+	protected $handle_IPN_in_this_request = false;
32
+
33
+
34
+	/**
35
+	 *    set_hooks - for hooking into EE Core, other modules, etc
36
+	 *
37
+	 * @access    public
38
+	 * @return    void
39
+	 */
40
+	public static function set_hooks()
41
+	{
42
+		add_filter(
43
+			'FHEE__SPCO__EE_Line_Item_Filter_Collection',
44
+			['EE_SPCO_Reg_Step_Payment_Options', 'add_spco_line_item_filters']
45
+		);
46
+		add_action(
47
+			'wp_ajax_switch_spco_billing_form',
48
+			['EE_SPCO_Reg_Step_Payment_Options', 'switch_spco_billing_form']
49
+		);
50
+		add_action(
51
+			'wp_ajax_nopriv_switch_spco_billing_form',
52
+			['EE_SPCO_Reg_Step_Payment_Options', 'switch_spco_billing_form']
53
+		);
54
+		add_action('wp_ajax_save_payer_details', ['EE_SPCO_Reg_Step_Payment_Options', 'save_payer_details']);
55
+		add_action(
56
+			'wp_ajax_nopriv_save_payer_details',
57
+			['EE_SPCO_Reg_Step_Payment_Options', 'save_payer_details']
58
+		);
59
+		add_action(
60
+			'wp_ajax_get_transaction_details_for_gateways',
61
+			['EE_SPCO_Reg_Step_Payment_Options', 'get_transaction_details']
62
+		);
63
+		add_action(
64
+			'wp_ajax_nopriv_get_transaction_details_for_gateways',
65
+			['EE_SPCO_Reg_Step_Payment_Options', 'get_transaction_details']
66
+		);
67
+		add_filter(
68
+			'FHEE__EED_Recaptcha___bypass_recaptcha__bypass_request_params_array',
69
+			['EE_SPCO_Reg_Step_Payment_Options', 'bypass_recaptcha_for_load_payment_method'],
70
+			10,
71
+			1
72
+		);
73
+	}
74
+
75
+
76
+	/**
77
+	 *    ajax switch_spco_billing_form
78
+	 *
79
+	 */
80
+	public static function switch_spco_billing_form()
81
+	{
82
+		EED_Single_Page_Checkout::process_ajax_request('switch_payment_method');
83
+	}
84
+
85
+
86
+	/**
87
+	 *    ajax save_payer_details
88
+	 *
89
+	 */
90
+	public static function save_payer_details()
91
+	{
92
+		EED_Single_Page_Checkout::process_ajax_request('save_payer_details_via_ajax');
93
+	}
94
+
95
+
96
+	/**
97
+	 *    ajax get_transaction_details
98
+	 *
99
+	 */
100
+	public static function get_transaction_details()
101
+	{
102
+		EED_Single_Page_Checkout::process_ajax_request('get_transaction_details_for_gateways');
103
+	}
104
+
105
+
106
+	/**
107
+	 * bypass_recaptcha_for_load_payment_method
108
+	 *
109
+	 * @access public
110
+	 * @return array
111
+	 * @throws InvalidArgumentException
112
+	 * @throws InvalidDataTypeException
113
+	 * @throws InvalidInterfaceException
114
+	 */
115
+	public static function bypass_recaptcha_for_load_payment_method()
116
+	{
117
+		return [
118
+			'EESID'  => EE_Registry::instance()->SSN->id(),
119
+			'step'   => 'payment_options',
120
+			'action' => 'spco_billing_form',
121
+		];
122
+	}
123
+
124
+
125
+	/**
126
+	 *    class constructor
127
+	 *
128
+	 * @access    public
129
+	 * @param EE_Checkout $checkout
130
+	 */
131
+	public function __construct(EE_Checkout $checkout)
132
+	{
133
+		$this->request   = EED_Single_Page_Checkout::getRequest();
134
+		$this->_slug     = 'payment_options';
135
+		$this->_name     = esc_html__('Payment Options', 'event_espresso');
136
+		$this->_template = SPCO_REG_STEPS_PATH . $this->_slug . '/payment_options_main.template.php';
137
+		$this->checkout  = $checkout;
138
+		$this->_reset_success_message();
139
+		$this->set_instructions(
140
+			esc_html__(
141
+				'Please select a method of payment and provide any necessary billing information before proceeding.',
142
+				'event_espresso'
143
+			)
144
+		);
145
+	}
146
+
147
+
148
+	/**
149
+	 * @return null
150
+	 */
151
+	public function line_item_display()
152
+	{
153
+		return $this->line_item_display;
154
+	}
155
+
156
+
157
+	/**
158
+	 * @param null $line_item_display
159
+	 */
160
+	public function set_line_item_display($line_item_display)
161
+	{
162
+		$this->line_item_display = $line_item_display;
163
+	}
164
+
165
+
166
+	/**
167
+	 * @return boolean
168
+	 */
169
+	public function handle_IPN_in_this_request()
170
+	{
171
+		return $this->handle_IPN_in_this_request;
172
+	}
173
+
174
+
175
+	/**
176
+	 * @param boolean $handle_IPN_in_this_request
177
+	 */
178
+	public function set_handle_IPN_in_this_request($handle_IPN_in_this_request)
179
+	{
180
+		$this->handle_IPN_in_this_request = filter_var($handle_IPN_in_this_request, FILTER_VALIDATE_BOOLEAN);
181
+	}
182
+
183
+
184
+	/**
185
+	 * translate_js_strings
186
+	 *
187
+	 * @return void
188
+	 */
189
+	public function translate_js_strings()
190
+	{
191
+		EE_Registry::$i18n_js_strings['no_payment_method']      = esc_html__(
192
+			'Please select a method of payment in order to continue.',
193
+			'event_espresso'
194
+		);
195
+		EE_Registry::$i18n_js_strings['invalid_payment_method'] = esc_html__(
196
+			'A valid method of payment could not be determined. Please refresh the page and try again.',
197
+			'event_espresso'
198
+		);
199
+		EE_Registry::$i18n_js_strings['forwarding_to_offsite']  = esc_html__(
200
+			'Forwarding to Secure Payment Provider.',
201
+			'event_espresso'
202
+		);
203
+	}
204
+
205
+
206
+	/**
207
+	 * enqueue_styles_and_scripts
208
+	 *
209
+	 * @return void
210
+	 * @throws EE_Error
211
+	 * @throws InvalidArgumentException
212
+	 * @throws InvalidDataTypeException
213
+	 * @throws InvalidInterfaceException
214
+	 * @throws ReflectionException
215
+	 */
216
+	public function enqueue_styles_and_scripts()
217
+	{
218
+		$transaction = $this->checkout->transaction;
219
+		// if the transaction isn't set or nothing is owed on it, don't enqueue any JS
220
+		if (! $transaction instanceof EE_Transaction || EEH_Money::compare_floats($transaction->remaining(), 0)) {
221
+			return;
222
+		}
223
+		foreach (
224
+			EEM_Payment_Method::instance()->get_all_for_transaction(
225
+				$transaction,
226
+				EEM_Payment_Method::scope_cart
227
+			) as $payment_method
228
+		) {
229
+			$type_obj = $payment_method->type_obj();
230
+			if ($type_obj instanceof EE_PMT_Base) {
231
+				$billing_form = $type_obj->generate_new_billing_form($transaction);
232
+				if ($billing_form instanceof EE_Form_Section_Proper) {
233
+					$billing_form->enqueue_js();
234
+				}
235
+			}
236
+		}
237
+	}
238
+
239
+
240
+	/**
241
+	 * initialize_reg_step
242
+	 *
243
+	 * @return bool
244
+	 * @throws EE_Error
245
+	 * @throws InvalidArgumentException
246
+	 * @throws ReflectionException
247
+	 * @throws InvalidDataTypeException
248
+	 * @throws InvalidInterfaceException
249
+	 */
250
+	public function initialize_reg_step()
251
+	{
252
+		// TODO: if /when we implement donations, then this will need overriding
253
+		if (
254
+			// don't need payment options for:
255
+			// registrations made via the admin
256
+			// completed transactions
257
+			// overpaid transactions
258
+			// $ 0.00 transactions(no payment required)
259
+			! $this->checkout->payment_required()
260
+			// but do NOT remove if current action being called belongs to this reg step
261
+			&& ! is_callable([$this, $this->checkout->action])
262
+			&& ! $this->completed()
263
+		) {
264
+			// and if so, then we no longer need the Payment Options step
265
+			if ($this->is_current_step()) {
266
+				$this->checkout->generate_reg_form = false;
267
+			}
268
+			$this->checkout->remove_reg_step($this->_slug);
269
+			// DEBUG LOG
270
+			// $this->checkout->log( __CLASS__, __FUNCTION__, __LINE__ );
271
+			return false;
272
+		}
273
+		// load EEM_Payment_Method
274
+		EE_Registry::instance()->load_model('Payment_Method');
275
+		// get all active payment methods
276
+		$this->checkout->available_payment_methods = EEM_Payment_Method::instance()->get_all_for_transaction(
277
+			$this->checkout->transaction,
278
+			EEM_Payment_Method::scope_cart
279
+		);
280
+		return true;
281
+	}
282
+
283
+
284
+	/**
285
+	 * @return EE_Form_Section_Proper
286
+	 * @throws EE_Error
287
+	 * @throws InvalidArgumentException
288
+	 * @throws ReflectionException
289
+	 * @throws EntityNotFoundException
290
+	 * @throws InvalidDataTypeException
291
+	 * @throws InvalidInterfaceException
292
+	 * @throws InvalidStatusException
293
+	 */
294
+	public function generate_reg_form()
295
+	{
296
+		// reset in case someone changes their mind
297
+		$this->_reset_selected_method_of_payment();
298
+		// set some defaults
299
+		$this->checkout->selected_method_of_payment = 'payments_closed';
300
+		$registrations_requiring_payment            = [];
301
+		$registrations_for_free_events              = [];
302
+		$registrations_requiring_pre_approval       = [];
303
+		$sold_out_events                            = [];
304
+		$insufficient_spaces_available              = [];
305
+		$no_payment_required                        = true;
306
+		// loop thru registrations to gather info
307
+		$registrations         = $this->checkout->transaction->registrations($this->checkout->reg_cache_where_params);
308
+		$ejected_registrations = EE_SPCO_Reg_Step_Payment_Options::find_registrations_that_lost_their_space(
309
+			$registrations,
310
+			$this->checkout->revisit
311
+		);
312
+		foreach ($registrations as $REG_ID => $registration) {
313
+			/** @var $registration EE_Registration */
314
+			// has this registration lost it's space ?
315
+			if (isset($ejected_registrations[ $REG_ID ])) {
316
+				if ($registration->event()->is_sold_out() || $registration->event()->is_sold_out(true)) {
317
+					$sold_out_events[ $registration->event()->ID() ] = $registration->event();
318
+				} else {
319
+					$insufficient_spaces_available[ $registration->event()->ID() ] = $registration->event();
320
+				}
321
+				continue;
322
+			}
323
+			// event requires admin approval
324
+			if ($registration->status_ID() === EEM_Registration::status_id_not_approved) {
325
+				// add event to list of events with pre-approval reg status
326
+				$registrations_requiring_pre_approval[ $REG_ID ] = $registration;
327
+				do_action(
328
+					'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__event_requires_pre_approval',
329
+					$registration->event(),
330
+					$this
331
+				);
332
+				continue;
333
+			}
334
+			if (
335
+				$this->checkout->revisit
336
+				&& $registration->status_ID() !== EEM_Registration::status_id_approved
337
+				&& (
338
+					$registration->event()->is_sold_out()
339
+					|| $registration->event()->is_sold_out(true)
340
+				)
341
+			) {
342
+				// add event to list of events that are sold out
343
+				$sold_out_events[ $registration->event()->ID() ] = $registration->event();
344
+				do_action(
345
+					'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__sold_out_event',
346
+					$registration->event(),
347
+					$this
348
+				);
349
+				continue;
350
+			}
351
+			// are they allowed to pay now and is there monies owing?
352
+			if ($registration->owes_monies_and_can_pay()) {
353
+				$registrations_requiring_payment[ $REG_ID ] = $registration;
354
+				do_action(
355
+					'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__event_requires_payment',
356
+					$registration->event(),
357
+					$this
358
+				);
359
+			} elseif (
360
+				! $this->checkout->revisit
361
+					  && $registration->status_ID() !== EEM_Registration::status_id_not_approved
362
+					  && $registration->ticket()->is_free()
363
+			) {
364
+				$registrations_for_free_events[ $registration->ticket()->ID() ] = $registration;
365
+			}
366
+		}
367
+		$subsections = [];
368
+		// now decide which template to load
369
+		if (! empty($sold_out_events)) {
370
+			$subsections['sold_out_events'] = $this->_sold_out_events($sold_out_events);
371
+		}
372
+		if (! empty($insufficient_spaces_available)) {
373
+			$subsections['insufficient_space'] = $this->_insufficient_spaces_available(
374
+				$insufficient_spaces_available
375
+			);
376
+		}
377
+		if (! empty($registrations_requiring_pre_approval)) {
378
+			$subsections['registrations_requiring_pre_approval'] = $this->_registrations_requiring_pre_approval(
379
+				$registrations_requiring_pre_approval
380
+			);
381
+		}
382
+		if (! empty($registrations_for_free_events)) {
383
+			$subsections['no_payment_required'] = $this->_no_payment_required($registrations_for_free_events);
384
+		}
385
+		if (! empty($registrations_requiring_payment)) {
386
+			if ($this->checkout->amount_owing > 0) {
387
+				// autoload Line_Item_Display classes
388
+				EEH_Autoloader::register_line_item_filter_autoloaders();
389
+				$line_item_filter_processor = new EE_Line_Item_Filter_Processor(
390
+					apply_filters(
391
+						'FHEE__SPCO__EE_Line_Item_Filter_Collection',
392
+						new EE_Line_Item_Filter_Collection()
393
+					),
394
+					$this->checkout->cart->get_grand_total()
395
+				);
396
+				/** @var EE_Line_Item $filtered_line_item_tree */
397
+				$filtered_line_item_tree = $line_item_filter_processor->process();
398
+				EEH_Autoloader::register_line_item_display_autoloaders();
399
+				$this->set_line_item_display(new EE_Line_Item_Display('spco'));
400
+				$subsections['payment_options'] = $this->_display_payment_options(
401
+					$this->line_item_display->display_line_item(
402
+						$filtered_line_item_tree,
403
+						['registrations' => $registrations]
404
+					)
405
+				);
406
+				$this->checkout->amount_owing   = $filtered_line_item_tree->total();
407
+				$this->_apply_registration_payments_to_amount_owing($registrations);
408
+			}
409
+			$no_payment_required = false;
410
+		} else {
411
+			$this->_hide_reg_step_submit_button_if_revisit();
412
+		}
413
+		$this->_save_selected_method_of_payment();
414
+
415
+		$subsections['default_hidden_inputs'] = $this->reg_step_hidden_inputs();
416
+		$subsections['extra_hidden_inputs']   = $this->_extra_hidden_inputs($no_payment_required);
417
+
418
+		return new EE_Form_Section_Proper(
419
+			[
420
+				'name'            => $this->reg_form_name(),
421
+				'html_id'         => $this->reg_form_name(),
422
+				'subsections'     => $subsections,
423
+				'layout_strategy' => new EE_No_Layout(),
424
+			]
425
+		);
426
+	}
427
+
428
+
429
+	/**
430
+	 * add line item filters required for this reg step
431
+	 * these filters are applied via this line in EE_SPCO_Reg_Step_Payment_Options::set_hooks():
432
+	 *        add_filter( 'FHEE__SPCO__EE_Line_Item_Filter_Collection', array( 'EE_SPCO_Reg_Step_Payment_Options',
433
+	 *        'add_spco_line_item_filters' ) ); so any code that wants to use the same set of filters during the
434
+	 *        payment options reg step, can apply these filters via the following: apply_filters(
435
+	 *        'FHEE__SPCO__EE_Line_Item_Filter_Collection', new EE_Line_Item_Filter_Collection() ) or to an existing
436
+	 *        filter collection by passing that instead of instantiating a new collection
437
+	 *
438
+	 * @param EE_Line_Item_Filter_Collection $line_item_filter_collection
439
+	 * @return EE_Line_Item_Filter_Collection
440
+	 * @throws EE_Error
441
+	 * @throws InvalidArgumentException
442
+	 * @throws ReflectionException
443
+	 * @throws EntityNotFoundException
444
+	 * @throws InvalidDataTypeException
445
+	 * @throws InvalidInterfaceException
446
+	 * @throws InvalidStatusException
447
+	 */
448
+	public static function add_spco_line_item_filters(EE_Line_Item_Filter_Collection $line_item_filter_collection)
449
+	{
450
+		if (! EE_Registry::instance()->SSN instanceof EE_Session) {
451
+			return $line_item_filter_collection;
452
+		}
453
+		if (! EE_Registry::instance()->SSN->checkout() instanceof EE_Checkout) {
454
+			return $line_item_filter_collection;
455
+		}
456
+		if (! EE_Registry::instance()->SSN->checkout()->transaction instanceof EE_Transaction) {
457
+			return $line_item_filter_collection;
458
+		}
459
+		$line_item_filter_collection->add(
460
+			new EE_Billable_Line_Item_Filter(
461
+				EE_SPCO_Reg_Step_Payment_Options::remove_ejected_registrations(
462
+					EE_Registry::instance()->SSN->checkout()->transaction->registrations(
463
+						EE_Registry::instance()->SSN->checkout()->reg_cache_where_params
464
+					)
465
+				)
466
+			)
467
+		);
468
+		$line_item_filter_collection->add(new EE_Non_Zero_Line_Item_Filter());
469
+		return $line_item_filter_collection;
470
+	}
471
+
472
+
473
+	/**
474
+	 * remove_ejected_registrations
475
+	 * if a registrant has lost their potential space at an event due to lack of payment,
476
+	 * then this method removes them from the list of registrations being paid for during this request
477
+	 *
478
+	 * @param EE_Registration[] $registrations
479
+	 * @return EE_Registration[]
480
+	 * @throws EE_Error
481
+	 * @throws InvalidArgumentException
482
+	 * @throws ReflectionException
483
+	 * @throws EntityNotFoundException
484
+	 * @throws InvalidDataTypeException
485
+	 * @throws InvalidInterfaceException
486
+	 * @throws InvalidStatusException
487
+	 */
488
+	public static function remove_ejected_registrations(array $registrations)
489
+	{
490
+		$ejected_registrations = EE_SPCO_Reg_Step_Payment_Options::find_registrations_that_lost_their_space(
491
+			$registrations,
492
+			EE_Registry::instance()->SSN->checkout()->revisit
493
+		);
494
+		foreach ($registrations as $REG_ID => $registration) {
495
+			// has this registration lost it's space ?
496
+			if (isset($ejected_registrations[ $REG_ID ])) {
497
+				unset($registrations[ $REG_ID ]);
498
+			}
499
+		}
500
+		return $registrations;
501
+	}
502
+
503
+
504
+	/**
505
+	 * find_registrations_that_lost_their_space
506
+	 * If a registrant chooses an offline payment method like Invoice,
507
+	 * then no space is reserved for them at the event until they fully pay fo that site
508
+	 * (unless the event's default reg status is set to APPROVED)
509
+	 * if a registrant then later returns to pay, but the number of spaces available has been reduced due to sales,
510
+	 * then this method will determine which registrations have lost the ability to complete the reg process.
511
+	 *
512
+	 * @param EE_Registration[] $registrations
513
+	 * @param bool              $revisit
514
+	 * @return array
515
+	 * @throws EE_Error
516
+	 * @throws InvalidArgumentException
517
+	 * @throws ReflectionException
518
+	 * @throws EntityNotFoundException
519
+	 * @throws InvalidDataTypeException
520
+	 * @throws InvalidInterfaceException
521
+	 * @throws InvalidStatusException
522
+	 */
523
+	public static function find_registrations_that_lost_their_space(array $registrations, $revisit = false)
524
+	{
525
+		// registrations per event
526
+		$event_reg_count = [];
527
+		// spaces left per event
528
+		$event_spaces_remaining = [];
529
+		// tickets left sorted by ID
530
+		$tickets_remaining = [];
531
+		// registrations that have lost their space
532
+		$ejected_registrations = [];
533
+		foreach ($registrations as $REG_ID => $registration) {
534
+			if (
535
+				$registration->status_ID() === EEM_Registration::status_id_approved
536
+				|| apply_filters(
537
+					'FHEE__EE_SPCO_Reg_Step_Payment_Options__find_registrations_that_lost_their_space__allow_reg_payment',
538
+					false,
539
+					$registration,
540
+					$revisit
541
+				)
542
+			) {
543
+				continue;
544
+			}
545
+			$EVT_ID = $registration->event_ID();
546
+			$ticket = $registration->ticket();
547
+			if (! isset($tickets_remaining[ $ticket->ID() ])) {
548
+				$tickets_remaining[ $ticket->ID() ] = $ticket->remaining();
549
+			}
550
+			if ($tickets_remaining[ $ticket->ID() ] > 0) {
551
+				if (! isset($event_reg_count[ $EVT_ID ])) {
552
+					$event_reg_count[ $EVT_ID ] = 0;
553
+				}
554
+				$event_reg_count[ $EVT_ID ]++;
555
+				if (! isset($event_spaces_remaining[ $EVT_ID ])) {
556
+					$event_spaces_remaining[ $EVT_ID ] = $registration->event()->spaces_remaining_for_sale();
557
+				}
558
+			}
559
+			if (
560
+				$revisit
561
+				&& ($tickets_remaining[ $ticket->ID() ] === 0
562
+					|| $event_reg_count[ $EVT_ID ] > $event_spaces_remaining[ $EVT_ID ]
563
+				)
564
+			) {
565
+				$ejected_registrations[ $REG_ID ] = $registration->event();
566
+				if ($registration->status_ID() !== EEM_Registration::status_id_wait_list) {
567
+					/** @type EE_Registration_Processor $registration_processor */
568
+					$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
569
+					// at this point, we should have enough details about the registrant to consider the registration
570
+					// NOT incomplete
571
+					$registration_processor->manually_update_registration_status(
572
+						$registration,
573
+						EEM_Registration::status_id_wait_list
574
+					);
575
+				}
576
+			}
577
+		}
578
+		return $ejected_registrations;
579
+	}
580
+
581
+
582
+	/**
583
+	 * _hide_reg_step_submit_button
584
+	 * removes the html for the reg step submit button
585
+	 * by replacing it with an empty string via filter callback
586
+	 *
587
+	 * @return void
588
+	 */
589
+	protected function _adjust_registration_status_if_event_old_sold()
590
+	{
591
+	}
592
+
593
+
594
+	/**
595
+	 * _hide_reg_step_submit_button
596
+	 * removes the html for the reg step submit button
597
+	 * by replacing it with an empty string via filter callback
598
+	 *
599
+	 * @return void
600
+	 */
601
+	protected function _hide_reg_step_submit_button_if_revisit()
602
+	{
603
+		if ($this->checkout->revisit) {
604
+			add_filter('FHEE__EE_SPCO_Reg_Step__reg_step_submit_button__sbmt_btn_html', '__return_empty_string');
605
+		}
606
+	}
607
+
608
+
609
+	/**
610
+	 * sold_out_events
611
+	 * displays notices regarding events that have sold out since hte registrant first signed up
612
+	 *
613
+	 * @param EE_Event[] $sold_out_events_array
614
+	 * @return EE_Form_Section_Proper
615
+	 * @throws EE_Error
616
+	 */
617
+	private function _sold_out_events($sold_out_events_array = [])
618
+	{
619
+		// set some defaults
620
+		$this->checkout->selected_method_of_payment = 'events_sold_out';
621
+		$sold_out_events                            = '';
622
+		foreach ($sold_out_events_array as $sold_out_event) {
623
+			$sold_out_events .= EEH_HTML::li(
624
+				EEH_HTML::span(
625
+					'  ' . $sold_out_event->name(),
626
+					'',
627
+					'dashicons dashicons-marker ee-icon-size-16 pink-text'
628
+				)
629
+			);
630
+		}
631
+		return new EE_Form_Section_Proper(
632
+			[
633
+				'layout_strategy' => new EE_Template_Layout(
634
+					[
635
+						'layout_template_file' => SPCO_REG_STEPS_PATH
636
+												  . $this->_slug
637
+												  . '/sold_out_events.template.php',
638
+						'template_args'        => apply_filters(
639
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___sold_out_events__template_args',
640
+							[
641
+								'sold_out_events'     => $sold_out_events,
642
+								'sold_out_events_msg' => apply_filters(
643
+									'FHEE__EE_SPCO_Reg_Step_Payment_Options___sold_out_events__sold_out_events_msg',
644
+									sprintf(
645
+										esc_html__(
646
+											'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',
647
+											'event_espresso'
648
+										),
649
+										'<strong>',
650
+										'</strong>',
651
+										'<br />'
652
+									)
653
+								),
654
+							]
655
+						),
656
+					]
657
+				),
658
+			]
659
+		);
660
+	}
661
+
662
+
663
+	/**
664
+	 * _insufficient_spaces_available
665
+	 * displays notices regarding events that do not have enough remaining spaces
666
+	 * to satisfy the current number of registrations looking to pay
667
+	 *
668
+	 * @param EE_Event[] $insufficient_spaces_events_array
669
+	 * @return EE_Form_Section_Proper
670
+	 * @throws EE_Error
671
+	 * @throws ReflectionException
672
+	 */
673
+	private function _insufficient_spaces_available($insufficient_spaces_events_array = [])
674
+	{
675
+		// set some defaults
676
+		$this->checkout->selected_method_of_payment = 'invoice';
677
+		$insufficient_space_events                  = '';
678
+		foreach ($insufficient_spaces_events_array as $event) {
679
+			if ($event instanceof EE_Event) {
680
+				$insufficient_space_events .= EEH_HTML::li(
681
+					EEH_HTML::span(' ' . $event->name(), '', 'dashicons dashicons-marker ee-icon-size-16 pink-text')
682
+				);
683
+			}
684
+		}
685
+		return new EE_Form_Section_Proper(
686
+			[
687
+				'subsections'     => [
688
+					'default_hidden_inputs' => $this->reg_step_hidden_inputs(),
689
+					'extra_hidden_inputs'   => $this->_extra_hidden_inputs(),
690
+				],
691
+				'layout_strategy' => new EE_Template_Layout(
692
+					[
693
+						'layout_template_file' => SPCO_REG_STEPS_PATH
694
+												  . $this->_slug
695
+												  . '/sold_out_events.template.php',
696
+						'template_args'        => apply_filters(
697
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___insufficient_spaces_available__template_args',
698
+							[
699
+								'sold_out_events'     => $insufficient_space_events,
700
+								'sold_out_events_msg' => apply_filters(
701
+									'FHEE__EE_SPCO_Reg_Step_Payment_Options___insufficient_spaces_available__insufficient_space_msg',
702
+									esc_html__(
703
+										'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.',
704
+										'event_espresso'
705
+									)
706
+								),
707
+							]
708
+						),
709
+					]
710
+				),
711
+			]
712
+		);
713
+	}
714
+
715
+
716
+	/**
717
+	 * registrations_requiring_pre_approval
718
+	 *
719
+	 * @param array $registrations_requiring_pre_approval
720
+	 * @return EE_Form_Section_Proper
721
+	 * @throws EE_Error
722
+	 * @throws EntityNotFoundException
723
+	 * @throws ReflectionException
724
+	 */
725
+	private function _registrations_requiring_pre_approval($registrations_requiring_pre_approval = [])
726
+	{
727
+		$events_requiring_pre_approval = [];
728
+		foreach ($registrations_requiring_pre_approval as $registration) {
729
+			if ($registration instanceof EE_Registration && $registration->event() instanceof EE_Event) {
730
+				$events_requiring_pre_approval[ $registration->event()->ID() ] = EEH_HTML::li(
731
+					EEH_HTML::span(
732
+						'',
733
+						'',
734
+						'dashicons dashicons-marker ee-icon-size-16 orange-text'
735
+					)
736
+					. EEH_HTML::span($registration->event()->name(), '', 'orange-text')
737
+				);
738
+			}
739
+		}
740
+		return new EE_Form_Section_Proper(
741
+			[
742
+				'layout_strategy' => new EE_Template_Layout(
743
+					[
744
+						'layout_template_file' => SPCO_REG_STEPS_PATH
745
+												  . $this->_slug
746
+												  . '/events_requiring_pre_approval.template.php', // layout_template
747
+						'template_args'        => apply_filters(
748
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___sold_out_events__template_args',
749
+							[
750
+								'events_requiring_pre_approval'     => implode('', $events_requiring_pre_approval),
751
+								'events_requiring_pre_approval_msg' => apply_filters(
752
+									'FHEE__EE_SPCO_Reg_Step_Payment_Options___events_requiring_pre_approval__events_requiring_pre_approval_msg',
753
+									esc_html__(
754
+										'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.',
755
+										'event_espresso'
756
+									)
757
+								),
758
+							]
759
+						),
760
+					]
761
+				),
762
+			]
763
+		);
764
+	}
765
+
766
+
767
+	/**
768
+	 * _no_payment_required
769
+	 *
770
+	 * @param EE_Event[] $registrations_for_free_events
771
+	 * @return EE_Form_Section_Proper
772
+	 * @throws EE_Error
773
+	 */
774
+	private function _no_payment_required($registrations_for_free_events = [])
775
+	{
776
+		// set some defaults
777
+		$this->checkout->selected_method_of_payment = 'no_payment_required';
778
+		// generate no_payment_required form
779
+		return new EE_Form_Section_Proper(
780
+			[
781
+				'layout_strategy' => new EE_Template_Layout(
782
+					[
783
+						'layout_template_file' => SPCO_REG_STEPS_PATH
784
+												  . $this->_slug
785
+												  . '/no_payment_required.template.php', // layout_template
786
+						'template_args'        => apply_filters(
787
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___no_payment_required__template_args',
788
+							[
789
+								'revisit'                       => $this->checkout->revisit,
790
+								'registrations'                 => [],
791
+								'ticket_count'                  => [],
792
+								'registrations_for_free_events' => $registrations_for_free_events,
793
+								'no_payment_required_msg'       => EEH_HTML::p(
794
+									esc_html__('This is a free event, so no billing will occur.', 'event_espresso')
795
+								),
796
+							]
797
+						),
798
+					]
799
+				),
800
+			]
801
+		);
802
+	}
803
+
804
+
805
+	/**
806
+	 * _display_payment_options
807
+	 *
808
+	 * @param string $transaction_details
809
+	 * @return EE_Form_Section_Proper
810
+	 * @throws EE_Error
811
+	 * @throws InvalidArgumentException
812
+	 * @throws InvalidDataTypeException
813
+	 * @throws InvalidInterfaceException
814
+	 */
815
+	private function _display_payment_options($transaction_details = '')
816
+	{
817
+		// has method_of_payment been set by no-js user?
818
+		$this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment();
819
+		// build payment options form
820
+		return apply_filters(
821
+			'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__payment_options_form',
822
+			new EE_Form_Section_Proper(
823
+				[
824
+					'subsections'     => [
825
+						'before_payment_options' => apply_filters(
826
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__before_payment_options',
827
+							new EE_Form_Section_Proper(
828
+								['layout_strategy' => new EE_Div_Per_Section_Layout()]
829
+							)
830
+						),
831
+						'payment_options'        => $this->_setup_payment_options(),
832
+						'after_payment_options'  => apply_filters(
833
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__after_payment_options',
834
+							new EE_Form_Section_Proper(
835
+								['layout_strategy' => new EE_Div_Per_Section_Layout()]
836
+							)
837
+						),
838
+					],
839
+					'layout_strategy' => new EE_Template_Layout(
840
+						[
841
+							'layout_template_file' => $this->_template,
842
+							'template_args'        => apply_filters(
843
+								'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__template_args',
844
+								[
845
+									'reg_count'                 => $this->line_item_display->total_items(),
846
+									'transaction_details'       => $transaction_details,
847
+									'available_payment_methods' => [],
848
+								]
849
+							),
850
+						]
851
+					),
852
+				]
853
+			)
854
+		);
855
+	}
856
+
857
+
858
+	/**
859
+	 * _extra_hidden_inputs
860
+	 *
861
+	 * @param bool $no_payment_required
862
+	 * @return EE_Form_Section_Proper
863
+	 * @throws EE_Error
864
+	 * @throws ReflectionException
865
+	 */
866
+	private function _extra_hidden_inputs($no_payment_required = true)
867
+	{
868
+		return new EE_Form_Section_Proper(
869
+			[
870
+				'html_id'         => 'ee-' . $this->slug() . '-extra-hidden-inputs',
871
+				'layout_strategy' => new EE_Div_Per_Section_Layout(),
872
+				'subsections'     => [
873
+					'spco_no_payment_required' => new EE_Hidden_Input(
874
+						[
875
+							'normalization_strategy' => new EE_Boolean_Normalization(),
876
+							'html_name'              => 'spco_no_payment_required',
877
+							'html_id'                => 'spco-no-payment-required-payment_options',
878
+							'default'                => $no_payment_required,
879
+						]
880
+					),
881
+					'spco_transaction_id'      => new EE_Fixed_Hidden_Input(
882
+						[
883
+							'normalization_strategy' => new EE_Int_Normalization(),
884
+							'html_name'              => 'spco_transaction_id',
885
+							'html_id'                => 'spco-transaction-id',
886
+							'default'                => $this->checkout->transaction->ID(),
887
+						]
888
+					),
889
+				],
890
+			]
891
+		);
892
+	}
893
+
894
+
895
+	/**
896
+	 *    _apply_registration_payments_to_amount_owing
897
+	 *
898
+	 * @param array $registrations
899
+	 * @throws EE_Error
900
+	 */
901
+	protected function _apply_registration_payments_to_amount_owing(array $registrations)
902
+	{
903
+		$payments = [];
904
+		foreach ($registrations as $registration) {
905
+			if ($registration instanceof EE_Registration && $registration->owes_monies_and_can_pay()) {
906
+				$payments += $registration->registration_payments();
907
+			}
908
+		}
909
+		if (! empty($payments)) {
910
+			foreach ($payments as $payment) {
911
+				if ($payment instanceof EE_Registration_Payment) {
912
+					$this->checkout->amount_owing -= $payment->amount();
913
+				}
914
+			}
915
+		}
916
+	}
917
+
918
+
919
+	/**
920
+	 *    _reset_selected_method_of_payment
921
+	 *
922
+	 * @access    private
923
+	 * @param bool $force_reset
924
+	 * @return void
925
+	 * @throws InvalidArgumentException
926
+	 * @throws InvalidDataTypeException
927
+	 * @throws InvalidInterfaceException
928
+	 */
929
+	private function _reset_selected_method_of_payment($force_reset = false)
930
+	{
931
+		/** @var RequestInterface $request */
932
+		$request              = LoaderFactory::getLoader()->getShared(RequestInterface::class);
933
+		$reset_payment_method = $request->getRequestParam('reset_payment_method', $force_reset, 'bool');
934
+		if ($reset_payment_method) {
935
+			$this->checkout->selected_method_of_payment = null;
936
+			$this->checkout->payment_method             = null;
937
+			$this->checkout->billing_form               = null;
938
+			$this->_save_selected_method_of_payment();
939
+		}
940
+	}
941
+
942
+
943
+	/**
944
+	 * _save_selected_method_of_payment
945
+	 * stores the selected_method_of_payment in the session
946
+	 * so that it's available for all subsequent requests including AJAX
947
+	 *
948
+	 * @access        private
949
+	 * @param string $selected_method_of_payment
950
+	 * @return void
951
+	 * @throws InvalidArgumentException
952
+	 * @throws InvalidDataTypeException
953
+	 * @throws InvalidInterfaceException
954
+	 */
955
+	private function _save_selected_method_of_payment($selected_method_of_payment = '')
956
+	{
957
+		$selected_method_of_payment = ! empty($selected_method_of_payment)
958
+			? $selected_method_of_payment
959
+			: $this->checkout->selected_method_of_payment;
960
+		EE_Registry::instance()->SSN->set_session_data(
961
+			['selected_method_of_payment' => $selected_method_of_payment]
962
+		);
963
+	}
964
+
965
+
966
+	/**
967
+	 * _setup_payment_options
968
+	 *
969
+	 * @return EE_Form_Section_Proper
970
+	 * @throws EE_Error
971
+	 * @throws InvalidArgumentException
972
+	 * @throws InvalidDataTypeException
973
+	 * @throws InvalidInterfaceException
974
+	 */
975
+	public function _setup_payment_options()
976
+	{
977
+		// load payment method classes
978
+		$this->checkout->available_payment_methods = $this->_get_available_payment_methods();
979
+		if (empty($this->checkout->available_payment_methods)) {
980
+			EE_Error::add_error(
981
+				apply_filters(
982
+					'FHEE__EE_SPCO_Reg_Step_Payment_Options___setup_payment_options__error_message_no_payment_methods',
983
+					sprintf(
984
+						esc_html__(
985
+							'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.',
986
+							'event_espresso'
987
+						),
988
+						'<br>',
989
+						EE_Registry::instance()->CFG->organization->get_pretty('email')
990
+					)
991
+				),
992
+				__FILE__,
993
+				__FUNCTION__,
994
+				__LINE__
995
+			);
996
+		}
997
+		// switch up header depending on number of available payment methods
998
+		$payment_method_header     = count($this->checkout->available_payment_methods) > 1
999
+			? apply_filters(
1000
+				'FHEE__registration_page_payment_options__method_of_payment_hdr',
1001
+				esc_html__('Please Select Your Method of Payment', 'event_espresso')
1002
+			)
1003
+			: apply_filters(
1004
+				'FHEE__registration_page_payment_options__method_of_payment_hdr',
1005
+				esc_html__('Method of Payment', 'event_espresso')
1006
+			);
1007
+		$available_payment_methods = [
1008
+			// display the "Payment Method" header
1009
+			'payment_method_header' => new EE_Form_Section_HTML(
1010
+				apply_filters(
1011
+					'FHEE__EE_SPCO_Reg_Step_Payment_Options___setup_payment_options__payment_method_header',
1012
+					EEH_HTML::h4($payment_method_header, 'method-of-payment-hdr'),
1013
+					$payment_method_header
1014
+				)
1015
+			),
1016
+		];
1017
+		// the list of actual payment methods ( invoice, paypal, etc ) in a  ( slug => HTML )  format
1018
+		$available_payment_method_options = [];
1019
+		$default_payment_method_option    = [];
1020
+		// additional instructions to be displayed and hidden below payment methods (adding a clearing div to start)
1021
+		$payment_methods_billing_info = [
1022
+			new EE_Form_Section_HTML(
1023
+				EEH_HTML::div('<br />', '', '', 'clear:both;')
1024
+			),
1025
+		];
1026
+		// loop through payment methods
1027
+		foreach ($this->checkout->available_payment_methods as $payment_method) {
1028
+			if ($payment_method instanceof EE_Payment_Method) {
1029
+				$payment_method_button = EEH_HTML::img(
1030
+					$payment_method->button_url(),
1031
+					$payment_method->name(),
1032
+					'spco-payment-method-' . $payment_method->slug() . '-btn-img',
1033
+					'spco-payment-method-btn-img'
1034
+				);
1035
+				// check if any payment methods are set as default
1036
+				// if payment method is already selected OR nothing is selected and this payment method should be
1037
+				// open_by_default
1038
+				if (
1039
+					($this->checkout->selected_method_of_payment === $payment_method->slug())
1040
+					|| (! $this->checkout->selected_method_of_payment && $payment_method->open_by_default())
1041
+				) {
1042
+					$this->checkout->selected_method_of_payment = $payment_method->slug();
1043
+					$this->_save_selected_method_of_payment();
1044
+					$default_payment_method_option[ $payment_method->slug() ] = $payment_method_button;
1045
+				} else {
1046
+					$available_payment_method_options[ $payment_method->slug() ] = $payment_method_button;
1047
+				}
1048
+				$payment_methods_billing_info[ $payment_method->slug() . '-info' ] =
1049
+					$this->_payment_method_billing_info(
1050
+						$payment_method
1051
+					);
1052
+			}
1053
+		}
1054
+		// prepend available_payment_method_options with default_payment_method_option so that it appears first in list
1055
+		// of PMs
1056
+		$available_payment_method_options = $default_payment_method_option + $available_payment_method_options;
1057
+		// now generate the actual form  inputs
1058
+		$available_payment_methods['available_payment_methods'] = $this->_available_payment_method_inputs(
1059
+			$available_payment_method_options
1060
+		);
1061
+		$available_payment_methods                              += $payment_methods_billing_info;
1062
+		// build the available payment methods form
1063
+		return new EE_Form_Section_Proper(
1064
+			[
1065
+				'html_id'         => 'spco-available-methods-of-payment-dv',
1066
+				'subsections'     => $available_payment_methods,
1067
+				'layout_strategy' => new EE_Div_Per_Section_Layout(),
1068
+			]
1069
+		);
1070
+	}
1071
+
1072
+
1073
+	/**
1074
+	 * _get_available_payment_methods
1075
+	 *
1076
+	 * @return EE_Payment_Method[]
1077
+	 * @throws EE_Error
1078
+	 * @throws InvalidArgumentException
1079
+	 * @throws InvalidDataTypeException
1080
+	 * @throws InvalidInterfaceException
1081
+	 */
1082
+	protected function _get_available_payment_methods()
1083
+	{
1084
+		if (! empty($this->checkout->available_payment_methods)) {
1085
+			return $this->checkout->available_payment_methods;
1086
+		}
1087
+		$available_payment_methods = [];
1088
+		$EEM_Payment_Method        = EEM_Payment_Method::instance();
1089
+		// get all active payment methods
1090
+		$payment_methods = $EEM_Payment_Method->get_all_for_transaction(
1091
+			$this->checkout->transaction,
1092
+			EEM_Payment_Method::scope_cart
1093
+		);
1094
+		foreach ($payment_methods as $payment_method) {
1095
+			if ($payment_method instanceof EE_Payment_Method) {
1096
+				$available_payment_methods[ $payment_method->slug() ] = $payment_method;
1097
+			}
1098
+		}
1099
+		return $available_payment_methods;
1100
+	}
1101
+
1102
+
1103
+	/**
1104
+	 *    _available_payment_method_inputs
1105
+	 *
1106
+	 * @access    private
1107
+	 * @param array $available_payment_method_options
1108
+	 * @return    EE_Form_Section_Proper
1109
+	 * @throws EE_Error
1110
+	 * @throws EE_Error
1111
+	 */
1112
+	private function _available_payment_method_inputs($available_payment_method_options = [])
1113
+	{
1114
+		// generate inputs
1115
+		return new EE_Form_Section_Proper(
1116
+			[
1117
+				'html_id'         => 'ee-available-payment-method-inputs',
1118
+				'layout_strategy' => new EE_Div_Per_Section_Layout(),
1119
+				'subsections'     => [
1120
+					'' => new EE_Radio_Button_Input(
1121
+						$available_payment_method_options,
1122
+						[
1123
+							'html_name'          => 'selected_method_of_payment',
1124
+							'html_class'         => 'spco-payment-method',
1125
+							'default'            => $this->checkout->selected_method_of_payment,
1126
+							'label_size'         => 11,
1127
+							'enforce_label_size' => true,
1128
+						]
1129
+					),
1130
+				],
1131
+			]
1132
+		);
1133
+	}
1134
+
1135
+
1136
+	/**
1137
+	 *    _payment_method_billing_info
1138
+	 *
1139
+	 * @access    private
1140
+	 * @param EE_Payment_Method $payment_method
1141
+	 * @return EE_Form_Section_Proper
1142
+	 * @throws EE_Error
1143
+	 * @throws InvalidArgumentException
1144
+	 * @throws InvalidDataTypeException
1145
+	 * @throws InvalidInterfaceException
1146
+	 */
1147
+	private function _payment_method_billing_info(EE_Payment_Method $payment_method)
1148
+	{
1149
+		$currently_selected = $this->checkout->selected_method_of_payment === $payment_method->slug();
1150
+		// generate the billing form for payment method
1151
+		$billing_form                 = $currently_selected
1152
+			? $this->_get_billing_form_for_payment_method($payment_method)
1153
+			: new EE_Form_Section_HTML();
1154
+		$this->checkout->billing_form = $currently_selected
1155
+			? $billing_form
1156
+			: $this->checkout->billing_form;
1157
+		// it's all in the details
1158
+		$info_html = EEH_HTML::h3(
1159
+			esc_html__('Important information regarding your payment', 'event_espresso'),
1160
+			'',
1161
+			'spco-payment-method-hdr'
1162
+		);
1163
+		// add some info regarding the step, either from what's saved in the admin,
1164
+		// or a default string depending on whether the PM has a billing form or not
1165
+		if ($payment_method->description()) {
1166
+			$payment_method_info = $payment_method->description();
1167
+		} elseif ($billing_form instanceof EE_Billing_Info_Form) {
1168
+			$payment_method_info = sprintf(
1169
+				esc_html__(
1170
+					'Please provide the following billing information, then click the "%1$s" button below in order to proceed.',
1171
+					'event_espresso'
1172
+				),
1173
+				$this->submit_button_text()
1174
+			);
1175
+		} else {
1176
+			$payment_method_info = sprintf(
1177
+				esc_html__('Please click the "%1$s" button below in order to proceed.', 'event_espresso'),
1178
+				$this->submit_button_text()
1179
+			);
1180
+		}
1181
+		$info_html .= EEH_HTML::div(
1182
+			apply_filters(
1183
+				'FHEE__EE_SPCO_Reg_Step_Payment_Options___payment_method_billing_info__payment_method_info',
1184
+				$payment_method_info
1185
+			),
1186
+			'',
1187
+			'spco-payment-method-desc ee-attention'
1188
+		);
1189
+		return new EE_Form_Section_Proper(
1190
+			[
1191
+				'html_id'         => 'spco-payment-method-info-' . $payment_method->slug(),
1192
+				'html_class'      => 'spco-payment-method-info-dv',
1193
+				// only display the selected or default PM
1194
+				'html_style'      => $currently_selected ? '' : 'display:none;',
1195
+				'layout_strategy' => new EE_Div_Per_Section_Layout(),
1196
+				'subsections'     => [
1197
+					'info'         => new EE_Form_Section_HTML($info_html),
1198
+					'billing_form' => $currently_selected ? $billing_form : new EE_Form_Section_HTML(),
1199
+				],
1200
+			]
1201
+		);
1202
+	}
1203
+
1204
+
1205
+	/**
1206
+	 * get_billing_form_html_for_payment_method
1207
+	 *
1208
+	 * @return bool
1209
+	 * @throws EE_Error
1210
+	 * @throws InvalidArgumentException
1211
+	 * @throws ReflectionException
1212
+	 * @throws InvalidDataTypeException
1213
+	 * @throws InvalidInterfaceException
1214
+	 */
1215
+	public function get_billing_form_html_for_payment_method()
1216
+	{
1217
+		// how have they chosen to pay?
1218
+		$this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
1219
+		$this->checkout->payment_method             = $this->_get_payment_method_for_selected_method_of_payment();
1220
+		if (! $this->checkout->payment_method instanceof EE_Payment_Method) {
1221
+			return false;
1222
+		}
1223
+		if (
1224
+			apply_filters(
1225
+				'FHEE__EE_SPCO_Reg_Step_Payment_Options__registration_checkout__selected_payment_method__display_success',
1226
+				false
1227
+			)
1228
+		) {
1229
+			EE_Error::add_success(
1230
+				apply_filters(
1231
+					'FHEE__Single_Page_Checkout__registration_checkout__selected_payment_method',
1232
+					sprintf(
1233
+						esc_html__(
1234
+							'You have selected "%s" as your method of payment. Please note the important payment information below.',
1235
+							'event_espresso'
1236
+						),
1237
+						$this->checkout->payment_method->name()
1238
+					)
1239
+				)
1240
+			);
1241
+		}
1242
+		// now generate billing form for selected method of payment
1243
+		$payment_method_billing_form = $this->_get_billing_form_for_payment_method($this->checkout->payment_method);
1244
+		// fill form with attendee info if applicable
1245
+		if (
1246
+			$payment_method_billing_form instanceof EE_Billing_Attendee_Info_Form
1247
+			&& $this->checkout->transaction_has_primary_registrant()
1248
+		) {
1249
+			$payment_method_billing_form->populate_from_attendee(
1250
+				$this->checkout->transaction->primary_registration()->attendee()
1251
+			);
1252
+		}
1253
+		// and debug content
1254
+		if (
1255
+			$payment_method_billing_form instanceof EE_Billing_Info_Form
1256
+			&& $this->checkout->payment_method->type_obj() instanceof EE_PMT_Base
1257
+		) {
1258
+			$payment_method_billing_form =
1259
+				$this->checkout->payment_method->type_obj()->apply_billing_form_debug_settings(
1260
+					$payment_method_billing_form
1261
+				);
1262
+		}
1263
+		$billing_info = $payment_method_billing_form instanceof EE_Form_Section_Proper
1264
+			? $payment_method_billing_form->get_html()
1265
+			: '';
1266
+		$this->checkout->json_response->set_return_data(['payment_method_info' => $billing_info]);
1267
+		// localize validation rules for main form
1268
+		$this->checkout->current_step->reg_form->localize_validation_rules();
1269
+		$this->checkout->json_response->add_validation_rules(EE_Form_Section_Proper::js_localization());
1270
+		return true;
1271
+	}
1272
+
1273
+
1274
+	/**
1275
+	 * _get_billing_form_for_payment_method
1276
+	 *
1277
+	 * @param EE_Payment_Method $payment_method
1278
+	 * @return EE_Billing_Info_Form|EE_Form_Section_HTML
1279
+	 * @throws EE_Error
1280
+	 * @throws InvalidArgumentException
1281
+	 * @throws InvalidDataTypeException
1282
+	 * @throws InvalidInterfaceException
1283
+	 */
1284
+	private function _get_billing_form_for_payment_method(EE_Payment_Method $payment_method)
1285
+	{
1286
+		$billing_form = $payment_method->type_obj()->billing_form(
1287
+			$this->checkout->transaction,
1288
+			['amount_owing' => $this->checkout->amount_owing]
1289
+		);
1290
+		if ($billing_form instanceof EE_Billing_Info_Form) {
1291
+			if (
1292
+				apply_filters(
1293
+					'FHEE__EE_SPCO_Reg_Step_Payment_Options__registration_checkout__selected_payment_method__display_success',
1294
+					false
1295
+				)
1296
+				&& $this->request->requestParamIsSet('payment_method')
1297
+			) {
1298
+				EE_Error::add_success(
1299
+					apply_filters(
1300
+						'FHEE__Single_Page_Checkout__registration_checkout__selected_payment_method',
1301
+						sprintf(
1302
+							esc_html__(
1303
+								'You have selected "%s" as your method of payment. Please note the important payment information below.',
1304
+								'event_espresso'
1305
+							),
1306
+							$payment_method->name()
1307
+						)
1308
+					)
1309
+				);
1310
+			}
1311
+			return apply_filters(
1312
+				'FHEE__EE_SPCO_Reg_Step_Payment_Options___get_billing_form_for_payment_method__billing_form',
1313
+				$billing_form,
1314
+				$payment_method
1315
+			);
1316
+		}
1317
+		// no actual billing form, so return empty HTML form section
1318
+		return new EE_Form_Section_HTML();
1319
+	}
1320
+
1321
+
1322
+	/**
1323
+	 * _get_selected_method_of_payment
1324
+	 *
1325
+	 * @param boolean $required whether to throw an error if the "selected_method_of_payment"
1326
+	 *                          is not found in the incoming request
1327
+	 * @param string  $request_param
1328
+	 * @return NULL|string
1329
+	 * @throws EE_Error
1330
+	 * @throws InvalidArgumentException
1331
+	 * @throws InvalidDataTypeException
1332
+	 * @throws InvalidInterfaceException
1333
+	 */
1334
+	private function _get_selected_method_of_payment(
1335
+		$required = false,
1336
+		$request_param = 'selected_method_of_payment'
1337
+	) {
1338
+		// is selected_method_of_payment set in the request ?
1339
+		$selected_method_of_payment = $this->request->getRequestParam($request_param);
1340
+		if ($selected_method_of_payment) {
1341
+			// sanitize it
1342
+			$selected_method_of_payment = is_array($selected_method_of_payment)
1343
+				? array_shift($selected_method_of_payment)
1344
+				: $selected_method_of_payment;
1345
+			$selected_method_of_payment = sanitize_text_field($selected_method_of_payment);
1346
+			// store it in the session so that it's available for all subsequent requests including AJAX
1347
+			$this->_save_selected_method_of_payment($selected_method_of_payment);
1348
+		} else {
1349
+			// or is is set in the session ?
1350
+			$selected_method_of_payment = EE_Registry::instance()->SSN->get_session_data(
1351
+				'selected_method_of_payment'
1352
+			);
1353
+		}
1354
+		// do ya really really gotta have it?
1355
+		if (empty($selected_method_of_payment) && $required) {
1356
+			EE_Error::add_error(
1357
+				sprintf(
1358
+					esc_html__(
1359
+						'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.',
1360
+						'event_espresso'
1361
+					),
1362
+					'<br/>',
1363
+					'<br/>',
1364
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
1365
+				),
1366
+				__FILE__,
1367
+				__FUNCTION__,
1368
+				__LINE__
1369
+			);
1370
+			return null;
1371
+		}
1372
+		return $selected_method_of_payment;
1373
+	}
1374
+
1375
+
1376
+
1377
+
1378
+
1379
+
1380
+	/********************************************************************************************************/
1381
+	/***********************************  SWITCH PAYMENT METHOD  ************************************/
1382
+	/********************************************************************************************************/
1383
+	/**
1384
+	 * switch_payment_method
1385
+	 *
1386
+	 * @return bool
1387
+	 * @throws EE_Error
1388
+	 * @throws InvalidArgumentException
1389
+	 * @throws InvalidDataTypeException
1390
+	 * @throws InvalidInterfaceException
1391
+	 * @throws ReflectionException
1392
+	 */
1393
+	public function switch_payment_method()
1394
+	{
1395
+		if (! $this->_verify_payment_method_is_set()) {
1396
+			return false;
1397
+		}
1398
+		if (
1399
+			apply_filters(
1400
+				'FHEE__EE_SPCO_Reg_Step_Payment_Options__registration_checkout__selected_payment_method__display_success',
1401
+				false
1402
+			)
1403
+		) {
1404
+			EE_Error::add_success(
1405
+				apply_filters(
1406
+					'FHEE__Single_Page_Checkout__registration_checkout__selected_payment_method',
1407
+					sprintf(
1408
+						esc_html__(
1409
+							'You have selected "%s" as your method of payment. Please note the important payment information below.',
1410
+							'event_espresso'
1411
+						),
1412
+						$this->checkout->payment_method->name()
1413
+					)
1414
+				)
1415
+			);
1416
+		}
1417
+		// generate billing form for selected method of payment if it hasn't been done already
1418
+		if ($this->checkout->payment_method->type_obj()->has_billing_form()) {
1419
+			$this->checkout->billing_form = $this->_get_billing_form_for_payment_method(
1420
+				$this->checkout->payment_method
1421
+			);
1422
+		}
1423
+		// fill form with attendee info if applicable
1424
+		if (
1425
+			apply_filters(
1426
+				'FHEE__populate_billing_form_fields_from_attendee',
1427
+				(
1428
+				$this->checkout->billing_form instanceof EE_Billing_Attendee_Info_Form
1429
+				&& $this->checkout->transaction_has_primary_registrant()
1430
+				),
1431
+				$this->checkout->billing_form,
1432
+				$this->checkout->transaction
1433
+			)
1434
+		) {
1435
+			$this->checkout->billing_form->populate_from_attendee(
1436
+				$this->checkout->transaction->primary_registration()->attendee()
1437
+			);
1438
+		}
1439
+		// and debug content
1440
+		if (
1441
+			$this->checkout->billing_form instanceof EE_Billing_Info_Form
1442
+			&& $this->checkout->payment_method->type_obj() instanceof EE_PMT_Base
1443
+		) {
1444
+			$this->checkout->billing_form =
1445
+				$this->checkout->payment_method->type_obj()->apply_billing_form_debug_settings(
1446
+					$this->checkout->billing_form
1447
+				);
1448
+		}
1449
+		// get html and validation rules for form
1450
+		if ($this->checkout->billing_form instanceof EE_Form_Section_Proper) {
1451
+			$this->checkout->json_response->set_return_data(
1452
+				['payment_method_info' => $this->checkout->billing_form->get_html()]
1453
+			);
1454
+			// localize validation rules for main form
1455
+			$this->checkout->billing_form->localize_validation_rules(true);
1456
+			$this->checkout->json_response->add_validation_rules(EE_Form_Section_Proper::js_localization());
1457
+		} else {
1458
+			$this->checkout->json_response->set_return_data(['payment_method_info' => '']);
1459
+		}
1460
+		// prevents advancement to next step
1461
+		$this->checkout->continue_reg = false;
1462
+		return true;
1463
+	}
1464
+
1465
+
1466
+	/**
1467
+	 * _verify_payment_method_is_set
1468
+	 *
1469
+	 * @return bool
1470
+	 * @throws EE_Error
1471
+	 * @throws InvalidArgumentException
1472
+	 * @throws ReflectionException
1473
+	 * @throws InvalidDataTypeException
1474
+	 * @throws InvalidInterfaceException
1475
+	 */
1476
+	protected function _verify_payment_method_is_set()
1477
+	{
1478
+		// generate billing form for selected method of payment if it hasn't been done already
1479
+		if (empty($this->checkout->selected_method_of_payment)) {
1480
+			// how have they chosen to pay?
1481
+			$this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
1482
+		} else {
1483
+			// choose your own adventure based on method_of_payment
1484
+			switch ($this->checkout->selected_method_of_payment) {
1485
+				case 'events_sold_out':
1486
+					EE_Error::add_attention(
1487
+						apply_filters(
1488
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___verify_payment_method_is_set__sold_out_events_msg',
1489
+							esc_html__(
1490
+								'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.',
1491
+								'event_espresso'
1492
+							)
1493
+						),
1494
+						__FILE__,
1495
+						__FUNCTION__,
1496
+						__LINE__
1497
+					);
1498
+					return false;
1499
+				case 'payments_closed':
1500
+					EE_Error::add_attention(
1501
+						apply_filters(
1502
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___verify_payment_method_is_set__payments_closed_msg',
1503
+							esc_html__(
1504
+								'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.',
1505
+								'event_espresso'
1506
+							)
1507
+						),
1508
+						__FILE__,
1509
+						__FUNCTION__,
1510
+						__LINE__
1511
+					);
1512
+					return false;
1513
+				case 'no_payment_required':
1514
+					EE_Error::add_attention(
1515
+						apply_filters(
1516
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___verify_payment_method_is_set__no_payment_required_msg',
1517
+							esc_html__(
1518
+								'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.',
1519
+								'event_espresso'
1520
+							)
1521
+						),
1522
+						__FILE__,
1523
+						__FUNCTION__,
1524
+						__LINE__
1525
+					);
1526
+					return false;
1527
+				default:
1528
+			}
1529
+		}
1530
+		// verify payment method
1531
+		if (! $this->checkout->payment_method instanceof EE_Payment_Method) {
1532
+			// get payment method for selected method of payment
1533
+			$this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment();
1534
+		}
1535
+		return $this->checkout->payment_method instanceof EE_Payment_Method;
1536
+	}
1537
+
1538
+
1539
+
1540
+	/********************************************************************************************************/
1541
+	/***************************************  SAVE PAYER DETAILS  ****************************************/
1542
+	/********************************************************************************************************/
1543
+	/**
1544
+	 * save_payer_details_via_ajax
1545
+	 *
1546
+	 * @return void
1547
+	 * @throws EE_Error
1548
+	 * @throws InvalidArgumentException
1549
+	 * @throws ReflectionException
1550
+	 * @throws RuntimeException
1551
+	 * @throws InvalidDataTypeException
1552
+	 * @throws InvalidInterfaceException
1553
+	 */
1554
+	public function save_payer_details_via_ajax()
1555
+	{
1556
+		if (! $this->_verify_payment_method_is_set()) {
1557
+			return;
1558
+		}
1559
+		// generate billing form for selected method of payment if it hasn't been done already
1560
+		if ($this->checkout->payment_method->type_obj()->has_billing_form()) {
1561
+			$this->checkout->billing_form = $this->_get_billing_form_for_payment_method(
1562
+				$this->checkout->payment_method
1563
+			);
1564
+		}
1565
+		// generate primary attendee from payer info if applicable
1566
+		if (! $this->checkout->transaction_has_primary_registrant()) {
1567
+			$attendee = $this->_create_attendee_from_request_data();
1568
+			if ($attendee instanceof EE_Attendee) {
1569
+				foreach ($this->checkout->transaction->registrations() as $registration) {
1570
+					if ($registration->is_primary_registrant()) {
1571
+						$this->checkout->primary_attendee_obj = $attendee;
1572
+						$registration->_add_relation_to($attendee, 'Attendee');
1573
+						$registration->set_attendee_id($attendee->ID());
1574
+						$registration->update_cache_after_object_save('Attendee', $attendee);
1575
+					}
1576
+				}
1577
+			}
1578
+		}
1579
+	}
1580
+
1581
+
1582
+	/**
1583
+	 * create_attendee_from_request_data
1584
+	 * uses info from alternate GET or POST data (such as AJAX) to create a new attendee
1585
+	 *
1586
+	 * @return EE_Attendee
1587
+	 * @throws EE_Error
1588
+	 * @throws InvalidArgumentException
1589
+	 * @throws ReflectionException
1590
+	 * @throws InvalidDataTypeException
1591
+	 * @throws InvalidInterfaceException
1592
+	 */
1593
+	protected function _create_attendee_from_request_data()
1594
+	{
1595
+		// get State ID
1596
+		$STA_ID = $this->request->getRequestParam('state');
1597
+		if (! empty($STA_ID)) {
1598
+			// can we get state object from name ?
1599
+			EE_Registry::instance()->load_model('State');
1600
+			$state  = EEM_State::instance()->get_col([['STA_name' => $STA_ID], 'limit' => 1], 'STA_ID');
1601
+			$STA_ID = is_array($state) && ! empty($state) ? reset($state) : $STA_ID;
1602
+		}
1603
+		// get Country ISO
1604
+		$CNT_ISO = $this->request->getRequestParam('country');
1605
+		if (! empty($CNT_ISO)) {
1606
+			// can we get country object from name ?
1607
+			EE_Registry::instance()->load_model('Country');
1608
+			$country = EEM_Country::instance()->get_col(
1609
+				[['CNT_name' => $CNT_ISO], 'limit' => 1],
1610
+				'CNT_ISO'
1611
+			);
1612
+			$CNT_ISO = is_array($country) && ! empty($country) ? reset($country) : $CNT_ISO;
1613
+		}
1614
+		// grab attendee data
1615
+		$attendee_data = [
1616
+			'ATT_fname'    => $this->request->getRequestParam('first_name'),
1617
+			'ATT_lname'    => $this->request->getRequestParam('last_name'),
1618
+			'ATT_email'    => $this->request->getRequestParam('email'),
1619
+			'ATT_address'  => $this->request->getRequestParam('address'),
1620
+			'ATT_address2' => $this->request->getRequestParam('address2'),
1621
+			'ATT_city'     => $this->request->getRequestParam('city'),
1622
+			'STA_ID'       => $STA_ID,
1623
+			'CNT_ISO'      => $CNT_ISO,
1624
+			'ATT_zip'      => $this->request->getRequestParam('zip'),
1625
+			'ATT_phone'    => $this->request->getRequestParam('phone'),
1626
+		];
1627
+		// validate the email address since it is the most important piece of info
1628
+		if (empty($attendee_data['ATT_email'])) {
1629
+			EE_Error::add_error(
1630
+				esc_html__('An invalid email address was submitted.', 'event_espresso'),
1631
+				__FILE__,
1632
+				__FUNCTION__,
1633
+				__LINE__
1634
+			);
1635
+		}
1636
+		// does this attendee already exist in the db ? we're searching using a combination of first name, last name,
1637
+		// AND email address
1638
+		if (
1639
+			! empty($attendee_data['ATT_fname'])
1640
+			&& ! empty($attendee_data['ATT_lname'])
1641
+			&& ! empty($attendee_data['ATT_email'])
1642
+		) {
1643
+			$existing_attendee = EEM_Attendee::instance()->find_existing_attendee(
1644
+				[
1645
+					'ATT_fname' => $attendee_data['ATT_fname'],
1646
+					'ATT_lname' => $attendee_data['ATT_lname'],
1647
+					'ATT_email' => $attendee_data['ATT_email'],
1648
+				]
1649
+			);
1650
+			if ($existing_attendee instanceof EE_Attendee) {
1651
+				return $existing_attendee;
1652
+			}
1653
+		}
1654
+		// no existing attendee? kk let's create a new one
1655
+		// kinda lame, but we need a first and last name to create an attendee, so use the email address if those
1656
+		// don't exist
1657
+		$attendee_data['ATT_fname'] = ! empty($attendee_data['ATT_fname'])
1658
+			? $attendee_data['ATT_fname']
1659
+			: $attendee_data['ATT_email'];
1660
+		$attendee_data['ATT_lname'] = ! empty($attendee_data['ATT_lname'])
1661
+			? $attendee_data['ATT_lname']
1662
+			: $attendee_data['ATT_email'];
1663
+		return EE_Attendee::new_instance($attendee_data);
1664
+	}
1665
+
1666
+
1667
+
1668
+	/********************************************************************************************************/
1669
+	/****************************************  PROCESS REG STEP  *****************************************/
1670
+	/********************************************************************************************************/
1671
+	/**
1672
+	 * process_reg_step
1673
+	 *
1674
+	 * @return bool
1675
+	 * @throws EE_Error
1676
+	 * @throws InvalidArgumentException
1677
+	 * @throws ReflectionException
1678
+	 * @throws EntityNotFoundException
1679
+	 * @throws InvalidDataTypeException
1680
+	 * @throws InvalidInterfaceException
1681
+	 * @throws InvalidStatusException
1682
+	 */
1683
+	public function process_reg_step()
1684
+	{
1685
+		// how have they chosen to pay?
1686
+		$this->checkout->selected_method_of_payment = $this->checkout->transaction->is_free()
1687
+			? 'no_payment_required'
1688
+			: $this->_get_selected_method_of_payment(true);
1689
+		// choose your own adventure based on method_of_payment
1690
+		switch ($this->checkout->selected_method_of_payment) {
1691
+			case 'events_sold_out':
1692
+				$this->checkout->redirect     = true;
1693
+				$this->checkout->redirect_url = $this->checkout->cancel_page_url;
1694
+				$this->checkout->json_response->set_redirect_url($this->checkout->redirect_url);
1695
+				// mark this reg step as completed
1696
+				$this->set_completed();
1697
+				return false;
1698
+
1699
+			case 'payments_closed':
1700
+				if (
1701
+					apply_filters(
1702
+						'FHEE__EE_SPCO_Reg_Step_Payment_Options__process_reg_step__payments_closed__display_success',
1703
+						false
1704
+					)
1705
+				) {
1706
+					EE_Error::add_success(
1707
+						esc_html__('no payment required at this time.', 'event_espresso'),
1708
+						__FILE__,
1709
+						__FUNCTION__,
1710
+						__LINE__
1711
+					);
1712
+				}
1713
+				// mark this reg step as completed
1714
+				$this->set_completed();
1715
+				return true;
1716
+
1717
+			case 'no_payment_required':
1718
+				if (
1719
+					apply_filters(
1720
+						'FHEE__EE_SPCO_Reg_Step_Payment_Options__process_reg_step__no_payment_required__display_success',
1721
+						false
1722
+					)
1723
+				) {
1724
+					EE_Error::add_success(
1725
+						esc_html__('no payment required.', 'event_espresso'),
1726
+						__FILE__,
1727
+						__FUNCTION__,
1728
+						__LINE__
1729
+					);
1730
+				}
1731
+				// mark this reg step as completed
1732
+				$this->set_completed();
1733
+				return true;
1734
+
1735
+			default:
1736
+				$registrations         = EE_Registry::instance()->SSN->checkout()->transaction->registrations(
1737
+					EE_Registry::instance()->SSN->checkout()->reg_cache_where_params
1738
+				);
1739
+				$ejected_registrations = EE_SPCO_Reg_Step_Payment_Options::find_registrations_that_lost_their_space(
1740
+					$registrations,
1741
+					EE_Registry::instance()->SSN->checkout()->revisit
1742
+				);
1743
+				// calculate difference between the two arrays
1744
+				$registrations = array_diff($registrations, $ejected_registrations);
1745
+				if (empty($registrations)) {
1746
+					$this->_redirect_because_event_sold_out();
1747
+					return false;
1748
+				}
1749
+				$payment_successful = $this->_process_payment();
1750
+				if ($payment_successful) {
1751
+					$this->checkout->continue_reg = true;
1752
+					$this->_maybe_set_completed($this->checkout->payment_method);
1753
+				} else {
1754
+					$this->checkout->continue_reg = false;
1755
+				}
1756
+				return $payment_successful;
1757
+		}
1758
+	}
1759
+
1760
+
1761
+	/**
1762
+	 * _redirect_because_event_sold_out
1763
+	 *
1764
+	 * @return void
1765
+	 */
1766
+	protected function _redirect_because_event_sold_out()
1767
+	{
1768
+		$this->checkout->continue_reg = false;
1769
+		// set redirect URL
1770
+		$this->checkout->redirect_url = add_query_arg(
1771
+			['e_reg_url_link' => $this->checkout->reg_url_link],
1772
+			$this->checkout->current_step->reg_step_url()
1773
+		);
1774
+		$this->checkout->json_response->set_redirect_url($this->checkout->redirect_url);
1775
+	}
1776
+
1777
+
1778
+	/**
1779
+	 * _maybe_set_completed
1780
+	 *
1781
+	 * @param EE_Payment_Method $payment_method
1782
+	 * @return void
1783
+	 * @throws EE_Error
1784
+	 */
1785
+	protected function _maybe_set_completed(EE_Payment_Method $payment_method)
1786
+	{
1787
+		switch ($payment_method->type_obj()->payment_occurs()) {
1788
+			case EE_PMT_Base::offsite:
1789
+				break;
1790
+			case EE_PMT_Base::onsite:
1791
+			case EE_PMT_Base::offline:
1792
+				// mark this reg step as completed
1793
+				$this->set_completed();
1794
+				break;
1795
+		}
1796
+	}
1797
+
1798
+
1799
+	/**
1800
+	 *    update_reg_step
1801
+	 *    this is the final step after a user  revisits the site to retry a payment
1802
+	 *
1803
+	 * @return bool
1804
+	 * @throws EE_Error
1805
+	 * @throws InvalidArgumentException
1806
+	 * @throws ReflectionException
1807
+	 * @throws EntityNotFoundException
1808
+	 * @throws InvalidDataTypeException
1809
+	 * @throws InvalidInterfaceException
1810
+	 * @throws InvalidStatusException
1811
+	 */
1812
+	public function update_reg_step()
1813
+	{
1814
+		$success = true;
1815
+		// if payment required
1816
+		if ($this->checkout->transaction->total() > 0) {
1817
+			do_action(
1818
+				'AHEE__EE_Single_Page_Checkout__process_finalize_registration__before_gateway',
1819
+				$this->checkout->transaction
1820
+			);
1821
+			// attempt payment via payment method
1822
+			$success = $this->process_reg_step();
1823
+		}
1824
+		if ($success && ! $this->checkout->redirect) {
1825
+			$this->checkout->cart->get_grand_total()->save_this_and_descendants_to_txn(
1826
+				$this->checkout->transaction->ID()
1827
+			);
1828
+			// set return URL
1829
+			$this->checkout->redirect_url = add_query_arg(
1830
+				['e_reg_url_link' => $this->checkout->reg_url_link],
1831
+				$this->checkout->thank_you_page_url
1832
+			);
1833
+		}
1834
+		return $success;
1835
+	}
1836
+
1837
+
1838
+	/**
1839
+	 *    _process_payment
1840
+	 *
1841
+	 * @return bool
1842
+	 * @throws EE_Error
1843
+	 * @throws InvalidArgumentException
1844
+	 * @throws ReflectionException
1845
+	 * @throws RuntimeException
1846
+	 * @throws InvalidDataTypeException
1847
+	 * @throws InvalidInterfaceException
1848
+	 */
1849
+	private function _process_payment()
1850
+	{
1851
+		// basically confirm that the event hasn't sold out since they hit the page
1852
+		if (! $this->_last_second_ticket_verifications()) {
1853
+			return false;
1854
+		}
1855
+		// ya gotta make a choice man
1856
+		if (empty($this->checkout->selected_method_of_payment)) {
1857
+			$this->checkout->json_response->set_plz_select_method_of_payment(
1858
+				esc_html__('Please select a method of payment before proceeding.', 'event_espresso')
1859
+			);
1860
+			return false;
1861
+		}
1862
+		// get EE_Payment_Method object
1863
+		if (! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()) {
1864
+			return false;
1865
+		}
1866
+		// setup billing form
1867
+		if ($this->checkout->payment_method->is_on_site()) {
1868
+			$this->checkout->billing_form = $this->_get_billing_form_for_payment_method(
1869
+				$this->checkout->payment_method
1870
+			);
1871
+			// bad billing form ?
1872
+			if (! $this->_billing_form_is_valid()) {
1873
+				return false;
1874
+			}
1875
+		}
1876
+		// ensure primary registrant has been fully processed
1877
+		if (! $this->_setup_primary_registrant_prior_to_payment()) {
1878
+			return false;
1879
+		}
1880
+		// if session is close to expiring (under 10 minutes by default)
1881
+		if ((time() - EE_Registry::instance()->SSN->expiration()) < EE_Registry::instance()->SSN->extension()) {
1882
+			// add some time to session expiration so that payment can be completed
1883
+			EE_Registry::instance()->SSN->extend_expiration();
1884
+		}
1885
+		/** @type EE_Transaction_Processor $transaction_processor */
1886
+		// $transaction_processor = EE_Registry::instance()->load_class( 'Transaction_Processor' );
1887
+		// in case a registrant leaves to an Off-Site Gateway and never returns, we want to approve any registrations
1888
+		// for events with a default reg status of Approved
1889
+		// $transaction_processor->toggle_registration_statuses_for_default_approved_events(
1890
+		//      $this->checkout->transaction, $this->checkout->reg_cache_where_params
1891
+		// );
1892
+		// attempt payment
1893
+		$payment = $this->_attempt_payment($this->checkout->payment_method);
1894
+		// process results
1895
+		$payment = $this->_validate_payment($payment);
1896
+		$payment = $this->_post_payment_processing($payment);
1897
+		// verify payment
1898
+		if ($payment instanceof EE_Payment) {
1899
+			// store that for later
1900
+			$this->checkout->payment = $payment;
1901
+			// we can also consider the TXN to not have been failed, so temporarily upgrade it's status to abandoned
1902
+			$this->checkout->transaction->toggle_failed_transaction_status();
1903
+			$payment_status = $payment->status();
1904
+			return $payment_status === EEM_Payment::status_id_approved
1905
+				   || $payment_status === EEM_Payment::status_id_pending;
1906
+		}
1907
+		if ($payment === true) {
1908
+			// please note that offline payment methods will NOT make a payment,
1909
+			// but instead just mark themselves as the PMD_ID on the transaction, and return true
1910
+			$this->checkout->payment = $payment;
1911
+			return true;
1912
+		}
1913
+		// where's my money?
1914
+		return false;
1915
+	}
1916
+
1917
+
1918
+	/**
1919
+	 * _last_second_ticket_verifications
1920
+	 *
1921
+	 * @return bool
1922
+	 * @throws EE_Error
1923
+	 * @throws ReflectionException
1924
+	 */
1925
+	protected function _last_second_ticket_verifications()
1926
+	{
1927
+		// don't bother re-validating if not a return visit
1928
+		if (! $this->checkout->revisit) {
1929
+			return true;
1930
+		}
1931
+		$registrations = $this->checkout->transaction->registrations();
1932
+		if (empty($registrations)) {
1933
+			return false;
1934
+		}
1935
+		foreach ($registrations as $registration) {
1936
+			if ($registration instanceof EE_Registration && ! $registration->is_approved()) {
1937
+				$event = $registration->event_obj();
1938
+				if ($event instanceof EE_Event && $event->is_sold_out(true)) {
1939
+					EE_Error::add_error(
1940
+						apply_filters(
1941
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___last_second_ticket_verifications__sold_out_events_msg',
1942
+							sprintf(
1943
+								esc_html__(
1944
+									'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.',
1945
+									'event_espresso'
1946
+								),
1947
+								$event->name()
1948
+							)
1949
+						),
1950
+						__FILE__,
1951
+						__FUNCTION__,
1952
+						__LINE__
1953
+					);
1954
+					return false;
1955
+				}
1956
+			}
1957
+		}
1958
+		return true;
1959
+	}
1960
+
1961
+
1962
+	/**
1963
+	 * redirect_form
1964
+	 *
1965
+	 * @return bool
1966
+	 * @throws EE_Error
1967
+	 * @throws InvalidArgumentException
1968
+	 * @throws ReflectionException
1969
+	 * @throws InvalidDataTypeException
1970
+	 * @throws InvalidInterfaceException
1971
+	 */
1972
+	public function redirect_form()
1973
+	{
1974
+		$payment_method_billing_info = $this->_payment_method_billing_info(
1975
+			$this->_get_payment_method_for_selected_method_of_payment()
1976
+		);
1977
+		$html                        = $payment_method_billing_info->get_html();
1978
+		$html                        .= $this->checkout->redirect_form;
1979
+		/** @var ResponseInterface $response */
1980
+		$response = LoaderFactory::getLoader()->getShared(ResponseInterface::class);
1981
+		$response->addOutput($html);
1982
+		return true;
1983
+	}
1984
+
1985
+
1986
+	/**
1987
+	 * _billing_form_is_valid
1988
+	 *
1989
+	 * @return bool
1990
+	 * @throws EE_Error
1991
+	 */
1992
+	private function _billing_form_is_valid()
1993
+	{
1994
+		if (! $this->checkout->payment_method->type_obj()->has_billing_form()) {
1995
+			return true;
1996
+		}
1997
+		if ($this->checkout->billing_form instanceof EE_Billing_Info_Form) {
1998
+			if ($this->checkout->billing_form->was_submitted()) {
1999
+				$this->checkout->billing_form->receive_form_submission();
2000
+				if ($this->checkout->billing_form->is_valid()) {
2001
+					return true;
2002
+				}
2003
+				$validation_errors = $this->checkout->billing_form->get_validation_errors_accumulated();
2004
+				$error_strings     = [];
2005
+				foreach ($validation_errors as $validation_error) {
2006
+					if ($validation_error instanceof EE_Validation_Error) {
2007
+						$form_section = $validation_error->get_form_section();
2008
+						if ($form_section instanceof EE_Form_Input_Base) {
2009
+							$label = $form_section->html_label_text();
2010
+						} elseif ($form_section instanceof EE_Form_Section_Base) {
2011
+							$label = $form_section->name();
2012
+						} else {
2013
+							$label = esc_html__('Validation Error', 'event_espresso');
2014
+						}
2015
+						$error_strings[] = sprintf('%1$s: %2$s', $label, $validation_error->getMessage());
2016
+					}
2017
+				}
2018
+				EE_Error::add_error(
2019
+					sprintf(
2020
+						esc_html__(
2021
+							'One or more billing form inputs are invalid and require correction before proceeding. %1$s %2$s',
2022
+							'event_espresso'
2023
+						),
2024
+						'<br/>',
2025
+						implode('<br/>', $error_strings)
2026
+					),
2027
+					__FILE__,
2028
+					__FUNCTION__,
2029
+					__LINE__
2030
+				);
2031
+			} else {
2032
+				EE_Error::add_error(
2033
+					esc_html__(
2034
+						'The billing form was not submitted or something prevented it\'s submission.',
2035
+						'event_espresso'
2036
+					),
2037
+					__FILE__,
2038
+					__FUNCTION__,
2039
+					__LINE__
2040
+				);
2041
+			}
2042
+		} else {
2043
+			EE_Error::add_error(
2044
+				esc_html__(
2045
+					'The submitted billing form is invalid possibly due to a technical reason.',
2046
+					'event_espresso'
2047
+				),
2048
+				__FILE__,
2049
+				__FUNCTION__,
2050
+				__LINE__
2051
+			);
2052
+		}
2053
+		return false;
2054
+	}
2055
+
2056
+
2057
+	/**
2058
+	 * _setup_primary_registrant_prior_to_payment
2059
+	 * ensures that the primary registrant has a valid attendee object created with the critical details populated
2060
+	 * (first & last name & email) and that both the transaction object and primary registration object have been saved
2061
+	 * plz note that any other registrations will NOT be saved at this point (because they may not have any details
2062
+	 * yet)
2063
+	 *
2064
+	 * @return bool
2065
+	 * @throws EE_Error
2066
+	 * @throws InvalidArgumentException
2067
+	 * @throws ReflectionException
2068
+	 * @throws RuntimeException
2069
+	 * @throws InvalidDataTypeException
2070
+	 * @throws InvalidInterfaceException
2071
+	 */
2072
+	private function _setup_primary_registrant_prior_to_payment()
2073
+	{
2074
+		// check if transaction has a primary registrant and that it has a related Attendee object
2075
+		// if not, then we need to at least gather some primary registrant data before attempting payment
2076
+		if (
2077
+			$this->checkout->billing_form instanceof EE_Billing_Attendee_Info_Form
2078
+			&& ! $this->checkout->transaction_has_primary_registrant()
2079
+			&& ! $this->_capture_primary_registration_data_from_billing_form()
2080
+		) {
2081
+			return false;
2082
+		}
2083
+		// because saving an object clears it's cache, we need to do the chevy shuffle
2084
+		// grab the primary_registration object
2085
+		$primary_registration = $this->checkout->transaction->primary_registration();
2086
+		// at this point we'll consider a TXN to not have been failed
2087
+		$this->checkout->transaction->toggle_failed_transaction_status();
2088
+		// save the TXN ( which clears cached copy of primary_registration)
2089
+		$this->checkout->transaction->save();
2090
+		// grab TXN ID and save it to the primary_registration
2091
+		$primary_registration->set_transaction_id($this->checkout->transaction->ID());
2092
+		// save what we have so far
2093
+		$primary_registration->save();
2094
+		return true;
2095
+	}
2096
+
2097
+
2098
+	/**
2099
+	 * _capture_primary_registration_data_from_billing_form
2100
+	 *
2101
+	 * @return bool
2102
+	 * @throws EE_Error
2103
+	 * @throws InvalidArgumentException
2104
+	 * @throws ReflectionException
2105
+	 * @throws InvalidDataTypeException
2106
+	 * @throws InvalidInterfaceException
2107
+	 */
2108
+	private function _capture_primary_registration_data_from_billing_form()
2109
+	{
2110
+		// convert billing form data into an attendee
2111
+		$this->checkout->primary_attendee_obj = $this->checkout->billing_form->create_attendee_from_billing_form_data();
2112
+		if (! $this->checkout->primary_attendee_obj instanceof EE_Attendee) {
2113
+			EE_Error::add_error(
2114
+				sprintf(
2115
+					esc_html__(
2116
+						'The billing form details could not be used for attendee details due to a technical issue.%sPlease try again or contact %s for assistance.',
2117
+						'event_espresso'
2118
+					),
2119
+					'<br/>',
2120
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
2121
+				),
2122
+				__FILE__,
2123
+				__FUNCTION__,
2124
+				__LINE__
2125
+			);
2126
+			return false;
2127
+		}
2128
+		$primary_registration = $this->checkout->transaction->primary_registration();
2129
+		if (! $primary_registration instanceof EE_Registration) {
2130
+			EE_Error::add_error(
2131
+				sprintf(
2132
+					esc_html__(
2133
+						'The primary registrant for this transaction could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.',
2134
+						'event_espresso'
2135
+					),
2136
+					'<br/>',
2137
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
2138
+				),
2139
+				__FILE__,
2140
+				__FUNCTION__,
2141
+				__LINE__
2142
+			);
2143
+			return false;
2144
+		}
2145
+		if (
2146
+			! $primary_registration->_add_relation_to($this->checkout->primary_attendee_obj, 'Attendee')
2147
+			  instanceof
2148
+			  EE_Attendee
2149
+		) {
2150
+			EE_Error::add_error(
2151
+				sprintf(
2152
+					esc_html__(
2153
+						'The primary registrant could not be associated with this transaction due to a technical issue.%sPlease try again or contact %s for assistance.',
2154
+						'event_espresso'
2155
+					),
2156
+					'<br/>',
2157
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
2158
+				),
2159
+				__FILE__,
2160
+				__FUNCTION__,
2161
+				__LINE__
2162
+			);
2163
+			return false;
2164
+		}
2165
+		/** @type EE_Registration_Processor $registration_processor */
2166
+		$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
2167
+		// at this point, we should have enough details about the registrant to consider the registration NOT incomplete
2168
+		$registration_processor->toggle_incomplete_registration_status_to_default($primary_registration);
2169
+		return true;
2170
+	}
2171
+
2172
+
2173
+	/**
2174
+	 * _get_payment_method_for_selected_method_of_payment
2175
+	 * retrieves a valid payment method
2176
+	 *
2177
+	 * @return EE_Payment_Method
2178
+	 * @throws EE_Error
2179
+	 * @throws InvalidArgumentException
2180
+	 * @throws ReflectionException
2181
+	 * @throws InvalidDataTypeException
2182
+	 * @throws InvalidInterfaceException
2183
+	 */
2184
+	private function _get_payment_method_for_selected_method_of_payment()
2185
+	{
2186
+		if ($this->checkout->selected_method_of_payment === 'events_sold_out') {
2187
+			$this->_redirect_because_event_sold_out();
2188
+			return null;
2189
+		}
2190
+		// get EE_Payment_Method object
2191
+		if (isset($this->checkout->available_payment_methods[ $this->checkout->selected_method_of_payment ])) {
2192
+			$payment_method = $this->checkout->available_payment_methods[ $this->checkout->selected_method_of_payment ];
2193
+		} else {
2194
+			// load EEM_Payment_Method
2195
+			EE_Registry::instance()->load_model('Payment_Method');
2196
+			$EEM_Payment_Method = EEM_Payment_Method::instance();
2197
+			$payment_method     = $EEM_Payment_Method->get_one_by_slug($this->checkout->selected_method_of_payment);
2198
+		}
2199
+		// verify $payment_method
2200
+		if (! $payment_method instanceof EE_Payment_Method) {
2201
+			// not a payment
2202
+			EE_Error::add_error(
2203
+				sprintf(
2204
+					esc_html__(
2205
+						'The selected method of payment could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.',
2206
+						'event_espresso'
2207
+					),
2208
+					'<br/>',
2209
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
2210
+				),
2211
+				__FILE__,
2212
+				__FUNCTION__,
2213
+				__LINE__
2214
+			);
2215
+			return null;
2216
+		}
2217
+		// and verify it has a valid Payment_Method Type object
2218
+		if (! $payment_method->type_obj() instanceof EE_PMT_Base) {
2219
+			// not a payment
2220
+			EE_Error::add_error(
2221
+				sprintf(
2222
+					esc_html__(
2223
+						'A valid payment method could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.',
2224
+						'event_espresso'
2225
+					),
2226
+					'<br/>',
2227
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
2228
+				),
2229
+				__FILE__,
2230
+				__FUNCTION__,
2231
+				__LINE__
2232
+			);
2233
+			return null;
2234
+		}
2235
+		return $payment_method;
2236
+	}
2237
+
2238
+
2239
+	/**
2240
+	 *    _attempt_payment
2241
+	 *
2242
+	 * @access    private
2243
+	 * @type    EE_Payment_Method $payment_method
2244
+	 * @return mixed EE_Payment | boolean
2245
+	 * @throws EE_Error
2246
+	 * @throws InvalidArgumentException
2247
+	 * @throws ReflectionException
2248
+	 * @throws InvalidDataTypeException
2249
+	 * @throws InvalidInterfaceException
2250
+	 */
2251
+	private function _attempt_payment(EE_Payment_Method $payment_method)
2252
+	{
2253
+		$payment = null;
2254
+		$this->checkout->transaction->save();
2255
+		$payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2256
+		if (! $payment_processor instanceof EE_Payment_Processor) {
2257
+			return false;
2258
+		}
2259
+		try {
2260
+			$payment_processor->set_revisit($this->checkout->revisit);
2261
+			// generate payment object
2262
+			$payment = $payment_processor->process_payment(
2263
+				$payment_method,
2264
+				$this->checkout->transaction,
2265
+				$this->checkout->amount_owing,
2266
+				$this->checkout->billing_form,
2267
+				$this->_get_return_url($payment_method),
2268
+				'CART',
2269
+				$this->checkout->admin_request,
2270
+				true,
2271
+				$this->reg_step_url()
2272
+			);
2273
+		} catch (Exception $e) {
2274
+			$this->_handle_payment_processor_exception($e);
2275
+		}
2276
+		return $payment;
2277
+	}
2278
+
2279
+
2280
+	/**
2281
+	 * _handle_payment_processor_exception
2282
+	 *
2283
+	 * @param Exception $e
2284
+	 * @return void
2285
+	 * @throws EE_Error
2286
+	 * @throws InvalidArgumentException
2287
+	 * @throws InvalidDataTypeException
2288
+	 * @throws InvalidInterfaceException
2289
+	 */
2290
+	protected function _handle_payment_processor_exception(Exception $e)
2291
+	{
2292
+		EE_Error::add_error(
2293
+			sprintf(
2294
+				esc_html__(
2295
+					'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',
2296
+					'event_espresso'
2297
+				),
2298
+				'<br/>',
2299
+				EE_Registry::instance()->CFG->organization->get_pretty('email'),
2300
+				$e->getMessage(),
2301
+				$e->getFile(),
2302
+				$e->getLine()
2303
+			),
2304
+			__FILE__,
2305
+			__FUNCTION__,
2306
+			__LINE__
2307
+		);
2308
+	}
2309
+
2310
+
2311
+	/**
2312
+	 * _get_return_url
2313
+	 *
2314
+	 * @param EE_Payment_Method $payment_method
2315
+	 * @return string
2316
+	 * @throws EE_Error
2317
+	 * @throws ReflectionException
2318
+	 */
2319
+	protected function _get_return_url(EE_Payment_Method $payment_method)
2320
+	{
2321
+		$return_url = '';
2322
+		switch ($payment_method->type_obj()->payment_occurs()) {
2323
+			case EE_PMT_Base::offsite:
2324
+				$return_url = add_query_arg(
2325
+					[
2326
+						'action'                     => 'process_gateway_response',
2327
+						'selected_method_of_payment' => $this->checkout->selected_method_of_payment,
2328
+						'spco_txn'                   => $this->checkout->transaction->ID(),
2329
+					],
2330
+					$this->reg_step_url()
2331
+				);
2332
+				break;
2333
+			case EE_PMT_Base::onsite:
2334
+			case EE_PMT_Base::offline:
2335
+				$return_url = $this->checkout->next_step->reg_step_url();
2336
+				break;
2337
+		}
2338
+		return $return_url;
2339
+	}
2340
+
2341
+
2342
+	/**
2343
+	 * _validate_payment
2344
+	 *
2345
+	 * @param EE_Payment $payment
2346
+	 * @return EE_Payment|FALSE
2347
+	 * @throws EE_Error
2348
+	 * @throws InvalidArgumentException
2349
+	 * @throws InvalidDataTypeException
2350
+	 * @throws InvalidInterfaceException
2351
+	 */
2352
+	private function _validate_payment($payment = null)
2353
+	{
2354
+		if ($this->checkout->payment_method->is_off_line()) {
2355
+			return true;
2356
+		}
2357
+		// verify payment object
2358
+		if (! $payment instanceof EE_Payment) {
2359
+			// not a payment
2360
+			EE_Error::add_error(
2361
+				sprintf(
2362
+					esc_html__(
2363
+						'A valid payment was not generated due to a technical issue.%1$sPlease try again or contact %2$s for assistance.',
2364
+						'event_espresso'
2365
+					),
2366
+					'<br/>',
2367
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
2368
+				),
2369
+				__FILE__,
2370
+				__FUNCTION__,
2371
+				__LINE__
2372
+			);
2373
+			return false;
2374
+		}
2375
+		return $payment;
2376
+	}
2377
+
2378
+
2379
+	/**
2380
+	 * _post_payment_processing
2381
+	 *
2382
+	 * @param EE_Payment|bool $payment
2383
+	 * @return bool
2384
+	 * @throws EE_Error
2385
+	 * @throws InvalidArgumentException
2386
+	 * @throws InvalidDataTypeException
2387
+	 * @throws InvalidInterfaceException
2388
+	 * @throws ReflectionException
2389
+	 */
2390
+	private function _post_payment_processing($payment = null)
2391
+	{
2392
+		// Off-Line payment?
2393
+		if ($payment === true) {
2394
+			// $this->_setup_redirect_for_next_step();
2395
+			return true;
2396
+			// On-Site payment?
2397
+		} elseif ($this->checkout->payment_method->is_on_site()) {
2398
+			if (! $this->_process_payment_status($payment, EE_PMT_Base::onsite)) {
2399
+				// $this->_setup_redirect_for_next_step();
2400
+				$this->checkout->continue_reg = false;
2401
+			}
2402
+			// Off-Site payment?
2403
+		} elseif ($this->checkout->payment_method->is_off_site()) {
2404
+			// if a payment object was made and it specifies a redirect url, then we'll setup that redirect info
2405
+			if ($payment instanceof EE_Payment && $payment->redirect_url()) {
2406
+				do_action('AHEE_log', __CLASS__, __FUNCTION__, $payment->redirect_url(), '$payment->redirect_url()');
2407
+				$this->checkout->redirect      = true;
2408
+				$this->checkout->redirect_form = $payment->redirect_form();
2409
+				$this->checkout->redirect_url  = $this->reg_step_url('redirect_form');
2410
+				// set JSON response
2411
+				$this->checkout->json_response->set_redirect_form($this->checkout->redirect_form);
2412
+				// and lastly, let's bump the payment status to pending
2413
+				$payment->set_status(EEM_Payment::status_id_pending);
2414
+				$payment->save();
2415
+			} else {
2416
+				// we couldn't redirect the user. Let's tell them why.
2417
+				$error_message = sprintf(
2418
+					esc_html__(
2419
+						'It appears the Off Site Payment Method was not configured properly.%sPlease try again or contact %s for assistance.',
2420
+						'event_espresso'
2421
+					),
2422
+					'<br/>',
2423
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
2424
+				);
2425
+				if ($payment instanceof EE_Payment && $payment->gateway_response()) {
2426
+					$error_message = $error_message . '<br/>' . $payment->gateway_response();
2427
+				}
2428
+				$this->checkout->continue_reg = false;
2429
+				EE_Error::add_error(
2430
+					$error_message,
2431
+					__FILE__,
2432
+					__FUNCTION__,
2433
+					__LINE__
2434
+				);
2435
+			}
2436
+		} else {
2437
+			// ummm ya... not Off-Line, not On-Site, not off-Site ????
2438
+			$this->checkout->continue_reg = false;
2439
+			return false;
2440
+		}
2441
+		return $payment;
2442
+	}
2443
+
2444
+
2445
+	/**
2446
+	 *    _process_payment_status
2447
+	 *
2448
+	 * @type    EE_Payment $payment
2449
+	 * @param string       $payment_occurs
2450
+	 * @return bool
2451
+	 * @throws EE_Error
2452
+	 * @throws InvalidArgumentException
2453
+	 * @throws InvalidDataTypeException
2454
+	 * @throws InvalidInterfaceException
2455
+	 */
2456
+	private function _process_payment_status($payment, $payment_occurs = EE_PMT_Base::offline)
2457
+	{
2458
+		// off-line payment? carry on
2459
+		if ($payment_occurs === EE_PMT_Base::offline) {
2460
+			return true;
2461
+		}
2462
+		// verify payment validity
2463
+		if ($payment instanceof EE_Payment) {
2464
+			do_action('AHEE_log', __CLASS__, __FUNCTION__, $payment->status(), '$payment->status()');
2465
+			$msg = $payment->gateway_response();
2466
+			// check results
2467
+			switch ($payment->status()) {
2468
+				// good payment
2469
+				case EEM_Payment::status_id_approved:
2470
+					EE_Error::add_success(
2471
+						esc_html__('Your payment was processed successfully.', 'event_espresso'),
2472
+						__FILE__,
2473
+						__FUNCTION__,
2474
+						__LINE__
2475
+					);
2476
+					return true;
2477
+				// slow payment
2478
+				case EEM_Payment::status_id_pending:
2479
+					if (empty($msg)) {
2480
+						$msg = esc_html__(
2481
+							'Your payment appears to have been processed successfully, but the Instant Payment Notification has not yet been received. It should arrive shortly.',
2482
+							'event_espresso'
2483
+						);
2484
+					}
2485
+					EE_Error::add_success($msg, __FILE__, __FUNCTION__, __LINE__);
2486
+					return true;
2487
+				// don't wanna payment
2488
+				case EEM_Payment::status_id_cancelled:
2489
+					if (empty($msg)) {
2490
+						$msg = _n(
2491
+							'Payment cancelled. Please try again.',
2492
+							'Payment cancelled. Please try again or select another method of payment.',
2493
+							count($this->checkout->available_payment_methods),
2494
+							'event_espresso'
2495
+						);
2496
+					}
2497
+					EE_Error::add_attention($msg, __FILE__, __FUNCTION__, __LINE__);
2498
+					return false;
2499
+				// not enough payment
2500
+				case EEM_Payment::status_id_declined:
2501
+					if (empty($msg)) {
2502
+						$msg = _n(
2503
+							'We\'re sorry but your payment was declined. Please try again.',
2504
+							'We\'re sorry but your payment was declined. Please try again or select another method of payment.',
2505
+							count($this->checkout->available_payment_methods),
2506
+							'event_espresso'
2507
+						);
2508
+					}
2509
+					EE_Error::add_attention($msg, __FILE__, __FUNCTION__, __LINE__);
2510
+					return false;
2511
+				// bad payment
2512
+				case EEM_Payment::status_id_failed:
2513
+					if (! empty($msg)) {
2514
+						EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2515
+						return false;
2516
+					}
2517
+					// default to error below
2518
+					break;
2519
+			}
2520
+		}
2521
+		// off-site payment gateway responses are too unreliable, so let's just assume that
2522
+		// the payment processing is just running slower than the registrant's request
2523
+		if ($payment_occurs === EE_PMT_Base::offsite) {
2524
+			return true;
2525
+		}
2526
+		EE_Error::add_error(
2527
+			sprintf(
2528
+				esc_html__(
2529
+					'Your payment could not be processed successfully due to a technical issue.%sPlease try again or contact %s for assistance.',
2530
+					'event_espresso'
2531
+				),
2532
+				'<br/>',
2533
+				EE_Registry::instance()->CFG->organization->get_pretty('email')
2534
+			),
2535
+			__FILE__,
2536
+			__FUNCTION__,
2537
+			__LINE__
2538
+		);
2539
+		return false;
2540
+	}
2541
+
2542
+
2543
+
2544
+
2545
+
2546
+
2547
+	/********************************************************************************************************/
2548
+	/**********************************  PROCESS GATEWAY RESPONSE  **********************************/
2549
+	/********************************************************************************************************/
2550
+	/**
2551
+	 * process_gateway_response
2552
+	 * this is the return point for Off-Site Payment Methods
2553
+	 * It will attempt to "handle the IPN" if it appears that this has not already occurred,
2554
+	 * otherwise, it will load up the last payment made for the TXN.
2555
+	 * If the payment retrieved looks good, it will then either:
2556
+	 *    complete the current step and allow advancement to the next reg step
2557
+	 *        or present the payment options again
2558
+	 *
2559
+	 * @return bool
2560
+	 * @throws EE_Error
2561
+	 * @throws InvalidArgumentException
2562
+	 * @throws ReflectionException
2563
+	 * @throws InvalidDataTypeException
2564
+	 * @throws InvalidInterfaceException
2565
+	 */
2566
+	public function process_gateway_response()
2567
+	{
2568
+		// how have they chosen to pay?
2569
+		$this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
2570
+		// get EE_Payment_Method object
2571
+		if (! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()) {
2572
+			$this->checkout->continue_reg = false;
2573
+			return false;
2574
+		}
2575
+		if (! $this->checkout->payment_method->is_off_site()) {
2576
+			return false;
2577
+		}
2578
+		$this->_validate_offsite_return();
2579
+		// verify TXN
2580
+		if ($this->checkout->transaction instanceof EE_Transaction) {
2581
+			$gateway = $this->checkout->payment_method->type_obj()->get_gateway();
2582
+			if (! $gateway instanceof EE_Offsite_Gateway) {
2583
+				$this->checkout->continue_reg = false;
2584
+				return false;
2585
+			}
2586
+			$payment = $this->_process_off_site_payment($gateway);
2587
+			$payment = $this->_process_cancelled_payments($payment);
2588
+			$payment = $this->_validate_payment($payment);
2589
+			// if payment was not declined by the payment gateway or cancelled by the registrant
2590
+			if ($this->_process_payment_status($payment, EE_PMT_Base::offsite)) {
2591
+				// $this->_setup_redirect_for_next_step();
2592
+				// store that for later
2593
+				$this->checkout->payment = $payment;
2594
+				// mark this reg step as completed, as long as gateway doesn't use a separate IPN request,
2595
+				// because we will complete this step during the IPN processing then
2596
+				if (! $this->handle_IPN_in_this_request()) {
2597
+					$this->set_completed();
2598
+				}
2599
+				return true;
2600
+			}
2601
+		}
2602
+		// DEBUG LOG
2603
+		// $this->checkout->log(
2604
+		//     __CLASS__,
2605
+		//     __FUNCTION__,
2606
+		//     __LINE__,
2607
+		//     array('payment' => $payment)
2608
+		// );
2609
+		$this->checkout->continue_reg = false;
2610
+		return false;
2611
+	}
2612
+
2613
+
2614
+	/**
2615
+	 * _validate_return
2616
+	 *
2617
+	 * @return void
2618
+	 * @throws EE_Error
2619
+	 * @throws InvalidArgumentException
2620
+	 * @throws InvalidDataTypeException
2621
+	 * @throws InvalidInterfaceException
2622
+	 * @throws ReflectionException
2623
+	 */
2624
+	private function _validate_offsite_return()
2625
+	{
2626
+		$TXN_ID = $this->request->getRequestParam('spco_txn', 0, 'int');
2627
+		if ($TXN_ID !== $this->checkout->transaction->ID()) {
2628
+			// Houston... we might have a problem
2629
+			$invalid_TXN = false;
2630
+			// first gather some info
2631
+			$valid_TXN          = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
2632
+			$primary_registrant = $valid_TXN instanceof EE_Transaction
2633
+				? $valid_TXN->primary_registration()
2634
+				: null;
2635
+			// let's start by retrieving the cart for this TXN
2636
+			$cart = $this->checkout->get_cart_for_transaction($this->checkout->transaction);
2637
+			if ($cart instanceof EE_Cart) {
2638
+				// verify that the current cart has tickets
2639
+				$tickets = $cart->get_tickets();
2640
+				if (empty($tickets)) {
2641
+					$invalid_TXN = true;
2642
+				}
2643
+			} else {
2644
+				$invalid_TXN = true;
2645
+			}
2646
+			$valid_TXN_SID = $primary_registrant instanceof EE_Registration
2647
+				? $primary_registrant->session_ID()
2648
+				: null;
2649
+			// validate current Session ID and compare against valid TXN session ID
2650
+			if (
2651
+				$invalid_TXN // if this is already true, then skip other checks
2652
+				|| EE_Session::instance()->id() === null
2653
+				|| (
2654
+					// WARNING !!!
2655
+					// this could be PayPal sending back duplicate requests (ya they do that)
2656
+					// or it **could** mean someone is simply registering AGAIN after having just done so
2657
+					// so now we need to determine if this current TXN looks valid or not
2658
+					// and whether this reg step has even been started ?
2659
+					EE_Session::instance()->id() === $valid_TXN_SID
2660
+					// really? you're half way through this reg step, but you never started it ?
2661
+					&& $this->checkout->transaction->reg_step_completed($this->slug()) === false
2662
+				)
2663
+			) {
2664
+				$invalid_TXN = true;
2665
+			}
2666
+			if ($invalid_TXN) {
2667
+				// is the valid TXN completed ?
2668
+				if ($valid_TXN instanceof EE_Transaction) {
2669
+					// has this step even been started ?
2670
+					$reg_step_completed = $valid_TXN->reg_step_completed($this->slug());
2671
+					if ($reg_step_completed !== false && $reg_step_completed !== true) {
2672
+						// so it **looks** like this is a double request from PayPal
2673
+						// so let's try to pick up where we left off
2674
+						$this->checkout->transaction = $valid_TXN;
2675
+						$this->checkout->refresh_all_entities(true);
2676
+						return;
2677
+					}
2678
+				}
2679
+				// you appear to be lost?
2680
+				$this->_redirect_wayward_request($primary_registrant);
2681
+			}
2682
+		}
2683
+	}
2684
+
2685
+
2686
+	/**
2687
+	 * _redirect_wayward_request
2688
+	 *
2689
+	 * @param EE_Registration|null $primary_registrant
2690
+	 * @return void
2691
+	 * @throws EE_Error
2692
+	 * @throws InvalidArgumentException
2693
+	 * @throws InvalidDataTypeException
2694
+	 * @throws InvalidInterfaceException
2695
+	 * @throws ReflectionException
2696
+	 */
2697
+	private function _redirect_wayward_request(EE_Registration $primary_registrant)
2698
+	{
2699
+		if (! $primary_registrant instanceof EE_Registration) {
2700
+			// try redirecting based on the current TXN
2701
+			$primary_registrant = $this->checkout->transaction instanceof EE_Transaction
2702
+				? $this->checkout->transaction->primary_registration()
2703
+				: null;
2704
+		}
2705
+		if (! $primary_registrant instanceof EE_Registration) {
2706
+			EE_Error::add_error(
2707
+				sprintf(
2708
+					esc_html__(
2709
+						'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.',
2710
+						'event_espresso'
2711
+					),
2712
+					'<br/>',
2713
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
2714
+				),
2715
+				__FILE__,
2716
+				__FUNCTION__,
2717
+				__LINE__
2718
+			);
2719
+			return;
2720
+		}
2721
+		// make sure transaction is not locked
2722
+		$this->checkout->transaction->unlock();
2723
+		wp_safe_redirect(
2724
+			add_query_arg(
2725
+				[
2726
+					'e_reg_url_link' => $primary_registrant->reg_url_link(),
2727
+				],
2728
+				$this->checkout->thank_you_page_url
2729
+			)
2730
+		);
2731
+		exit();
2732
+	}
2733
+
2734
+
2735
+	/**
2736
+	 * _process_off_site_payment
2737
+	 *
2738
+	 * @param EE_Offsite_Gateway $gateway
2739
+	 * @return EE_Payment
2740
+	 * @throws EE_Error
2741
+	 * @throws InvalidArgumentException
2742
+	 * @throws InvalidDataTypeException
2743
+	 * @throws InvalidInterfaceException
2744
+	 * @throws ReflectionException
2745
+	 */
2746
+	private function _process_off_site_payment(EE_Offsite_Gateway $gateway)
2747
+	{
2748
+		try {
2749
+			$request      = LoaderFactory::getLoader()->getShared(RequestInterface::class);
2750
+			$request_data = $request->requestParams();
2751
+			// if gateway uses_separate_IPN_request, then we don't have to process the IPN manually
2752
+			$this->set_handle_IPN_in_this_request(
2753
+				$gateway->handle_IPN_in_this_request($request_data, false)
2754
+			);
2755
+			if ($this->handle_IPN_in_this_request()) {
2756
+				// get payment details and process results
2757
+				/** @type EE_Payment_Processor $payment_processor */
2758
+				$payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2759
+				$payment           = $payment_processor->process_ipn(
2760
+					$request_data,
2761
+					$this->checkout->transaction,
2762
+					$this->checkout->payment_method,
2763
+					true,
2764
+					false
2765
+				);
2766
+				// $payment_source = 'process_ipn';
2767
+			} else {
2768
+				$payment = $this->checkout->transaction->last_payment();
2769
+				// $payment_source = 'last_payment';
2770
+			}
2771
+		} catch (Exception $e) {
2772
+			// let's just eat the exception and try to move on using any previously set payment info
2773
+			$payment = $this->checkout->transaction->last_payment();
2774
+			// $payment_source = 'last_payment after Exception';
2775
+			// but if we STILL don't have a payment object
2776
+			if (! $payment instanceof EE_Payment) {
2777
+				// then we'll object ! ( not object like a thing... but object like what a lawyer says ! )
2778
+				$this->_handle_payment_processor_exception($e);
2779
+			}
2780
+		}
2781
+		return $payment;
2782
+	}
2783
+
2784
+
2785
+	/**
2786
+	 * _process_cancelled_payments
2787
+	 * just makes sure that the payment status gets updated correctly
2788
+	 * so tha tan error isn't generated during payment validation
2789
+	 *
2790
+	 * @param EE_Payment $payment
2791
+	 * @return EE_Payment|null
2792
+	 * @throws EE_Error
2793
+	 */
2794
+	private function _process_cancelled_payments($payment = null)
2795
+	{
2796
+		if (
2797
+			$payment instanceof EE_Payment
2798
+			&& $this->request->requestParamIsSet('ee_cancel_payment')
2799
+			&& $payment->status() === EEM_Payment::status_id_failed
2800
+		) {
2801
+			$payment->set_status(EEM_Payment::status_id_cancelled);
2802
+		}
2803
+		return $payment;
2804
+	}
2805
+
2806
+
2807
+	/**
2808
+	 *    get_transaction_details_for_gateways
2809
+	 *
2810
+	 * @access    public
2811
+	 * @return void
2812
+	 * @throws EE_Error
2813
+	 * @throws InvalidArgumentException
2814
+	 * @throws ReflectionException
2815
+	 * @throws InvalidDataTypeException
2816
+	 * @throws InvalidInterfaceException
2817
+	 */
2818
+	public function get_transaction_details_for_gateways()
2819
+	{
2820
+		$txn_details = [];
2821
+		// ya gotta make a choice man
2822
+		if (empty($this->checkout->selected_method_of_payment)) {
2823
+			$txn_details = [
2824
+				'error' => esc_html__('Please select a method of payment before proceeding.', 'event_espresso'),
2825
+			];
2826
+		}
2827
+		// get EE_Payment_Method object
2828
+		if (
2829
+			empty($txn_details)
2830
+			&& ! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()
2831
+		) {
2832
+			$txn_details = [
2833
+				'selected_method_of_payment' => $this->checkout->selected_method_of_payment,
2834
+				'error'                      => esc_html__(
2835
+					'A valid Payment Method could not be determined.',
2836
+					'event_espresso'
2837
+				),
2838
+			];
2839
+		}
2840
+		if (empty($txn_details) && $this->checkout->transaction instanceof EE_Transaction) {
2841
+			$return_url  = $this->_get_return_url($this->checkout->payment_method);
2842
+			$txn_details = [
2843
+				'TXN_ID'         => $this->checkout->transaction->ID(),
2844
+				'TXN_timestamp'  => $this->checkout->transaction->datetime(),
2845
+				'TXN_total'      => $this->checkout->transaction->total(),
2846
+				'TXN_paid'       => $this->checkout->transaction->paid(),
2847
+				'TXN_reg_steps'  => $this->checkout->transaction->reg_steps(),
2848
+				'STS_ID'         => $this->checkout->transaction->status_ID(),
2849
+				'PMD_ID'         => $this->checkout->transaction->payment_method_ID(),
2850
+				'payment_amount' => $this->checkout->amount_owing,
2851
+				'return_url'     => $return_url,
2852
+				'cancel_url'     => add_query_arg(['ee_cancel_payment' => true], $return_url),
2853
+				'notify_url'     => EE_Config::instance()->core->txn_page_url(
2854
+					[
2855
+						'e_reg_url_link'    => $this->checkout->transaction->primary_registration()->reg_url_link(),
2856
+						'ee_payment_method' => $this->checkout->payment_method->slug(),
2857
+					]
2858
+				),
2859
+			];
2860
+		}
2861
+		echo wp_json_encode($txn_details);
2862
+		exit();
2863
+	}
2864
+
2865
+
2866
+	/**
2867
+	 *    __sleep
2868
+	 * to conserve db space, let's remove the reg_form and the EE_Checkout object from EE_SPCO_Reg_Step objects upon
2869
+	 * serialization EE_Checkout will handle the reimplementation of itself upon waking, but we won't bother with the
2870
+	 * reg form, because if needed, it will be regenerated anyways
2871
+	 *
2872
+	 * @return array
2873
+	 */
2874
+	public function __sleep()
2875
+	{
2876
+		// remove the reg form and the checkout
2877
+		return array_diff(array_keys(get_object_vars($this)), ['reg_form', 'checkout', 'line_item_display']);
2878
+	}
2879 2879
 }
Please login to merge, or discard this patch.
modules/certificate/EED_Certificate.module.php 1 patch
Indentation   +94 added lines, -94 removed lines patch added patch discarded remove patch
@@ -12,98 +12,98 @@
 block discarded – undo
12 12
 {
13 13
 
14 14
 
15
-    /**
16
-     * @return EED_Module|EED_Certificate
17
-     * @throws EE_Error
18
-     * @throws ReflectionException
19
-     */
20
-    public static function instance()
21
-    {
22
-        return parent::get_instance(__CLASS__);
23
-    }
24
-
25
-
26
-    /**
27
-     *    set_hooks - for hooking into EE Core, other modules, etc
28
-     *
29
-     * @access    public
30
-     * @return    void
31
-     */
32
-    public static function set_hooks()
33
-    {
34
-    }
35
-
36
-    /**
37
-     *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
38
-     *
39
-     * @access    public
40
-     * @return    void
41
-     */
42
-    public static function set_hooks_admin()
43
-    {
44
-    }
45
-
46
-
47
-    /**
48
-     *    run - initial module setup
49
-     *
50
-     * @access    public
51
-     * @return    void
52
-     */
53
-    public function run($WP)
54
-    {
55
-    }
56
-
57
-
58
-    /**
59
-     *    certificate_launch
60
-     *
61
-     * @access    public
62
-     * @return    void
63
-     */
64
-    public function certificate_launch()
65
-    {
66
-        $request = self::getRequest();
67
-        if ($request->requestParamIsSet('id') && $request->requestParamIsSet('r_id')) {
68
-            echo espresso_certificate_launch(
69
-                $request->getRequestParam('id'),
70
-                $request->getRequestParam('r_id')
71
-            );
72
-        }
73
-    }
74
-
75
-
76
-    /**
77
-     *    wp_loaded
78
-     *
79
-     * @access    public
80
-     * @return    void
81
-     */
82
-    public function wp_loaded()
83
-    {
84
-    }
85
-
86
-
87
-    /**
88
-     *    wp
89
-     *
90
-     * @access    public
91
-     * @return    void
92
-     */
93
-    public function wp()
94
-    {
95
-    }
96
-
97
-
98
-    /**
99
-     *    the_content
100
-     *
101
-     * @access    public
102
-     * @return    string
103
-     */
104
-    public function the_content($content)
105
-    {
106
-        $content .= $this->ouput;
107
-        return $content;
108
-    }
15
+	/**
16
+	 * @return EED_Module|EED_Certificate
17
+	 * @throws EE_Error
18
+	 * @throws ReflectionException
19
+	 */
20
+	public static function instance()
21
+	{
22
+		return parent::get_instance(__CLASS__);
23
+	}
24
+
25
+
26
+	/**
27
+	 *    set_hooks - for hooking into EE Core, other modules, etc
28
+	 *
29
+	 * @access    public
30
+	 * @return    void
31
+	 */
32
+	public static function set_hooks()
33
+	{
34
+	}
35
+
36
+	/**
37
+	 *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
38
+	 *
39
+	 * @access    public
40
+	 * @return    void
41
+	 */
42
+	public static function set_hooks_admin()
43
+	{
44
+	}
45
+
46
+
47
+	/**
48
+	 *    run - initial module setup
49
+	 *
50
+	 * @access    public
51
+	 * @return    void
52
+	 */
53
+	public function run($WP)
54
+	{
55
+	}
56
+
57
+
58
+	/**
59
+	 *    certificate_launch
60
+	 *
61
+	 * @access    public
62
+	 * @return    void
63
+	 */
64
+	public function certificate_launch()
65
+	{
66
+		$request = self::getRequest();
67
+		if ($request->requestParamIsSet('id') && $request->requestParamIsSet('r_id')) {
68
+			echo espresso_certificate_launch(
69
+				$request->getRequestParam('id'),
70
+				$request->getRequestParam('r_id')
71
+			);
72
+		}
73
+	}
74
+
75
+
76
+	/**
77
+	 *    wp_loaded
78
+	 *
79
+	 * @access    public
80
+	 * @return    void
81
+	 */
82
+	public function wp_loaded()
83
+	{
84
+	}
85
+
86
+
87
+	/**
88
+	 *    wp
89
+	 *
90
+	 * @access    public
91
+	 * @return    void
92
+	 */
93
+	public function wp()
94
+	{
95
+	}
96
+
97
+
98
+	/**
99
+	 *    the_content
100
+	 *
101
+	 * @access    public
102
+	 * @return    string
103
+	 */
104
+	public function the_content($content)
105
+	{
106
+		$content .= $this->ouput;
107
+		return $content;
108
+	}
109 109
 }
Please login to merge, or discard this patch.
modules/core_rest_api/EED_Core_Rest_Api.module.php 2 patches
Spacing   +51 added lines, -51 removed lines patch added patch discarded remove patch
@@ -123,7 +123,7 @@  discard block
 block discarded – undo
123 123
      */
124 124
     protected static function _set_hooks_for_changes()
125 125
     {
126
-        $folder_contents = EEH_File::get_contents_of_folders(array(EE_LIBRARIES . 'rest_api/changes'), false);
126
+        $folder_contents = EEH_File::get_contents_of_folders(array(EE_LIBRARIES.'rest_api/changes'), false);
127 127
         foreach ($folder_contents as $classname_in_namespace => $filepath) {
128 128
             // ignore the base parent class
129 129
             // and legacy named classes
@@ -133,7 +133,7 @@  discard block
 block discarded – undo
133 133
             ) {
134 134
                 continue;
135 135
             }
136
-            $full_classname = 'EventEspresso\core\libraries\rest_api\changes\\' . $classname_in_namespace;
136
+            $full_classname = 'EventEspresso\core\libraries\rest_api\changes\\'.$classname_in_namespace;
137 137
             if (class_exists($full_classname)) {
138 138
                 $instance_of_class = new $full_classname();
139 139
                 if ($instance_of_class instanceof ChangesInBase) {
@@ -178,10 +178,10 @@  discard block
 block discarded – undo
178 178
                      * }
179 179
                      */
180 180
                     // skip route options
181
-                    if (! is_numeric($endpoint_key)) {
181
+                    if ( ! is_numeric($endpoint_key)) {
182 182
                         continue;
183 183
                     }
184
-                    if (! isset($data_for_single_endpoint['callback'], $data_for_single_endpoint['methods'])) {
184
+                    if ( ! isset($data_for_single_endpoint['callback'], $data_for_single_endpoint['methods'])) {
185 185
                         throw new EE_Error(
186 186
                             esc_html__(
187 187
                             // @codingStandardsIgnoreStart
@@ -202,7 +202,7 @@  discard block
 block discarded – undo
202 202
                     }
203 203
                     if (isset($data_for_single_endpoint['callback_args'])) {
204 204
                         $callback_args = $data_for_single_endpoint['callback_args'];
205
-                        $single_endpoint_args['callback'] = function (\WP_REST_Request $request) use (
205
+                        $single_endpoint_args['callback'] = function(\WP_REST_Request $request) use (
206 206
                             $callback,
207 207
                             $callback_args
208 208
                         ) {
@@ -219,7 +219,7 @@  discard block
 block discarded – undo
219 219
                     // the REST API will issue a _doing_it_wrong notice.
220 220
                     // Since the EE REST API defers capabilities to the db model system,
221 221
                     // we will just use the generic WP callback for public endpoints
222
-                    if (! isset($single_endpoint_args['permission_callback'])) {
222
+                    if ( ! isset($single_endpoint_args['permission_callback'])) {
223 223
                         $single_endpoint_args['permission_callback'] = '__return_true';
224 224
                     }
225 225
                     $multiple_endpoint_args[] = $single_endpoint_args;
@@ -228,7 +228,7 @@  discard block
 block discarded – undo
228 228
                     $schema_route_data = $data_for_multiple_endpoints['schema'];
229 229
                     $schema_callback = $schema_route_data['schema_callback'];
230 230
                     $callback_args = $schema_route_data['callback_args'];
231
-                    $multiple_endpoint_args['schema'] = function () use ($schema_callback, $callback_args) {
231
+                    $multiple_endpoint_args['schema'] = function() use ($schema_callback, $callback_args) {
232 232
                         return call_user_func_array(
233 233
                             $schema_callback,
234 234
                             $callback_args
@@ -270,7 +270,7 @@  discard block
 block discarded – undo
270 270
     {
271 271
         // delete the saved EE REST API routes
272 272
         foreach (EED_Core_Rest_Api::versions_served() as $version => $hidden) {
273
-            delete_option(EED_Core_Rest_Api::saved_routes_option_names . $version);
273
+            delete_option(EED_Core_Rest_Api::saved_routes_option_names.$version);
274 274
         }
275 275
     }
276 276
 
@@ -289,7 +289,7 @@  discard block
 block discarded – undo
289 289
     {
290 290
         $ee_routes = array();
291 291
         foreach (self::versions_served() as $version => $hidden_endpoints) {
292
-            $ee_routes[ self::ee_api_namespace . $version ] = self::_get_ee_route_data_for_version(
292
+            $ee_routes[self::ee_api_namespace.$version] = self::_get_ee_route_data_for_version(
293 293
                 $version,
294 294
                 $hidden_endpoints
295 295
             );
@@ -309,8 +309,8 @@  discard block
 block discarded – undo
309 309
      */
310 310
     protected static function _get_ee_route_data_for_version($version, $hidden_endpoints = false)
311 311
     {
312
-        $ee_routes = get_option(self::saved_routes_option_names . $version, null);
313
-        if (! $ee_routes || EED_Core_Rest_Api::debugMode()) {
312
+        $ee_routes = get_option(self::saved_routes_option_names.$version, null);
313
+        if ( ! $ee_routes || EED_Core_Rest_Api::debugMode()) {
314 314
             $ee_routes = self::_save_ee_route_data_for_version($version, $hidden_endpoints);
315 315
         }
316 316
         return $ee_routes;
@@ -337,7 +337,7 @@  discard block
 block discarded – undo
337 337
                 $instance->_get_rpc_route_data_for_version($version, $hidden_endpoints)
338 338
             )
339 339
         );
340
-        $option_name = self::saved_routes_option_names . $version;
340
+        $option_name = self::saved_routes_option_names.$version;
341 341
         if (get_option($option_name)) {
342 342
             update_option($option_name, $routes, true);
343 343
         } else {
@@ -382,8 +382,8 @@  discard block
 block discarded – undo
382 382
     {
383 383
         $model_routes = array();
384 384
         foreach (self::versions_served() as $version => $hidden_endpoint) {
385
-            $model_routes[ EED_Core_Rest_Api::ee_api_namespace
386
-                           . $version ] = $this->_get_config_route_data_for_version($version, $hidden_endpoint);
385
+            $model_routes[EED_Core_Rest_Api::ee_api_namespace
386
+                           . $version] = $this->_get_config_route_data_for_version($version, $hidden_endpoint);
387 387
         }
388 388
         return $model_routes;
389 389
     }
@@ -452,13 +452,13 @@  discard block
 block discarded – undo
452 452
         foreach (EED_Core_Rest_Api::model_names_with_plural_routes($version) as $model_name => $model_classname) {
453 453
             $model = \EE_Registry::instance()->load_model($model_name);
454 454
             // if this isn't a valid model then let's skip iterate to the next item in the loop.
455
-            if (! $model instanceof EEM_Base) {
455
+            if ( ! $model instanceof EEM_Base) {
456 456
                 continue;
457 457
             }
458 458
             // yes we could just register one route for ALL models, but then they wouldn't show up in the index
459 459
             $plural_model_route = EED_Core_Rest_Api::get_collection_route($model);
460 460
             $singular_model_route = EED_Core_Rest_Api::get_entity_route($model, '(?P<id>[^\/]+)');
461
-            $model_routes[ $plural_model_route ] = array(
461
+            $model_routes[$plural_model_route] = array(
462 462
                 array(
463 463
                     'callback'        => array(
464 464
                         'EventEspresso\core\libraries\rest_api\controllers\model\Read',
@@ -469,7 +469,7 @@  discard block
 block discarded – undo
469 469
                     'hidden_endpoint' => $hidden_endpoint,
470 470
                     'args'            => $this->_get_read_query_params($model, $version),
471 471
                     '_links'          => array(
472
-                        'self' => rest_url(EED_Core_Rest_Api::ee_api_namespace . $version . $singular_model_route),
472
+                        'self' => rest_url(EED_Core_Rest_Api::ee_api_namespace.$version.$singular_model_route),
473 473
                     ),
474 474
                 ),
475 475
                 'schema' => array(
@@ -480,7 +480,7 @@  discard block
 block discarded – undo
480 480
                     'callback_args'   => array($version, $model_name),
481 481
                 ),
482 482
             );
483
-            $model_routes[ $singular_model_route ] = array(
483
+            $model_routes[$singular_model_route] = array(
484 484
                 array(
485 485
                     'callback'        => array(
486 486
                         'EventEspresso\core\libraries\rest_api\controllers\model\Read',
@@ -499,7 +499,7 @@  discard block
 block discarded – undo
499 499
                     $model
500 500
                 )
501 501
             ) {
502
-                $model_routes[ $plural_model_route ][] = array(
502
+                $model_routes[$plural_model_route][] = array(
503 503
                     'callback'        => array(
504 504
                         'EventEspresso\core\libraries\rest_api\controllers\model\Write',
505 505
                         'handleRequestInsert',
@@ -509,8 +509,8 @@  discard block
 block discarded – undo
509 509
                     'hidden_endpoint' => $hidden_endpoint,
510 510
                     'args'            => $this->_get_write_params($model_name, $model_version_info, true),
511 511
                 );
512
-                $model_routes[ $singular_model_route ] = array_merge(
513
-                    $model_routes[ $singular_model_route ],
512
+                $model_routes[$singular_model_route] = array_merge(
513
+                    $model_routes[$singular_model_route],
514 514
                     array(
515 515
                         array(
516 516
                             'callback'        => array(
@@ -541,7 +541,7 @@  discard block
 block discarded – undo
541 541
                     '(?P<id>[^\/]+)',
542 542
                     $relation_obj
543 543
                 );
544
-                $model_routes[ $related_route ] = array(
544
+                $model_routes[$related_route] = array(
545 545
                     array(
546 546
                         'callback'        => array(
547 547
                             'EventEspresso\core\libraries\rest_api\controllers\model\Read',
@@ -554,8 +554,8 @@  discard block
 block discarded – undo
554 554
                     ),
555 555
                 );
556 556
 
557
-                $related_write_route = $related_route . '/' . '(?P<related_id>[^\/]+)';
558
-                $model_routes[ $related_write_route ] = array(
557
+                $related_write_route = $related_route.'/'.'(?P<related_id>[^\/]+)';
558
+                $model_routes[$related_write_route] = array(
559 559
                     array(
560 560
                         'callback'        => array(
561 561
                             'EventEspresso\core\libraries\rest_api\controllers\model\Write',
@@ -608,7 +608,7 @@  discard block
 block discarded – undo
608 608
      */
609 609
     public static function get_entity_route($model, $id)
610 610
     {
611
-        return EED_Core_Rest_Api::get_collection_route($model) . '/' . $id;
611
+        return EED_Core_Rest_Api::get_collection_route($model).'/'.$id;
612 612
     }
613 613
 
614 614
 
@@ -628,7 +628,7 @@  discard block
 block discarded – undo
628 628
             $relation_obj->get_other_model()->get_this_model_name(),
629 629
             $relation_obj
630 630
         );
631
-        return EED_Core_Rest_Api::get_entity_route($model, $id) . '/' . $related_model_name_endpoint_part;
631
+        return EED_Core_Rest_Api::get_entity_route($model, $id).'/'.$related_model_name_endpoint_part;
632 632
     }
633 633
 
634 634
 
@@ -642,7 +642,7 @@  discard block
 block discarded – undo
642 642
      */
643 643
     public static function get_versioned_route_to($relative_route, $version = '4.8.36')
644 644
     {
645
-        return '/' . EED_Core_Rest_Api::ee_api_namespace . $version . '/' . $relative_route;
645
+        return '/'.EED_Core_Rest_Api::ee_api_namespace.$version.'/'.$relative_route;
646 646
     }
647 647
 
648 648
 
@@ -656,7 +656,7 @@  discard block
 block discarded – undo
656 656
     {
657 657
         $routes = array();
658 658
         foreach (self::versions_served() as $version => $hidden_endpoint) {
659
-            $routes[ self::ee_api_namespace . $version ] = $this->_get_rpc_route_data_for_version(
659
+            $routes[self::ee_api_namespace.$version] = $this->_get_rpc_route_data_for_version(
660 660
                 $version,
661 661
                 $hidden_endpoint
662 662
             );
@@ -779,12 +779,12 @@  discard block
 block discarded – undo
779 779
     {
780 780
         // if they're related through a HABTM relation, check for any non-FKs
781 781
         $all_relation_settings = $source_model->relation_settings();
782
-        $relation_settings = $all_relation_settings[ $related_model->get_this_model_name() ];
782
+        $relation_settings = $all_relation_settings[$related_model->get_this_model_name()];
783 783
         $params = array();
784 784
         if ($relation_settings instanceof EE_HABTM_Relation && $relation_settings->hasNonKeyFields()) {
785 785
             foreach ($relation_settings->getNonKeyFields() as $field) {
786 786
                 /* @var $field EE_Model_Field_Base */
787
-                $params[ $field->get_name() ] = array(
787
+                $params[$field->get_name()] = array(
788 788
                     'required' => ! $field->is_nullable(),
789 789
                     'default' => ModelDataTranslator::prepareFieldValueForJson($field, $field->get_default_value(), $version),
790 790
                     'type' => $field->getSchemaType(),
@@ -809,7 +809,7 @@  discard block
 block discarded – undo
809 809
     {
810 810
         $default_orderby = array();
811 811
         foreach ($model->get_combined_primary_key_fields() as $key_field) {
812
-            $default_orderby[ $key_field->get_name() ] = 'ASC';
812
+            $default_orderby[$key_field->get_name()] = 'ASC';
813 813
         }
814 814
         return array_merge(
815 815
             $this->_get_response_selection_query_params($model, $version),
@@ -843,7 +843,7 @@  discard block
 block discarded – undo
843 843
                     'type'              => array(
844 844
                         'object',
845 845
                         'string',
846
-                    ),// because we accept a variety of types, WP core validation and sanitization
846
+                    ), // because we accept a variety of types, WP core validation and sanitization
847 847
                     // freaks out. We'll just validate this argument while handling the request
848 848
                     'validate_callback' => null,
849 849
                     'sanitize_callback' => null,
@@ -942,7 +942,7 @@  discard block
 block discarded – undo
942 942
                 $sanitize_callback = null;
943 943
             }
944 944
             $arg_info['sanitize_callback'] = $sanitize_callback;
945
-            $args_info[ $field_name ] = $arg_info;
945
+            $args_info[$field_name] = $arg_info;
946 946
             if ($field_obj instanceof EE_Datetime_Field) {
947 947
                 $gmt_arg_info = $arg_info;
948 948
                 $gmt_arg_info['description'] = sprintf(
@@ -953,7 +953,7 @@  discard block
 block discarded – undo
953 953
                     $field_obj->get_nicename(),
954 954
                     $field_name
955 955
                 );
956
-                $args_info[ $field_name . '_gmt' ] = $gmt_arg_info;
956
+                $args_info[$field_name.'_gmt'] = $gmt_arg_info;
957 957
             }
958 958
         }
959 959
         return $args_info;
@@ -977,18 +977,18 @@  discard block
 block discarded – undo
977 977
     {
978 978
         $attributes = $request->get_attributes();
979 979
         if (
980
-            ! isset($attributes['args'][ $param ])
981
-            || ! is_array($attributes['args'][ $param ])
980
+            ! isset($attributes['args'][$param])
981
+            || ! is_array($attributes['args'][$param])
982 982
         ) {
983 983
             $validation_result = true;
984 984
         } else {
985
-            $args = $attributes['args'][ $param ];
985
+            $args = $attributes['args'][$param];
986 986
             if (
987 987
                 (
988 988
                     $value === ''
989 989
                     || $value === null
990 990
                 )
991
-                && (! isset($args['required'])
991
+                && ( ! isset($args['required'])
992 992
                     || $args['required'] === false
993 993
                 )
994 994
             ) {
@@ -999,7 +999,7 @@  discard block
 block discarded – undo
999 999
                       && $args['format'] === 'email'
1000 1000
             ) {
1001 1001
                 $validation_result = true;
1002
-                if (! self::_validate_email($value)) {
1002
+                if ( ! self::_validate_email($value)) {
1003 1003
                     $validation_result = new WP_Error(
1004 1004
                         'rest_invalid_param',
1005 1005
                         esc_html__(
@@ -1049,7 +1049,7 @@  discard block
 block discarded – undo
1049 1049
     {
1050 1050
         $config_routes = array();
1051 1051
         foreach (self::versions_served() as $version => $hidden_endpoint) {
1052
-            $config_routes[ self::ee_api_namespace . $version ] = $this->_get_config_route_data_for_version(
1052
+            $config_routes[self::ee_api_namespace.$version] = $this->_get_config_route_data_for_version(
1053 1053
                 $version,
1054 1054
                 $hidden_endpoint
1055 1055
             );
@@ -1104,7 +1104,7 @@  discard block
 block discarded – undo
1104 1104
     {
1105 1105
         $meta_routes = array();
1106 1106
         foreach (self::versions_served() as $version => $hidden_endpoint) {
1107
-            $meta_routes[ self::ee_api_namespace . $version ] = $this->_get_meta_route_data_for_version(
1107
+            $meta_routes[self::ee_api_namespace.$version] = $this->_get_meta_route_data_for_version(
1108 1108
                 $version,
1109 1109
                 $hidden_endpoint
1110 1110
             );
@@ -1156,7 +1156,7 @@  discard block
 block discarded – undo
1156 1156
             foreach ($relative_urls as $resource_name => $endpoints) {
1157 1157
                 foreach ($endpoints as $key => $endpoint) {
1158 1158
                     // skip schema and other route options
1159
-                    if (! is_numeric($key)) {
1159
+                    if ( ! is_numeric($key)) {
1160 1160
                         continue;
1161 1161
                     }
1162 1162
                     // by default, hide "hidden_endpoint"s, unless the request indicates
@@ -1166,9 +1166,9 @@  discard block
 block discarded – undo
1166 1166
                         ($force_show_ee_namespace !== '' && $force_show_ee_namespace !== $namespace)
1167 1167
                         || ($endpoint['hidden_endpoint'] && $force_show_ee_namespace === '')
1168 1168
                     ) {
1169
-                        $full_route = '/' . ltrim($namespace, '/');
1170
-                        $full_route .= '/' . ltrim($resource_name, '/');
1171
-                        unset($route_data[ $full_route ]);
1169
+                        $full_route = '/'.ltrim($namespace, '/');
1170
+                        $full_route .= '/'.ltrim($resource_name, '/');
1171
+                        unset($route_data[$full_route]);
1172 1172
                     }
1173 1173
                 }
1174 1174
             }
@@ -1242,13 +1242,13 @@  discard block
 block discarded – undo
1242 1242
 
1243 1243
             if ($key_versioned_endpoint === $latest_version) {
1244 1244
                 // don't hide the latest version in the index
1245
-                $versions_served[ $key_versioned_endpoint ] = false;
1245
+                $versions_served[$key_versioned_endpoint] = false;
1246 1246
             } elseif (
1247 1247
                 version_compare($key_versioned_endpoint, $lowest_compatible_version, '>=')
1248 1248
                 && version_compare($key_versioned_endpoint, EED_Core_Rest_Api::core_version(), '<')
1249 1249
             ) {
1250 1250
                 // include, but hide, previous versions which are still supported
1251
-                $versions_served[ $key_versioned_endpoint ] = true;
1251
+                $versions_served[$key_versioned_endpoint] = true;
1252 1252
             } elseif (
1253 1253
                 apply_filters(
1254 1254
                     'FHEE__EED_Core_Rest_Api__versions_served__include_incompatible_versions',
@@ -1257,7 +1257,7 @@  discard block
 block discarded – undo
1257 1257
                 )
1258 1258
             ) {
1259 1259
                 // if a version is no longer supported, don't include it in index or list of versions served
1260
-                $versions_served[ $key_versioned_endpoint ] = true;
1260
+                $versions_served[$key_versioned_endpoint] = true;
1261 1261
             }
1262 1262
         }
1263 1263
         return $versions_served;
@@ -1315,7 +1315,7 @@  discard block
 block discarded – undo
1315 1315
         $model_names = self::model_names_with_plural_routes($version);
1316 1316
         $collection_routes = array();
1317 1317
         foreach ($model_names as $model_name => $model_class_name) {
1318
-            $collection_routes[ strtolower($model_name) ] = '/' . self::ee_api_namespace . $version . '/'
1318
+            $collection_routes[strtolower($model_name)] = '/'.self::ee_api_namespace.$version.'/'
1319 1319
                                                             . EEH_Inflector::pluralize_and_lower($model_name);
1320 1320
         }
1321 1321
         return $collection_routes;
@@ -1336,9 +1336,9 @@  discard block
 block discarded – undo
1336 1336
             $primary_keys = $model_class_name::instance()->get_combined_primary_key_fields();
1337 1337
             foreach ($primary_keys as $primary_key_name => $primary_key_field) {
1338 1338
                 if (count($primary_keys) > 1) {
1339
-                    $primary_key_items[ strtolower($model_name) ][] = $primary_key_name;
1339
+                    $primary_key_items[strtolower($model_name)][] = $primary_key_name;
1340 1340
                 } else {
1341
-                    $primary_key_items[ strtolower($model_name) ] = $primary_key_name;
1341
+                    $primary_key_items[strtolower($model_name)] = $primary_key_name;
1342 1342
                 }
1343 1343
             }
1344 1344
         }
Please login to merge, or discard this patch.
Indentation   +1348 added lines, -1348 removed lines patch added patch discarded remove patch
@@ -23,1352 +23,1352 @@
 block discarded – undo
23 23
 class EED_Core_Rest_Api extends \EED_Module
24 24
 {
25 25
 
26
-    const ee_api_namespace = Domain::API_NAMESPACE;
27
-
28
-    const ee_api_namespace_for_regex = 'ee\/v([^/]*)\/';
29
-
30
-    const saved_routes_option_names = 'ee_core_routes';
31
-
32
-    /**
33
-     * string used in _links response bodies to make them globally unique.
34
-     *
35
-     * @see http://v2.wp-api.org/extending/linking/
36
-     */
37
-    const ee_api_link_namespace = 'https://api.eventespresso.com/';
38
-
39
-    /**
40
-     * @var CalculatedModelFields
41
-     */
42
-    protected static $_field_calculator;
43
-
44
-
45
-    /**
46
-     * @return EED_Core_Rest_Api|EED_Module
47
-     */
48
-    public static function instance()
49
-    {
50
-        self::$_field_calculator = LoaderFactory::getLoader()->load('EventEspresso\core\libraries\rest_api\CalculatedModelFields');
51
-        return parent::get_instance(__CLASS__);
52
-    }
53
-
54
-
55
-    /**
56
-     *    set_hooks - for hooking into EE Core, other modules, etc
57
-     *
58
-     * @access    public
59
-     * @return    void
60
-     */
61
-    public static function set_hooks()
62
-    {
63
-        self::set_hooks_both();
64
-    }
65
-
66
-
67
-    /**
68
-     *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
69
-     *
70
-     * @access    public
71
-     * @return    void
72
-     */
73
-    public static function set_hooks_admin()
74
-    {
75
-        self::set_hooks_both();
76
-    }
77
-
78
-
79
-    public static function set_hooks_both()
80
-    {
81
-        add_action('rest_api_init', array('EED_Core_Rest_Api', 'set_hooks_rest_api'), 5);
82
-        add_action('rest_api_init', array('EED_Core_Rest_Api', 'register_routes'), 10);
83
-        add_filter('rest_route_data', array('EED_Core_Rest_Api', 'hide_old_endpoints'), 10, 2);
84
-        add_filter(
85
-            'rest_index',
86
-            array('EventEspresso\core\libraries\rest_api\controllers\model\Meta', 'filterEeMetadataIntoIndex')
87
-        );
88
-        EED_Core_Rest_Api::invalidate_cached_route_data_on_version_change();
89
-    }
90
-
91
-
92
-    /**
93
-     * sets up hooks which only need to be included as part of REST API requests;
94
-     * other requests like to the frontend or admin etc don't need them
95
-     *
96
-     * @throws \EE_Error
97
-     */
98
-    public static function set_hooks_rest_api()
99
-    {
100
-        // set hooks which account for changes made to the API
101
-        EED_Core_Rest_Api::_set_hooks_for_changes();
102
-    }
103
-
104
-
105
-    /**
106
-     * public wrapper of _set_hooks_for_changes.
107
-     * Loads all the hooks which make requests to old versions of the API
108
-     * appear the same as they always did
109
-     *
110
-     * @throws EE_Error
111
-     */
112
-    public static function set_hooks_for_changes()
113
-    {
114
-        self::_set_hooks_for_changes();
115
-    }
116
-
117
-
118
-    /**
119
-     * Loads all the hooks which make requests to old versions of the API
120
-     * appear the same as they always did
121
-     *
122
-     * @throws EE_Error
123
-     */
124
-    protected static function _set_hooks_for_changes()
125
-    {
126
-        $folder_contents = EEH_File::get_contents_of_folders(array(EE_LIBRARIES . 'rest_api/changes'), false);
127
-        foreach ($folder_contents as $classname_in_namespace => $filepath) {
128
-            // ignore the base parent class
129
-            // and legacy named classes
130
-            if (
131
-                $classname_in_namespace === 'ChangesInBase'
132
-                || strpos($classname_in_namespace, 'Changes_In_') === 0
133
-            ) {
134
-                continue;
135
-            }
136
-            $full_classname = 'EventEspresso\core\libraries\rest_api\changes\\' . $classname_in_namespace;
137
-            if (class_exists($full_classname)) {
138
-                $instance_of_class = new $full_classname();
139
-                if ($instance_of_class instanceof ChangesInBase) {
140
-                    $instance_of_class->setHooks();
141
-                }
142
-            }
143
-        }
144
-    }
145
-
146
-
147
-    /**
148
-     * Filters the WP routes to add our EE-related ones. This takes a bit of time
149
-     * so we actually prefer to only do it when an EE plugin is activated or upgraded
150
-     *
151
-     * @throws \EE_Error
152
-     */
153
-    public static function register_routes()
154
-    {
155
-        foreach (EED_Core_Rest_Api::get_ee_route_data() as $namespace => $relative_routes) {
156
-            foreach ($relative_routes as $relative_route => $data_for_multiple_endpoints) {
157
-                /**
158
-                 * @var array     $data_for_multiple_endpoints numerically indexed array
159
-                 *                                         but can also contain route options like {
160
-                 * @type array    $schema                      {
161
-                 * @type callable $schema_callback
162
-                 * @type array    $callback_args               arguments that will be passed to the callback, after the
163
-                 * WP_REST_Request of course
164
-                 * }
165
-                 * }
166
-                 */
167
-                // when registering routes, register all the endpoints' data at the same time
168
-                $multiple_endpoint_args = array();
169
-                foreach ($data_for_multiple_endpoints as $endpoint_key => $data_for_single_endpoint) {
170
-                    /**
171
-                     * @var array     $data_for_single_endpoint {
172
-                     * @type callable $callback
173
-                     * @type string methods
174
-                     * @type array args
175
-                     * @type array _links
176
-                     * @type array    $callback_args            arguments that will be passed to the callback, after the
177
-                     * WP_REST_Request of course
178
-                     * }
179
-                     */
180
-                    // skip route options
181
-                    if (! is_numeric($endpoint_key)) {
182
-                        continue;
183
-                    }
184
-                    if (! isset($data_for_single_endpoint['callback'], $data_for_single_endpoint['methods'])) {
185
-                        throw new EE_Error(
186
-                            esc_html__(
187
-                            // @codingStandardsIgnoreStart
188
-                                'Endpoint configuration data needs to have entries "callback" (callable) and "methods" (comma-separated list of accepts HTTP methods).',
189
-                                // @codingStandardsIgnoreEnd
190
-                                'event_espresso'
191
-                            )
192
-                        );
193
-                    }
194
-                    $callback = $data_for_single_endpoint['callback'];
195
-                    $single_endpoint_args = array(
196
-                        'methods' => $data_for_single_endpoint['methods'],
197
-                        'args'    => isset($data_for_single_endpoint['args']) ? $data_for_single_endpoint['args']
198
-                            : array(),
199
-                    );
200
-                    if (isset($data_for_single_endpoint['_links'])) {
201
-                        $single_endpoint_args['_links'] = $data_for_single_endpoint['_links'];
202
-                    }
203
-                    if (isset($data_for_single_endpoint['callback_args'])) {
204
-                        $callback_args = $data_for_single_endpoint['callback_args'];
205
-                        $single_endpoint_args['callback'] = function (\WP_REST_Request $request) use (
206
-                            $callback,
207
-                            $callback_args
208
-                        ) {
209
-                            array_unshift($callback_args, $request);
210
-                            return call_user_func_array(
211
-                                $callback,
212
-                                $callback_args
213
-                            );
214
-                        };
215
-                    } else {
216
-                        $single_endpoint_args['callback'] = $data_for_single_endpoint['callback'];
217
-                    }
218
-                    // As of WordPress 5.5, if a permission_callback is not provided,
219
-                    // the REST API will issue a _doing_it_wrong notice.
220
-                    // Since the EE REST API defers capabilities to the db model system,
221
-                    // we will just use the generic WP callback for public endpoints
222
-                    if (! isset($single_endpoint_args['permission_callback'])) {
223
-                        $single_endpoint_args['permission_callback'] = '__return_true';
224
-                    }
225
-                    $multiple_endpoint_args[] = $single_endpoint_args;
226
-                }
227
-                if (isset($data_for_multiple_endpoints['schema'])) {
228
-                    $schema_route_data = $data_for_multiple_endpoints['schema'];
229
-                    $schema_callback = $schema_route_data['schema_callback'];
230
-                    $callback_args = $schema_route_data['callback_args'];
231
-                    $multiple_endpoint_args['schema'] = function () use ($schema_callback, $callback_args) {
232
-                        return call_user_func_array(
233
-                            $schema_callback,
234
-                            $callback_args
235
-                        );
236
-                    };
237
-                }
238
-                register_rest_route(
239
-                    $namespace,
240
-                    $relative_route,
241
-                    $multiple_endpoint_args
242
-                );
243
-            }
244
-        }
245
-    }
246
-
247
-
248
-    /**
249
-     * Checks if there was a version change or something that merits invalidating the cached
250
-     * route data. If so, invalidates the cached route data so that it gets refreshed
251
-     * next time the WP API is used
252
-     */
253
-    public static function invalidate_cached_route_data_on_version_change()
254
-    {
255
-        if (EE_System::instance()->detect_req_type() !== EE_System::req_type_normal) {
256
-            EED_Core_Rest_Api::invalidate_cached_route_data();
257
-        }
258
-        foreach (EE_Registry::instance()->addons as $addon) {
259
-            if ($addon instanceof EE_Addon && $addon->detect_req_type() !== EE_System::req_type_normal) {
260
-                EED_Core_Rest_Api::invalidate_cached_route_data();
261
-            }
262
-        }
263
-    }
264
-
265
-
266
-    /**
267
-     * Removes the cached route data so it will get refreshed next time the WP API is used
268
-     */
269
-    public static function invalidate_cached_route_data()
270
-    {
271
-        // delete the saved EE REST API routes
272
-        foreach (EED_Core_Rest_Api::versions_served() as $version => $hidden) {
273
-            delete_option(EED_Core_Rest_Api::saved_routes_option_names . $version);
274
-        }
275
-    }
276
-
277
-
278
-    /**
279
-     * Gets the EE route data
280
-     *
281
-     * @return array top-level key is the namespace, next-level key is the route and its value is array{
282
-     * @throws \EE_Error
283
-     * @type string|array $callback
284
-     * @type string       $methods
285
-     * @type boolean      $hidden_endpoint
286
-     * }
287
-     */
288
-    public static function get_ee_route_data()
289
-    {
290
-        $ee_routes = array();
291
-        foreach (self::versions_served() as $version => $hidden_endpoints) {
292
-            $ee_routes[ self::ee_api_namespace . $version ] = self::_get_ee_route_data_for_version(
293
-                $version,
294
-                $hidden_endpoints
295
-            );
296
-        }
297
-        return $ee_routes;
298
-    }
299
-
300
-
301
-    /**
302
-     * Gets the EE route data from the wp options if it exists already,
303
-     * otherwise re-generates it and saves it to the option
304
-     *
305
-     * @param string  $version
306
-     * @param boolean $hidden_endpoints
307
-     * @return array
308
-     * @throws \EE_Error
309
-     */
310
-    protected static function _get_ee_route_data_for_version($version, $hidden_endpoints = false)
311
-    {
312
-        $ee_routes = get_option(self::saved_routes_option_names . $version, null);
313
-        if (! $ee_routes || EED_Core_Rest_Api::debugMode()) {
314
-            $ee_routes = self::_save_ee_route_data_for_version($version, $hidden_endpoints);
315
-        }
316
-        return $ee_routes;
317
-    }
318
-
319
-
320
-    /**
321
-     * Saves the EE REST API route data to a wp option and returns it
322
-     *
323
-     * @param string  $version
324
-     * @param boolean $hidden_endpoints
325
-     * @return mixed|null
326
-     * @throws \EE_Error
327
-     */
328
-    protected static function _save_ee_route_data_for_version($version, $hidden_endpoints = false)
329
-    {
330
-        $instance = self::instance();
331
-        $routes = apply_filters(
332
-            'EED_Core_Rest_Api__save_ee_route_data_for_version__routes',
333
-            array_replace_recursive(
334
-                $instance->_get_config_route_data_for_version($version, $hidden_endpoints),
335
-                $instance->_get_meta_route_data_for_version($version, $hidden_endpoints),
336
-                $instance->_get_model_route_data_for_version($version, $hidden_endpoints),
337
-                $instance->_get_rpc_route_data_for_version($version, $hidden_endpoints)
338
-            )
339
-        );
340
-        $option_name = self::saved_routes_option_names . $version;
341
-        if (get_option($option_name)) {
342
-            update_option($option_name, $routes, true);
343
-        } else {
344
-            add_option($option_name, $routes, null, 'no');
345
-        }
346
-        return $routes;
347
-    }
348
-
349
-
350
-    /**
351
-     * Calculates all the EE routes and saves it to a WordPress option so we don't
352
-     * need to calculate it on every request
353
-     *
354
-     * @deprecated since version 4.9.1
355
-     * @return void
356
-     */
357
-    public static function save_ee_routes()
358
-    {
359
-        if (EE_Maintenance_Mode::instance()->models_can_query()) {
360
-            $instance = self::instance();
361
-            $routes = apply_filters(
362
-                'EED_Core_Rest_Api__save_ee_routes__routes',
363
-                array_replace_recursive(
364
-                    $instance->_register_config_routes(),
365
-                    $instance->_register_meta_routes(),
366
-                    $instance->_register_model_routes(),
367
-                    $instance->_register_rpc_routes()
368
-                )
369
-            );
370
-            update_option(self::saved_routes_option_names, $routes, true);
371
-        }
372
-    }
373
-
374
-
375
-    /**
376
-     * Gets all the route information relating to EE models
377
-     *
378
-     * @return array @see get_ee_route_data
379
-     * @deprecated since version 4.9.1
380
-     */
381
-    protected function _register_model_routes()
382
-    {
383
-        $model_routes = array();
384
-        foreach (self::versions_served() as $version => $hidden_endpoint) {
385
-            $model_routes[ EED_Core_Rest_Api::ee_api_namespace
386
-                           . $version ] = $this->_get_config_route_data_for_version($version, $hidden_endpoint);
387
-        }
388
-        return $model_routes;
389
-    }
390
-
391
-
392
-    /**
393
-     * Decides whether or not to add write endpoints for this model.
394
-     *
395
-     * Currently, this defaults to exclude all global tables and models
396
-     * which would allow inserting WP core data (we don't want to duplicate
397
-     * what WP API does, as it's unnecessary, extra work, and potentially extra bugs)
398
-     *
399
-     * @param EEM_Base $model
400
-     * @return bool
401
-     */
402
-    public static function should_have_write_endpoints(EEM_Base $model)
403
-    {
404
-        if ($model->is_wp_core_model()) {
405
-            return false;
406
-        }
407
-        foreach ($model->get_tables() as $table) {
408
-            if ($table->is_global()) {
409
-                return false;
410
-            }
411
-        }
412
-        return true;
413
-    }
414
-
415
-
416
-    /**
417
-     * Gets the names of all models which should have plural routes (eg `ee/v4.8.36/events`)
418
-     * in this versioned namespace of EE4
419
-     *
420
-     * @param $version
421
-     * @return array keys are model names (eg 'Event') and values ar either classnames (eg 'EEM_Event')
422
-     */
423
-    public static function model_names_with_plural_routes($version)
424
-    {
425
-        $model_version_info = new ModelVersionInfo($version);
426
-        $models_to_register = $model_version_info->modelsForRequestedVersion();
427
-        // let's not bother having endpoints for extra metas
428
-        unset(
429
-            $models_to_register['Extra_Meta'],
430
-            $models_to_register['Extra_Join'],
431
-            $models_to_register['Post_Meta']
432
-        );
433
-        return apply_filters(
434
-            'FHEE__EED_Core_REST_API___register_model_routes',
435
-            $models_to_register
436
-        );
437
-    }
438
-
439
-
440
-    /**
441
-     * Gets the route data for EE models in the specified version
442
-     *
443
-     * @param string  $version
444
-     * @param boolean $hidden_endpoint
445
-     * @return array
446
-     * @throws EE_Error
447
-     */
448
-    protected function _get_model_route_data_for_version($version, $hidden_endpoint = false)
449
-    {
450
-        $model_routes = array();
451
-        $model_version_info = new ModelVersionInfo($version);
452
-        foreach (EED_Core_Rest_Api::model_names_with_plural_routes($version) as $model_name => $model_classname) {
453
-            $model = \EE_Registry::instance()->load_model($model_name);
454
-            // if this isn't a valid model then let's skip iterate to the next item in the loop.
455
-            if (! $model instanceof EEM_Base) {
456
-                continue;
457
-            }
458
-            // yes we could just register one route for ALL models, but then they wouldn't show up in the index
459
-            $plural_model_route = EED_Core_Rest_Api::get_collection_route($model);
460
-            $singular_model_route = EED_Core_Rest_Api::get_entity_route($model, '(?P<id>[^\/]+)');
461
-            $model_routes[ $plural_model_route ] = array(
462
-                array(
463
-                    'callback'        => array(
464
-                        'EventEspresso\core\libraries\rest_api\controllers\model\Read',
465
-                        'handleRequestGetAll',
466
-                    ),
467
-                    'callback_args'   => array($version, $model_name),
468
-                    'methods'         => WP_REST_Server::READABLE,
469
-                    'hidden_endpoint' => $hidden_endpoint,
470
-                    'args'            => $this->_get_read_query_params($model, $version),
471
-                    '_links'          => array(
472
-                        'self' => rest_url(EED_Core_Rest_Api::ee_api_namespace . $version . $singular_model_route),
473
-                    ),
474
-                ),
475
-                'schema' => array(
476
-                    'schema_callback' => array(
477
-                        'EventEspresso\core\libraries\rest_api\controllers\model\Read',
478
-                        'handleSchemaRequest',
479
-                    ),
480
-                    'callback_args'   => array($version, $model_name),
481
-                ),
482
-            );
483
-            $model_routes[ $singular_model_route ] = array(
484
-                array(
485
-                    'callback'        => array(
486
-                        'EventEspresso\core\libraries\rest_api\controllers\model\Read',
487
-                        'handleRequestGetOne',
488
-                    ),
489
-                    'callback_args'   => array($version, $model_name),
490
-                    'methods'         => WP_REST_Server::READABLE,
491
-                    'hidden_endpoint' => $hidden_endpoint,
492
-                    'args'            => $this->_get_response_selection_query_params($model, $version, true),
493
-                ),
494
-            );
495
-            if (
496
-                apply_filters(
497
-                    'FHEE__EED_Core_Rest_Api___get_model_route_data_for_version__add_write_endpoints',
498
-                    EED_Core_Rest_Api::should_have_write_endpoints($model),
499
-                    $model
500
-                )
501
-            ) {
502
-                $model_routes[ $plural_model_route ][] = array(
503
-                    'callback'        => array(
504
-                        'EventEspresso\core\libraries\rest_api\controllers\model\Write',
505
-                        'handleRequestInsert',
506
-                    ),
507
-                    'callback_args'   => array($version, $model_name),
508
-                    'methods'         => WP_REST_Server::CREATABLE,
509
-                    'hidden_endpoint' => $hidden_endpoint,
510
-                    'args'            => $this->_get_write_params($model_name, $model_version_info, true),
511
-                );
512
-                $model_routes[ $singular_model_route ] = array_merge(
513
-                    $model_routes[ $singular_model_route ],
514
-                    array(
515
-                        array(
516
-                            'callback'        => array(
517
-                                'EventEspresso\core\libraries\rest_api\controllers\model\Write',
518
-                                'handleRequestUpdate',
519
-                            ),
520
-                            'callback_args'   => array($version, $model_name),
521
-                            'methods'         => WP_REST_Server::EDITABLE,
522
-                            'hidden_endpoint' => $hidden_endpoint,
523
-                            'args'            => $this->_get_write_params($model_name, $model_version_info),
524
-                        ),
525
-                        array(
526
-                            'callback'        => array(
527
-                                'EventEspresso\core\libraries\rest_api\controllers\model\Write',
528
-                                'handleRequestDelete',
529
-                            ),
530
-                            'callback_args'   => array($version, $model_name),
531
-                            'methods'         => WP_REST_Server::DELETABLE,
532
-                            'hidden_endpoint' => $hidden_endpoint,
533
-                            'args'            => $this->_get_delete_query_params($model, $version),
534
-                        ),
535
-                    )
536
-                );
537
-            }
538
-            foreach ($model->relation_settings() as $relation_name => $relation_obj) {
539
-                $related_route = EED_Core_Rest_Api::get_relation_route_via(
540
-                    $model,
541
-                    '(?P<id>[^\/]+)',
542
-                    $relation_obj
543
-                );
544
-                $model_routes[ $related_route ] = array(
545
-                    array(
546
-                        'callback'        => array(
547
-                            'EventEspresso\core\libraries\rest_api\controllers\model\Read',
548
-                            'handleRequestGetRelated',
549
-                        ),
550
-                        'callback_args'   => array($version, $model_name, $relation_name),
551
-                        'methods'         => WP_REST_Server::READABLE,
552
-                        'hidden_endpoint' => $hidden_endpoint,
553
-                        'args'            => $this->_get_read_query_params($relation_obj->get_other_model(), $version),
554
-                    ),
555
-                );
556
-
557
-                $related_write_route = $related_route . '/' . '(?P<related_id>[^\/]+)';
558
-                $model_routes[ $related_write_route ] = array(
559
-                    array(
560
-                        'callback'        => array(
561
-                            'EventEspresso\core\libraries\rest_api\controllers\model\Write',
562
-                            'handleRequestAddRelation',
563
-                        ),
564
-                        'callback_args'   => array($version, $model_name, $relation_name),
565
-                        'methods'         => WP_REST_Server::EDITABLE,
566
-                        'hidden_endpoint' => $hidden_endpoint,
567
-                        'args'            => $this->_get_add_relation_query_params($model, $relation_obj->get_other_model(), $version)
568
-                    ),
569
-                    array(
570
-                        'callback'        => array(
571
-                            'EventEspresso\core\libraries\rest_api\controllers\model\Write',
572
-                            'handleRequestRemoveRelation',
573
-                        ),
574
-                        'callback_args'   => array($version, $model_name, $relation_name),
575
-                        'methods'         => WP_REST_Server::DELETABLE,
576
-                        'hidden_endpoint' => $hidden_endpoint,
577
-                        'args'            => array()
578
-                    ),
579
-                );
580
-            }
581
-        }
582
-        return $model_routes;
583
-    }
584
-
585
-
586
-    /**
587
-     * Gets the relative URI to a model's REST API plural route, after the EE4 versioned namespace,
588
-     * excluding the preceding slash.
589
-     * Eg you pass get_plural_route_to('Event') = 'events'
590
-     *
591
-     * @param EEM_Base $model
592
-     * @return string
593
-     */
594
-    public static function get_collection_route(EEM_Base $model)
595
-    {
596
-        return EEH_Inflector::pluralize_and_lower($model->get_this_model_name());
597
-    }
598
-
599
-
600
-    /**
601
-     * Gets the relative URI to a model's REST API singular route, after the EE4 versioned namespace,
602
-     * excluding the preceding slash.
603
-     * Eg you pass get_plural_route_to('Event', 12) = 'events/12'
604
-     *
605
-     * @param EEM_Base $model eg Event or Venue
606
-     * @param string   $id
607
-     * @return string
608
-     */
609
-    public static function get_entity_route($model, $id)
610
-    {
611
-        return EED_Core_Rest_Api::get_collection_route($model) . '/' . $id;
612
-    }
613
-
614
-
615
-    /**
616
-     * Gets the relative URI to a model's REST API singular route, after the EE4 versioned namespace,
617
-     * excluding the preceding slash.
618
-     * Eg you pass get_plural_route_to('Event', 12) = 'events/12'
619
-     *
620
-     * @param EEM_Base               $model eg Event or Venue
621
-     * @param string                 $id
622
-     * @param EE_Model_Relation_Base $relation_obj
623
-     * @return string
624
-     */
625
-    public static function get_relation_route_via(EEM_Base $model, $id, EE_Model_Relation_Base $relation_obj)
626
-    {
627
-        $related_model_name_endpoint_part = ModelRead::getRelatedEntityName(
628
-            $relation_obj->get_other_model()->get_this_model_name(),
629
-            $relation_obj
630
-        );
631
-        return EED_Core_Rest_Api::get_entity_route($model, $id) . '/' . $related_model_name_endpoint_part;
632
-    }
633
-
634
-
635
-    /**
636
-     * Adds onto the $relative_route the EE4 REST API versioned namespace.
637
-     * Eg if given '4.8.36' and 'events', will return 'ee/v4.8.36/events'
638
-     *
639
-     * @param string $relative_route
640
-     * @param string $version
641
-     * @return string
642
-     */
643
-    public static function get_versioned_route_to($relative_route, $version = '4.8.36')
644
-    {
645
-        return '/' . EED_Core_Rest_Api::ee_api_namespace . $version . '/' . $relative_route;
646
-    }
647
-
648
-
649
-    /**
650
-     * Adds all the RPC-style routes (remote procedure call-like routes, ie
651
-     * routes that don't conform to the traditional REST CRUD-style).
652
-     *
653
-     * @deprecated since 4.9.1
654
-     */
655
-    protected function _register_rpc_routes()
656
-    {
657
-        $routes = array();
658
-        foreach (self::versions_served() as $version => $hidden_endpoint) {
659
-            $routes[ self::ee_api_namespace . $version ] = $this->_get_rpc_route_data_for_version(
660
-                $version,
661
-                $hidden_endpoint
662
-            );
663
-        }
664
-        return $routes;
665
-    }
666
-
667
-
668
-    /**
669
-     * @param string  $version
670
-     * @param boolean $hidden_endpoint
671
-     * @return array
672
-     */
673
-    protected function _get_rpc_route_data_for_version($version, $hidden_endpoint = false)
674
-    {
675
-        $this_versions_routes = array();
676
-        // checkin endpoint
677
-        $this_versions_routes['registrations/(?P<REG_ID>\d+)/toggle_checkin_for_datetime/(?P<DTT_ID>\d+)'] = array(
678
-            array(
679
-                'callback'        => array(
680
-                    'EventEspresso\core\libraries\rest_api\controllers\rpc\Checkin',
681
-                    'handleRequestToggleCheckin',
682
-                ),
683
-                'methods'         => WP_REST_Server::CREATABLE,
684
-                'hidden_endpoint' => $hidden_endpoint,
685
-                'args'            => array(
686
-                    'force' => array(
687
-                        'required'    => false,
688
-                        'default'     => false,
689
-                        'description' => esc_html__(
690
-                        // @codingStandardsIgnoreStart
691
-                            'Whether to force toggle checkin, or to verify the registration status and allowed ticket uses',
692
-                            // @codingStandardsIgnoreEnd
693
-                            'event_espresso'
694
-                        ),
695
-                    ),
696
-                ),
697
-                'callback_args'   => array($version),
698
-            ),
699
-        );
700
-        return apply_filters(
701
-            'FHEE__EED_Core_Rest_Api___register_rpc_routes__this_versions_routes',
702
-            $this_versions_routes,
703
-            $version,
704
-            $hidden_endpoint
705
-        );
706
-    }
707
-
708
-
709
-    /**
710
-     * Gets the query params that can be used when request one or many
711
-     *
712
-     * @param EEM_Base $model
713
-     * @param string   $version
714
-     * @return array
715
-     */
716
-    protected function _get_response_selection_query_params(\EEM_Base $model, $version, $single_only = false)
717
-    {
718
-        $query_params = array(
719
-            'include'   => array(
720
-                'required' => false,
721
-                'default'  => '*',
722
-                'type'     => 'string',
723
-            ),
724
-            'calculate' => array(
725
-                'required'          => false,
726
-                'default'           => '',
727
-                'enum'              => self::$_field_calculator->retrieveCalculatedFieldsForModel($model),
728
-                'type'              => 'string',
729
-                // because we accept a CSV'd list of the enumerated strings, WP core validation and sanitization
730
-                // freaks out. We'll just validate this argument while handling the request
731
-                'validate_callback' => null,
732
-                'sanitize_callback' => null,
733
-            ),
734
-            'password' => array(
735
-                'required' => false,
736
-                'default' => '',
737
-                'type' => 'string'
738
-            )
739
-        );
740
-        return apply_filters(
741
-            'FHEE__EED_Core_Rest_Api___get_response_selection_query_params',
742
-            $query_params,
743
-            $model,
744
-            $version
745
-        );
746
-    }
747
-
748
-
749
-    /**
750
-     * Gets the parameters acceptable for delete requests
751
-     *
752
-     * @param \EEM_Base $model
753
-     * @param string    $version
754
-     * @return array
755
-     */
756
-    protected function _get_delete_query_params(\EEM_Base $model, $version)
757
-    {
758
-        $params_for_delete = array(
759
-            'allow_blocking' => array(
760
-                'required' => false,
761
-                'default'  => true,
762
-                'type'     => 'boolean',
763
-            ),
764
-        );
765
-        $params_for_delete['force'] = array(
766
-            'required' => false,
767
-            'default'  => false,
768
-            'type'     => 'boolean',
769
-        );
770
-        return apply_filters(
771
-            'FHEE__EED_Core_Rest_Api___get_delete_query_params',
772
-            $params_for_delete,
773
-            $model,
774
-            $version
775
-        );
776
-    }
777
-
778
-    protected function _get_add_relation_query_params(\EEM_Base $source_model, \EEM_Base $related_model, $version)
779
-    {
780
-        // if they're related through a HABTM relation, check for any non-FKs
781
-        $all_relation_settings = $source_model->relation_settings();
782
-        $relation_settings = $all_relation_settings[ $related_model->get_this_model_name() ];
783
-        $params = array();
784
-        if ($relation_settings instanceof EE_HABTM_Relation && $relation_settings->hasNonKeyFields()) {
785
-            foreach ($relation_settings->getNonKeyFields() as $field) {
786
-                /* @var $field EE_Model_Field_Base */
787
-                $params[ $field->get_name() ] = array(
788
-                    'required' => ! $field->is_nullable(),
789
-                    'default' => ModelDataTranslator::prepareFieldValueForJson($field, $field->get_default_value(), $version),
790
-                    'type' => $field->getSchemaType(),
791
-                    'validate_callbaack' => null,
792
-                    'sanitize_callback' => null
793
-                );
794
-            }
795
-        }
796
-        return $params;
797
-    }
798
-
799
-
800
-    /**
801
-     * Gets info about reading query params that are acceptable
802
-     *
803
-     * @param \EEM_Base $model eg 'Event' or 'Venue'
804
-     * @param  string   $version
805
-     * @return array    describing the args acceptable when querying this model
806
-     * @throws EE_Error
807
-     */
808
-    protected function _get_read_query_params(\EEM_Base $model, $version)
809
-    {
810
-        $default_orderby = array();
811
-        foreach ($model->get_combined_primary_key_fields() as $key_field) {
812
-            $default_orderby[ $key_field->get_name() ] = 'ASC';
813
-        }
814
-        return array_merge(
815
-            $this->_get_response_selection_query_params($model, $version),
816
-            array(
817
-                'where'    => array(
818
-                    'required'          => false,
819
-                    'default'           => array(),
820
-                    'type'              => 'object',
821
-                    // because we accept an almost infinite list of possible where conditions, WP
822
-                    // core validation and sanitization freaks out. We'll just validate this argument
823
-                    // while handling the request
824
-                    'validate_callback' => null,
825
-                    'sanitize_callback' => null,
826
-                ),
827
-                'limit'    => array(
828
-                    'required'          => false,
829
-                    'default'           => EED_Core_Rest_Api::get_default_query_limit(),
830
-                    'type'              => array(
831
-                        'array',
832
-                        'string',
833
-                        'integer',
834
-                    ),
835
-                    // because we accept a variety of types, WP core validation and sanitization
836
-                    // freaks out. We'll just validate this argument while handling the request
837
-                    'validate_callback' => null,
838
-                    'sanitize_callback' => null,
839
-                ),
840
-                'order_by' => array(
841
-                    'required'          => false,
842
-                    'default'           => $default_orderby,
843
-                    'type'              => array(
844
-                        'object',
845
-                        'string',
846
-                    ),// because we accept a variety of types, WP core validation and sanitization
847
-                    // freaks out. We'll just validate this argument while handling the request
848
-                    'validate_callback' => null,
849
-                    'sanitize_callback' => null,
850
-                ),
851
-                'group_by' => array(
852
-                    'required'          => false,
853
-                    'default'           => null,
854
-                    'type'              => array(
855
-                        'object',
856
-                        'string',
857
-                    ),
858
-                    // because we accept  an almost infinite list of possible groupings,
859
-                    // WP core validation and sanitization
860
-                    // freaks out. We'll just validate this argument while handling the request
861
-                    'validate_callback' => null,
862
-                    'sanitize_callback' => null,
863
-                ),
864
-                'having'   => array(
865
-                    'required'          => false,
866
-                    'default'           => null,
867
-                    'type'              => 'object',
868
-                    // because we accept an almost infinite list of possible where conditions, WP
869
-                    // core validation and sanitization freaks out. We'll just validate this argument
870
-                    // while handling the request
871
-                    'validate_callback' => null,
872
-                    'sanitize_callback' => null,
873
-                ),
874
-                'caps'     => array(
875
-                    'required' => false,
876
-                    'default'  => EEM_Base::caps_read,
877
-                    'type'     => 'string',
878
-                    'enum'     => array(
879
-                        EEM_Base::caps_read,
880
-                        EEM_Base::caps_read_admin,
881
-                        EEM_Base::caps_edit,
882
-                        EEM_Base::caps_delete,
883
-                    ),
884
-                ),
885
-            )
886
-        );
887
-    }
888
-
889
-
890
-    /**
891
-     * Gets parameter information for a model regarding writing data
892
-     *
893
-     * @param string           $model_name
894
-     * @param ModelVersionInfo $model_version_info
895
-     * @param boolean          $create                                       whether this is for request to create (in
896
-     *                                                                       which case we need all required params) or
897
-     *                                                                       just to update (in which case we don't
898
-     *                                                                       need those on every request)
899
-     * @return array
900
-     */
901
-    protected function _get_write_params(
902
-        $model_name,
903
-        ModelVersionInfo $model_version_info,
904
-        $create = false
905
-    ) {
906
-        $model = EE_Registry::instance()->load_model($model_name);
907
-        $fields = $model_version_info->fieldsOnModelInThisVersion($model);
908
-        $args_info = array();
909
-        foreach ($fields as $field_name => $field_obj) {
910
-            if ($field_obj->is_auto_increment()) {
911
-                // totally ignore auto increment IDs
912
-                continue;
913
-            }
914
-            $arg_info = $field_obj->getSchema();
915
-            $required = $create && ! $field_obj->is_nullable() && $field_obj->get_default_value() === null;
916
-            $arg_info['required'] = $required;
917
-            // remove the read-only flag. If it were read-only we wouldn't list it as an argument while writing, right?
918
-            unset($arg_info['readonly']);
919
-            $schema_properties = $field_obj->getSchemaProperties();
920
-            if (
921
-                isset($schema_properties['raw'])
922
-                && $field_obj->getSchemaType() === 'object'
923
-            ) {
924
-                // if there's a "raw" form of this argument, use those properties instead
925
-                $arg_info = array_replace(
926
-                    $arg_info,
927
-                    $schema_properties['raw']
928
-                );
929
-            }
930
-            $arg_info['default'] = ModelDataTranslator::prepareFieldValueForJson(
931
-                $field_obj,
932
-                $field_obj->get_default_value(),
933
-                $model_version_info->requestedVersion()
934
-            );
935
-            // we do our own validation and sanitization within the controller
936
-            if (function_exists('rest_validate_value_from_schema')) {
937
-                $sanitize_callback = array(
938
-                    'EED_Core_Rest_Api',
939
-                    'default_sanitize_callback',
940
-                );
941
-            } else {
942
-                $sanitize_callback = null;
943
-            }
944
-            $arg_info['sanitize_callback'] = $sanitize_callback;
945
-            $args_info[ $field_name ] = $arg_info;
946
-            if ($field_obj instanceof EE_Datetime_Field) {
947
-                $gmt_arg_info = $arg_info;
948
-                $gmt_arg_info['description'] = sprintf(
949
-                    esc_html__(
950
-                        '%1$s - the value for this field in UTC. Ignored if %2$s is provided.',
951
-                        'event_espresso'
952
-                    ),
953
-                    $field_obj->get_nicename(),
954
-                    $field_name
955
-                );
956
-                $args_info[ $field_name . '_gmt' ] = $gmt_arg_info;
957
-            }
958
-        }
959
-        return $args_info;
960
-    }
961
-
962
-
963
-    /**
964
-     * Replacement for WP API's 'rest_parse_request_arg'.
965
-     * If the value is blank but not required, don't bother validating it.
966
-     * Also, it uses our email validation instead of WP API's default.
967
-     *
968
-     * @param                 $value
969
-     * @param WP_REST_Request $request
970
-     * @param                 $param
971
-     * @return bool|true|WP_Error
972
-     * @throws InvalidArgumentException
973
-     * @throws InvalidInterfaceException
974
-     * @throws InvalidDataTypeException
975
-     */
976
-    public static function default_sanitize_callback($value, WP_REST_Request $request, $param)
977
-    {
978
-        $attributes = $request->get_attributes();
979
-        if (
980
-            ! isset($attributes['args'][ $param ])
981
-            || ! is_array($attributes['args'][ $param ])
982
-        ) {
983
-            $validation_result = true;
984
-        } else {
985
-            $args = $attributes['args'][ $param ];
986
-            if (
987
-                (
988
-                    $value === ''
989
-                    || $value === null
990
-                )
991
-                && (! isset($args['required'])
992
-                    || $args['required'] === false
993
-                )
994
-            ) {
995
-                // not required and not provided? that's cool
996
-                $validation_result = true;
997
-            } elseif (
998
-                isset($args['format'])
999
-                      && $args['format'] === 'email'
1000
-            ) {
1001
-                $validation_result = true;
1002
-                if (! self::_validate_email($value)) {
1003
-                    $validation_result = new WP_Error(
1004
-                        'rest_invalid_param',
1005
-                        esc_html__(
1006
-                            'The email address is not valid or does not exist.',
1007
-                            'event_espresso'
1008
-                        )
1009
-                    );
1010
-                }
1011
-            } else {
1012
-                $validation_result = rest_validate_value_from_schema($value, $args, $param);
1013
-            }
1014
-        }
1015
-        if (is_wp_error($validation_result)) {
1016
-            return $validation_result;
1017
-        }
1018
-        return rest_sanitize_request_arg($value, $request, $param);
1019
-    }
1020
-
1021
-
1022
-    /**
1023
-     * Returns whether or not this email address is valid. Copied from EE_Email_Validation_Strategy::_validate_email()
1024
-     *
1025
-     * @param $email
1026
-     * @return bool
1027
-     * @throws InvalidArgumentException
1028
-     * @throws InvalidInterfaceException
1029
-     * @throws InvalidDataTypeException
1030
-     */
1031
-    protected static function _validate_email($email)
1032
-    {
1033
-        try {
1034
-            EmailAddressFactory::create($email);
1035
-            return true;
1036
-        } catch (EmailValidationException $e) {
1037
-            return false;
1038
-        }
1039
-    }
1040
-
1041
-
1042
-    /**
1043
-     * Gets routes for the config
1044
-     *
1045
-     * @return array @see _register_model_routes
1046
-     * @deprecated since version 4.9.1
1047
-     */
1048
-    protected function _register_config_routes()
1049
-    {
1050
-        $config_routes = array();
1051
-        foreach (self::versions_served() as $version => $hidden_endpoint) {
1052
-            $config_routes[ self::ee_api_namespace . $version ] = $this->_get_config_route_data_for_version(
1053
-                $version,
1054
-                $hidden_endpoint
1055
-            );
1056
-        }
1057
-        return $config_routes;
1058
-    }
1059
-
1060
-
1061
-    /**
1062
-     * Gets routes for the config for the specified version
1063
-     *
1064
-     * @param string  $version
1065
-     * @param boolean $hidden_endpoint
1066
-     * @return array
1067
-     */
1068
-    protected function _get_config_route_data_for_version($version, $hidden_endpoint)
1069
-    {
1070
-        return array(
1071
-            'config'    => array(
1072
-                array(
1073
-                    'callback'        => array(
1074
-                        'EventEspresso\core\libraries\rest_api\controllers\config\Read',
1075
-                        'handleRequest',
1076
-                    ),
1077
-                    'methods'         => WP_REST_Server::READABLE,
1078
-                    'hidden_endpoint' => $hidden_endpoint,
1079
-                    'callback_args'   => array($version),
1080
-                ),
1081
-            ),
1082
-            'site_info' => array(
1083
-                array(
1084
-                    'callback'        => array(
1085
-                        'EventEspresso\core\libraries\rest_api\controllers\config\Read',
1086
-                        'handleRequestSiteInfo',
1087
-                    ),
1088
-                    'methods'         => WP_REST_Server::READABLE,
1089
-                    'hidden_endpoint' => $hidden_endpoint,
1090
-                    'callback_args'   => array($version),
1091
-                ),
1092
-            ),
1093
-        );
1094
-    }
1095
-
1096
-
1097
-    /**
1098
-     * Gets the meta info routes
1099
-     *
1100
-     * @return array @see _register_model_routes
1101
-     * @deprecated since version 4.9.1
1102
-     */
1103
-    protected function _register_meta_routes()
1104
-    {
1105
-        $meta_routes = array();
1106
-        foreach (self::versions_served() as $version => $hidden_endpoint) {
1107
-            $meta_routes[ self::ee_api_namespace . $version ] = $this->_get_meta_route_data_for_version(
1108
-                $version,
1109
-                $hidden_endpoint
1110
-            );
1111
-        }
1112
-        return $meta_routes;
1113
-    }
1114
-
1115
-
1116
-    /**
1117
-     * @param string  $version
1118
-     * @param boolean $hidden_endpoint
1119
-     * @return array
1120
-     */
1121
-    protected function _get_meta_route_data_for_version($version, $hidden_endpoint = false)
1122
-    {
1123
-        return array(
1124
-            'resources' => array(
1125
-                array(
1126
-                    'callback'        => array(
1127
-                        'EventEspresso\core\libraries\rest_api\controllers\model\Meta',
1128
-                        'handleRequestModelsMeta',
1129
-                    ),
1130
-                    'methods'         => WP_REST_Server::READABLE,
1131
-                    'hidden_endpoint' => $hidden_endpoint,
1132
-                    'callback_args'   => array($version),
1133
-                ),
1134
-            ),
1135
-        );
1136
-    }
1137
-
1138
-
1139
-    /**
1140
-     * Tries to hide old 4.6 endpoints from the
1141
-     *
1142
-     * @param array $route_data
1143
-     * @return array
1144
-     * @throws \EE_Error
1145
-     */
1146
-    public static function hide_old_endpoints($route_data)
1147
-    {
1148
-        // allow API clients to override which endpoints get hidden, in case
1149
-        // they want to discover particular endpoints
1150
-        // also, we don't have access to the request so we have to just grab it from the superglobal
1151
-        $force_show_ee_namespace = ltrim(
1152
-            EED_Core_Rest_Api::getRequest()->getRequestParam('force_show_ee_namespace'),
1153
-            '/'
1154
-        );
1155
-        foreach (EED_Core_Rest_Api::get_ee_route_data() as $namespace => $relative_urls) {
1156
-            foreach ($relative_urls as $resource_name => $endpoints) {
1157
-                foreach ($endpoints as $key => $endpoint) {
1158
-                    // skip schema and other route options
1159
-                    if (! is_numeric($key)) {
1160
-                        continue;
1161
-                    }
1162
-                    // by default, hide "hidden_endpoint"s, unless the request indicates
1163
-                    // to $force_show_ee_namespace, in which case only show that one
1164
-                    // namespace's endpoints (and hide all others)
1165
-                    if (
1166
-                        ($force_show_ee_namespace !== '' && $force_show_ee_namespace !== $namespace)
1167
-                        || ($endpoint['hidden_endpoint'] && $force_show_ee_namespace === '')
1168
-                    ) {
1169
-                        $full_route = '/' . ltrim($namespace, '/');
1170
-                        $full_route .= '/' . ltrim($resource_name, '/');
1171
-                        unset($route_data[ $full_route ]);
1172
-                    }
1173
-                }
1174
-            }
1175
-        }
1176
-        return $route_data;
1177
-    }
1178
-
1179
-
1180
-    /**
1181
-     * Returns an array describing which versions of core support serving requests for.
1182
-     * Keys are core versions' major and minor version, and values are the
1183
-     * LOWEST requested version they can serve. Eg, 4.7 can serve requests for 4.6-like
1184
-     * data by just removing a few models and fields from the responses. However, 4.15 might remove
1185
-     * the answers table entirely, in which case it would be very difficult for
1186
-     * it to serve 4.6-style responses.
1187
-     * Versions of core that are missing from this array are unknowns.
1188
-     * previous ver
1189
-     *
1190
-     * @return array
1191
-     */
1192
-    public static function version_compatibilities()
1193
-    {
1194
-        return apply_filters(
1195
-            'FHEE__EED_Core_REST_API__version_compatibilities',
1196
-            array(
1197
-                '4.8.29' => '4.8.29',
1198
-                '4.8.33' => '4.8.29',
1199
-                '4.8.34' => '4.8.29',
1200
-                '4.8.36' => '4.8.29',
1201
-            )
1202
-        );
1203
-    }
1204
-
1205
-
1206
-    /**
1207
-     * Gets the latest API version served. Eg if there
1208
-     * are two versions served of the API, 4.8.29 and 4.8.32, and
1209
-     * we are on core version 4.8.34, it will return the string "4.8.32"
1210
-     *
1211
-     * @return string
1212
-     */
1213
-    public static function latest_rest_api_version()
1214
-    {
1215
-        $versions_served = \EED_Core_Rest_Api::versions_served();
1216
-        $versions_served_keys = array_keys($versions_served);
1217
-        return end($versions_served_keys);
1218
-    }
1219
-
1220
-
1221
-    /**
1222
-     * Using EED_Core_Rest_Api::version_compatibilities(), determines what version of
1223
-     * EE the API can serve requests for. Eg, if we are on 4.15 of core, and
1224
-     * we can serve requests from 4.12 or later, this will return array( '4.12', '4.13', '4.14', '4.15' ).
1225
-     * We also indicate whether or not this version should be put in the index or not
1226
-     *
1227
-     * @return array keys are API version numbers (just major and minor numbers), and values
1228
-     * are whether or not they should be hidden
1229
-     */
1230
-    public static function versions_served()
1231
-    {
1232
-        $versions_served = array();
1233
-        $possibly_served_versions = EED_Core_Rest_Api::version_compatibilities();
1234
-        $lowest_compatible_version = end($possibly_served_versions);
1235
-        reset($possibly_served_versions);
1236
-        $versions_served_historically = array_keys($possibly_served_versions);
1237
-        $latest_version = end($versions_served_historically);
1238
-        reset($versions_served_historically);
1239
-        // for each version of core we have ever served:
1240
-        foreach ($versions_served_historically as $key_versioned_endpoint) {
1241
-            // if it's not above the current core version, and it's compatible with the current version of core
1242
-
1243
-            if ($key_versioned_endpoint === $latest_version) {
1244
-                // don't hide the latest version in the index
1245
-                $versions_served[ $key_versioned_endpoint ] = false;
1246
-            } elseif (
1247
-                version_compare($key_versioned_endpoint, $lowest_compatible_version, '>=')
1248
-                && version_compare($key_versioned_endpoint, EED_Core_Rest_Api::core_version(), '<')
1249
-            ) {
1250
-                // include, but hide, previous versions which are still supported
1251
-                $versions_served[ $key_versioned_endpoint ] = true;
1252
-            } elseif (
1253
-                apply_filters(
1254
-                    'FHEE__EED_Core_Rest_Api__versions_served__include_incompatible_versions',
1255
-                    false,
1256
-                    $possibly_served_versions
1257
-                )
1258
-            ) {
1259
-                // if a version is no longer supported, don't include it in index or list of versions served
1260
-                $versions_served[ $key_versioned_endpoint ] = true;
1261
-            }
1262
-        }
1263
-        return $versions_served;
1264
-    }
1265
-
1266
-
1267
-    /**
1268
-     * Gets the major and minor version of EE core's version string
1269
-     *
1270
-     * @return string
1271
-     */
1272
-    public static function core_version()
1273
-    {
1274
-        return apply_filters(
1275
-            'FHEE__EED_Core_REST_API__core_version',
1276
-            implode(
1277
-                '.',
1278
-                array_slice(
1279
-                    explode(
1280
-                        '.',
1281
-                        espresso_version()
1282
-                    ),
1283
-                    0,
1284
-                    3
1285
-                )
1286
-            )
1287
-        );
1288
-    }
1289
-
1290
-
1291
-    /**
1292
-     * Gets the default limit that should be used when querying for resources
1293
-     *
1294
-     * @return int
1295
-     */
1296
-    public static function get_default_query_limit()
1297
-    {
1298
-        // we actually don't use a const because we want folks to always use
1299
-        // this method, not the const directly
1300
-        return apply_filters(
1301
-            'FHEE__EED_Core_Rest_Api__get_default_query_limit',
1302
-            50
1303
-        );
1304
-    }
1305
-
1306
-
1307
-    /**
1308
-     *
1309
-     * @param string $version api version string (i.e. '4.8.36')
1310
-     * @return array
1311
-     */
1312
-    public static function getCollectionRoutesIndexedByModelName($version = '')
1313
-    {
1314
-        $version = empty($version) ? self::latest_rest_api_version() : $version;
1315
-        $model_names = self::model_names_with_plural_routes($version);
1316
-        $collection_routes = array();
1317
-        foreach ($model_names as $model_name => $model_class_name) {
1318
-            $collection_routes[ strtolower($model_name) ] = '/' . self::ee_api_namespace . $version . '/'
1319
-                                                            . EEH_Inflector::pluralize_and_lower($model_name);
1320
-        }
1321
-        return $collection_routes;
1322
-    }
1323
-
1324
-
1325
-    /**
1326
-     * Returns an array of primary key names indexed by model names.
1327
-     * @param string $version
1328
-     * @return array
1329
-     */
1330
-    public static function getPrimaryKeyNamesIndexedByModelName($version = '')
1331
-    {
1332
-        $version = empty($version) ? self::latest_rest_api_version() : $version;
1333
-        $model_names = self::model_names_with_plural_routes($version);
1334
-        $primary_key_items = array();
1335
-        foreach ($model_names as $model_name => $model_class_name) {
1336
-            $primary_keys = $model_class_name::instance()->get_combined_primary_key_fields();
1337
-            foreach ($primary_keys as $primary_key_name => $primary_key_field) {
1338
-                if (count($primary_keys) > 1) {
1339
-                    $primary_key_items[ strtolower($model_name) ][] = $primary_key_name;
1340
-                } else {
1341
-                    $primary_key_items[ strtolower($model_name) ] = $primary_key_name;
1342
-                }
1343
-            }
1344
-        }
1345
-        return $primary_key_items;
1346
-    }
1347
-
1348
-    /**
1349
-     * Determines the EE REST API debug mode is activated, or not.
1350
-     * @since 4.9.76.p
1351
-     * @return bool
1352
-     */
1353
-    public static function debugMode()
1354
-    {
1355
-        static $debug_mode = null; // could be class prop
1356
-        if ($debug_mode === null) {
1357
-            $debug_mode = defined('EE_REST_API_DEBUG_MODE') && EE_REST_API_DEBUG_MODE;
1358
-        }
1359
-        return $debug_mode;
1360
-    }
1361
-
1362
-
1363
-
1364
-    /**
1365
-     *    run - initial module setup
1366
-     *
1367
-     * @access    public
1368
-     * @param  WP $WP
1369
-     * @return    void
1370
-     */
1371
-    public function run($WP)
1372
-    {
1373
-    }
26
+	const ee_api_namespace = Domain::API_NAMESPACE;
27
+
28
+	const ee_api_namespace_for_regex = 'ee\/v([^/]*)\/';
29
+
30
+	const saved_routes_option_names = 'ee_core_routes';
31
+
32
+	/**
33
+	 * string used in _links response bodies to make them globally unique.
34
+	 *
35
+	 * @see http://v2.wp-api.org/extending/linking/
36
+	 */
37
+	const ee_api_link_namespace = 'https://api.eventespresso.com/';
38
+
39
+	/**
40
+	 * @var CalculatedModelFields
41
+	 */
42
+	protected static $_field_calculator;
43
+
44
+
45
+	/**
46
+	 * @return EED_Core_Rest_Api|EED_Module
47
+	 */
48
+	public static function instance()
49
+	{
50
+		self::$_field_calculator = LoaderFactory::getLoader()->load('EventEspresso\core\libraries\rest_api\CalculatedModelFields');
51
+		return parent::get_instance(__CLASS__);
52
+	}
53
+
54
+
55
+	/**
56
+	 *    set_hooks - for hooking into EE Core, other modules, etc
57
+	 *
58
+	 * @access    public
59
+	 * @return    void
60
+	 */
61
+	public static function set_hooks()
62
+	{
63
+		self::set_hooks_both();
64
+	}
65
+
66
+
67
+	/**
68
+	 *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
69
+	 *
70
+	 * @access    public
71
+	 * @return    void
72
+	 */
73
+	public static function set_hooks_admin()
74
+	{
75
+		self::set_hooks_both();
76
+	}
77
+
78
+
79
+	public static function set_hooks_both()
80
+	{
81
+		add_action('rest_api_init', array('EED_Core_Rest_Api', 'set_hooks_rest_api'), 5);
82
+		add_action('rest_api_init', array('EED_Core_Rest_Api', 'register_routes'), 10);
83
+		add_filter('rest_route_data', array('EED_Core_Rest_Api', 'hide_old_endpoints'), 10, 2);
84
+		add_filter(
85
+			'rest_index',
86
+			array('EventEspresso\core\libraries\rest_api\controllers\model\Meta', 'filterEeMetadataIntoIndex')
87
+		);
88
+		EED_Core_Rest_Api::invalidate_cached_route_data_on_version_change();
89
+	}
90
+
91
+
92
+	/**
93
+	 * sets up hooks which only need to be included as part of REST API requests;
94
+	 * other requests like to the frontend or admin etc don't need them
95
+	 *
96
+	 * @throws \EE_Error
97
+	 */
98
+	public static function set_hooks_rest_api()
99
+	{
100
+		// set hooks which account for changes made to the API
101
+		EED_Core_Rest_Api::_set_hooks_for_changes();
102
+	}
103
+
104
+
105
+	/**
106
+	 * public wrapper of _set_hooks_for_changes.
107
+	 * Loads all the hooks which make requests to old versions of the API
108
+	 * appear the same as they always did
109
+	 *
110
+	 * @throws EE_Error
111
+	 */
112
+	public static function set_hooks_for_changes()
113
+	{
114
+		self::_set_hooks_for_changes();
115
+	}
116
+
117
+
118
+	/**
119
+	 * Loads all the hooks which make requests to old versions of the API
120
+	 * appear the same as they always did
121
+	 *
122
+	 * @throws EE_Error
123
+	 */
124
+	protected static function _set_hooks_for_changes()
125
+	{
126
+		$folder_contents = EEH_File::get_contents_of_folders(array(EE_LIBRARIES . 'rest_api/changes'), false);
127
+		foreach ($folder_contents as $classname_in_namespace => $filepath) {
128
+			// ignore the base parent class
129
+			// and legacy named classes
130
+			if (
131
+				$classname_in_namespace === 'ChangesInBase'
132
+				|| strpos($classname_in_namespace, 'Changes_In_') === 0
133
+			) {
134
+				continue;
135
+			}
136
+			$full_classname = 'EventEspresso\core\libraries\rest_api\changes\\' . $classname_in_namespace;
137
+			if (class_exists($full_classname)) {
138
+				$instance_of_class = new $full_classname();
139
+				if ($instance_of_class instanceof ChangesInBase) {
140
+					$instance_of_class->setHooks();
141
+				}
142
+			}
143
+		}
144
+	}
145
+
146
+
147
+	/**
148
+	 * Filters the WP routes to add our EE-related ones. This takes a bit of time
149
+	 * so we actually prefer to only do it when an EE plugin is activated or upgraded
150
+	 *
151
+	 * @throws \EE_Error
152
+	 */
153
+	public static function register_routes()
154
+	{
155
+		foreach (EED_Core_Rest_Api::get_ee_route_data() as $namespace => $relative_routes) {
156
+			foreach ($relative_routes as $relative_route => $data_for_multiple_endpoints) {
157
+				/**
158
+				 * @var array     $data_for_multiple_endpoints numerically indexed array
159
+				 *                                         but can also contain route options like {
160
+				 * @type array    $schema                      {
161
+				 * @type callable $schema_callback
162
+				 * @type array    $callback_args               arguments that will be passed to the callback, after the
163
+				 * WP_REST_Request of course
164
+				 * }
165
+				 * }
166
+				 */
167
+				// when registering routes, register all the endpoints' data at the same time
168
+				$multiple_endpoint_args = array();
169
+				foreach ($data_for_multiple_endpoints as $endpoint_key => $data_for_single_endpoint) {
170
+					/**
171
+					 * @var array     $data_for_single_endpoint {
172
+					 * @type callable $callback
173
+					 * @type string methods
174
+					 * @type array args
175
+					 * @type array _links
176
+					 * @type array    $callback_args            arguments that will be passed to the callback, after the
177
+					 * WP_REST_Request of course
178
+					 * }
179
+					 */
180
+					// skip route options
181
+					if (! is_numeric($endpoint_key)) {
182
+						continue;
183
+					}
184
+					if (! isset($data_for_single_endpoint['callback'], $data_for_single_endpoint['methods'])) {
185
+						throw new EE_Error(
186
+							esc_html__(
187
+							// @codingStandardsIgnoreStart
188
+								'Endpoint configuration data needs to have entries "callback" (callable) and "methods" (comma-separated list of accepts HTTP methods).',
189
+								// @codingStandardsIgnoreEnd
190
+								'event_espresso'
191
+							)
192
+						);
193
+					}
194
+					$callback = $data_for_single_endpoint['callback'];
195
+					$single_endpoint_args = array(
196
+						'methods' => $data_for_single_endpoint['methods'],
197
+						'args'    => isset($data_for_single_endpoint['args']) ? $data_for_single_endpoint['args']
198
+							: array(),
199
+					);
200
+					if (isset($data_for_single_endpoint['_links'])) {
201
+						$single_endpoint_args['_links'] = $data_for_single_endpoint['_links'];
202
+					}
203
+					if (isset($data_for_single_endpoint['callback_args'])) {
204
+						$callback_args = $data_for_single_endpoint['callback_args'];
205
+						$single_endpoint_args['callback'] = function (\WP_REST_Request $request) use (
206
+							$callback,
207
+							$callback_args
208
+						) {
209
+							array_unshift($callback_args, $request);
210
+							return call_user_func_array(
211
+								$callback,
212
+								$callback_args
213
+							);
214
+						};
215
+					} else {
216
+						$single_endpoint_args['callback'] = $data_for_single_endpoint['callback'];
217
+					}
218
+					// As of WordPress 5.5, if a permission_callback is not provided,
219
+					// the REST API will issue a _doing_it_wrong notice.
220
+					// Since the EE REST API defers capabilities to the db model system,
221
+					// we will just use the generic WP callback for public endpoints
222
+					if (! isset($single_endpoint_args['permission_callback'])) {
223
+						$single_endpoint_args['permission_callback'] = '__return_true';
224
+					}
225
+					$multiple_endpoint_args[] = $single_endpoint_args;
226
+				}
227
+				if (isset($data_for_multiple_endpoints['schema'])) {
228
+					$schema_route_data = $data_for_multiple_endpoints['schema'];
229
+					$schema_callback = $schema_route_data['schema_callback'];
230
+					$callback_args = $schema_route_data['callback_args'];
231
+					$multiple_endpoint_args['schema'] = function () use ($schema_callback, $callback_args) {
232
+						return call_user_func_array(
233
+							$schema_callback,
234
+							$callback_args
235
+						);
236
+					};
237
+				}
238
+				register_rest_route(
239
+					$namespace,
240
+					$relative_route,
241
+					$multiple_endpoint_args
242
+				);
243
+			}
244
+		}
245
+	}
246
+
247
+
248
+	/**
249
+	 * Checks if there was a version change or something that merits invalidating the cached
250
+	 * route data. If so, invalidates the cached route data so that it gets refreshed
251
+	 * next time the WP API is used
252
+	 */
253
+	public static function invalidate_cached_route_data_on_version_change()
254
+	{
255
+		if (EE_System::instance()->detect_req_type() !== EE_System::req_type_normal) {
256
+			EED_Core_Rest_Api::invalidate_cached_route_data();
257
+		}
258
+		foreach (EE_Registry::instance()->addons as $addon) {
259
+			if ($addon instanceof EE_Addon && $addon->detect_req_type() !== EE_System::req_type_normal) {
260
+				EED_Core_Rest_Api::invalidate_cached_route_data();
261
+			}
262
+		}
263
+	}
264
+
265
+
266
+	/**
267
+	 * Removes the cached route data so it will get refreshed next time the WP API is used
268
+	 */
269
+	public static function invalidate_cached_route_data()
270
+	{
271
+		// delete the saved EE REST API routes
272
+		foreach (EED_Core_Rest_Api::versions_served() as $version => $hidden) {
273
+			delete_option(EED_Core_Rest_Api::saved_routes_option_names . $version);
274
+		}
275
+	}
276
+
277
+
278
+	/**
279
+	 * Gets the EE route data
280
+	 *
281
+	 * @return array top-level key is the namespace, next-level key is the route and its value is array{
282
+	 * @throws \EE_Error
283
+	 * @type string|array $callback
284
+	 * @type string       $methods
285
+	 * @type boolean      $hidden_endpoint
286
+	 * }
287
+	 */
288
+	public static function get_ee_route_data()
289
+	{
290
+		$ee_routes = array();
291
+		foreach (self::versions_served() as $version => $hidden_endpoints) {
292
+			$ee_routes[ self::ee_api_namespace . $version ] = self::_get_ee_route_data_for_version(
293
+				$version,
294
+				$hidden_endpoints
295
+			);
296
+		}
297
+		return $ee_routes;
298
+	}
299
+
300
+
301
+	/**
302
+	 * Gets the EE route data from the wp options if it exists already,
303
+	 * otherwise re-generates it and saves it to the option
304
+	 *
305
+	 * @param string  $version
306
+	 * @param boolean $hidden_endpoints
307
+	 * @return array
308
+	 * @throws \EE_Error
309
+	 */
310
+	protected static function _get_ee_route_data_for_version($version, $hidden_endpoints = false)
311
+	{
312
+		$ee_routes = get_option(self::saved_routes_option_names . $version, null);
313
+		if (! $ee_routes || EED_Core_Rest_Api::debugMode()) {
314
+			$ee_routes = self::_save_ee_route_data_for_version($version, $hidden_endpoints);
315
+		}
316
+		return $ee_routes;
317
+	}
318
+
319
+
320
+	/**
321
+	 * Saves the EE REST API route data to a wp option and returns it
322
+	 *
323
+	 * @param string  $version
324
+	 * @param boolean $hidden_endpoints
325
+	 * @return mixed|null
326
+	 * @throws \EE_Error
327
+	 */
328
+	protected static function _save_ee_route_data_for_version($version, $hidden_endpoints = false)
329
+	{
330
+		$instance = self::instance();
331
+		$routes = apply_filters(
332
+			'EED_Core_Rest_Api__save_ee_route_data_for_version__routes',
333
+			array_replace_recursive(
334
+				$instance->_get_config_route_data_for_version($version, $hidden_endpoints),
335
+				$instance->_get_meta_route_data_for_version($version, $hidden_endpoints),
336
+				$instance->_get_model_route_data_for_version($version, $hidden_endpoints),
337
+				$instance->_get_rpc_route_data_for_version($version, $hidden_endpoints)
338
+			)
339
+		);
340
+		$option_name = self::saved_routes_option_names . $version;
341
+		if (get_option($option_name)) {
342
+			update_option($option_name, $routes, true);
343
+		} else {
344
+			add_option($option_name, $routes, null, 'no');
345
+		}
346
+		return $routes;
347
+	}
348
+
349
+
350
+	/**
351
+	 * Calculates all the EE routes and saves it to a WordPress option so we don't
352
+	 * need to calculate it on every request
353
+	 *
354
+	 * @deprecated since version 4.9.1
355
+	 * @return void
356
+	 */
357
+	public static function save_ee_routes()
358
+	{
359
+		if (EE_Maintenance_Mode::instance()->models_can_query()) {
360
+			$instance = self::instance();
361
+			$routes = apply_filters(
362
+				'EED_Core_Rest_Api__save_ee_routes__routes',
363
+				array_replace_recursive(
364
+					$instance->_register_config_routes(),
365
+					$instance->_register_meta_routes(),
366
+					$instance->_register_model_routes(),
367
+					$instance->_register_rpc_routes()
368
+				)
369
+			);
370
+			update_option(self::saved_routes_option_names, $routes, true);
371
+		}
372
+	}
373
+
374
+
375
+	/**
376
+	 * Gets all the route information relating to EE models
377
+	 *
378
+	 * @return array @see get_ee_route_data
379
+	 * @deprecated since version 4.9.1
380
+	 */
381
+	protected function _register_model_routes()
382
+	{
383
+		$model_routes = array();
384
+		foreach (self::versions_served() as $version => $hidden_endpoint) {
385
+			$model_routes[ EED_Core_Rest_Api::ee_api_namespace
386
+						   . $version ] = $this->_get_config_route_data_for_version($version, $hidden_endpoint);
387
+		}
388
+		return $model_routes;
389
+	}
390
+
391
+
392
+	/**
393
+	 * Decides whether or not to add write endpoints for this model.
394
+	 *
395
+	 * Currently, this defaults to exclude all global tables and models
396
+	 * which would allow inserting WP core data (we don't want to duplicate
397
+	 * what WP API does, as it's unnecessary, extra work, and potentially extra bugs)
398
+	 *
399
+	 * @param EEM_Base $model
400
+	 * @return bool
401
+	 */
402
+	public static function should_have_write_endpoints(EEM_Base $model)
403
+	{
404
+		if ($model->is_wp_core_model()) {
405
+			return false;
406
+		}
407
+		foreach ($model->get_tables() as $table) {
408
+			if ($table->is_global()) {
409
+				return false;
410
+			}
411
+		}
412
+		return true;
413
+	}
414
+
415
+
416
+	/**
417
+	 * Gets the names of all models which should have plural routes (eg `ee/v4.8.36/events`)
418
+	 * in this versioned namespace of EE4
419
+	 *
420
+	 * @param $version
421
+	 * @return array keys are model names (eg 'Event') and values ar either classnames (eg 'EEM_Event')
422
+	 */
423
+	public static function model_names_with_plural_routes($version)
424
+	{
425
+		$model_version_info = new ModelVersionInfo($version);
426
+		$models_to_register = $model_version_info->modelsForRequestedVersion();
427
+		// let's not bother having endpoints for extra metas
428
+		unset(
429
+			$models_to_register['Extra_Meta'],
430
+			$models_to_register['Extra_Join'],
431
+			$models_to_register['Post_Meta']
432
+		);
433
+		return apply_filters(
434
+			'FHEE__EED_Core_REST_API___register_model_routes',
435
+			$models_to_register
436
+		);
437
+	}
438
+
439
+
440
+	/**
441
+	 * Gets the route data for EE models in the specified version
442
+	 *
443
+	 * @param string  $version
444
+	 * @param boolean $hidden_endpoint
445
+	 * @return array
446
+	 * @throws EE_Error
447
+	 */
448
+	protected function _get_model_route_data_for_version($version, $hidden_endpoint = false)
449
+	{
450
+		$model_routes = array();
451
+		$model_version_info = new ModelVersionInfo($version);
452
+		foreach (EED_Core_Rest_Api::model_names_with_plural_routes($version) as $model_name => $model_classname) {
453
+			$model = \EE_Registry::instance()->load_model($model_name);
454
+			// if this isn't a valid model then let's skip iterate to the next item in the loop.
455
+			if (! $model instanceof EEM_Base) {
456
+				continue;
457
+			}
458
+			// yes we could just register one route for ALL models, but then they wouldn't show up in the index
459
+			$plural_model_route = EED_Core_Rest_Api::get_collection_route($model);
460
+			$singular_model_route = EED_Core_Rest_Api::get_entity_route($model, '(?P<id>[^\/]+)');
461
+			$model_routes[ $plural_model_route ] = array(
462
+				array(
463
+					'callback'        => array(
464
+						'EventEspresso\core\libraries\rest_api\controllers\model\Read',
465
+						'handleRequestGetAll',
466
+					),
467
+					'callback_args'   => array($version, $model_name),
468
+					'methods'         => WP_REST_Server::READABLE,
469
+					'hidden_endpoint' => $hidden_endpoint,
470
+					'args'            => $this->_get_read_query_params($model, $version),
471
+					'_links'          => array(
472
+						'self' => rest_url(EED_Core_Rest_Api::ee_api_namespace . $version . $singular_model_route),
473
+					),
474
+				),
475
+				'schema' => array(
476
+					'schema_callback' => array(
477
+						'EventEspresso\core\libraries\rest_api\controllers\model\Read',
478
+						'handleSchemaRequest',
479
+					),
480
+					'callback_args'   => array($version, $model_name),
481
+				),
482
+			);
483
+			$model_routes[ $singular_model_route ] = array(
484
+				array(
485
+					'callback'        => array(
486
+						'EventEspresso\core\libraries\rest_api\controllers\model\Read',
487
+						'handleRequestGetOne',
488
+					),
489
+					'callback_args'   => array($version, $model_name),
490
+					'methods'         => WP_REST_Server::READABLE,
491
+					'hidden_endpoint' => $hidden_endpoint,
492
+					'args'            => $this->_get_response_selection_query_params($model, $version, true),
493
+				),
494
+			);
495
+			if (
496
+				apply_filters(
497
+					'FHEE__EED_Core_Rest_Api___get_model_route_data_for_version__add_write_endpoints',
498
+					EED_Core_Rest_Api::should_have_write_endpoints($model),
499
+					$model
500
+				)
501
+			) {
502
+				$model_routes[ $plural_model_route ][] = array(
503
+					'callback'        => array(
504
+						'EventEspresso\core\libraries\rest_api\controllers\model\Write',
505
+						'handleRequestInsert',
506
+					),
507
+					'callback_args'   => array($version, $model_name),
508
+					'methods'         => WP_REST_Server::CREATABLE,
509
+					'hidden_endpoint' => $hidden_endpoint,
510
+					'args'            => $this->_get_write_params($model_name, $model_version_info, true),
511
+				);
512
+				$model_routes[ $singular_model_route ] = array_merge(
513
+					$model_routes[ $singular_model_route ],
514
+					array(
515
+						array(
516
+							'callback'        => array(
517
+								'EventEspresso\core\libraries\rest_api\controllers\model\Write',
518
+								'handleRequestUpdate',
519
+							),
520
+							'callback_args'   => array($version, $model_name),
521
+							'methods'         => WP_REST_Server::EDITABLE,
522
+							'hidden_endpoint' => $hidden_endpoint,
523
+							'args'            => $this->_get_write_params($model_name, $model_version_info),
524
+						),
525
+						array(
526
+							'callback'        => array(
527
+								'EventEspresso\core\libraries\rest_api\controllers\model\Write',
528
+								'handleRequestDelete',
529
+							),
530
+							'callback_args'   => array($version, $model_name),
531
+							'methods'         => WP_REST_Server::DELETABLE,
532
+							'hidden_endpoint' => $hidden_endpoint,
533
+							'args'            => $this->_get_delete_query_params($model, $version),
534
+						),
535
+					)
536
+				);
537
+			}
538
+			foreach ($model->relation_settings() as $relation_name => $relation_obj) {
539
+				$related_route = EED_Core_Rest_Api::get_relation_route_via(
540
+					$model,
541
+					'(?P<id>[^\/]+)',
542
+					$relation_obj
543
+				);
544
+				$model_routes[ $related_route ] = array(
545
+					array(
546
+						'callback'        => array(
547
+							'EventEspresso\core\libraries\rest_api\controllers\model\Read',
548
+							'handleRequestGetRelated',
549
+						),
550
+						'callback_args'   => array($version, $model_name, $relation_name),
551
+						'methods'         => WP_REST_Server::READABLE,
552
+						'hidden_endpoint' => $hidden_endpoint,
553
+						'args'            => $this->_get_read_query_params($relation_obj->get_other_model(), $version),
554
+					),
555
+				);
556
+
557
+				$related_write_route = $related_route . '/' . '(?P<related_id>[^\/]+)';
558
+				$model_routes[ $related_write_route ] = array(
559
+					array(
560
+						'callback'        => array(
561
+							'EventEspresso\core\libraries\rest_api\controllers\model\Write',
562
+							'handleRequestAddRelation',
563
+						),
564
+						'callback_args'   => array($version, $model_name, $relation_name),
565
+						'methods'         => WP_REST_Server::EDITABLE,
566
+						'hidden_endpoint' => $hidden_endpoint,
567
+						'args'            => $this->_get_add_relation_query_params($model, $relation_obj->get_other_model(), $version)
568
+					),
569
+					array(
570
+						'callback'        => array(
571
+							'EventEspresso\core\libraries\rest_api\controllers\model\Write',
572
+							'handleRequestRemoveRelation',
573
+						),
574
+						'callback_args'   => array($version, $model_name, $relation_name),
575
+						'methods'         => WP_REST_Server::DELETABLE,
576
+						'hidden_endpoint' => $hidden_endpoint,
577
+						'args'            => array()
578
+					),
579
+				);
580
+			}
581
+		}
582
+		return $model_routes;
583
+	}
584
+
585
+
586
+	/**
587
+	 * Gets the relative URI to a model's REST API plural route, after the EE4 versioned namespace,
588
+	 * excluding the preceding slash.
589
+	 * Eg you pass get_plural_route_to('Event') = 'events'
590
+	 *
591
+	 * @param EEM_Base $model
592
+	 * @return string
593
+	 */
594
+	public static function get_collection_route(EEM_Base $model)
595
+	{
596
+		return EEH_Inflector::pluralize_and_lower($model->get_this_model_name());
597
+	}
598
+
599
+
600
+	/**
601
+	 * Gets the relative URI to a model's REST API singular route, after the EE4 versioned namespace,
602
+	 * excluding the preceding slash.
603
+	 * Eg you pass get_plural_route_to('Event', 12) = 'events/12'
604
+	 *
605
+	 * @param EEM_Base $model eg Event or Venue
606
+	 * @param string   $id
607
+	 * @return string
608
+	 */
609
+	public static function get_entity_route($model, $id)
610
+	{
611
+		return EED_Core_Rest_Api::get_collection_route($model) . '/' . $id;
612
+	}
613
+
614
+
615
+	/**
616
+	 * Gets the relative URI to a model's REST API singular route, after the EE4 versioned namespace,
617
+	 * excluding the preceding slash.
618
+	 * Eg you pass get_plural_route_to('Event', 12) = 'events/12'
619
+	 *
620
+	 * @param EEM_Base               $model eg Event or Venue
621
+	 * @param string                 $id
622
+	 * @param EE_Model_Relation_Base $relation_obj
623
+	 * @return string
624
+	 */
625
+	public static function get_relation_route_via(EEM_Base $model, $id, EE_Model_Relation_Base $relation_obj)
626
+	{
627
+		$related_model_name_endpoint_part = ModelRead::getRelatedEntityName(
628
+			$relation_obj->get_other_model()->get_this_model_name(),
629
+			$relation_obj
630
+		);
631
+		return EED_Core_Rest_Api::get_entity_route($model, $id) . '/' . $related_model_name_endpoint_part;
632
+	}
633
+
634
+
635
+	/**
636
+	 * Adds onto the $relative_route the EE4 REST API versioned namespace.
637
+	 * Eg if given '4.8.36' and 'events', will return 'ee/v4.8.36/events'
638
+	 *
639
+	 * @param string $relative_route
640
+	 * @param string $version
641
+	 * @return string
642
+	 */
643
+	public static function get_versioned_route_to($relative_route, $version = '4.8.36')
644
+	{
645
+		return '/' . EED_Core_Rest_Api::ee_api_namespace . $version . '/' . $relative_route;
646
+	}
647
+
648
+
649
+	/**
650
+	 * Adds all the RPC-style routes (remote procedure call-like routes, ie
651
+	 * routes that don't conform to the traditional REST CRUD-style).
652
+	 *
653
+	 * @deprecated since 4.9.1
654
+	 */
655
+	protected function _register_rpc_routes()
656
+	{
657
+		$routes = array();
658
+		foreach (self::versions_served() as $version => $hidden_endpoint) {
659
+			$routes[ self::ee_api_namespace . $version ] = $this->_get_rpc_route_data_for_version(
660
+				$version,
661
+				$hidden_endpoint
662
+			);
663
+		}
664
+		return $routes;
665
+	}
666
+
667
+
668
+	/**
669
+	 * @param string  $version
670
+	 * @param boolean $hidden_endpoint
671
+	 * @return array
672
+	 */
673
+	protected function _get_rpc_route_data_for_version($version, $hidden_endpoint = false)
674
+	{
675
+		$this_versions_routes = array();
676
+		// checkin endpoint
677
+		$this_versions_routes['registrations/(?P<REG_ID>\d+)/toggle_checkin_for_datetime/(?P<DTT_ID>\d+)'] = array(
678
+			array(
679
+				'callback'        => array(
680
+					'EventEspresso\core\libraries\rest_api\controllers\rpc\Checkin',
681
+					'handleRequestToggleCheckin',
682
+				),
683
+				'methods'         => WP_REST_Server::CREATABLE,
684
+				'hidden_endpoint' => $hidden_endpoint,
685
+				'args'            => array(
686
+					'force' => array(
687
+						'required'    => false,
688
+						'default'     => false,
689
+						'description' => esc_html__(
690
+						// @codingStandardsIgnoreStart
691
+							'Whether to force toggle checkin, or to verify the registration status and allowed ticket uses',
692
+							// @codingStandardsIgnoreEnd
693
+							'event_espresso'
694
+						),
695
+					),
696
+				),
697
+				'callback_args'   => array($version),
698
+			),
699
+		);
700
+		return apply_filters(
701
+			'FHEE__EED_Core_Rest_Api___register_rpc_routes__this_versions_routes',
702
+			$this_versions_routes,
703
+			$version,
704
+			$hidden_endpoint
705
+		);
706
+	}
707
+
708
+
709
+	/**
710
+	 * Gets the query params that can be used when request one or many
711
+	 *
712
+	 * @param EEM_Base $model
713
+	 * @param string   $version
714
+	 * @return array
715
+	 */
716
+	protected function _get_response_selection_query_params(\EEM_Base $model, $version, $single_only = false)
717
+	{
718
+		$query_params = array(
719
+			'include'   => array(
720
+				'required' => false,
721
+				'default'  => '*',
722
+				'type'     => 'string',
723
+			),
724
+			'calculate' => array(
725
+				'required'          => false,
726
+				'default'           => '',
727
+				'enum'              => self::$_field_calculator->retrieveCalculatedFieldsForModel($model),
728
+				'type'              => 'string',
729
+				// because we accept a CSV'd list of the enumerated strings, WP core validation and sanitization
730
+				// freaks out. We'll just validate this argument while handling the request
731
+				'validate_callback' => null,
732
+				'sanitize_callback' => null,
733
+			),
734
+			'password' => array(
735
+				'required' => false,
736
+				'default' => '',
737
+				'type' => 'string'
738
+			)
739
+		);
740
+		return apply_filters(
741
+			'FHEE__EED_Core_Rest_Api___get_response_selection_query_params',
742
+			$query_params,
743
+			$model,
744
+			$version
745
+		);
746
+	}
747
+
748
+
749
+	/**
750
+	 * Gets the parameters acceptable for delete requests
751
+	 *
752
+	 * @param \EEM_Base $model
753
+	 * @param string    $version
754
+	 * @return array
755
+	 */
756
+	protected function _get_delete_query_params(\EEM_Base $model, $version)
757
+	{
758
+		$params_for_delete = array(
759
+			'allow_blocking' => array(
760
+				'required' => false,
761
+				'default'  => true,
762
+				'type'     => 'boolean',
763
+			),
764
+		);
765
+		$params_for_delete['force'] = array(
766
+			'required' => false,
767
+			'default'  => false,
768
+			'type'     => 'boolean',
769
+		);
770
+		return apply_filters(
771
+			'FHEE__EED_Core_Rest_Api___get_delete_query_params',
772
+			$params_for_delete,
773
+			$model,
774
+			$version
775
+		);
776
+	}
777
+
778
+	protected function _get_add_relation_query_params(\EEM_Base $source_model, \EEM_Base $related_model, $version)
779
+	{
780
+		// if they're related through a HABTM relation, check for any non-FKs
781
+		$all_relation_settings = $source_model->relation_settings();
782
+		$relation_settings = $all_relation_settings[ $related_model->get_this_model_name() ];
783
+		$params = array();
784
+		if ($relation_settings instanceof EE_HABTM_Relation && $relation_settings->hasNonKeyFields()) {
785
+			foreach ($relation_settings->getNonKeyFields() as $field) {
786
+				/* @var $field EE_Model_Field_Base */
787
+				$params[ $field->get_name() ] = array(
788
+					'required' => ! $field->is_nullable(),
789
+					'default' => ModelDataTranslator::prepareFieldValueForJson($field, $field->get_default_value(), $version),
790
+					'type' => $field->getSchemaType(),
791
+					'validate_callbaack' => null,
792
+					'sanitize_callback' => null
793
+				);
794
+			}
795
+		}
796
+		return $params;
797
+	}
798
+
799
+
800
+	/**
801
+	 * Gets info about reading query params that are acceptable
802
+	 *
803
+	 * @param \EEM_Base $model eg 'Event' or 'Venue'
804
+	 * @param  string   $version
805
+	 * @return array    describing the args acceptable when querying this model
806
+	 * @throws EE_Error
807
+	 */
808
+	protected function _get_read_query_params(\EEM_Base $model, $version)
809
+	{
810
+		$default_orderby = array();
811
+		foreach ($model->get_combined_primary_key_fields() as $key_field) {
812
+			$default_orderby[ $key_field->get_name() ] = 'ASC';
813
+		}
814
+		return array_merge(
815
+			$this->_get_response_selection_query_params($model, $version),
816
+			array(
817
+				'where'    => array(
818
+					'required'          => false,
819
+					'default'           => array(),
820
+					'type'              => 'object',
821
+					// because we accept an almost infinite list of possible where conditions, WP
822
+					// core validation and sanitization freaks out. We'll just validate this argument
823
+					// while handling the request
824
+					'validate_callback' => null,
825
+					'sanitize_callback' => null,
826
+				),
827
+				'limit'    => array(
828
+					'required'          => false,
829
+					'default'           => EED_Core_Rest_Api::get_default_query_limit(),
830
+					'type'              => array(
831
+						'array',
832
+						'string',
833
+						'integer',
834
+					),
835
+					// because we accept a variety of types, WP core validation and sanitization
836
+					// freaks out. We'll just validate this argument while handling the request
837
+					'validate_callback' => null,
838
+					'sanitize_callback' => null,
839
+				),
840
+				'order_by' => array(
841
+					'required'          => false,
842
+					'default'           => $default_orderby,
843
+					'type'              => array(
844
+						'object',
845
+						'string',
846
+					),// because we accept a variety of types, WP core validation and sanitization
847
+					// freaks out. We'll just validate this argument while handling the request
848
+					'validate_callback' => null,
849
+					'sanitize_callback' => null,
850
+				),
851
+				'group_by' => array(
852
+					'required'          => false,
853
+					'default'           => null,
854
+					'type'              => array(
855
+						'object',
856
+						'string',
857
+					),
858
+					// because we accept  an almost infinite list of possible groupings,
859
+					// WP core validation and sanitization
860
+					// freaks out. We'll just validate this argument while handling the request
861
+					'validate_callback' => null,
862
+					'sanitize_callback' => null,
863
+				),
864
+				'having'   => array(
865
+					'required'          => false,
866
+					'default'           => null,
867
+					'type'              => 'object',
868
+					// because we accept an almost infinite list of possible where conditions, WP
869
+					// core validation and sanitization freaks out. We'll just validate this argument
870
+					// while handling the request
871
+					'validate_callback' => null,
872
+					'sanitize_callback' => null,
873
+				),
874
+				'caps'     => array(
875
+					'required' => false,
876
+					'default'  => EEM_Base::caps_read,
877
+					'type'     => 'string',
878
+					'enum'     => array(
879
+						EEM_Base::caps_read,
880
+						EEM_Base::caps_read_admin,
881
+						EEM_Base::caps_edit,
882
+						EEM_Base::caps_delete,
883
+					),
884
+				),
885
+			)
886
+		);
887
+	}
888
+
889
+
890
+	/**
891
+	 * Gets parameter information for a model regarding writing data
892
+	 *
893
+	 * @param string           $model_name
894
+	 * @param ModelVersionInfo $model_version_info
895
+	 * @param boolean          $create                                       whether this is for request to create (in
896
+	 *                                                                       which case we need all required params) or
897
+	 *                                                                       just to update (in which case we don't
898
+	 *                                                                       need those on every request)
899
+	 * @return array
900
+	 */
901
+	protected function _get_write_params(
902
+		$model_name,
903
+		ModelVersionInfo $model_version_info,
904
+		$create = false
905
+	) {
906
+		$model = EE_Registry::instance()->load_model($model_name);
907
+		$fields = $model_version_info->fieldsOnModelInThisVersion($model);
908
+		$args_info = array();
909
+		foreach ($fields as $field_name => $field_obj) {
910
+			if ($field_obj->is_auto_increment()) {
911
+				// totally ignore auto increment IDs
912
+				continue;
913
+			}
914
+			$arg_info = $field_obj->getSchema();
915
+			$required = $create && ! $field_obj->is_nullable() && $field_obj->get_default_value() === null;
916
+			$arg_info['required'] = $required;
917
+			// remove the read-only flag. If it were read-only we wouldn't list it as an argument while writing, right?
918
+			unset($arg_info['readonly']);
919
+			$schema_properties = $field_obj->getSchemaProperties();
920
+			if (
921
+				isset($schema_properties['raw'])
922
+				&& $field_obj->getSchemaType() === 'object'
923
+			) {
924
+				// if there's a "raw" form of this argument, use those properties instead
925
+				$arg_info = array_replace(
926
+					$arg_info,
927
+					$schema_properties['raw']
928
+				);
929
+			}
930
+			$arg_info['default'] = ModelDataTranslator::prepareFieldValueForJson(
931
+				$field_obj,
932
+				$field_obj->get_default_value(),
933
+				$model_version_info->requestedVersion()
934
+			);
935
+			// we do our own validation and sanitization within the controller
936
+			if (function_exists('rest_validate_value_from_schema')) {
937
+				$sanitize_callback = array(
938
+					'EED_Core_Rest_Api',
939
+					'default_sanitize_callback',
940
+				);
941
+			} else {
942
+				$sanitize_callback = null;
943
+			}
944
+			$arg_info['sanitize_callback'] = $sanitize_callback;
945
+			$args_info[ $field_name ] = $arg_info;
946
+			if ($field_obj instanceof EE_Datetime_Field) {
947
+				$gmt_arg_info = $arg_info;
948
+				$gmt_arg_info['description'] = sprintf(
949
+					esc_html__(
950
+						'%1$s - the value for this field in UTC. Ignored if %2$s is provided.',
951
+						'event_espresso'
952
+					),
953
+					$field_obj->get_nicename(),
954
+					$field_name
955
+				);
956
+				$args_info[ $field_name . '_gmt' ] = $gmt_arg_info;
957
+			}
958
+		}
959
+		return $args_info;
960
+	}
961
+
962
+
963
+	/**
964
+	 * Replacement for WP API's 'rest_parse_request_arg'.
965
+	 * If the value is blank but not required, don't bother validating it.
966
+	 * Also, it uses our email validation instead of WP API's default.
967
+	 *
968
+	 * @param                 $value
969
+	 * @param WP_REST_Request $request
970
+	 * @param                 $param
971
+	 * @return bool|true|WP_Error
972
+	 * @throws InvalidArgumentException
973
+	 * @throws InvalidInterfaceException
974
+	 * @throws InvalidDataTypeException
975
+	 */
976
+	public static function default_sanitize_callback($value, WP_REST_Request $request, $param)
977
+	{
978
+		$attributes = $request->get_attributes();
979
+		if (
980
+			! isset($attributes['args'][ $param ])
981
+			|| ! is_array($attributes['args'][ $param ])
982
+		) {
983
+			$validation_result = true;
984
+		} else {
985
+			$args = $attributes['args'][ $param ];
986
+			if (
987
+				(
988
+					$value === ''
989
+					|| $value === null
990
+				)
991
+				&& (! isset($args['required'])
992
+					|| $args['required'] === false
993
+				)
994
+			) {
995
+				// not required and not provided? that's cool
996
+				$validation_result = true;
997
+			} elseif (
998
+				isset($args['format'])
999
+					  && $args['format'] === 'email'
1000
+			) {
1001
+				$validation_result = true;
1002
+				if (! self::_validate_email($value)) {
1003
+					$validation_result = new WP_Error(
1004
+						'rest_invalid_param',
1005
+						esc_html__(
1006
+							'The email address is not valid or does not exist.',
1007
+							'event_espresso'
1008
+						)
1009
+					);
1010
+				}
1011
+			} else {
1012
+				$validation_result = rest_validate_value_from_schema($value, $args, $param);
1013
+			}
1014
+		}
1015
+		if (is_wp_error($validation_result)) {
1016
+			return $validation_result;
1017
+		}
1018
+		return rest_sanitize_request_arg($value, $request, $param);
1019
+	}
1020
+
1021
+
1022
+	/**
1023
+	 * Returns whether or not this email address is valid. Copied from EE_Email_Validation_Strategy::_validate_email()
1024
+	 *
1025
+	 * @param $email
1026
+	 * @return bool
1027
+	 * @throws InvalidArgumentException
1028
+	 * @throws InvalidInterfaceException
1029
+	 * @throws InvalidDataTypeException
1030
+	 */
1031
+	protected static function _validate_email($email)
1032
+	{
1033
+		try {
1034
+			EmailAddressFactory::create($email);
1035
+			return true;
1036
+		} catch (EmailValidationException $e) {
1037
+			return false;
1038
+		}
1039
+	}
1040
+
1041
+
1042
+	/**
1043
+	 * Gets routes for the config
1044
+	 *
1045
+	 * @return array @see _register_model_routes
1046
+	 * @deprecated since version 4.9.1
1047
+	 */
1048
+	protected function _register_config_routes()
1049
+	{
1050
+		$config_routes = array();
1051
+		foreach (self::versions_served() as $version => $hidden_endpoint) {
1052
+			$config_routes[ self::ee_api_namespace . $version ] = $this->_get_config_route_data_for_version(
1053
+				$version,
1054
+				$hidden_endpoint
1055
+			);
1056
+		}
1057
+		return $config_routes;
1058
+	}
1059
+
1060
+
1061
+	/**
1062
+	 * Gets routes for the config for the specified version
1063
+	 *
1064
+	 * @param string  $version
1065
+	 * @param boolean $hidden_endpoint
1066
+	 * @return array
1067
+	 */
1068
+	protected function _get_config_route_data_for_version($version, $hidden_endpoint)
1069
+	{
1070
+		return array(
1071
+			'config'    => array(
1072
+				array(
1073
+					'callback'        => array(
1074
+						'EventEspresso\core\libraries\rest_api\controllers\config\Read',
1075
+						'handleRequest',
1076
+					),
1077
+					'methods'         => WP_REST_Server::READABLE,
1078
+					'hidden_endpoint' => $hidden_endpoint,
1079
+					'callback_args'   => array($version),
1080
+				),
1081
+			),
1082
+			'site_info' => array(
1083
+				array(
1084
+					'callback'        => array(
1085
+						'EventEspresso\core\libraries\rest_api\controllers\config\Read',
1086
+						'handleRequestSiteInfo',
1087
+					),
1088
+					'methods'         => WP_REST_Server::READABLE,
1089
+					'hidden_endpoint' => $hidden_endpoint,
1090
+					'callback_args'   => array($version),
1091
+				),
1092
+			),
1093
+		);
1094
+	}
1095
+
1096
+
1097
+	/**
1098
+	 * Gets the meta info routes
1099
+	 *
1100
+	 * @return array @see _register_model_routes
1101
+	 * @deprecated since version 4.9.1
1102
+	 */
1103
+	protected function _register_meta_routes()
1104
+	{
1105
+		$meta_routes = array();
1106
+		foreach (self::versions_served() as $version => $hidden_endpoint) {
1107
+			$meta_routes[ self::ee_api_namespace . $version ] = $this->_get_meta_route_data_for_version(
1108
+				$version,
1109
+				$hidden_endpoint
1110
+			);
1111
+		}
1112
+		return $meta_routes;
1113
+	}
1114
+
1115
+
1116
+	/**
1117
+	 * @param string  $version
1118
+	 * @param boolean $hidden_endpoint
1119
+	 * @return array
1120
+	 */
1121
+	protected function _get_meta_route_data_for_version($version, $hidden_endpoint = false)
1122
+	{
1123
+		return array(
1124
+			'resources' => array(
1125
+				array(
1126
+					'callback'        => array(
1127
+						'EventEspresso\core\libraries\rest_api\controllers\model\Meta',
1128
+						'handleRequestModelsMeta',
1129
+					),
1130
+					'methods'         => WP_REST_Server::READABLE,
1131
+					'hidden_endpoint' => $hidden_endpoint,
1132
+					'callback_args'   => array($version),
1133
+				),
1134
+			),
1135
+		);
1136
+	}
1137
+
1138
+
1139
+	/**
1140
+	 * Tries to hide old 4.6 endpoints from the
1141
+	 *
1142
+	 * @param array $route_data
1143
+	 * @return array
1144
+	 * @throws \EE_Error
1145
+	 */
1146
+	public static function hide_old_endpoints($route_data)
1147
+	{
1148
+		// allow API clients to override which endpoints get hidden, in case
1149
+		// they want to discover particular endpoints
1150
+		// also, we don't have access to the request so we have to just grab it from the superglobal
1151
+		$force_show_ee_namespace = ltrim(
1152
+			EED_Core_Rest_Api::getRequest()->getRequestParam('force_show_ee_namespace'),
1153
+			'/'
1154
+		);
1155
+		foreach (EED_Core_Rest_Api::get_ee_route_data() as $namespace => $relative_urls) {
1156
+			foreach ($relative_urls as $resource_name => $endpoints) {
1157
+				foreach ($endpoints as $key => $endpoint) {
1158
+					// skip schema and other route options
1159
+					if (! is_numeric($key)) {
1160
+						continue;
1161
+					}
1162
+					// by default, hide "hidden_endpoint"s, unless the request indicates
1163
+					// to $force_show_ee_namespace, in which case only show that one
1164
+					// namespace's endpoints (and hide all others)
1165
+					if (
1166
+						($force_show_ee_namespace !== '' && $force_show_ee_namespace !== $namespace)
1167
+						|| ($endpoint['hidden_endpoint'] && $force_show_ee_namespace === '')
1168
+					) {
1169
+						$full_route = '/' . ltrim($namespace, '/');
1170
+						$full_route .= '/' . ltrim($resource_name, '/');
1171
+						unset($route_data[ $full_route ]);
1172
+					}
1173
+				}
1174
+			}
1175
+		}
1176
+		return $route_data;
1177
+	}
1178
+
1179
+
1180
+	/**
1181
+	 * Returns an array describing which versions of core support serving requests for.
1182
+	 * Keys are core versions' major and minor version, and values are the
1183
+	 * LOWEST requested version they can serve. Eg, 4.7 can serve requests for 4.6-like
1184
+	 * data by just removing a few models and fields from the responses. However, 4.15 might remove
1185
+	 * the answers table entirely, in which case it would be very difficult for
1186
+	 * it to serve 4.6-style responses.
1187
+	 * Versions of core that are missing from this array are unknowns.
1188
+	 * previous ver
1189
+	 *
1190
+	 * @return array
1191
+	 */
1192
+	public static function version_compatibilities()
1193
+	{
1194
+		return apply_filters(
1195
+			'FHEE__EED_Core_REST_API__version_compatibilities',
1196
+			array(
1197
+				'4.8.29' => '4.8.29',
1198
+				'4.8.33' => '4.8.29',
1199
+				'4.8.34' => '4.8.29',
1200
+				'4.8.36' => '4.8.29',
1201
+			)
1202
+		);
1203
+	}
1204
+
1205
+
1206
+	/**
1207
+	 * Gets the latest API version served. Eg if there
1208
+	 * are two versions served of the API, 4.8.29 and 4.8.32, and
1209
+	 * we are on core version 4.8.34, it will return the string "4.8.32"
1210
+	 *
1211
+	 * @return string
1212
+	 */
1213
+	public static function latest_rest_api_version()
1214
+	{
1215
+		$versions_served = \EED_Core_Rest_Api::versions_served();
1216
+		$versions_served_keys = array_keys($versions_served);
1217
+		return end($versions_served_keys);
1218
+	}
1219
+
1220
+
1221
+	/**
1222
+	 * Using EED_Core_Rest_Api::version_compatibilities(), determines what version of
1223
+	 * EE the API can serve requests for. Eg, if we are on 4.15 of core, and
1224
+	 * we can serve requests from 4.12 or later, this will return array( '4.12', '4.13', '4.14', '4.15' ).
1225
+	 * We also indicate whether or not this version should be put in the index or not
1226
+	 *
1227
+	 * @return array keys are API version numbers (just major and minor numbers), and values
1228
+	 * are whether or not they should be hidden
1229
+	 */
1230
+	public static function versions_served()
1231
+	{
1232
+		$versions_served = array();
1233
+		$possibly_served_versions = EED_Core_Rest_Api::version_compatibilities();
1234
+		$lowest_compatible_version = end($possibly_served_versions);
1235
+		reset($possibly_served_versions);
1236
+		$versions_served_historically = array_keys($possibly_served_versions);
1237
+		$latest_version = end($versions_served_historically);
1238
+		reset($versions_served_historically);
1239
+		// for each version of core we have ever served:
1240
+		foreach ($versions_served_historically as $key_versioned_endpoint) {
1241
+			// if it's not above the current core version, and it's compatible with the current version of core
1242
+
1243
+			if ($key_versioned_endpoint === $latest_version) {
1244
+				// don't hide the latest version in the index
1245
+				$versions_served[ $key_versioned_endpoint ] = false;
1246
+			} elseif (
1247
+				version_compare($key_versioned_endpoint, $lowest_compatible_version, '>=')
1248
+				&& version_compare($key_versioned_endpoint, EED_Core_Rest_Api::core_version(), '<')
1249
+			) {
1250
+				// include, but hide, previous versions which are still supported
1251
+				$versions_served[ $key_versioned_endpoint ] = true;
1252
+			} elseif (
1253
+				apply_filters(
1254
+					'FHEE__EED_Core_Rest_Api__versions_served__include_incompatible_versions',
1255
+					false,
1256
+					$possibly_served_versions
1257
+				)
1258
+			) {
1259
+				// if a version is no longer supported, don't include it in index or list of versions served
1260
+				$versions_served[ $key_versioned_endpoint ] = true;
1261
+			}
1262
+		}
1263
+		return $versions_served;
1264
+	}
1265
+
1266
+
1267
+	/**
1268
+	 * Gets the major and minor version of EE core's version string
1269
+	 *
1270
+	 * @return string
1271
+	 */
1272
+	public static function core_version()
1273
+	{
1274
+		return apply_filters(
1275
+			'FHEE__EED_Core_REST_API__core_version',
1276
+			implode(
1277
+				'.',
1278
+				array_slice(
1279
+					explode(
1280
+						'.',
1281
+						espresso_version()
1282
+					),
1283
+					0,
1284
+					3
1285
+				)
1286
+			)
1287
+		);
1288
+	}
1289
+
1290
+
1291
+	/**
1292
+	 * Gets the default limit that should be used when querying for resources
1293
+	 *
1294
+	 * @return int
1295
+	 */
1296
+	public static function get_default_query_limit()
1297
+	{
1298
+		// we actually don't use a const because we want folks to always use
1299
+		// this method, not the const directly
1300
+		return apply_filters(
1301
+			'FHEE__EED_Core_Rest_Api__get_default_query_limit',
1302
+			50
1303
+		);
1304
+	}
1305
+
1306
+
1307
+	/**
1308
+	 *
1309
+	 * @param string $version api version string (i.e. '4.8.36')
1310
+	 * @return array
1311
+	 */
1312
+	public static function getCollectionRoutesIndexedByModelName($version = '')
1313
+	{
1314
+		$version = empty($version) ? self::latest_rest_api_version() : $version;
1315
+		$model_names = self::model_names_with_plural_routes($version);
1316
+		$collection_routes = array();
1317
+		foreach ($model_names as $model_name => $model_class_name) {
1318
+			$collection_routes[ strtolower($model_name) ] = '/' . self::ee_api_namespace . $version . '/'
1319
+															. EEH_Inflector::pluralize_and_lower($model_name);
1320
+		}
1321
+		return $collection_routes;
1322
+	}
1323
+
1324
+
1325
+	/**
1326
+	 * Returns an array of primary key names indexed by model names.
1327
+	 * @param string $version
1328
+	 * @return array
1329
+	 */
1330
+	public static function getPrimaryKeyNamesIndexedByModelName($version = '')
1331
+	{
1332
+		$version = empty($version) ? self::latest_rest_api_version() : $version;
1333
+		$model_names = self::model_names_with_plural_routes($version);
1334
+		$primary_key_items = array();
1335
+		foreach ($model_names as $model_name => $model_class_name) {
1336
+			$primary_keys = $model_class_name::instance()->get_combined_primary_key_fields();
1337
+			foreach ($primary_keys as $primary_key_name => $primary_key_field) {
1338
+				if (count($primary_keys) > 1) {
1339
+					$primary_key_items[ strtolower($model_name) ][] = $primary_key_name;
1340
+				} else {
1341
+					$primary_key_items[ strtolower($model_name) ] = $primary_key_name;
1342
+				}
1343
+			}
1344
+		}
1345
+		return $primary_key_items;
1346
+	}
1347
+
1348
+	/**
1349
+	 * Determines the EE REST API debug mode is activated, or not.
1350
+	 * @since 4.9.76.p
1351
+	 * @return bool
1352
+	 */
1353
+	public static function debugMode()
1354
+	{
1355
+		static $debug_mode = null; // could be class prop
1356
+		if ($debug_mode === null) {
1357
+			$debug_mode = defined('EE_REST_API_DEBUG_MODE') && EE_REST_API_DEBUG_MODE;
1358
+		}
1359
+		return $debug_mode;
1360
+	}
1361
+
1362
+
1363
+
1364
+	/**
1365
+	 *    run - initial module setup
1366
+	 *
1367
+	 * @access    public
1368
+	 * @param  WP $WP
1369
+	 * @return    void
1370
+	 */
1371
+	public function run($WP)
1372
+	{
1373
+	}
1374 1374
 }
Please login to merge, or discard this patch.
modules/ticket_selector/TicketSelectorStandard.php 2 patches
Indentation   +105 added lines, -105 removed lines patch added patch discarded remove patch
@@ -20,116 +20,116 @@
 block discarded – undo
20 20
 class TicketSelectorStandard extends TicketSelector
21 21
 {
22 22
 
23
-    /**
24
-     * @var string $date_format
25
-     */
26
-    protected $date_format;
23
+	/**
24
+	 * @var string $date_format
25
+	 */
26
+	protected $date_format;
27 27
 
28
-    /**
29
-     * @var string $time_format
30
-     */
31
-    protected $time_format;
28
+	/**
29
+	 * @var string $time_format
30
+	 */
31
+	protected $time_format;
32 32
 
33
-    /**
34
-     * @var EE_Ticket_Selector_Config $ticket_selector_config
35
-     */
36
-    protected $ticket_selector_config;
33
+	/**
34
+	 * @var EE_Ticket_Selector_Config $ticket_selector_config
35
+	 */
36
+	protected $ticket_selector_config;
37 37
 
38
-    /**
39
-     * @var EE_Tax_Config $tax_config
40
-     */
41
-    protected $tax_config;
38
+	/**
39
+	 * @var EE_Tax_Config $tax_config
40
+	 */
41
+	protected $tax_config;
42 42
 
43 43
 
44
-    /**
45
-     * TicketSelectorSimple constructor.
46
-     *
47
-     * @param EE_Ticket_Selector_Config $ticket_selector_config
48
-     * @param EE_Tax_Config             $tax_config
49
-     * @param EE_Event                  $event
50
-     * @param EE_Ticket[]               $tickets
51
-     * @param int                       $max_attendees
52
-     * @param array                     $template_args
53
-     * @param string                    $date_format
54
-     * @param string                    $time_format
55
-     * @throws EE_Error
56
-     */
57
-    public function __construct(
58
-        EE_Ticket_Selector_Config $ticket_selector_config,
59
-        EE_Tax_Config $tax_config,
60
-        EE_Event $event,
61
-        array $tickets,
62
-        $max_attendees,
63
-        array $template_args,
64
-        $date_format = 'Y-m-d',
65
-        $time_format = 'g:i a'
66
-    ) {
67
-        $this->ticket_selector_config = $ticket_selector_config;
68
-        $this->tax_config             = $tax_config;
69
-        $this->date_format            = $date_format;
70
-        $this->time_format            = $time_format;
71
-        parent::__construct($event, $tickets, $max_attendees, $template_args);
72
-    }
44
+	/**
45
+	 * TicketSelectorSimple constructor.
46
+	 *
47
+	 * @param EE_Ticket_Selector_Config $ticket_selector_config
48
+	 * @param EE_Tax_Config             $tax_config
49
+	 * @param EE_Event                  $event
50
+	 * @param EE_Ticket[]               $tickets
51
+	 * @param int                       $max_attendees
52
+	 * @param array                     $template_args
53
+	 * @param string                    $date_format
54
+	 * @param string                    $time_format
55
+	 * @throws EE_Error
56
+	 */
57
+	public function __construct(
58
+		EE_Ticket_Selector_Config $ticket_selector_config,
59
+		EE_Tax_Config $tax_config,
60
+		EE_Event $event,
61
+		array $tickets,
62
+		$max_attendees,
63
+		array $template_args,
64
+		$date_format = 'Y-m-d',
65
+		$time_format = 'g:i a'
66
+	) {
67
+		$this->ticket_selector_config = $ticket_selector_config;
68
+		$this->tax_config             = $tax_config;
69
+		$this->date_format            = $date_format;
70
+		$this->time_format            = $time_format;
71
+		parent::__construct($event, $tickets, $max_attendees, $template_args);
72
+	}
73 73
 
74 74
 
75
-    /**
76
-     * sets any and all template args that are required for this Ticket Selector
77
-     *
78
-     * @return void
79
-     * @throws EE_Error
80
-     */
81
-    protected function addTemplateArgs()
82
-    {
83
-        $row                      = 1;
84
-        $ticket_row_html          = '';
85
-        $required_ticket_sold_out = false;
86
-        // flag to indicate that at least one taxable ticket has been encountered
87
-        $taxable_tickets                          = false;
88
-        $datetime_selector                        = null;
89
-        $this->template_args['datetime_selector'] = '';
90
-        if (
91
-            $this->ticket_selector_config->getShowDatetimeSelector()
92
-            !== EE_Ticket_Selector_Config::DO_NOT_SHOW_DATETIME_SELECTOR
93
-        ) {
94
-            $datetime_selector                        = new DatetimeSelector(
95
-                $this->event,
96
-                $this->tickets,
97
-                $this->ticket_selector_config,
98
-                $this->date_format,
99
-                $this->time_format
100
-            );
101
-            $this->template_args['datetime_selector'] = $datetime_selector->getDatetimeSelector();
102
-        }
103
-        $total_tickets = count($this->tickets);
104
-        // loop through tickets
105
-        foreach ($this->tickets as $ticket) {
106
-            if ($ticket instanceof EE_Ticket) {
107
-                $cols                     = 2;
108
-                $taxable_tickets          = $ticket->taxable() ? true : $taxable_tickets;
109
-                $ticket_selector_row      = new TicketSelectorRowStandard(
110
-                    new TicketDetails($ticket, $this->ticket_selector_config, $this->template_args),
111
-                    $this->tax_config,
112
-                    $total_tickets,
113
-                    $this->max_attendees,
114
-                    $row,
115
-                    $cols,
116
-                    $required_ticket_sold_out,
117
-                    $this->template_args['event_status'],
118
-                    $datetime_selector instanceof DatetimeSelector
119
-                        ? $datetime_selector->getTicketDatetimeClasses($ticket)
120
-                        : ''
121
-                );
122
-                $ticket_row_html          .= $ticket_selector_row->getHtml();
123
-                $required_ticket_sold_out = $ticket_selector_row->getRequiredTicketSoldOut();
124
-                $row++;
125
-            }
126
-        }
127
-        $this->template_args['row']                              = $row;
128
-        $this->template_args['ticket_row_html']                  = $ticket_row_html;
129
-        $this->template_args['taxable_tickets']                  = $taxable_tickets;
130
-        $this->template_args['prices_displayed_including_taxes'] = $this->tax_config->prices_displayed_including_taxes;
131
-        $this->template_args['template_path']                    =
132
-            TICKET_SELECTOR_TEMPLATES_PATH . 'standard_ticket_selector.template.php';
133
-        remove_all_filters('FHEE__EE_Ticket_Selector__hide_ticket_selector');
134
-    }
75
+	/**
76
+	 * sets any and all template args that are required for this Ticket Selector
77
+	 *
78
+	 * @return void
79
+	 * @throws EE_Error
80
+	 */
81
+	protected function addTemplateArgs()
82
+	{
83
+		$row                      = 1;
84
+		$ticket_row_html          = '';
85
+		$required_ticket_sold_out = false;
86
+		// flag to indicate that at least one taxable ticket has been encountered
87
+		$taxable_tickets                          = false;
88
+		$datetime_selector                        = null;
89
+		$this->template_args['datetime_selector'] = '';
90
+		if (
91
+			$this->ticket_selector_config->getShowDatetimeSelector()
92
+			!== EE_Ticket_Selector_Config::DO_NOT_SHOW_DATETIME_SELECTOR
93
+		) {
94
+			$datetime_selector                        = new DatetimeSelector(
95
+				$this->event,
96
+				$this->tickets,
97
+				$this->ticket_selector_config,
98
+				$this->date_format,
99
+				$this->time_format
100
+			);
101
+			$this->template_args['datetime_selector'] = $datetime_selector->getDatetimeSelector();
102
+		}
103
+		$total_tickets = count($this->tickets);
104
+		// loop through tickets
105
+		foreach ($this->tickets as $ticket) {
106
+			if ($ticket instanceof EE_Ticket) {
107
+				$cols                     = 2;
108
+				$taxable_tickets          = $ticket->taxable() ? true : $taxable_tickets;
109
+				$ticket_selector_row      = new TicketSelectorRowStandard(
110
+					new TicketDetails($ticket, $this->ticket_selector_config, $this->template_args),
111
+					$this->tax_config,
112
+					$total_tickets,
113
+					$this->max_attendees,
114
+					$row,
115
+					$cols,
116
+					$required_ticket_sold_out,
117
+					$this->template_args['event_status'],
118
+					$datetime_selector instanceof DatetimeSelector
119
+						? $datetime_selector->getTicketDatetimeClasses($ticket)
120
+						: ''
121
+				);
122
+				$ticket_row_html          .= $ticket_selector_row->getHtml();
123
+				$required_ticket_sold_out = $ticket_selector_row->getRequiredTicketSoldOut();
124
+				$row++;
125
+			}
126
+		}
127
+		$this->template_args['row']                              = $row;
128
+		$this->template_args['ticket_row_html']                  = $ticket_row_html;
129
+		$this->template_args['taxable_tickets']                  = $taxable_tickets;
130
+		$this->template_args['prices_displayed_including_taxes'] = $this->tax_config->prices_displayed_including_taxes;
131
+		$this->template_args['template_path']                    =
132
+			TICKET_SELECTOR_TEMPLATES_PATH . 'standard_ticket_selector.template.php';
133
+		remove_all_filters('FHEE__EE_Ticket_Selector__hide_ticket_selector');
134
+	}
135 135
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -91,7 +91,7 @@  discard block
 block discarded – undo
91 91
             $this->ticket_selector_config->getShowDatetimeSelector()
92 92
             !== EE_Ticket_Selector_Config::DO_NOT_SHOW_DATETIME_SELECTOR
93 93
         ) {
94
-            $datetime_selector                        = new DatetimeSelector(
94
+            $datetime_selector = new DatetimeSelector(
95 95
                 $this->event,
96 96
                 $this->tickets,
97 97
                 $this->ticket_selector_config,
@@ -119,7 +119,7 @@  discard block
 block discarded – undo
119 119
                         ? $datetime_selector->getTicketDatetimeClasses($ticket)
120 120
                         : ''
121 121
                 );
122
-                $ticket_row_html          .= $ticket_selector_row->getHtml();
122
+                $ticket_row_html .= $ticket_selector_row->getHtml();
123 123
                 $required_ticket_sold_out = $ticket_selector_row->getRequiredTicketSoldOut();
124 124
                 $row++;
125 125
             }
@@ -129,7 +129,7 @@  discard block
 block discarded – undo
129 129
         $this->template_args['taxable_tickets']                  = $taxable_tickets;
130 130
         $this->template_args['prices_displayed_including_taxes'] = $this->tax_config->prices_displayed_including_taxes;
131 131
         $this->template_args['template_path']                    =
132
-            TICKET_SELECTOR_TEMPLATES_PATH . 'standard_ticket_selector.template.php';
132
+            TICKET_SELECTOR_TEMPLATES_PATH.'standard_ticket_selector.template.php';
133 133
         remove_all_filters('FHEE__EE_Ticket_Selector__hide_ticket_selector');
134 134
     }
135 135
 }
Please login to merge, or discard this patch.
modules/ticket_selector/EED_Ticket_Selector.module.php 2 patches
Indentation   +487 added lines, -487 removed lines patch added patch discarded remove patch
@@ -19,491 +19,491 @@
 block discarded – undo
19 19
 class EED_Ticket_Selector extends EED_Module
20 20
 {
21 21
 
22
-    /**
23
-     * @var DisplayTicketSelector $ticket_selector
24
-     */
25
-    private static $ticket_selector;
26
-
27
-    /**
28
-     * @var TicketSelectorIframeEmbedButton $iframe_embed_button
29
-     */
30
-    private static $iframe_embed_button;
31
-
32
-
33
-    /**
34
-     * @return EED_Module|EED_Ticket_Selector
35
-     * @throws EE_Error
36
-     * @throws ReflectionException
37
-     */
38
-    public static function instance()
39
-    {
40
-        return parent::get_instance(__CLASS__);
41
-    }
42
-
43
-
44
-    /**
45
-     * @return EE_Ticket_Selector_Config
46
-     * @throws EE_Error
47
-     * @throws ReflectionException
48
-     */
49
-    public static function ticketConfig()
50
-    {
51
-        EED_Ticket_Selector::instance()->set_config();
52
-        return EED_Ticket_Selector::instance()->config();
53
-    }
54
-
55
-
56
-    /**
57
-     * @return void
58
-     */
59
-    protected function set_config()
60
-    {
61
-        if ($this->_config instanceof EE_Ticket_Selector_Config) {
62
-            return;
63
-        }
64
-        $this->set_config_section('template_settings');
65
-        $this->set_config_class('EE_Ticket_Selector_Config');
66
-        $this->set_config_name('EED_Ticket_Selector');
67
-    }
68
-
69
-
70
-    /**
71
-     *    set_hooks - for hooking into EE Core, other modules, etc
72
-     *
73
-     * @return void
74
-     */
75
-    public static function set_hooks()
76
-    {
77
-        // routing
78
-        EE_Config::register_route(
79
-            'iframe',
80
-            'EED_Ticket_Selector',
81
-            'ticket_selector_iframe',
82
-            'ticket_selector'
83
-        );
84
-        EE_Config::register_route(
85
-            'process_ticket_selections',
86
-            'EED_Ticket_Selector',
87
-            'process_ticket_selections'
88
-        );
89
-        EE_Config::register_route(
90
-            'cancel_ticket_selections',
91
-            'EED_Ticket_Selector',
92
-            'cancel_ticket_selections'
93
-        );
94
-        add_action('wp_loaded', ['EED_Ticket_Selector', 'set_definitions'], 2);
95
-        add_action('AHEE_event_details_header_bottom', ['EED_Ticket_Selector', 'display_ticket_selector'], 10, 1);
96
-        add_action('wp_enqueue_scripts', ['EED_Ticket_Selector', 'translate_js_strings'], 0);
97
-        add_action('wp_enqueue_scripts', ['EED_Ticket_Selector', 'load_tckt_slctr_assets'], 10);
98
-        EED_Ticket_Selector::loadIframeAssets();
99
-    }
100
-
101
-
102
-    /**
103
-     *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
104
-     *
105
-     * @return void
106
-     */
107
-    public static function set_hooks_admin()
108
-    {
109
-        // hook into the end of the \EE_Admin_Page::_load_page_dependencies()
110
-        // to load assets for "espresso_events" page on the "edit" route (action)
111
-        add_action(
112
-            'FHEE__EE_Admin_Page___load_page_dependencies__after_load__espresso_events__edit',
113
-            ['EED_Ticket_Selector', 'ticket_selector_iframe_embed_button'],
114
-            10
115
-        );
116
-        /**
117
-         * Make sure assets for the ticket selector are loaded on the espresso registrations route so  admin side
118
-         * registrations work.
119
-         */
120
-        add_action(
121
-            'FHEE__EE_Admin_Page___load_page_dependencies__after_load__espresso_registrations__new_registration',
122
-            ['EED_Ticket_Selector', 'set_definitions'],
123
-            10
124
-        );
125
-    }
126
-
127
-
128
-    /**
129
-     *    set_definitions
130
-     *
131
-     * @return void
132
-     * @throws EE_Error
133
-     * @throws ReflectionException
134
-     */
135
-    public static function set_definitions()
136
-    {
137
-        // don't do this twice
138
-        if (defined('TICKET_SELECTOR_ASSETS_URL')) {
139
-            return;
140
-        }
141
-        define('TICKET_SELECTOR_ASSETS_URL', plugin_dir_url(__FILE__) . 'assets/');
142
-        define(
143
-            'TICKET_SELECTOR_TEMPLATES_PATH',
144
-            str_replace('\\', '/', plugin_dir_path(__FILE__)) . 'templates/'
145
-        );
146
-        // initialize config
147
-        EED_Ticket_Selector::instance()->set_config();
148
-        // if config is not set, initialize
149
-        if (
150
-            ! EE_Registry::instance()->CFG->template_settings->EED_Ticket_Selector instanceof EE_Ticket_Selector_Config
151
-        ) {
152
-            EED_Ticket_Selector::instance()->set_config();
153
-            EE_Registry::instance()->CFG->template_settings->EED_Ticket_Selector =
154
-                EED_Ticket_Selector::instance()->config();
155
-        }
156
-    }
157
-
158
-
159
-    /**
160
-     * @return DisplayTicketSelector
161
-     * @throws EE_Error
162
-     * @throws ReflectionException
163
-     */
164
-    public static function ticketSelector()
165
-    {
166
-        if (! EED_Ticket_Selector::$ticket_selector instanceof DisplayTicketSelector) {
167
-            EED_Ticket_Selector::$ticket_selector = new DisplayTicketSelector(
168
-                EED_Ticket_Selector::getRequest(),
169
-                EED_Ticket_Selector::ticketConfig(),
170
-                EED_Events_Archive::is_iframe()
171
-            );
172
-        }
173
-        return EED_Ticket_Selector::$ticket_selector;
174
-    }
175
-
176
-
177
-    /**
178
-     * gets the ball rolling
179
-     *
180
-     * @param WP $WP
181
-     * @return void
182
-     */
183
-    public function run($WP)
184
-    {
185
-    }
186
-
187
-
188
-    /**
189
-     * @return TicketSelectorIframeEmbedButton
190
-     */
191
-    public static function getIframeEmbedButton()
192
-    {
193
-        if (! self::$iframe_embed_button instanceof TicketSelectorIframeEmbedButton) {
194
-            self::$iframe_embed_button = new TicketSelectorIframeEmbedButton();
195
-        }
196
-        return self::$iframe_embed_button;
197
-    }
198
-
199
-
200
-    /**
201
-     * ticket_selector_iframe_embed_button
202
-     *
203
-     * @return void
204
-     */
205
-    public static function ticket_selector_iframe_embed_button()
206
-    {
207
-        $iframe_embed_button = EED_Ticket_Selector::getIframeEmbedButton();
208
-        $iframe_embed_button->addEventEditorIframeEmbedButton();
209
-    }
210
-
211
-
212
-    /**
213
-     * ticket_selector_iframe
214
-     *
215
-     * @return void
216
-     * @throws DomainException
217
-     */
218
-    public function ticket_selector_iframe()
219
-    {
220
-        EE_Dependency_Map::register_dependencies(
221
-            TicketSelectorIframe::class,
222
-            [
223
-                'EEM_Event'                                            => EE_Dependency_Map::load_from_cache,
224
-                'EventEspresso\core\services\request\CurrentPage'      => EE_Dependency_Map::load_from_cache,
225
-                'EventEspresso\core\services\request\RequestInterface' => EE_Dependency_Map::load_from_cache,
226
-            ]
227
-        );
228
-        $ticket_selector_iframe = LoaderFactory::getLoader()->getNew(TicketSelectorIframe::class);
229
-        $ticket_selector_iframe->display();
230
-    }
231
-
232
-
233
-    /**
234
-     * creates buttons for selecting number of attendees for an event
235
-     *
236
-     * @param WP_Post|int $event
237
-     * @param bool        $view_details
238
-     * @return string
239
-     * @throws EE_Error
240
-     * @throws ReflectionException
241
-     */
242
-    public static function display_ticket_selector($event = null, $view_details = false)
243
-    {
244
-        return EED_Ticket_Selector::ticketSelector()->display($event, $view_details);
245
-    }
246
-
247
-
248
-    /**
249
-     * @return bool  or FALSE
250
-     * @throws EE_Error
251
-     * @throws InvalidArgumentException
252
-     * @throws InvalidInterfaceException
253
-     * @throws InvalidDataTypeException
254
-     * @throws ReflectionException
255
-     */
256
-    public function process_ticket_selections()
257
-    {
258
-        /** @var EventEspresso\modules\ticket_selector\ProcessTicketSelector $form */
259
-        $form = LoaderFactory::getLoader()->getShared('EventEspresso\modules\ticket_selector\ProcessTicketSelector');
260
-        return $form->processTicketSelections();
261
-    }
262
-
263
-
264
-    /**
265
-     * @return bool
266
-     * @throws InvalidArgumentException
267
-     * @throws InvalidInterfaceException
268
-     * @throws InvalidDataTypeException
269
-     * @throws EE_Error
270
-     * @throws ReflectionException
271
-     */
272
-    public static function cancel_ticket_selections()
273
-    {
274
-        /** @var EventEspresso\modules\ticket_selector\ProcessTicketSelector $form */
275
-        $form = LoaderFactory::getLoader()->getShared('EventEspresso\modules\ticket_selector\ProcessTicketSelector');
276
-        return $form->cancelTicketSelections();
277
-    }
278
-
279
-
280
-    /**
281
-     * @return void
282
-     */
283
-    public static function translate_js_strings()
284
-    {
285
-        EE_Registry::$i18n_js_strings['please_select_date_filter_notice'] = esc_html__(
286
-            'please select a datetime',
287
-            'event_espresso'
288
-        );
289
-    }
290
-
291
-
292
-    /**
293
-     * @return void
294
-     */
295
-    public static function load_tckt_slctr_assets()
296
-    {
297
-        if (apply_filters('FHEE__EED_Ticket_Selector__load_tckt_slctr_assets', false)) {
298
-            // add some style
299
-            wp_register_style(
300
-                'ticket_selector',
301
-                TICKET_SELECTOR_ASSETS_URL . 'ticket_selector.css',
302
-                [],
303
-                EVENT_ESPRESSO_VERSION
304
-            );
305
-            wp_enqueue_style('ticket_selector');
306
-            // make it dance
307
-            wp_register_script(
308
-                'ticket_selector',
309
-                TICKET_SELECTOR_ASSETS_URL . 'ticket_selector.js',
310
-                ['espresso_core'],
311
-                EVENT_ESPRESSO_VERSION,
312
-                true
313
-            );
314
-            wp_enqueue_script('ticket_selector');
315
-            require_once EE_LIBRARIES
316
-                         . 'form_sections/strategies/display/EE_Checkbox_Dropdown_Selector_Display_Strategy.strategy.php';
317
-            EE_Checkbox_Dropdown_Selector_Display_Strategy::enqueue_styles_and_scripts();
318
-        }
319
-    }
320
-
321
-
322
-    /**
323
-     * @return void
324
-     */
325
-    public static function loadIframeAssets()
326
-    {
327
-        // for event lists
328
-        add_filter(
329
-            'FHEE__EventEspresso_modules_events_archive_EventsArchiveIframe__display__css',
330
-            ['EED_Ticket_Selector', 'iframeCss']
331
-        );
332
-        add_filter(
333
-            'FHEE__EventEspresso_modules_events_archive_EventsArchiveIframe__display__js',
334
-            ['EED_Ticket_Selector', 'iframeJs']
335
-        );
336
-        // for ticket selectors
337
-        add_filter(
338
-            'FHEE__EED_Ticket_Selector__ticket_selector_iframe__css',
339
-            ['EED_Ticket_Selector', 'iframeCss']
340
-        );
341
-        add_filter(
342
-            'FHEE__EED_Ticket_Selector__ticket_selector_iframe__js',
343
-            ['EED_Ticket_Selector', 'iframeJs']
344
-        );
345
-    }
346
-
347
-
348
-    /**
349
-     * Informs the rest of the forms system what CSS and JS is needed to display the input
350
-     *
351
-     * @param array $iframe_css
352
-     * @return array
353
-     */
354
-    public static function iframeCss(array $iframe_css)
355
-    {
356
-        $iframe_css['ticket_selector'] = TICKET_SELECTOR_ASSETS_URL . 'ticket_selector.css';
357
-        return $iframe_css;
358
-    }
359
-
360
-
361
-    /**
362
-     * Informs the rest of the forms system what CSS and JS is needed to display the input
363
-     *
364
-     * @param array $iframe_js
365
-     * @return array
366
-     */
367
-    public static function iframeJs(array $iframe_js)
368
-    {
369
-        $iframe_js['ticket_selector'] = TICKET_SELECTOR_ASSETS_URL . 'ticket_selector.js';
370
-        return $iframe_js;
371
-    }
372
-
373
-
374
-    /****************************** DEPRECATED ******************************/
375
-
376
-
377
-    /**
378
-     * @return string
379
-     * @throws EE_Error
380
-     * @throws ReflectionException
381
-     * @deprecated
382
-     */
383
-    public static function display_view_details_btn()
384
-    {
385
-        // todo add doing_it_wrong() notice during next major version
386
-        return EED_Ticket_Selector::ticketSelector()->displayViewDetailsButton();
387
-    }
388
-
389
-
390
-    /**
391
-     * @return string
392
-     * @throws EE_Error
393
-     * @throws ReflectionException
394
-     * @deprecated
395
-     */
396
-    public static function display_ticket_selector_submit()
397
-    {
398
-        // todo add doing_it_wrong() notice during next major version
399
-        return EED_Ticket_Selector::ticketSelector()->displaySubmitButton();
400
-    }
401
-
402
-
403
-    /**
404
-     * @param string $permalink_string
405
-     * @param int    $id
406
-     * @param string $new_title
407
-     * @param string $new_slug
408
-     * @return string
409
-     * @throws InvalidArgumentException
410
-     * @throws InvalidDataTypeException
411
-     * @throws InvalidInterfaceException
412
-     * @deprecated
413
-     */
414
-    public static function iframe_code_button($permalink_string, $id, $new_title = '', $new_slug = '')
415
-    {
416
-        $request = self::getRequest();
417
-        // todo add doing_it_wrong() notice during next major version
418
-        if (
419
-            $request->getRequestParam('page') === 'espresso_events'
420
-            && $request->getRequestParam('action') === 'edit'
421
-        ) {
422
-            $iframe_embed_button = EED_Ticket_Selector::getIframeEmbedButton();
423
-            $iframe_embed_button->addEventEditorIframeEmbedButton();
424
-        }
425
-        return '';
426
-    }
427
-
428
-
429
-    /**
430
-     * @param int    $ID
431
-     * @param string $external_url
432
-     * @return string
433
-     * @throws EE_Error
434
-     * @throws ReflectionException
435
-     * @deprecated
436
-     */
437
-    public static function ticket_selector_form_open($ID = 0, $external_url = '')
438
-    {
439
-        // todo add doing_it_wrong() notice during next major version
440
-        return EED_Ticket_Selector::ticketSelector()->formOpen($ID, $external_url);
441
-    }
442
-
443
-
444
-    /**
445
-     * @return string
446
-     * @throws EE_Error
447
-     * @throws ReflectionException
448
-     * @deprecated
449
-     */
450
-    public static function ticket_selector_form_close()
451
-    {
452
-        // todo add doing_it_wrong() notice during next major version
453
-        return EED_Ticket_Selector::ticketSelector()->formClose();
454
-    }
455
-
456
-
457
-    /**
458
-     * @return string
459
-     * @throws EE_Error
460
-     * @throws ReflectionException
461
-     * @deprecated
462
-     */
463
-    public static function no_tkt_slctr_end_dv()
464
-    {
465
-        // todo add doing_it_wrong() notice during next major version
466
-        return EED_Ticket_Selector::ticketSelector()->ticketSelectorEndDiv();
467
-    }
468
-
469
-
470
-    /**
471
-     * @return string
472
-     * @throws EE_Error
473
-     * @throws ReflectionException
474
-     * @deprecated 4.9.13
475
-     */
476
-    public static function tkt_slctr_end_dv()
477
-    {
478
-        return EED_Ticket_Selector::ticketSelector()->clearTicketSelector();
479
-    }
480
-
481
-
482
-    /**
483
-     * @return string
484
-     * @throws EE_Error
485
-     * @throws ReflectionException
486
-     * @deprecated
487
-     */
488
-    public static function clear_tkt_slctr()
489
-    {
490
-        return EED_Ticket_Selector::ticketSelector()->clearTicketSelector();
491
-    }
492
-
493
-
494
-    /**
495
-     * @deprecated
496
-     */
497
-    public static function load_tckt_slctr_assets_admin()
498
-    {
499
-        $request = self::getRequest();
500
-        // todo add doing_it_wrong() notice during next major version
501
-        if (
502
-            $request->getRequestParam('page') === 'espresso_events'
503
-            && $request->getRequestParam('action') === 'edit'
504
-        ) {
505
-            $iframe_embed_button = EED_Ticket_Selector::getIframeEmbedButton();
506
-            $iframe_embed_button->embedButtonAssets();
507
-        }
508
-    }
22
+	/**
23
+	 * @var DisplayTicketSelector $ticket_selector
24
+	 */
25
+	private static $ticket_selector;
26
+
27
+	/**
28
+	 * @var TicketSelectorIframeEmbedButton $iframe_embed_button
29
+	 */
30
+	private static $iframe_embed_button;
31
+
32
+
33
+	/**
34
+	 * @return EED_Module|EED_Ticket_Selector
35
+	 * @throws EE_Error
36
+	 * @throws ReflectionException
37
+	 */
38
+	public static function instance()
39
+	{
40
+		return parent::get_instance(__CLASS__);
41
+	}
42
+
43
+
44
+	/**
45
+	 * @return EE_Ticket_Selector_Config
46
+	 * @throws EE_Error
47
+	 * @throws ReflectionException
48
+	 */
49
+	public static function ticketConfig()
50
+	{
51
+		EED_Ticket_Selector::instance()->set_config();
52
+		return EED_Ticket_Selector::instance()->config();
53
+	}
54
+
55
+
56
+	/**
57
+	 * @return void
58
+	 */
59
+	protected function set_config()
60
+	{
61
+		if ($this->_config instanceof EE_Ticket_Selector_Config) {
62
+			return;
63
+		}
64
+		$this->set_config_section('template_settings');
65
+		$this->set_config_class('EE_Ticket_Selector_Config');
66
+		$this->set_config_name('EED_Ticket_Selector');
67
+	}
68
+
69
+
70
+	/**
71
+	 *    set_hooks - for hooking into EE Core, other modules, etc
72
+	 *
73
+	 * @return void
74
+	 */
75
+	public static function set_hooks()
76
+	{
77
+		// routing
78
+		EE_Config::register_route(
79
+			'iframe',
80
+			'EED_Ticket_Selector',
81
+			'ticket_selector_iframe',
82
+			'ticket_selector'
83
+		);
84
+		EE_Config::register_route(
85
+			'process_ticket_selections',
86
+			'EED_Ticket_Selector',
87
+			'process_ticket_selections'
88
+		);
89
+		EE_Config::register_route(
90
+			'cancel_ticket_selections',
91
+			'EED_Ticket_Selector',
92
+			'cancel_ticket_selections'
93
+		);
94
+		add_action('wp_loaded', ['EED_Ticket_Selector', 'set_definitions'], 2);
95
+		add_action('AHEE_event_details_header_bottom', ['EED_Ticket_Selector', 'display_ticket_selector'], 10, 1);
96
+		add_action('wp_enqueue_scripts', ['EED_Ticket_Selector', 'translate_js_strings'], 0);
97
+		add_action('wp_enqueue_scripts', ['EED_Ticket_Selector', 'load_tckt_slctr_assets'], 10);
98
+		EED_Ticket_Selector::loadIframeAssets();
99
+	}
100
+
101
+
102
+	/**
103
+	 *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
104
+	 *
105
+	 * @return void
106
+	 */
107
+	public static function set_hooks_admin()
108
+	{
109
+		// hook into the end of the \EE_Admin_Page::_load_page_dependencies()
110
+		// to load assets for "espresso_events" page on the "edit" route (action)
111
+		add_action(
112
+			'FHEE__EE_Admin_Page___load_page_dependencies__after_load__espresso_events__edit',
113
+			['EED_Ticket_Selector', 'ticket_selector_iframe_embed_button'],
114
+			10
115
+		);
116
+		/**
117
+		 * Make sure assets for the ticket selector are loaded on the espresso registrations route so  admin side
118
+		 * registrations work.
119
+		 */
120
+		add_action(
121
+			'FHEE__EE_Admin_Page___load_page_dependencies__after_load__espresso_registrations__new_registration',
122
+			['EED_Ticket_Selector', 'set_definitions'],
123
+			10
124
+		);
125
+	}
126
+
127
+
128
+	/**
129
+	 *    set_definitions
130
+	 *
131
+	 * @return void
132
+	 * @throws EE_Error
133
+	 * @throws ReflectionException
134
+	 */
135
+	public static function set_definitions()
136
+	{
137
+		// don't do this twice
138
+		if (defined('TICKET_SELECTOR_ASSETS_URL')) {
139
+			return;
140
+		}
141
+		define('TICKET_SELECTOR_ASSETS_URL', plugin_dir_url(__FILE__) . 'assets/');
142
+		define(
143
+			'TICKET_SELECTOR_TEMPLATES_PATH',
144
+			str_replace('\\', '/', plugin_dir_path(__FILE__)) . 'templates/'
145
+		);
146
+		// initialize config
147
+		EED_Ticket_Selector::instance()->set_config();
148
+		// if config is not set, initialize
149
+		if (
150
+			! EE_Registry::instance()->CFG->template_settings->EED_Ticket_Selector instanceof EE_Ticket_Selector_Config
151
+		) {
152
+			EED_Ticket_Selector::instance()->set_config();
153
+			EE_Registry::instance()->CFG->template_settings->EED_Ticket_Selector =
154
+				EED_Ticket_Selector::instance()->config();
155
+		}
156
+	}
157
+
158
+
159
+	/**
160
+	 * @return DisplayTicketSelector
161
+	 * @throws EE_Error
162
+	 * @throws ReflectionException
163
+	 */
164
+	public static function ticketSelector()
165
+	{
166
+		if (! EED_Ticket_Selector::$ticket_selector instanceof DisplayTicketSelector) {
167
+			EED_Ticket_Selector::$ticket_selector = new DisplayTicketSelector(
168
+				EED_Ticket_Selector::getRequest(),
169
+				EED_Ticket_Selector::ticketConfig(),
170
+				EED_Events_Archive::is_iframe()
171
+			);
172
+		}
173
+		return EED_Ticket_Selector::$ticket_selector;
174
+	}
175
+
176
+
177
+	/**
178
+	 * gets the ball rolling
179
+	 *
180
+	 * @param WP $WP
181
+	 * @return void
182
+	 */
183
+	public function run($WP)
184
+	{
185
+	}
186
+
187
+
188
+	/**
189
+	 * @return TicketSelectorIframeEmbedButton
190
+	 */
191
+	public static function getIframeEmbedButton()
192
+	{
193
+		if (! self::$iframe_embed_button instanceof TicketSelectorIframeEmbedButton) {
194
+			self::$iframe_embed_button = new TicketSelectorIframeEmbedButton();
195
+		}
196
+		return self::$iframe_embed_button;
197
+	}
198
+
199
+
200
+	/**
201
+	 * ticket_selector_iframe_embed_button
202
+	 *
203
+	 * @return void
204
+	 */
205
+	public static function ticket_selector_iframe_embed_button()
206
+	{
207
+		$iframe_embed_button = EED_Ticket_Selector::getIframeEmbedButton();
208
+		$iframe_embed_button->addEventEditorIframeEmbedButton();
209
+	}
210
+
211
+
212
+	/**
213
+	 * ticket_selector_iframe
214
+	 *
215
+	 * @return void
216
+	 * @throws DomainException
217
+	 */
218
+	public function ticket_selector_iframe()
219
+	{
220
+		EE_Dependency_Map::register_dependencies(
221
+			TicketSelectorIframe::class,
222
+			[
223
+				'EEM_Event'                                            => EE_Dependency_Map::load_from_cache,
224
+				'EventEspresso\core\services\request\CurrentPage'      => EE_Dependency_Map::load_from_cache,
225
+				'EventEspresso\core\services\request\RequestInterface' => EE_Dependency_Map::load_from_cache,
226
+			]
227
+		);
228
+		$ticket_selector_iframe = LoaderFactory::getLoader()->getNew(TicketSelectorIframe::class);
229
+		$ticket_selector_iframe->display();
230
+	}
231
+
232
+
233
+	/**
234
+	 * creates buttons for selecting number of attendees for an event
235
+	 *
236
+	 * @param WP_Post|int $event
237
+	 * @param bool        $view_details
238
+	 * @return string
239
+	 * @throws EE_Error
240
+	 * @throws ReflectionException
241
+	 */
242
+	public static function display_ticket_selector($event = null, $view_details = false)
243
+	{
244
+		return EED_Ticket_Selector::ticketSelector()->display($event, $view_details);
245
+	}
246
+
247
+
248
+	/**
249
+	 * @return bool  or FALSE
250
+	 * @throws EE_Error
251
+	 * @throws InvalidArgumentException
252
+	 * @throws InvalidInterfaceException
253
+	 * @throws InvalidDataTypeException
254
+	 * @throws ReflectionException
255
+	 */
256
+	public function process_ticket_selections()
257
+	{
258
+		/** @var EventEspresso\modules\ticket_selector\ProcessTicketSelector $form */
259
+		$form = LoaderFactory::getLoader()->getShared('EventEspresso\modules\ticket_selector\ProcessTicketSelector');
260
+		return $form->processTicketSelections();
261
+	}
262
+
263
+
264
+	/**
265
+	 * @return bool
266
+	 * @throws InvalidArgumentException
267
+	 * @throws InvalidInterfaceException
268
+	 * @throws InvalidDataTypeException
269
+	 * @throws EE_Error
270
+	 * @throws ReflectionException
271
+	 */
272
+	public static function cancel_ticket_selections()
273
+	{
274
+		/** @var EventEspresso\modules\ticket_selector\ProcessTicketSelector $form */
275
+		$form = LoaderFactory::getLoader()->getShared('EventEspresso\modules\ticket_selector\ProcessTicketSelector');
276
+		return $form->cancelTicketSelections();
277
+	}
278
+
279
+
280
+	/**
281
+	 * @return void
282
+	 */
283
+	public static function translate_js_strings()
284
+	{
285
+		EE_Registry::$i18n_js_strings['please_select_date_filter_notice'] = esc_html__(
286
+			'please select a datetime',
287
+			'event_espresso'
288
+		);
289
+	}
290
+
291
+
292
+	/**
293
+	 * @return void
294
+	 */
295
+	public static function load_tckt_slctr_assets()
296
+	{
297
+		if (apply_filters('FHEE__EED_Ticket_Selector__load_tckt_slctr_assets', false)) {
298
+			// add some style
299
+			wp_register_style(
300
+				'ticket_selector',
301
+				TICKET_SELECTOR_ASSETS_URL . 'ticket_selector.css',
302
+				[],
303
+				EVENT_ESPRESSO_VERSION
304
+			);
305
+			wp_enqueue_style('ticket_selector');
306
+			// make it dance
307
+			wp_register_script(
308
+				'ticket_selector',
309
+				TICKET_SELECTOR_ASSETS_URL . 'ticket_selector.js',
310
+				['espresso_core'],
311
+				EVENT_ESPRESSO_VERSION,
312
+				true
313
+			);
314
+			wp_enqueue_script('ticket_selector');
315
+			require_once EE_LIBRARIES
316
+						 . 'form_sections/strategies/display/EE_Checkbox_Dropdown_Selector_Display_Strategy.strategy.php';
317
+			EE_Checkbox_Dropdown_Selector_Display_Strategy::enqueue_styles_and_scripts();
318
+		}
319
+	}
320
+
321
+
322
+	/**
323
+	 * @return void
324
+	 */
325
+	public static function loadIframeAssets()
326
+	{
327
+		// for event lists
328
+		add_filter(
329
+			'FHEE__EventEspresso_modules_events_archive_EventsArchiveIframe__display__css',
330
+			['EED_Ticket_Selector', 'iframeCss']
331
+		);
332
+		add_filter(
333
+			'FHEE__EventEspresso_modules_events_archive_EventsArchiveIframe__display__js',
334
+			['EED_Ticket_Selector', 'iframeJs']
335
+		);
336
+		// for ticket selectors
337
+		add_filter(
338
+			'FHEE__EED_Ticket_Selector__ticket_selector_iframe__css',
339
+			['EED_Ticket_Selector', 'iframeCss']
340
+		);
341
+		add_filter(
342
+			'FHEE__EED_Ticket_Selector__ticket_selector_iframe__js',
343
+			['EED_Ticket_Selector', 'iframeJs']
344
+		);
345
+	}
346
+
347
+
348
+	/**
349
+	 * Informs the rest of the forms system what CSS and JS is needed to display the input
350
+	 *
351
+	 * @param array $iframe_css
352
+	 * @return array
353
+	 */
354
+	public static function iframeCss(array $iframe_css)
355
+	{
356
+		$iframe_css['ticket_selector'] = TICKET_SELECTOR_ASSETS_URL . 'ticket_selector.css';
357
+		return $iframe_css;
358
+	}
359
+
360
+
361
+	/**
362
+	 * Informs the rest of the forms system what CSS and JS is needed to display the input
363
+	 *
364
+	 * @param array $iframe_js
365
+	 * @return array
366
+	 */
367
+	public static function iframeJs(array $iframe_js)
368
+	{
369
+		$iframe_js['ticket_selector'] = TICKET_SELECTOR_ASSETS_URL . 'ticket_selector.js';
370
+		return $iframe_js;
371
+	}
372
+
373
+
374
+	/****************************** DEPRECATED ******************************/
375
+
376
+
377
+	/**
378
+	 * @return string
379
+	 * @throws EE_Error
380
+	 * @throws ReflectionException
381
+	 * @deprecated
382
+	 */
383
+	public static function display_view_details_btn()
384
+	{
385
+		// todo add doing_it_wrong() notice during next major version
386
+		return EED_Ticket_Selector::ticketSelector()->displayViewDetailsButton();
387
+	}
388
+
389
+
390
+	/**
391
+	 * @return string
392
+	 * @throws EE_Error
393
+	 * @throws ReflectionException
394
+	 * @deprecated
395
+	 */
396
+	public static function display_ticket_selector_submit()
397
+	{
398
+		// todo add doing_it_wrong() notice during next major version
399
+		return EED_Ticket_Selector::ticketSelector()->displaySubmitButton();
400
+	}
401
+
402
+
403
+	/**
404
+	 * @param string $permalink_string
405
+	 * @param int    $id
406
+	 * @param string $new_title
407
+	 * @param string $new_slug
408
+	 * @return string
409
+	 * @throws InvalidArgumentException
410
+	 * @throws InvalidDataTypeException
411
+	 * @throws InvalidInterfaceException
412
+	 * @deprecated
413
+	 */
414
+	public static function iframe_code_button($permalink_string, $id, $new_title = '', $new_slug = '')
415
+	{
416
+		$request = self::getRequest();
417
+		// todo add doing_it_wrong() notice during next major version
418
+		if (
419
+			$request->getRequestParam('page') === 'espresso_events'
420
+			&& $request->getRequestParam('action') === 'edit'
421
+		) {
422
+			$iframe_embed_button = EED_Ticket_Selector::getIframeEmbedButton();
423
+			$iframe_embed_button->addEventEditorIframeEmbedButton();
424
+		}
425
+		return '';
426
+	}
427
+
428
+
429
+	/**
430
+	 * @param int    $ID
431
+	 * @param string $external_url
432
+	 * @return string
433
+	 * @throws EE_Error
434
+	 * @throws ReflectionException
435
+	 * @deprecated
436
+	 */
437
+	public static function ticket_selector_form_open($ID = 0, $external_url = '')
438
+	{
439
+		// todo add doing_it_wrong() notice during next major version
440
+		return EED_Ticket_Selector::ticketSelector()->formOpen($ID, $external_url);
441
+	}
442
+
443
+
444
+	/**
445
+	 * @return string
446
+	 * @throws EE_Error
447
+	 * @throws ReflectionException
448
+	 * @deprecated
449
+	 */
450
+	public static function ticket_selector_form_close()
451
+	{
452
+		// todo add doing_it_wrong() notice during next major version
453
+		return EED_Ticket_Selector::ticketSelector()->formClose();
454
+	}
455
+
456
+
457
+	/**
458
+	 * @return string
459
+	 * @throws EE_Error
460
+	 * @throws ReflectionException
461
+	 * @deprecated
462
+	 */
463
+	public static function no_tkt_slctr_end_dv()
464
+	{
465
+		// todo add doing_it_wrong() notice during next major version
466
+		return EED_Ticket_Selector::ticketSelector()->ticketSelectorEndDiv();
467
+	}
468
+
469
+
470
+	/**
471
+	 * @return string
472
+	 * @throws EE_Error
473
+	 * @throws ReflectionException
474
+	 * @deprecated 4.9.13
475
+	 */
476
+	public static function tkt_slctr_end_dv()
477
+	{
478
+		return EED_Ticket_Selector::ticketSelector()->clearTicketSelector();
479
+	}
480
+
481
+
482
+	/**
483
+	 * @return string
484
+	 * @throws EE_Error
485
+	 * @throws ReflectionException
486
+	 * @deprecated
487
+	 */
488
+	public static function clear_tkt_slctr()
489
+	{
490
+		return EED_Ticket_Selector::ticketSelector()->clearTicketSelector();
491
+	}
492
+
493
+
494
+	/**
495
+	 * @deprecated
496
+	 */
497
+	public static function load_tckt_slctr_assets_admin()
498
+	{
499
+		$request = self::getRequest();
500
+		// todo add doing_it_wrong() notice during next major version
501
+		if (
502
+			$request->getRequestParam('page') === 'espresso_events'
503
+			&& $request->getRequestParam('action') === 'edit'
504
+		) {
505
+			$iframe_embed_button = EED_Ticket_Selector::getIframeEmbedButton();
506
+			$iframe_embed_button->embedButtonAssets();
507
+		}
508
+	}
509 509
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -138,10 +138,10 @@  discard block
 block discarded – undo
138 138
         if (defined('TICKET_SELECTOR_ASSETS_URL')) {
139 139
             return;
140 140
         }
141
-        define('TICKET_SELECTOR_ASSETS_URL', plugin_dir_url(__FILE__) . 'assets/');
141
+        define('TICKET_SELECTOR_ASSETS_URL', plugin_dir_url(__FILE__).'assets/');
142 142
         define(
143 143
             'TICKET_SELECTOR_TEMPLATES_PATH',
144
-            str_replace('\\', '/', plugin_dir_path(__FILE__)) . 'templates/'
144
+            str_replace('\\', '/', plugin_dir_path(__FILE__)).'templates/'
145 145
         );
146 146
         // initialize config
147 147
         EED_Ticket_Selector::instance()->set_config();
@@ -163,7 +163,7 @@  discard block
 block discarded – undo
163 163
      */
164 164
     public static function ticketSelector()
165 165
     {
166
-        if (! EED_Ticket_Selector::$ticket_selector instanceof DisplayTicketSelector) {
166
+        if ( ! EED_Ticket_Selector::$ticket_selector instanceof DisplayTicketSelector) {
167 167
             EED_Ticket_Selector::$ticket_selector = new DisplayTicketSelector(
168 168
                 EED_Ticket_Selector::getRequest(),
169 169
                 EED_Ticket_Selector::ticketConfig(),
@@ -190,7 +190,7 @@  discard block
 block discarded – undo
190 190
      */
191 191
     public static function getIframeEmbedButton()
192 192
     {
193
-        if (! self::$iframe_embed_button instanceof TicketSelectorIframeEmbedButton) {
193
+        if ( ! self::$iframe_embed_button instanceof TicketSelectorIframeEmbedButton) {
194 194
             self::$iframe_embed_button = new TicketSelectorIframeEmbedButton();
195 195
         }
196 196
         return self::$iframe_embed_button;
@@ -298,7 +298,7 @@  discard block
 block discarded – undo
298 298
             // add some style
299 299
             wp_register_style(
300 300
                 'ticket_selector',
301
-                TICKET_SELECTOR_ASSETS_URL . 'ticket_selector.css',
301
+                TICKET_SELECTOR_ASSETS_URL.'ticket_selector.css',
302 302
                 [],
303 303
                 EVENT_ESPRESSO_VERSION
304 304
             );
@@ -306,7 +306,7 @@  discard block
 block discarded – undo
306 306
             // make it dance
307 307
             wp_register_script(
308 308
                 'ticket_selector',
309
-                TICKET_SELECTOR_ASSETS_URL . 'ticket_selector.js',
309
+                TICKET_SELECTOR_ASSETS_URL.'ticket_selector.js',
310 310
                 ['espresso_core'],
311 311
                 EVENT_ESPRESSO_VERSION,
312 312
                 true
@@ -353,7 +353,7 @@  discard block
 block discarded – undo
353 353
      */
354 354
     public static function iframeCss(array $iframe_css)
355 355
     {
356
-        $iframe_css['ticket_selector'] = TICKET_SELECTOR_ASSETS_URL . 'ticket_selector.css';
356
+        $iframe_css['ticket_selector'] = TICKET_SELECTOR_ASSETS_URL.'ticket_selector.css';
357 357
         return $iframe_css;
358 358
     }
359 359
 
@@ -366,7 +366,7 @@  discard block
 block discarded – undo
366 366
      */
367 367
     public static function iframeJs(array $iframe_js)
368 368
     {
369
-        $iframe_js['ticket_selector'] = TICKET_SELECTOR_ASSETS_URL . 'ticket_selector.js';
369
+        $iframe_js['ticket_selector'] = TICKET_SELECTOR_ASSETS_URL.'ticket_selector.js';
370 370
         return $iframe_js;
371 371
     }
372 372
 
Please login to merge, or discard this patch.
support/templates/support_admin_details_contact_support.template.php 1 patch
Indentation   +68 added lines, -68 removed lines patch added patch discarded remove patch
@@ -3,102 +3,102 @@
 block discarded – undo
3 3
 
4 4
     <h4>
5 5
         <?php
6
-        esc_html_e(
7
-            'You may be able to find an answer for your question or concern here:',
8
-            'event_espresso'
9
-        );
10
-        ?>
6
+		esc_html_e(
7
+			'You may be able to find an answer for your question or concern here:',
8
+			'event_espresso'
9
+		);
10
+		?>
11 11
     </h4>
12 12
     <ol>
13 13
         <li>
14 14
             <strong><em><?php esc_html_e('A known issue.', 'event_espresso'); ?></em></strong>
15 15
             <?php
16
-            printf(
17
-                esc_html__(
18
-                    'Some themes and plugins have %1$sknown conflicts%2$s with Event Espresso. (You can also browse the %3$sEvent Espresso support pages%2$s or %4$sEvent Espresso support forums%2$s to see if other members have experienced and solved the problem.)',
19
-                    'event_espresso'
20
-                ),
21
-                '<a href="https://eventespresso.com/wiki/known-third-party-plugin-theme-conflicts/" target="_blank">',
22
-                '</a>',
23
-                '<a href="https://eventespresso.com/support/documentation/versioned-docs/?doc_ver=ee4" target="_blank">',
24
-                '<a href="https://eventespresso.com/support/forums/" target="_blank">'
25
-            );
26
-            ?>
16
+			printf(
17
+				esc_html__(
18
+					'Some themes and plugins have %1$sknown conflicts%2$s with Event Espresso. (You can also browse the %3$sEvent Espresso support pages%2$s or %4$sEvent Espresso support forums%2$s to see if other members have experienced and solved the problem.)',
19
+					'event_espresso'
20
+				),
21
+				'<a href="https://eventespresso.com/wiki/known-third-party-plugin-theme-conflicts/" target="_blank">',
22
+				'</a>',
23
+				'<a href="https://eventespresso.com/support/documentation/versioned-docs/?doc_ver=ee4" target="_blank">',
24
+				'<a href="https://eventespresso.com/support/forums/" target="_blank">'
25
+			);
26
+			?>
27 27
         </li>
28 28
         <li>
29 29
             <strong><em><?php esc_html_e('A plugin conflict.', 'event_espresso'); ?></em></strong>
30 30
             <?php
31
-            esc_html_e(
32
-                'You can check to see if there is a plugin conflict by temporarily deactivating all plugins except for Event Espresso. If the problem goes away, then reactivate your plugins one by one until the issue returns. This will help you pinpoint the source of the conflict.',
33
-                'event_espresso'
34
-            );
35
-            ?>
31
+			esc_html_e(
32
+				'You can check to see if there is a plugin conflict by temporarily deactivating all plugins except for Event Espresso. If the problem goes away, then reactivate your plugins one by one until the issue returns. This will help you pinpoint the source of the conflict.',
33
+				'event_espresso'
34
+			);
35
+			?>
36 36
         </li>
37 37
         <li>
38 38
             <strong><em><?php esc_html_e('A theme conflict.', 'event_espresso'); ?></em></strong>
39 39
             <?php
40
-            $default_theme = wp_get_theme(WP_DEFAULT_THEME);
40
+			$default_theme = wp_get_theme(WP_DEFAULT_THEME);
41 41
 
42
-            if ($default_theme->exists()) {
43
-                printf(
44
-                    esc_html__(
45
-                        'If your problem is not a known issue or caused by a plugin, then try activating %s (the default WordPress theme).',
46
-                        'event_espresso'
47
-                    ),
48
-                    $default_theme->get('Name')
49
-                );
50
-            } else {
51
-                esc_html_e(
52
-                    'If your problem is not a known issue or caused by a plugin, then try activating the default WordPress theme.',
53
-                    'event_espresso'
54
-                );
55
-            }
56
-            ?>
42
+			if ($default_theme->exists()) {
43
+				printf(
44
+					esc_html__(
45
+						'If your problem is not a known issue or caused by a plugin, then try activating %s (the default WordPress theme).',
46
+						'event_espresso'
47
+					),
48
+					$default_theme->get('Name')
49
+				);
50
+			} else {
51
+				esc_html_e(
52
+					'If your problem is not a known issue or caused by a plugin, then try activating the default WordPress theme.',
53
+					'event_espresso'
54
+				);
55
+			}
56
+			?>
57 57
             <?php
58
-            esc_html_e(
59
-                'If this solves the problem for you, then something in your theme is causing this issue. Check to see if an update is available for your WordPress theme or reach out to the theme author.',
60
-                'event_espresso'
61
-            );
62
-            ?>
58
+			esc_html_e(
59
+				'If this solves the problem for you, then something in your theme is causing this issue. Check to see if an update is available for your WordPress theme or reach out to the theme author.',
60
+				'event_espresso'
61
+			);
62
+			?>
63 63
         </li>
64 64
     </ol>
65 65
 
66 66
     <p>
67 67
         <?php
68
-        esc_html_e(
69
-            'If none of the suggestions above help you find a solution, then feel free to reach out to the support team at Event Espresso.',
70
-            'event_espresso'
71
-        );
72
-        ?>
68
+		esc_html_e(
69
+			'If none of the suggestions above help you find a solution, then feel free to reach out to the support team at Event Espresso.',
70
+			'event_espresso'
71
+		);
72
+		?>
73 73
     </p>
74 74
     <p>
75 75
         <?php
76
-        printf(
77
-            esc_html__(
78
-                'Login to your account on EventEspresso.com and %1$screate a support post in our member support forums%2$s. Use a %3$sclear and descriptive title%4$s in your support post, %3$sdescribe the issue to the best of your knowledge%4$s, and %3$snever post any sensitive information such as login details%4$s. Be sure to also include %5$simportant information in the section below%2$s about your WordPress site.',
79
-                'event_espresso'
80
-            ),
81
-            '<a href="https://eventespresso.com/support/forums/" target="_blank">',
82
-            '</a>',
83
-            '<strong>',
84
-            '</strong>',
85
-            '<a href="#espresso_important_information_settings">'
86
-        );
87
-        ?>
76
+		printf(
77
+			esc_html__(
78
+				'Login to your account on EventEspresso.com and %1$screate a support post in our member support forums%2$s. Use a %3$sclear and descriptive title%4$s in your support post, %3$sdescribe the issue to the best of your knowledge%4$s, and %3$snever post any sensitive information such as login details%4$s. Be sure to also include %5$simportant information in the section below%2$s about your WordPress site.',
79
+				'event_espresso'
80
+			),
81
+			'<a href="https://eventespresso.com/support/forums/" target="_blank">',
82
+			'</a>',
83
+			'<strong>',
84
+			'</strong>',
85
+			'<a href="#espresso_important_information_settings">'
86
+		);
87
+		?>
88 88
     </p>
89 89
 
90 90
     <h4><?php esc_html_e('Have an emergency?', 'event_espresso'); ?></h4>
91 91
 
92 92
     <p>
93 93
         <?php
94
-        printf(
95
-            esc_html__(
96
-                'We offer support tokens to members that need help with a time-sensitive issue. A support token will provide you with up to 30 minutes of one-on-one time with a team member at Event Espresso. If you have an emergency and need help quickly, then please %1$spurchase a support token%2$s.',
97
-                'event_espresso'
98
-            ),
99
-            '<a href="https://eventespresso.com/product/premium-support-token/?utm_source=ee4_plugin_admin&utm_medium=link&utm_campaign=help_support_tab&utm_content=support_token" target="_blank">',
100
-            '</a>'
101
-        );
102
-        ?>
94
+		printf(
95
+			esc_html__(
96
+				'We offer support tokens to members that need help with a time-sensitive issue. A support token will provide you with up to 30 minutes of one-on-one time with a team member at Event Espresso. If you have an emergency and need help quickly, then please %1$spurchase a support token%2$s.',
97
+				'event_espresso'
98
+			),
99
+			'<a href="https://eventespresso.com/product/premium-support-token/?utm_source=ee4_plugin_admin&utm_medium=link&utm_campaign=help_support_tab&utm_content=support_token" target="_blank">',
100
+			'</a>'
101
+		);
102
+		?>
103 103
     </p>
104 104
 </div>
105 105
\ No newline at end of file
Please login to merge, or discard this patch.