Completed
Branch BUG/11288/fix-datepicker (04df7b)
by
unknown
65:36 queued 52:18
created
core/EE_System.core.php 2 patches
Indentation   +1236 added lines, -1236 removed lines patch added patch discarded remove patch
@@ -21,1242 +21,1242 @@
 block discarded – undo
21 21
 {
22 22
 
23 23
 
24
-    /**
25
-     * indicates this is a 'normal' request. Ie, not activation, nor upgrade, nor activation.
26
-     * So examples of this would be a normal GET request on the frontend or backend, or a POST, etc
27
-     */
28
-    const req_type_normal = 0;
29
-
30
-    /**
31
-     * Indicates this is a brand new installation of EE so we should install
32
-     * tables and default data etc
33
-     */
34
-    const req_type_new_activation = 1;
35
-
36
-    /**
37
-     * we've detected that EE has been reactivated (or EE was activated during maintenance mode,
38
-     * and we just exited maintenance mode). We MUST check the database is setup properly
39
-     * and that default data is setup too
40
-     */
41
-    const req_type_reactivation = 2;
42
-
43
-    /**
44
-     * indicates that EE has been upgraded since its previous request.
45
-     * We may have data migration scripts to call and will want to trigger maintenance mode
46
-     */
47
-    const req_type_upgrade = 3;
48
-
49
-    /**
50
-     * TODO  will detect that EE has been DOWNGRADED. We probably don't want to run in this case...
51
-     */
52
-    const req_type_downgrade = 4;
53
-
54
-    /**
55
-     * @deprecated since version 4.6.0.dev.006
56
-     * Now whenever a new_activation is detected the request type is still just
57
-     * new_activation (same for reactivation, upgrade, downgrade etc), but if we'r ein maintenance mode
58
-     * EE_System::initialize_db_if_no_migrations_required and EE_Addon::initialize_db_if_no_migrations_required
59
-     * will instead enqueue that EE plugin's db initialization for when we're taken out of maintenance mode.
60
-     * (Specifically, when the migration manager indicates migrations are finished
61
-     * EE_Data_Migration_Manager::initialize_db_for_enqueued_ee_plugins() will be called)
62
-     */
63
-    const req_type_activation_but_not_installed = 5;
64
-
65
-    /**
66
-     * option prefix for recording the activation history (like core's "espresso_db_update") of addons
67
-     */
68
-    const addon_activation_history_option_prefix = 'ee_addon_activation_history_';
69
-
70
-
71
-    /**
72
-     * @var EE_System $_instance
73
-     */
74
-    private static $_instance;
75
-
76
-    /**
77
-     * @var EE_Registry $registry
78
-     */
79
-    private $registry;
80
-
81
-    /**
82
-     * @var LoaderInterface $loader
83
-     */
84
-    private $loader;
85
-
86
-    /**
87
-     * @var EE_Capabilities $capabilities
88
-     */
89
-    private $capabilities;
90
-
91
-    /**
92
-     * @var EE_Request $request
93
-     */
94
-    private $request;
95
-
96
-    /**
97
-     * @var EE_Maintenance_Mode $maintenance_mode
98
-     */
99
-    private $maintenance_mode;
100
-
101
-    /**
102
-     * Stores which type of request this is, options being one of the constants on EE_System starting with req_type_*.
103
-     * It can be a brand-new activation, a reactivation, an upgrade, a downgrade, or a normal request.
104
-     *
105
-     * @var int $_req_type
106
-     */
107
-    private $_req_type;
108
-
109
-    /**
110
-     * Whether or not there was a non-micro version change in EE core version during this request
111
-     *
112
-     * @var boolean $_major_version_change
113
-     */
114
-    private $_major_version_change = false;
115
-
116
-
117
-
118
-    /**
119
-     * @singleton method used to instantiate class object
120
-     * @param EE_Registry|null         $registry
121
-     * @param LoaderInterface|null     $loader
122
-     * @param EE_Capabilities|null     $capabilities
123
-     * @param EE_Request|null          $request
124
-     * @param EE_Maintenance_Mode|null $maintenance_mode
125
-     * @return EE_System
126
-     */
127
-    public static function instance(
128
-        EE_Registry $registry = null,
129
-        LoaderInterface $loader = null,
130
-        EE_Capabilities $capabilities = null,
131
-        EE_Request $request = null,
132
-        EE_Maintenance_Mode $maintenance_mode = null
133
-    ) {
134
-        // check if class object is instantiated
135
-        if (! self::$_instance instanceof EE_System) {
136
-            self::$_instance = new self($registry, $loader, $capabilities, $request, $maintenance_mode);
137
-        }
138
-        return self::$_instance;
139
-    }
140
-
141
-
142
-
143
-    /**
144
-     * resets the instance and returns it
145
-     *
146
-     * @return EE_System
147
-     */
148
-    public static function reset()
149
-    {
150
-        self::$_instance->_req_type = null;
151
-        //make sure none of the old hooks are left hanging around
152
-        remove_all_actions('AHEE__EE_System__perform_activations_upgrades_and_migrations');
153
-        //we need to reset the migration manager in order for it to detect DMSs properly
154
-        EE_Data_Migration_Manager::reset();
155
-        self::instance()->detect_activations_or_upgrades();
156
-        self::instance()->perform_activations_upgrades_and_migrations();
157
-        return self::instance();
158
-    }
159
-
160
-
161
-
162
-    /**
163
-     * sets hooks for running rest of system
164
-     * provides "AHEE__EE_System__construct__complete" hook for EE Addons to use as their starting point
165
-     * starting EE Addons from any other point may lead to problems
166
-     *
167
-     * @param EE_Registry         $registry
168
-     * @param LoaderInterface     $loader
169
-     * @param EE_Capabilities     $capabilities
170
-     * @param EE_Request          $request
171
-     * @param EE_Maintenance_Mode $maintenance_mode
172
-     */
173
-    private function __construct(
174
-        EE_Registry $registry,
175
-        LoaderInterface $loader,
176
-        EE_Capabilities $capabilities,
177
-        EE_Request $request,
178
-        EE_Maintenance_Mode $maintenance_mode
179
-    ) {
180
-        $this->registry = $registry;
181
-        $this->loader = $loader;
182
-        $this->capabilities = $capabilities;
183
-        $this->request = $request;
184
-        $this->maintenance_mode = $maintenance_mode;
185
-        do_action('AHEE__EE_System__construct__begin', $this);
186
-        add_action(
187
-            'AHEE__EE_Bootstrap__load_espresso_addons',
188
-            array($this, 'loadCapabilities'),
189
-            5
190
-        );
191
-        add_action(
192
-            'AHEE__EE_Bootstrap__load_espresso_addons',
193
-            array($this, 'loadCommandBus'),
194
-            7
195
-        );
196
-        add_action(
197
-            'AHEE__EE_Bootstrap__load_espresso_addons',
198
-            array($this, 'loadPluginApi'),
199
-            9
200
-        );
201
-        // allow addons to load first so that they can register autoloaders, set hooks for running DMS's, etc
202
-        add_action(
203
-            'AHEE__EE_Bootstrap__load_espresso_addons',
204
-            array($this, 'load_espresso_addons')
205
-        );
206
-        // when an ee addon is activated, we want to call the core hook(s) again
207
-        // because the newly-activated addon didn't get a chance to run at all
208
-        add_action('activate_plugin', array($this, 'load_espresso_addons'), 1);
209
-        // detect whether install or upgrade
210
-        add_action(
211
-            'AHEE__EE_Bootstrap__detect_activations_or_upgrades',
212
-            array($this, 'detect_activations_or_upgrades'),
213
-            3
214
-        );
215
-        // load EE_Config, EE_Textdomain, etc
216
-        add_action(
217
-            'AHEE__EE_Bootstrap__load_core_configuration',
218
-            array($this, 'load_core_configuration'),
219
-            5
220
-        );
221
-        // load EE_Config, EE_Textdomain, etc
222
-        add_action(
223
-            'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets',
224
-            array($this, 'register_shortcodes_modules_and_widgets'),
225
-            7
226
-        );
227
-        // you wanna get going? I wanna get going... let's get going!
228
-        add_action(
229
-            'AHEE__EE_Bootstrap__brew_espresso',
230
-            array($this, 'brew_espresso'),
231
-            9
232
-        );
233
-        //other housekeeping
234
-        //exclude EE critical pages from wp_list_pages
235
-        add_filter(
236
-            'wp_list_pages_excludes',
237
-            array($this, 'remove_pages_from_wp_list_pages'),
238
-            10
239
-        );
240
-        // ALL EE Addons should use the following hook point to attach their initial setup too
241
-        // it's extremely important for EE Addons to register any class autoloaders so that they can be available when the EE_Config loads
242
-        do_action('AHEE__EE_System__construct__complete', $this);
243
-    }
244
-
245
-
246
-
247
-    /**
248
-     * load and setup EE_Capabilities
249
-     *
250
-     * @return void
251
-     * @throws EE_Error
252
-     */
253
-    public function loadCapabilities()
254
-    {
255
-        $this->loader->getShared('EE_Capabilities');
256
-        add_action(
257
-            'AHEE__EE_Capabilities__init_caps__before_initialization',
258
-            function() {
259
-                LoaderFactory::getLoader()->getShared('EE_Payment_Method_Manager');
260
-            }
261
-        );
262
-    }
263
-
264
-
265
-
266
-    /**
267
-     * create and cache the CommandBus, and also add middleware
268
-     * The CapChecker middleware requires the use of EE_Capabilities
269
-     * which is why we need to load the CommandBus after Caps are set up
270
-     *
271
-     * @return void
272
-     * @throws EE_Error
273
-     */
274
-    public function loadCommandBus()
275
-    {
276
-        $this->loader->getShared(
277
-            'CommandBusInterface',
278
-            array(
279
-                null,
280
-                apply_filters(
281
-                    'FHEE__EE_Load_Espresso_Core__handle_request__CommandBus_middleware',
282
-                    array(
283
-                        $this->loader->getShared('EventEspresso\core\services\commands\middleware\CapChecker'),
284
-                        $this->loader->getShared('EventEspresso\core\services\commands\middleware\AddActionHook'),
285
-                    )
286
-                ),
287
-            )
288
-        );
289
-    }
290
-
291
-
292
-
293
-    /**
294
-     * @return void
295
-     * @throws EE_Error
296
-     */
297
-    public function loadPluginApi()
298
-    {
299
-        // set autoloaders for all of the classes implementing EEI_Plugin_API
300
-        // which provide helpers for EE plugin authors to more easily register certain components with EE.
301
-        EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'plugin_api');
302
-    }
303
-
304
-
305
-    /**
306
-     * @param string $addon_name
307
-     * @param string $version_constant
308
-     * @param string $min_version_required
309
-     * @param string $load_callback
310
-     * @param string $plugin_file_constant
311
-     * @return void
312
-     */
313
-    private function deactivateIncompatibleAddon(
314
-        $addon_name,
315
-        $version_constant,
316
-        $min_version_required,
317
-        $load_callback,
318
-        $plugin_file_constant
319
-    ) {
320
-        if (! defined($version_constant)) {
321
-            return;
322
-        }
323
-        $addon_version = constant($version_constant);
324
-        if ($addon_version && version_compare($addon_version, $min_version_required, '<')) {
325
-            remove_action('AHEE__EE_System__load_espresso_addons', $load_callback);
326
-            if (! function_exists('deactivate_plugins')) {
327
-                require_once ABSPATH . 'wp-admin/includes/plugin.php';
328
-            }
329
-            deactivate_plugins(plugin_basename(constant($plugin_file_constant)));
330
-            unset($_GET['activate'], $_REQUEST['activate'], $_GET['activate-multi'], $_REQUEST['activate-multi']);
331
-            EE_Error::add_error(
332
-                sprintf(
333
-                    esc_html__(
334
-                        'We\'re sorry, but the Event Espresso %1$s addon was deactivated because version %2$s or higher is required with this version of Event Espresso core.',
335
-                        'event_espresso'
336
-                    ),
337
-                    $addon_name,
338
-                    $min_version_required
339
-                ),
340
-                __FILE__, __FUNCTION__ . "({$addon_name})", __LINE__
341
-            );
342
-            EE_Error::get_notices(false, true);
343
-        }
344
-    }
345
-
346
-
347
-    /**
348
-     * load_espresso_addons
349
-     * allow addons to load first so that they can set hooks for running DMS's, etc
350
-     * this is hooked into both:
351
-     *    'AHEE__EE_Bootstrap__load_core_configuration'
352
-     *        which runs during the WP 'plugins_loaded' action at priority 5
353
-     *    and the WP 'activate_plugin' hook point
354
-     *
355
-     * @access public
356
-     * @return void
357
-     */
358
-    public function load_espresso_addons()
359
-    {
360
-        $this->deactivateIncompatibleAddon(
361
-            'Wait Lists',
362
-            'EE_WAIT_LISTS_VERSION',
363
-            '1.0.0.rc.074',
364
-            'load_espresso_wait_lists',
365
-            'EE_WAIT_LISTS_PLUGIN_FILE'
366
-        );
367
-        $this->deactivateIncompatibleAddon(
368
-            'Automated Upcoming Event Notifications',
369
-            'EE_AUTOMATED_UPCOMING_EVENT_NOTIFICATION_VERSION',
370
-            '1.0.0.rc.091',
371
-            'load_espresso_automated_upcoming_event_notification',
372
-            'EE_AUTOMATED_UPCOMING_EVENT_NOTIFICATION_PLUGIN_FILE'
373
-        );
374
-        do_action('AHEE__EE_System__load_espresso_addons');
375
-        //if the WP API basic auth plugin isn't already loaded, load it now.
376
-        //We want it for mobile apps. Just include the entire plugin
377
-        //also, don't load the basic auth when a plugin is getting activated, because
378
-        //it could be the basic auth plugin, and it doesn't check if its methods are already defined
379
-        //and causes a fatal error
380
-        if (
381
-            ! (
382
-                isset($_GET['activate'])
383
-                && $_GET['activate'] === 'true'
384
-            )
385
-            && ! function_exists('json_basic_auth_handler')
386
-            && ! function_exists('json_basic_auth_error')
387
-            && ! (
388
-                isset($_GET['action'])
389
-                && in_array($_GET['action'], array('activate', 'activate-selected'), true)
390
-            )
391
-        ) {
392
-            include_once EE_THIRD_PARTY . 'wp-api-basic-auth' . DS . 'basic-auth.php';
393
-        }
394
-        do_action('AHEE__EE_System__load_espresso_addons__complete');
395
-    }
396
-
397
-
398
-
399
-    /**
400
-     * detect_activations_or_upgrades
401
-     * Checks for activation or upgrade of core first;
402
-     * then also checks if any registered addons have been activated or upgraded
403
-     * This is hooked into 'AHEE__EE_Bootstrap__detect_activations_or_upgrades'
404
-     * which runs during the WP 'plugins_loaded' action at priority 3
405
-     *
406
-     * @access public
407
-     * @return void
408
-     */
409
-    public function detect_activations_or_upgrades()
410
-    {
411
-        //first off: let's make sure to handle core
412
-        $this->detect_if_activation_or_upgrade();
413
-        foreach ($this->registry->addons as $addon) {
414
-            if ($addon instanceof EE_Addon) {
415
-                //detect teh request type for that addon
416
-                $addon->detect_activation_or_upgrade();
417
-            }
418
-        }
419
-    }
420
-
421
-
422
-
423
-    /**
424
-     * detect_if_activation_or_upgrade
425
-     * Takes care of detecting whether this is a brand new install or code upgrade,
426
-     * and either setting up the DB or setting up maintenance mode etc.
427
-     *
428
-     * @access public
429
-     * @return void
430
-     */
431
-    public function detect_if_activation_or_upgrade()
432
-    {
433
-        do_action('AHEE__EE_System___detect_if_activation_or_upgrade__begin');
434
-        // check if db has been updated, or if its a brand-new installation
435
-        $espresso_db_update = $this->fix_espresso_db_upgrade_option();
436
-        $request_type = $this->detect_req_type($espresso_db_update);
437
-        //EEH_Debug_Tools::printr( $request_type, '$request_type', __FILE__, __LINE__ );
438
-        switch ($request_type) {
439
-            case EE_System::req_type_new_activation:
440
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__new_activation');
441
-                $this->_handle_core_version_change($espresso_db_update);
442
-                break;
443
-            case EE_System::req_type_reactivation:
444
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__reactivation');
445
-                $this->_handle_core_version_change($espresso_db_update);
446
-                break;
447
-            case EE_System::req_type_upgrade:
448
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__upgrade');
449
-                //migrations may be required now that we've upgraded
450
-                $this->maintenance_mode->set_maintenance_mode_if_db_old();
451
-                $this->_handle_core_version_change($espresso_db_update);
452
-                //				echo "done upgrade";die;
453
-                break;
454
-            case EE_System::req_type_downgrade:
455
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__downgrade');
456
-                //its possible migrations are no longer required
457
-                $this->maintenance_mode->set_maintenance_mode_if_db_old();
458
-                $this->_handle_core_version_change($espresso_db_update);
459
-                break;
460
-            case EE_System::req_type_normal:
461
-            default:
462
-                //				$this->_maybe_redirect_to_ee_about();
463
-                break;
464
-        }
465
-        do_action('AHEE__EE_System__detect_if_activation_or_upgrade__complete');
466
-    }
467
-
468
-
469
-
470
-    /**
471
-     * Updates the list of installed versions and sets hooks for
472
-     * initializing the database later during the request
473
-     *
474
-     * @param array $espresso_db_update
475
-     */
476
-    private function _handle_core_version_change($espresso_db_update)
477
-    {
478
-        $this->update_list_of_installed_versions($espresso_db_update);
479
-        //get ready to verify the DB is ok (provided we aren't in maintenance mode, of course)
480
-        add_action(
481
-            'AHEE__EE_System__perform_activations_upgrades_and_migrations',
482
-            array($this, 'initialize_db_if_no_migrations_required')
483
-        );
484
-    }
485
-
486
-
487
-
488
-    /**
489
-     * standardizes the wp option 'espresso_db_upgrade' which actually stores
490
-     * information about what versions of EE have been installed and activated,
491
-     * NOT necessarily the state of the database
492
-     *
493
-     * @param mixed $espresso_db_update the value of the WordPress option.
494
-     *                                            If not supplied, fetches it from the options table
495
-     * @return array the correct value of 'espresso_db_upgrade', after saving it, if it needed correction
496
-     */
497
-    private function fix_espresso_db_upgrade_option($espresso_db_update = null)
498
-    {
499
-        do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__begin', $espresso_db_update);
500
-        if (! $espresso_db_update) {
501
-            $espresso_db_update = get_option('espresso_db_update');
502
-        }
503
-        // check that option is an array
504
-        if (! is_array($espresso_db_update)) {
505
-            // if option is FALSE, then it never existed
506
-            if ($espresso_db_update === false) {
507
-                // make $espresso_db_update an array and save option with autoload OFF
508
-                $espresso_db_update = array();
509
-                add_option('espresso_db_update', $espresso_db_update, '', 'no');
510
-            } else {
511
-                // option is NOT FALSE but also is NOT an array, so make it an array and save it
512
-                $espresso_db_update = array($espresso_db_update => array());
513
-                update_option('espresso_db_update', $espresso_db_update);
514
-            }
515
-        } else {
516
-            $corrected_db_update = array();
517
-            //if IS an array, but is it an array where KEYS are version numbers, and values are arrays?
518
-            foreach ($espresso_db_update as $should_be_version_string => $should_be_array) {
519
-                if (is_int($should_be_version_string) && ! is_array($should_be_array)) {
520
-                    //the key is an int, and the value IS NOT an array
521
-                    //so it must be numerically-indexed, where values are versions installed...
522
-                    //fix it!
523
-                    $version_string = $should_be_array;
524
-                    $corrected_db_update[$version_string] = array('unknown-date');
525
-                } else {
526
-                    //ok it checks out
527
-                    $corrected_db_update[$should_be_version_string] = $should_be_array;
528
-                }
529
-            }
530
-            $espresso_db_update = $corrected_db_update;
531
-            update_option('espresso_db_update', $espresso_db_update);
532
-        }
533
-        do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__complete', $espresso_db_update);
534
-        return $espresso_db_update;
535
-    }
536
-
537
-
538
-
539
-    /**
540
-     * Does the traditional work of setting up the plugin's database and adding default data.
541
-     * If migration script/process did not exist, this is what would happen on every activation/reactivation/upgrade.
542
-     * NOTE: if we're in maintenance mode (which would be the case if we detect there are data
543
-     * migration scripts that need to be run and a version change happens), enqueues core for database initialization,
544
-     * so that it will be done when migrations are finished
545
-     *
546
-     * @param boolean $initialize_addons_too if true, we double-check addons' database tables etc too;
547
-     * @param boolean $verify_schema         if true will re-check the database tables have the correct schema.
548
-     *                                       This is a resource-intensive job
549
-     *                                       so we prefer to only do it when necessary
550
-     * @return void
551
-     * @throws EE_Error
552
-     */
553
-    public function initialize_db_if_no_migrations_required($initialize_addons_too = false, $verify_schema = true)
554
-    {
555
-        $request_type = $this->detect_req_type();
556
-        //only initialize system if we're not in maintenance mode.
557
-        if ($this->maintenance_mode->level() !== EE_Maintenance_Mode::level_2_complete_maintenance) {
558
-            update_option('ee_flush_rewrite_rules', true);
559
-            if ($verify_schema) {
560
-                EEH_Activation::initialize_db_and_folders();
561
-            }
562
-            EEH_Activation::initialize_db_content();
563
-            EEH_Activation::system_initialization();
564
-            if ($initialize_addons_too) {
565
-                $this->initialize_addons();
566
-            }
567
-        } else {
568
-            EE_Data_Migration_Manager::instance()->enqueue_db_initialization_for('Core');
569
-        }
570
-        if ($request_type === EE_System::req_type_new_activation
571
-            || $request_type === EE_System::req_type_reactivation
572
-            || (
573
-                $request_type === EE_System::req_type_upgrade
574
-                && $this->is_major_version_change()
575
-            )
576
-        ) {
577
-            add_action('AHEE__EE_System__initialize_last', array($this, 'redirect_to_about_ee'), 9);
578
-        }
579
-    }
580
-
581
-
582
-
583
-    /**
584
-     * Initializes the db for all registered addons
585
-     *
586
-     * @throws EE_Error
587
-     */
588
-    public function initialize_addons()
589
-    {
590
-        //foreach registered addon, make sure its db is up-to-date too
591
-        foreach ($this->registry->addons as $addon) {
592
-            if ($addon instanceof EE_Addon) {
593
-                $addon->initialize_db_if_no_migrations_required();
594
-            }
595
-        }
596
-    }
597
-
598
-
599
-
600
-    /**
601
-     * Adds the current code version to the saved wp option which stores a list of all ee versions ever installed.
602
-     *
603
-     * @param    array  $version_history
604
-     * @param    string $current_version_to_add version to be added to the version history
605
-     * @return    boolean success as to whether or not this option was changed
606
-     */
607
-    public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null)
608
-    {
609
-        if (! $version_history) {
610
-            $version_history = $this->fix_espresso_db_upgrade_option($version_history);
611
-        }
612
-        if ($current_version_to_add === null) {
613
-            $current_version_to_add = espresso_version();
614
-        }
615
-        $version_history[$current_version_to_add][] = date('Y-m-d H:i:s', time());
616
-        // re-save
617
-        return update_option('espresso_db_update', $version_history);
618
-    }
619
-
620
-
621
-
622
-    /**
623
-     * Detects if the current version indicated in the has existed in the list of
624
-     * previously-installed versions of EE (espresso_db_update). Does NOT modify it (ie, no side-effect)
625
-     *
626
-     * @param array $espresso_db_update array from the wp option stored under the name 'espresso_db_update'.
627
-     *                                  If not supplied, fetches it from the options table.
628
-     *                                  Also, caches its result so later parts of the code can also know whether
629
-     *                                  there's been an update or not. This way we can add the current version to
630
-     *                                  espresso_db_update, but still know if this is a new install or not
631
-     * @return int one of the constants on EE_System::req_type_
632
-     */
633
-    public function detect_req_type($espresso_db_update = null)
634
-    {
635
-        if ($this->_req_type === null) {
636
-            $espresso_db_update = ! empty($espresso_db_update)
637
-                ? $espresso_db_update
638
-                : $this->fix_espresso_db_upgrade_option();
639
-            $this->_req_type = EE_System::detect_req_type_given_activation_history(
640
-                $espresso_db_update,
641
-                'ee_espresso_activation', espresso_version()
642
-            );
643
-            $this->_major_version_change = $this->_detect_major_version_change($espresso_db_update);
644
-        }
645
-        return $this->_req_type;
646
-    }
647
-
648
-
649
-
650
-    /**
651
-     * Returns whether or not there was a non-micro version change (ie, change in either
652
-     * the first or second number in the version. Eg 4.9.0.rc.001 to 4.10.0.rc.000,
653
-     * but not 4.9.0.rc.0001 to 4.9.1.rc.0001
654
-     *
655
-     * @param $activation_history
656
-     * @return bool
657
-     */
658
-    private function _detect_major_version_change($activation_history)
659
-    {
660
-        $previous_version = EE_System::_get_most_recently_active_version_from_activation_history($activation_history);
661
-        $previous_version_parts = explode('.', $previous_version);
662
-        $current_version_parts = explode('.', espresso_version());
663
-        return isset($previous_version_parts[0], $previous_version_parts[1], $current_version_parts[0], $current_version_parts[1])
664
-               && ($previous_version_parts[0] !== $current_version_parts[0]
665
-                   || $previous_version_parts[1] !== $current_version_parts[1]
666
-               );
667
-    }
668
-
669
-
670
-
671
-    /**
672
-     * Returns true if either the major or minor version of EE changed during this request.
673
-     * Eg 4.9.0.rc.001 to 4.10.0.rc.000, but not 4.9.0.rc.0001 to 4.9.1.rc.0001
674
-     *
675
-     * @return bool
676
-     */
677
-    public function is_major_version_change()
678
-    {
679
-        return $this->_major_version_change;
680
-    }
681
-
682
-
683
-
684
-    /**
685
-     * Determines the request type for any ee addon, given three piece of info: the current array of activation
686
-     * histories (for core that' 'espresso_db_update' wp option); the name of the WordPress option which is temporarily
687
-     * set upon activation of the plugin (for core it's 'ee_espresso_activation'); and the version that this plugin was
688
-     * just activated to (for core that will always be espresso_version())
689
-     *
690
-     * @param array  $activation_history_for_addon     the option's value which stores the activation history for this
691
-     *                                                 ee plugin. for core that's 'espresso_db_update'
692
-     * @param string $activation_indicator_option_name the name of the WordPress option that is temporarily set to
693
-     *                                                 indicate that this plugin was just activated
694
-     * @param string $version_to_upgrade_to            the version that was just upgraded to (for core that will be
695
-     *                                                 espresso_version())
696
-     * @return int one of the constants on EE_System::req_type_*
697
-     */
698
-    public static function detect_req_type_given_activation_history(
699
-        $activation_history_for_addon,
700
-        $activation_indicator_option_name,
701
-        $version_to_upgrade_to
702
-    ) {
703
-        $version_is_higher = self::_new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to);
704
-        if ($activation_history_for_addon) {
705
-            //it exists, so this isn't a completely new install
706
-            //check if this version already in that list of previously installed versions
707
-            if (! isset($activation_history_for_addon[$version_to_upgrade_to])) {
708
-                //it a version we haven't seen before
709
-                if ($version_is_higher === 1) {
710
-                    $req_type = EE_System::req_type_upgrade;
711
-                } else {
712
-                    $req_type = EE_System::req_type_downgrade;
713
-                }
714
-                delete_option($activation_indicator_option_name);
715
-            } else {
716
-                // its not an update. maybe a reactivation?
717
-                if (get_option($activation_indicator_option_name, false)) {
718
-                    if ($version_is_higher === -1) {
719
-                        $req_type = EE_System::req_type_downgrade;
720
-                    } else if ($version_is_higher === 0) {
721
-                        //we've seen this version before, but it's an activation. must be a reactivation
722
-                        $req_type = EE_System::req_type_reactivation;
723
-                    } else {//$version_is_higher === 1
724
-                        $req_type = EE_System::req_type_upgrade;
725
-                    }
726
-                    delete_option($activation_indicator_option_name);
727
-                } else {
728
-                    //we've seen this version before and the activation indicate doesn't show it was just activated
729
-                    if ($version_is_higher === -1) {
730
-                        $req_type = EE_System::req_type_downgrade;
731
-                    } else if ($version_is_higher === 0) {
732
-                        //we've seen this version before and it's not an activation. its normal request
733
-                        $req_type = EE_System::req_type_normal;
734
-                    } else {//$version_is_higher === 1
735
-                        $req_type = EE_System::req_type_upgrade;
736
-                    }
737
-                }
738
-            }
739
-        } else {
740
-            //brand new install
741
-            $req_type = EE_System::req_type_new_activation;
742
-            delete_option($activation_indicator_option_name);
743
-        }
744
-        return $req_type;
745
-    }
746
-
747
-
748
-
749
-    /**
750
-     * Detects if the $version_to_upgrade_to is higher than the most recent version in
751
-     * the $activation_history_for_addon
752
-     *
753
-     * @param array  $activation_history_for_addon (keys are versions, values are arrays of times activated,
754
-     *                                             sometimes containing 'unknown-date'
755
-     * @param string $version_to_upgrade_to        (current version)
756
-     * @return int results of version_compare( $version_to_upgrade_to, $most_recently_active_version ).
757
-     *                                             ie, -1 if $version_to_upgrade_to is LOWER (downgrade);
758
-     *                                             0 if $version_to_upgrade_to MATCHES (reactivation or normal request);
759
-     *                                             1 if $version_to_upgrade_to is HIGHER (upgrade) ;
760
-     */
761
-    private static function _new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to)
762
-    {
763
-        //find the most recently-activated version
764
-        $most_recently_active_version =
765
-            EE_System::_get_most_recently_active_version_from_activation_history($activation_history_for_addon);
766
-        return version_compare($version_to_upgrade_to, $most_recently_active_version);
767
-    }
768
-
769
-
770
-
771
-    /**
772
-     * Gets the most recently active version listed in the activation history,
773
-     * and if none are found (ie, it's a brand new install) returns '0.0.0.dev.000'.
774
-     *
775
-     * @param array $activation_history  (keys are versions, values are arrays of times activated,
776
-     *                                   sometimes containing 'unknown-date'
777
-     * @return string
778
-     */
779
-    private static function _get_most_recently_active_version_from_activation_history($activation_history)
780
-    {
781
-        $most_recently_active_version_activation = '1970-01-01 00:00:00';
782
-        $most_recently_active_version = '0.0.0.dev.000';
783
-        if (is_array($activation_history)) {
784
-            foreach ($activation_history as $version => $times_activated) {
785
-                //check there is a record of when this version was activated. Otherwise,
786
-                //mark it as unknown
787
-                if (! $times_activated) {
788
-                    $times_activated = array('unknown-date');
789
-                }
790
-                if (is_string($times_activated)) {
791
-                    $times_activated = array($times_activated);
792
-                }
793
-                foreach ($times_activated as $an_activation) {
794
-                    if ($an_activation !== 'unknown-date' && $an_activation > $most_recently_active_version_activation) {
795
-                        $most_recently_active_version = $version;
796
-                        $most_recently_active_version_activation = $an_activation === 'unknown-date'
797
-                            ? '1970-01-01 00:00:00'
798
-                            : $an_activation;
799
-                    }
800
-                }
801
-            }
802
-        }
803
-        return $most_recently_active_version;
804
-    }
805
-
806
-
807
-
808
-    /**
809
-     * This redirects to the about EE page after activation
810
-     *
811
-     * @return void
812
-     */
813
-    public function redirect_to_about_ee()
814
-    {
815
-        $notices = EE_Error::get_notices(false);
816
-        //if current user is an admin and it's not an ajax or rest request
817
-        if (
818
-            ! (defined('DOING_AJAX') && DOING_AJAX)
819
-            && ! (defined('REST_REQUEST') && REST_REQUEST)
820
-            && ! isset($notices['errors'])
821
-            && apply_filters(
822
-                'FHEE__EE_System__redirect_to_about_ee__do_redirect',
823
-                $this->capabilities->current_user_can('manage_options', 'espresso_about_default')
824
-            )
825
-        ) {
826
-            $query_params = array('page' => 'espresso_about');
827
-            if (EE_System::instance()->detect_req_type() === EE_System::req_type_new_activation) {
828
-                $query_params['new_activation'] = true;
829
-            }
830
-            if (EE_System::instance()->detect_req_type() === EE_System::req_type_reactivation) {
831
-                $query_params['reactivation'] = true;
832
-            }
833
-            $url = add_query_arg($query_params, admin_url('admin.php'));
834
-            wp_safe_redirect($url);
835
-            exit();
836
-        }
837
-    }
838
-
839
-
840
-
841
-    /**
842
-     * load_core_configuration
843
-     * this is hooked into 'AHEE__EE_Bootstrap__load_core_configuration'
844
-     * which runs during the WP 'plugins_loaded' action at priority 5
845
-     *
846
-     * @return void
847
-     * @throws ReflectionException
848
-     */
849
-    public function load_core_configuration()
850
-    {
851
-        do_action('AHEE__EE_System__load_core_configuration__begin', $this);
852
-        $this->loader->getShared('EE_Load_Textdomain');
853
-        //load textdomain
854
-        EE_Load_Textdomain::load_textdomain();
855
-        // load and setup EE_Config and EE_Network_Config
856
-        $config = $this->loader->getShared('EE_Config');
857
-        $this->loader->getShared('EE_Network_Config');
858
-        // setup autoloaders
859
-        // enable logging?
860
-        if ($config->admin->use_full_logging) {
861
-            $this->loader->getShared('EE_Log');
862
-        }
863
-        // check for activation errors
864
-        $activation_errors = get_option('ee_plugin_activation_errors', false);
865
-        if ($activation_errors) {
866
-            EE_Error::add_error($activation_errors, __FILE__, __FUNCTION__, __LINE__);
867
-            update_option('ee_plugin_activation_errors', false);
868
-        }
869
-        // get model names
870
-        $this->_parse_model_names();
871
-        //load caf stuff a chance to play during the activation process too.
872
-        $this->_maybe_brew_regular();
873
-        do_action('AHEE__EE_System__load_core_configuration__complete', $this);
874
-    }
875
-
876
-
877
-
878
-    /**
879
-     * cycles through all of the models/*.model.php files, and assembles an array of model names
880
-     *
881
-     * @return void
882
-     * @throws ReflectionException
883
-     */
884
-    private function _parse_model_names()
885
-    {
886
-        //get all the files in the EE_MODELS folder that end in .model.php
887
-        $models = glob(EE_MODELS . '*.model.php');
888
-        $model_names = array();
889
-        $non_abstract_db_models = array();
890
-        foreach ($models as $model) {
891
-            // get model classname
892
-            $classname = EEH_File::get_classname_from_filepath_with_standard_filename($model);
893
-            $short_name = str_replace('EEM_', '', $classname);
894
-            $reflectionClass = new ReflectionClass($classname);
895
-            if ($reflectionClass->isSubclassOf('EEM_Base') && ! $reflectionClass->isAbstract()) {
896
-                $non_abstract_db_models[$short_name] = $classname;
897
-            }
898
-            $model_names[$short_name] = $classname;
899
-        }
900
-        $this->registry->models = apply_filters('FHEE__EE_System__parse_model_names', $model_names);
901
-        $this->registry->non_abstract_db_models = apply_filters(
902
-            'FHEE__EE_System__parse_implemented_model_names',
903
-            $non_abstract_db_models
904
-        );
905
-    }
906
-
907
-
908
-
909
-    /**
910
-     * The purpose of this method is to simply check for a file named "caffeinated/brewing_regular.php" for any hooks
911
-     * that need to be setup before our EE_System launches.
912
-     *
913
-     * @return void
914
-     */
915
-    private function _maybe_brew_regular()
916
-    {
917
-        if ((! defined('EE_DECAF') || EE_DECAF !== true) && is_readable(EE_CAFF_PATH . 'brewing_regular.php')) {
918
-            require_once EE_CAFF_PATH . 'brewing_regular.php';
919
-        }
920
-    }
921
-
922
-
923
-
924
-    /**
925
-     * register_shortcodes_modules_and_widgets
926
-     * generate lists of shortcodes and modules, then verify paths and classes
927
-     * This is hooked into 'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets'
928
-     * which runs during the WP 'plugins_loaded' action at priority 7
929
-     *
930
-     * @access public
931
-     * @return void
932
-     * @throws Exception
933
-     */
934
-    public function register_shortcodes_modules_and_widgets()
935
-    {
936
-        try {
937
-            // load, register, and add shortcodes the new way
938
-            $this->loader->getShared(
939
-                'EventEspresso\core\services\shortcodes\ShortcodesManager',
940
-                array(
941
-                    // and the old way, but we'll put it under control of the new system
942
-                    EE_Config::getLegacyShortcodesManager()
943
-                )
944
-            );
945
-        } catch (Exception $exception) {
946
-            new ExceptionStackTraceDisplay($exception);
947
-        }
948
-        do_action('AHEE__EE_System__register_shortcodes_modules_and_widgets');
949
-        // check for addons using old hook point
950
-        if (has_action('AHEE__EE_System__register_shortcodes_modules_and_addons')) {
951
-            $this->_incompatible_addon_error();
952
-        }
953
-    }
954
-
955
-
956
-
957
-    /**
958
-     * _incompatible_addon_error
959
-     *
960
-     * @access public
961
-     * @return void
962
-     */
963
-    private function _incompatible_addon_error()
964
-    {
965
-        // get array of classes hooking into here
966
-        $class_names = EEH_Class_Tools::get_class_names_for_all_callbacks_on_hook(
967
-            'AHEE__EE_System__register_shortcodes_modules_and_addons'
968
-        );
969
-        if (! empty($class_names)) {
970
-            $msg = __(
971
-                'The following plugins, addons, or modules appear to be incompatible with this version of Event Espresso and were automatically deactivated to avoid fatal errors:',
972
-                'event_espresso'
973
-            );
974
-            $msg .= '<ul>';
975
-            foreach ($class_names as $class_name) {
976
-                $msg .= '<li><b>Event Espresso - ' . str_replace(
977
-                        array('EE_', 'EEM_', 'EED_', 'EES_', 'EEW_'), '',
978
-                        $class_name
979
-                    ) . '</b></li>';
980
-            }
981
-            $msg .= '</ul>';
982
-            $msg .= __(
983
-                'Compatibility issues can be avoided and/or resolved by keeping addons and plugins updated to the latest version.',
984
-                'event_espresso'
985
-            );
986
-            // save list of incompatible addons to wp-options for later use
987
-            add_option('ee_incompatible_addons', $class_names, '', 'no');
988
-            if (is_admin()) {
989
-                EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
990
-            }
991
-        }
992
-    }
993
-
994
-
995
-
996
-    /**
997
-     * brew_espresso
998
-     * begins the process of setting hooks for initializing EE in the correct order
999
-     * This is happening on the 'AHEE__EE_Bootstrap__brew_espresso' hook point
1000
-     * which runs during the WP 'plugins_loaded' action at priority 9
1001
-     *
1002
-     * @return void
1003
-     */
1004
-    public function brew_espresso()
1005
-    {
1006
-        do_action('AHEE__EE_System__brew_espresso__begin', $this);
1007
-        // load some final core systems
1008
-        add_action('init', array($this, 'set_hooks_for_core'), 1);
1009
-        add_action('init', array($this, 'perform_activations_upgrades_and_migrations'), 3);
1010
-        add_action('init', array($this, 'load_CPTs_and_session'), 5);
1011
-        add_action('init', array($this, 'load_controllers'), 7);
1012
-        add_action('init', array($this, 'core_loaded_and_ready'), 9);
1013
-        add_action('init', array($this, 'initialize'), 10);
1014
-        add_action('init', array($this, 'initialize_last'), 100);
1015
-        if (is_admin() && apply_filters('FHEE__EE_System__brew_espresso__load_pue', true)) {
1016
-            // pew pew pew
1017
-            $this->loader->getShared('EE_PUE');
1018
-            do_action('AHEE__EE_System__brew_espresso__after_pue_init');
1019
-        }
1020
-        do_action('AHEE__EE_System__brew_espresso__complete', $this);
1021
-    }
1022
-
1023
-
1024
-
1025
-    /**
1026
-     *    set_hooks_for_core
1027
-     *
1028
-     * @access public
1029
-     * @return    void
1030
-     * @throws EE_Error
1031
-     */
1032
-    public function set_hooks_for_core()
1033
-    {
1034
-        $this->_deactivate_incompatible_addons();
1035
-        do_action('AHEE__EE_System__set_hooks_for_core');
1036
-        //caps need to be initialized on every request so that capability maps are set.
1037
-        //@see https://events.codebasehq.com/projects/event-espresso/tickets/8674
1038
-        $this->registry->CAP->init_caps();
1039
-    }
1040
-
1041
-
1042
-
1043
-    /**
1044
-     * Using the information gathered in EE_System::_incompatible_addon_error,
1045
-     * deactivates any addons considered incompatible with the current version of EE
1046
-     */
1047
-    private function _deactivate_incompatible_addons()
1048
-    {
1049
-        $incompatible_addons = get_option('ee_incompatible_addons', array());
1050
-        if (! empty($incompatible_addons)) {
1051
-            $active_plugins = get_option('active_plugins', array());
1052
-            foreach ($active_plugins as $active_plugin) {
1053
-                foreach ($incompatible_addons as $incompatible_addon) {
1054
-                    if (strpos($active_plugin, $incompatible_addon) !== false) {
1055
-                        unset($_GET['activate']);
1056
-                        espresso_deactivate_plugin($active_plugin);
1057
-                    }
1058
-                }
1059
-            }
1060
-        }
1061
-    }
1062
-
1063
-
1064
-
1065
-    /**
1066
-     *    perform_activations_upgrades_and_migrations
1067
-     *
1068
-     * @access public
1069
-     * @return    void
1070
-     */
1071
-    public function perform_activations_upgrades_and_migrations()
1072
-    {
1073
-        //first check if we had previously attempted to setup EE's directories but failed
1074
-        if (EEH_Activation::upload_directories_incomplete()) {
1075
-            EEH_Activation::create_upload_directories();
1076
-        }
1077
-        do_action('AHEE__EE_System__perform_activations_upgrades_and_migrations');
1078
-    }
1079
-
1080
-
1081
-
1082
-    /**
1083
-     *    load_CPTs_and_session
1084
-     *
1085
-     * @access public
1086
-     * @return    void
1087
-     */
1088
-    public function load_CPTs_and_session()
1089
-    {
1090
-        do_action('AHEE__EE_System__load_CPTs_and_session__start');
1091
-        // register Custom Post Types
1092
-        $this->loader->getShared('EE_Register_CPTs');
1093
-        do_action('AHEE__EE_System__load_CPTs_and_session__complete');
1094
-    }
1095
-
1096
-
1097
-
1098
-    /**
1099
-     * load_controllers
1100
-     * this is the best place to load any additional controllers that needs access to EE core.
1101
-     * it is expected that all basic core EE systems, that are not dependant on the current request are loaded at this
1102
-     * time
1103
-     *
1104
-     * @access public
1105
-     * @return void
1106
-     */
1107
-    public function load_controllers()
1108
-    {
1109
-        do_action('AHEE__EE_System__load_controllers__start');
1110
-        // let's get it started
1111
-        if (! is_admin() && ! $this->maintenance_mode->level()) {
1112
-            do_action('AHEE__EE_System__load_controllers__load_front_controllers');
1113
-            $this->loader->getShared('EE_Front_Controller');
1114
-        } else if (! EE_FRONT_AJAX) {
1115
-            do_action('AHEE__EE_System__load_controllers__load_admin_controllers');
1116
-            $this->loader->getShared('EE_Admin');
1117
-        }
1118
-        do_action('AHEE__EE_System__load_controllers__complete');
1119
-    }
1120
-
1121
-
1122
-
1123
-    /**
1124
-     * core_loaded_and_ready
1125
-     * all of the basic EE core should be loaded at this point and available regardless of M-Mode
1126
-     *
1127
-     * @access public
1128
-     * @return void
1129
-     */
1130
-    public function core_loaded_and_ready()
1131
-    {
1132
-        $this->loader->getShared('EE_Session');
1133
-        do_action('AHEE__EE_System__core_loaded_and_ready');
1134
-        // load_espresso_template_tags
1135
-        if (is_readable(EE_PUBLIC . 'template_tags.php')) {
1136
-            require_once(EE_PUBLIC . 'template_tags.php');
1137
-        }
1138
-        do_action('AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons');
1139
-        $this->loader->getShared('EventEspresso\core\services\assets\Registry');
1140
-    }
1141
-
1142
-
1143
-
1144
-    /**
1145
-     * initialize
1146
-     * this is the best place to begin initializing client code
1147
-     *
1148
-     * @access public
1149
-     * @return void
1150
-     */
1151
-    public function initialize()
1152
-    {
1153
-        do_action('AHEE__EE_System__initialize');
1154
-    }
1155
-
1156
-
1157
-
1158
-    /**
1159
-     * initialize_last
1160
-     * this is run really late during the WP init hook point, and ensures that mostly everything else that needs to
1161
-     * initialize has done so
1162
-     *
1163
-     * @access public
1164
-     * @return void
1165
-     */
1166
-    public function initialize_last()
1167
-    {
1168
-        do_action('AHEE__EE_System__initialize_last');
1169
-        add_action('admin_bar_init', array($this, 'addEspressoToolbar'));
1170
-    }
1171
-
1172
-
1173
-
1174
-    /**
1175
-     * @return void
1176
-     * @throws EE_Error
1177
-     */
1178
-    public function addEspressoToolbar()
1179
-    {
1180
-        $this->loader->getShared(
1181
-            'EventEspresso\core\domain\services\admin\AdminToolBar',
1182
-            array($this->registry->CAP)
1183
-        );
1184
-    }
1185
-
1186
-
1187
-
1188
-    /**
1189
-     * do_not_cache
1190
-     * sets no cache headers and defines no cache constants for WP plugins
1191
-     *
1192
-     * @access public
1193
-     * @return void
1194
-     */
1195
-    public static function do_not_cache()
1196
-    {
1197
-        // set no cache constants
1198
-        if (! defined('DONOTCACHEPAGE')) {
1199
-            define('DONOTCACHEPAGE', true);
1200
-        }
1201
-        if (! defined('DONOTCACHCEOBJECT')) {
1202
-            define('DONOTCACHCEOBJECT', true);
1203
-        }
1204
-        if (! defined('DONOTCACHEDB')) {
1205
-            define('DONOTCACHEDB', true);
1206
-        }
1207
-        // add no cache headers
1208
-        add_action('send_headers', array('EE_System', 'nocache_headers'), 10);
1209
-        // plus a little extra for nginx and Google Chrome
1210
-        add_filter('nocache_headers', array('EE_System', 'extra_nocache_headers'), 10, 1);
1211
-        // prevent browsers from prefetching of the rel='next' link, because it may contain content that interferes with the registration process
1212
-        remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');
1213
-    }
1214
-
1215
-
1216
-
1217
-    /**
1218
-     *    extra_nocache_headers
1219
-     *
1220
-     * @access    public
1221
-     * @param $headers
1222
-     * @return    array
1223
-     */
1224
-    public static function extra_nocache_headers($headers)
1225
-    {
1226
-        // for NGINX
1227
-        $headers['X-Accel-Expires'] = 0;
1228
-        // plus extra for Google Chrome since it doesn't seem to respect "no-cache", but WILL respect "no-store"
1229
-        $headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0';
1230
-        return $headers;
1231
-    }
1232
-
1233
-
1234
-
1235
-    /**
1236
-     *    nocache_headers
1237
-     *
1238
-     * @access    public
1239
-     * @return    void
1240
-     */
1241
-    public static function nocache_headers()
1242
-    {
1243
-        nocache_headers();
1244
-    }
1245
-
1246
-
1247
-
1248
-
1249
-    /**
1250
-     * simply hooks into "wp_list_pages_exclude" filter (for wp_list_pages method) and makes sure EE critical pages are
1251
-     * never returned with the function.
1252
-     *
1253
-     * @param  array $exclude_array any existing pages being excluded are in this array.
1254
-     * @return array
1255
-     */
1256
-    public function remove_pages_from_wp_list_pages($exclude_array)
1257
-    {
1258
-        return array_merge($exclude_array, $this->registry->CFG->core->get_critical_pages_array());
1259
-    }
24
+	/**
25
+	 * indicates this is a 'normal' request. Ie, not activation, nor upgrade, nor activation.
26
+	 * So examples of this would be a normal GET request on the frontend or backend, or a POST, etc
27
+	 */
28
+	const req_type_normal = 0;
29
+
30
+	/**
31
+	 * Indicates this is a brand new installation of EE so we should install
32
+	 * tables and default data etc
33
+	 */
34
+	const req_type_new_activation = 1;
35
+
36
+	/**
37
+	 * we've detected that EE has been reactivated (or EE was activated during maintenance mode,
38
+	 * and we just exited maintenance mode). We MUST check the database is setup properly
39
+	 * and that default data is setup too
40
+	 */
41
+	const req_type_reactivation = 2;
42
+
43
+	/**
44
+	 * indicates that EE has been upgraded since its previous request.
45
+	 * We may have data migration scripts to call and will want to trigger maintenance mode
46
+	 */
47
+	const req_type_upgrade = 3;
48
+
49
+	/**
50
+	 * TODO  will detect that EE has been DOWNGRADED. We probably don't want to run in this case...
51
+	 */
52
+	const req_type_downgrade = 4;
53
+
54
+	/**
55
+	 * @deprecated since version 4.6.0.dev.006
56
+	 * Now whenever a new_activation is detected the request type is still just
57
+	 * new_activation (same for reactivation, upgrade, downgrade etc), but if we'r ein maintenance mode
58
+	 * EE_System::initialize_db_if_no_migrations_required and EE_Addon::initialize_db_if_no_migrations_required
59
+	 * will instead enqueue that EE plugin's db initialization for when we're taken out of maintenance mode.
60
+	 * (Specifically, when the migration manager indicates migrations are finished
61
+	 * EE_Data_Migration_Manager::initialize_db_for_enqueued_ee_plugins() will be called)
62
+	 */
63
+	const req_type_activation_but_not_installed = 5;
64
+
65
+	/**
66
+	 * option prefix for recording the activation history (like core's "espresso_db_update") of addons
67
+	 */
68
+	const addon_activation_history_option_prefix = 'ee_addon_activation_history_';
69
+
70
+
71
+	/**
72
+	 * @var EE_System $_instance
73
+	 */
74
+	private static $_instance;
75
+
76
+	/**
77
+	 * @var EE_Registry $registry
78
+	 */
79
+	private $registry;
80
+
81
+	/**
82
+	 * @var LoaderInterface $loader
83
+	 */
84
+	private $loader;
85
+
86
+	/**
87
+	 * @var EE_Capabilities $capabilities
88
+	 */
89
+	private $capabilities;
90
+
91
+	/**
92
+	 * @var EE_Request $request
93
+	 */
94
+	private $request;
95
+
96
+	/**
97
+	 * @var EE_Maintenance_Mode $maintenance_mode
98
+	 */
99
+	private $maintenance_mode;
100
+
101
+	/**
102
+	 * Stores which type of request this is, options being one of the constants on EE_System starting with req_type_*.
103
+	 * It can be a brand-new activation, a reactivation, an upgrade, a downgrade, or a normal request.
104
+	 *
105
+	 * @var int $_req_type
106
+	 */
107
+	private $_req_type;
108
+
109
+	/**
110
+	 * Whether or not there was a non-micro version change in EE core version during this request
111
+	 *
112
+	 * @var boolean $_major_version_change
113
+	 */
114
+	private $_major_version_change = false;
115
+
116
+
117
+
118
+	/**
119
+	 * @singleton method used to instantiate class object
120
+	 * @param EE_Registry|null         $registry
121
+	 * @param LoaderInterface|null     $loader
122
+	 * @param EE_Capabilities|null     $capabilities
123
+	 * @param EE_Request|null          $request
124
+	 * @param EE_Maintenance_Mode|null $maintenance_mode
125
+	 * @return EE_System
126
+	 */
127
+	public static function instance(
128
+		EE_Registry $registry = null,
129
+		LoaderInterface $loader = null,
130
+		EE_Capabilities $capabilities = null,
131
+		EE_Request $request = null,
132
+		EE_Maintenance_Mode $maintenance_mode = null
133
+	) {
134
+		// check if class object is instantiated
135
+		if (! self::$_instance instanceof EE_System) {
136
+			self::$_instance = new self($registry, $loader, $capabilities, $request, $maintenance_mode);
137
+		}
138
+		return self::$_instance;
139
+	}
140
+
141
+
142
+
143
+	/**
144
+	 * resets the instance and returns it
145
+	 *
146
+	 * @return EE_System
147
+	 */
148
+	public static function reset()
149
+	{
150
+		self::$_instance->_req_type = null;
151
+		//make sure none of the old hooks are left hanging around
152
+		remove_all_actions('AHEE__EE_System__perform_activations_upgrades_and_migrations');
153
+		//we need to reset the migration manager in order for it to detect DMSs properly
154
+		EE_Data_Migration_Manager::reset();
155
+		self::instance()->detect_activations_or_upgrades();
156
+		self::instance()->perform_activations_upgrades_and_migrations();
157
+		return self::instance();
158
+	}
159
+
160
+
161
+
162
+	/**
163
+	 * sets hooks for running rest of system
164
+	 * provides "AHEE__EE_System__construct__complete" hook for EE Addons to use as their starting point
165
+	 * starting EE Addons from any other point may lead to problems
166
+	 *
167
+	 * @param EE_Registry         $registry
168
+	 * @param LoaderInterface     $loader
169
+	 * @param EE_Capabilities     $capabilities
170
+	 * @param EE_Request          $request
171
+	 * @param EE_Maintenance_Mode $maintenance_mode
172
+	 */
173
+	private function __construct(
174
+		EE_Registry $registry,
175
+		LoaderInterface $loader,
176
+		EE_Capabilities $capabilities,
177
+		EE_Request $request,
178
+		EE_Maintenance_Mode $maintenance_mode
179
+	) {
180
+		$this->registry = $registry;
181
+		$this->loader = $loader;
182
+		$this->capabilities = $capabilities;
183
+		$this->request = $request;
184
+		$this->maintenance_mode = $maintenance_mode;
185
+		do_action('AHEE__EE_System__construct__begin', $this);
186
+		add_action(
187
+			'AHEE__EE_Bootstrap__load_espresso_addons',
188
+			array($this, 'loadCapabilities'),
189
+			5
190
+		);
191
+		add_action(
192
+			'AHEE__EE_Bootstrap__load_espresso_addons',
193
+			array($this, 'loadCommandBus'),
194
+			7
195
+		);
196
+		add_action(
197
+			'AHEE__EE_Bootstrap__load_espresso_addons',
198
+			array($this, 'loadPluginApi'),
199
+			9
200
+		);
201
+		// allow addons to load first so that they can register autoloaders, set hooks for running DMS's, etc
202
+		add_action(
203
+			'AHEE__EE_Bootstrap__load_espresso_addons',
204
+			array($this, 'load_espresso_addons')
205
+		);
206
+		// when an ee addon is activated, we want to call the core hook(s) again
207
+		// because the newly-activated addon didn't get a chance to run at all
208
+		add_action('activate_plugin', array($this, 'load_espresso_addons'), 1);
209
+		// detect whether install or upgrade
210
+		add_action(
211
+			'AHEE__EE_Bootstrap__detect_activations_or_upgrades',
212
+			array($this, 'detect_activations_or_upgrades'),
213
+			3
214
+		);
215
+		// load EE_Config, EE_Textdomain, etc
216
+		add_action(
217
+			'AHEE__EE_Bootstrap__load_core_configuration',
218
+			array($this, 'load_core_configuration'),
219
+			5
220
+		);
221
+		// load EE_Config, EE_Textdomain, etc
222
+		add_action(
223
+			'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets',
224
+			array($this, 'register_shortcodes_modules_and_widgets'),
225
+			7
226
+		);
227
+		// you wanna get going? I wanna get going... let's get going!
228
+		add_action(
229
+			'AHEE__EE_Bootstrap__brew_espresso',
230
+			array($this, 'brew_espresso'),
231
+			9
232
+		);
233
+		//other housekeeping
234
+		//exclude EE critical pages from wp_list_pages
235
+		add_filter(
236
+			'wp_list_pages_excludes',
237
+			array($this, 'remove_pages_from_wp_list_pages'),
238
+			10
239
+		);
240
+		// ALL EE Addons should use the following hook point to attach their initial setup too
241
+		// it's extremely important for EE Addons to register any class autoloaders so that they can be available when the EE_Config loads
242
+		do_action('AHEE__EE_System__construct__complete', $this);
243
+	}
244
+
245
+
246
+
247
+	/**
248
+	 * load and setup EE_Capabilities
249
+	 *
250
+	 * @return void
251
+	 * @throws EE_Error
252
+	 */
253
+	public function loadCapabilities()
254
+	{
255
+		$this->loader->getShared('EE_Capabilities');
256
+		add_action(
257
+			'AHEE__EE_Capabilities__init_caps__before_initialization',
258
+			function() {
259
+				LoaderFactory::getLoader()->getShared('EE_Payment_Method_Manager');
260
+			}
261
+		);
262
+	}
263
+
264
+
265
+
266
+	/**
267
+	 * create and cache the CommandBus, and also add middleware
268
+	 * The CapChecker middleware requires the use of EE_Capabilities
269
+	 * which is why we need to load the CommandBus after Caps are set up
270
+	 *
271
+	 * @return void
272
+	 * @throws EE_Error
273
+	 */
274
+	public function loadCommandBus()
275
+	{
276
+		$this->loader->getShared(
277
+			'CommandBusInterface',
278
+			array(
279
+				null,
280
+				apply_filters(
281
+					'FHEE__EE_Load_Espresso_Core__handle_request__CommandBus_middleware',
282
+					array(
283
+						$this->loader->getShared('EventEspresso\core\services\commands\middleware\CapChecker'),
284
+						$this->loader->getShared('EventEspresso\core\services\commands\middleware\AddActionHook'),
285
+					)
286
+				),
287
+			)
288
+		);
289
+	}
290
+
291
+
292
+
293
+	/**
294
+	 * @return void
295
+	 * @throws EE_Error
296
+	 */
297
+	public function loadPluginApi()
298
+	{
299
+		// set autoloaders for all of the classes implementing EEI_Plugin_API
300
+		// which provide helpers for EE plugin authors to more easily register certain components with EE.
301
+		EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'plugin_api');
302
+	}
303
+
304
+
305
+	/**
306
+	 * @param string $addon_name
307
+	 * @param string $version_constant
308
+	 * @param string $min_version_required
309
+	 * @param string $load_callback
310
+	 * @param string $plugin_file_constant
311
+	 * @return void
312
+	 */
313
+	private function deactivateIncompatibleAddon(
314
+		$addon_name,
315
+		$version_constant,
316
+		$min_version_required,
317
+		$load_callback,
318
+		$plugin_file_constant
319
+	) {
320
+		if (! defined($version_constant)) {
321
+			return;
322
+		}
323
+		$addon_version = constant($version_constant);
324
+		if ($addon_version && version_compare($addon_version, $min_version_required, '<')) {
325
+			remove_action('AHEE__EE_System__load_espresso_addons', $load_callback);
326
+			if (! function_exists('deactivate_plugins')) {
327
+				require_once ABSPATH . 'wp-admin/includes/plugin.php';
328
+			}
329
+			deactivate_plugins(plugin_basename(constant($plugin_file_constant)));
330
+			unset($_GET['activate'], $_REQUEST['activate'], $_GET['activate-multi'], $_REQUEST['activate-multi']);
331
+			EE_Error::add_error(
332
+				sprintf(
333
+					esc_html__(
334
+						'We\'re sorry, but the Event Espresso %1$s addon was deactivated because version %2$s or higher is required with this version of Event Espresso core.',
335
+						'event_espresso'
336
+					),
337
+					$addon_name,
338
+					$min_version_required
339
+				),
340
+				__FILE__, __FUNCTION__ . "({$addon_name})", __LINE__
341
+			);
342
+			EE_Error::get_notices(false, true);
343
+		}
344
+	}
345
+
346
+
347
+	/**
348
+	 * load_espresso_addons
349
+	 * allow addons to load first so that they can set hooks for running DMS's, etc
350
+	 * this is hooked into both:
351
+	 *    'AHEE__EE_Bootstrap__load_core_configuration'
352
+	 *        which runs during the WP 'plugins_loaded' action at priority 5
353
+	 *    and the WP 'activate_plugin' hook point
354
+	 *
355
+	 * @access public
356
+	 * @return void
357
+	 */
358
+	public function load_espresso_addons()
359
+	{
360
+		$this->deactivateIncompatibleAddon(
361
+			'Wait Lists',
362
+			'EE_WAIT_LISTS_VERSION',
363
+			'1.0.0.rc.074',
364
+			'load_espresso_wait_lists',
365
+			'EE_WAIT_LISTS_PLUGIN_FILE'
366
+		);
367
+		$this->deactivateIncompatibleAddon(
368
+			'Automated Upcoming Event Notifications',
369
+			'EE_AUTOMATED_UPCOMING_EVENT_NOTIFICATION_VERSION',
370
+			'1.0.0.rc.091',
371
+			'load_espresso_automated_upcoming_event_notification',
372
+			'EE_AUTOMATED_UPCOMING_EVENT_NOTIFICATION_PLUGIN_FILE'
373
+		);
374
+		do_action('AHEE__EE_System__load_espresso_addons');
375
+		//if the WP API basic auth plugin isn't already loaded, load it now.
376
+		//We want it for mobile apps. Just include the entire plugin
377
+		//also, don't load the basic auth when a plugin is getting activated, because
378
+		//it could be the basic auth plugin, and it doesn't check if its methods are already defined
379
+		//and causes a fatal error
380
+		if (
381
+			! (
382
+				isset($_GET['activate'])
383
+				&& $_GET['activate'] === 'true'
384
+			)
385
+			&& ! function_exists('json_basic_auth_handler')
386
+			&& ! function_exists('json_basic_auth_error')
387
+			&& ! (
388
+				isset($_GET['action'])
389
+				&& in_array($_GET['action'], array('activate', 'activate-selected'), true)
390
+			)
391
+		) {
392
+			include_once EE_THIRD_PARTY . 'wp-api-basic-auth' . DS . 'basic-auth.php';
393
+		}
394
+		do_action('AHEE__EE_System__load_espresso_addons__complete');
395
+	}
396
+
397
+
398
+
399
+	/**
400
+	 * detect_activations_or_upgrades
401
+	 * Checks for activation or upgrade of core first;
402
+	 * then also checks if any registered addons have been activated or upgraded
403
+	 * This is hooked into 'AHEE__EE_Bootstrap__detect_activations_or_upgrades'
404
+	 * which runs during the WP 'plugins_loaded' action at priority 3
405
+	 *
406
+	 * @access public
407
+	 * @return void
408
+	 */
409
+	public function detect_activations_or_upgrades()
410
+	{
411
+		//first off: let's make sure to handle core
412
+		$this->detect_if_activation_or_upgrade();
413
+		foreach ($this->registry->addons as $addon) {
414
+			if ($addon instanceof EE_Addon) {
415
+				//detect teh request type for that addon
416
+				$addon->detect_activation_or_upgrade();
417
+			}
418
+		}
419
+	}
420
+
421
+
422
+
423
+	/**
424
+	 * detect_if_activation_or_upgrade
425
+	 * Takes care of detecting whether this is a brand new install or code upgrade,
426
+	 * and either setting up the DB or setting up maintenance mode etc.
427
+	 *
428
+	 * @access public
429
+	 * @return void
430
+	 */
431
+	public function detect_if_activation_or_upgrade()
432
+	{
433
+		do_action('AHEE__EE_System___detect_if_activation_or_upgrade__begin');
434
+		// check if db has been updated, or if its a brand-new installation
435
+		$espresso_db_update = $this->fix_espresso_db_upgrade_option();
436
+		$request_type = $this->detect_req_type($espresso_db_update);
437
+		//EEH_Debug_Tools::printr( $request_type, '$request_type', __FILE__, __LINE__ );
438
+		switch ($request_type) {
439
+			case EE_System::req_type_new_activation:
440
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__new_activation');
441
+				$this->_handle_core_version_change($espresso_db_update);
442
+				break;
443
+			case EE_System::req_type_reactivation:
444
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__reactivation');
445
+				$this->_handle_core_version_change($espresso_db_update);
446
+				break;
447
+			case EE_System::req_type_upgrade:
448
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__upgrade');
449
+				//migrations may be required now that we've upgraded
450
+				$this->maintenance_mode->set_maintenance_mode_if_db_old();
451
+				$this->_handle_core_version_change($espresso_db_update);
452
+				//				echo "done upgrade";die;
453
+				break;
454
+			case EE_System::req_type_downgrade:
455
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__downgrade');
456
+				//its possible migrations are no longer required
457
+				$this->maintenance_mode->set_maintenance_mode_if_db_old();
458
+				$this->_handle_core_version_change($espresso_db_update);
459
+				break;
460
+			case EE_System::req_type_normal:
461
+			default:
462
+				//				$this->_maybe_redirect_to_ee_about();
463
+				break;
464
+		}
465
+		do_action('AHEE__EE_System__detect_if_activation_or_upgrade__complete');
466
+	}
467
+
468
+
469
+
470
+	/**
471
+	 * Updates the list of installed versions and sets hooks for
472
+	 * initializing the database later during the request
473
+	 *
474
+	 * @param array $espresso_db_update
475
+	 */
476
+	private function _handle_core_version_change($espresso_db_update)
477
+	{
478
+		$this->update_list_of_installed_versions($espresso_db_update);
479
+		//get ready to verify the DB is ok (provided we aren't in maintenance mode, of course)
480
+		add_action(
481
+			'AHEE__EE_System__perform_activations_upgrades_and_migrations',
482
+			array($this, 'initialize_db_if_no_migrations_required')
483
+		);
484
+	}
485
+
486
+
487
+
488
+	/**
489
+	 * standardizes the wp option 'espresso_db_upgrade' which actually stores
490
+	 * information about what versions of EE have been installed and activated,
491
+	 * NOT necessarily the state of the database
492
+	 *
493
+	 * @param mixed $espresso_db_update the value of the WordPress option.
494
+	 *                                            If not supplied, fetches it from the options table
495
+	 * @return array the correct value of 'espresso_db_upgrade', after saving it, if it needed correction
496
+	 */
497
+	private function fix_espresso_db_upgrade_option($espresso_db_update = null)
498
+	{
499
+		do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__begin', $espresso_db_update);
500
+		if (! $espresso_db_update) {
501
+			$espresso_db_update = get_option('espresso_db_update');
502
+		}
503
+		// check that option is an array
504
+		if (! is_array($espresso_db_update)) {
505
+			// if option is FALSE, then it never existed
506
+			if ($espresso_db_update === false) {
507
+				// make $espresso_db_update an array and save option with autoload OFF
508
+				$espresso_db_update = array();
509
+				add_option('espresso_db_update', $espresso_db_update, '', 'no');
510
+			} else {
511
+				// option is NOT FALSE but also is NOT an array, so make it an array and save it
512
+				$espresso_db_update = array($espresso_db_update => array());
513
+				update_option('espresso_db_update', $espresso_db_update);
514
+			}
515
+		} else {
516
+			$corrected_db_update = array();
517
+			//if IS an array, but is it an array where KEYS are version numbers, and values are arrays?
518
+			foreach ($espresso_db_update as $should_be_version_string => $should_be_array) {
519
+				if (is_int($should_be_version_string) && ! is_array($should_be_array)) {
520
+					//the key is an int, and the value IS NOT an array
521
+					//so it must be numerically-indexed, where values are versions installed...
522
+					//fix it!
523
+					$version_string = $should_be_array;
524
+					$corrected_db_update[$version_string] = array('unknown-date');
525
+				} else {
526
+					//ok it checks out
527
+					$corrected_db_update[$should_be_version_string] = $should_be_array;
528
+				}
529
+			}
530
+			$espresso_db_update = $corrected_db_update;
531
+			update_option('espresso_db_update', $espresso_db_update);
532
+		}
533
+		do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__complete', $espresso_db_update);
534
+		return $espresso_db_update;
535
+	}
536
+
537
+
538
+
539
+	/**
540
+	 * Does the traditional work of setting up the plugin's database and adding default data.
541
+	 * If migration script/process did not exist, this is what would happen on every activation/reactivation/upgrade.
542
+	 * NOTE: if we're in maintenance mode (which would be the case if we detect there are data
543
+	 * migration scripts that need to be run and a version change happens), enqueues core for database initialization,
544
+	 * so that it will be done when migrations are finished
545
+	 *
546
+	 * @param boolean $initialize_addons_too if true, we double-check addons' database tables etc too;
547
+	 * @param boolean $verify_schema         if true will re-check the database tables have the correct schema.
548
+	 *                                       This is a resource-intensive job
549
+	 *                                       so we prefer to only do it when necessary
550
+	 * @return void
551
+	 * @throws EE_Error
552
+	 */
553
+	public function initialize_db_if_no_migrations_required($initialize_addons_too = false, $verify_schema = true)
554
+	{
555
+		$request_type = $this->detect_req_type();
556
+		//only initialize system if we're not in maintenance mode.
557
+		if ($this->maintenance_mode->level() !== EE_Maintenance_Mode::level_2_complete_maintenance) {
558
+			update_option('ee_flush_rewrite_rules', true);
559
+			if ($verify_schema) {
560
+				EEH_Activation::initialize_db_and_folders();
561
+			}
562
+			EEH_Activation::initialize_db_content();
563
+			EEH_Activation::system_initialization();
564
+			if ($initialize_addons_too) {
565
+				$this->initialize_addons();
566
+			}
567
+		} else {
568
+			EE_Data_Migration_Manager::instance()->enqueue_db_initialization_for('Core');
569
+		}
570
+		if ($request_type === EE_System::req_type_new_activation
571
+			|| $request_type === EE_System::req_type_reactivation
572
+			|| (
573
+				$request_type === EE_System::req_type_upgrade
574
+				&& $this->is_major_version_change()
575
+			)
576
+		) {
577
+			add_action('AHEE__EE_System__initialize_last', array($this, 'redirect_to_about_ee'), 9);
578
+		}
579
+	}
580
+
581
+
582
+
583
+	/**
584
+	 * Initializes the db for all registered addons
585
+	 *
586
+	 * @throws EE_Error
587
+	 */
588
+	public function initialize_addons()
589
+	{
590
+		//foreach registered addon, make sure its db is up-to-date too
591
+		foreach ($this->registry->addons as $addon) {
592
+			if ($addon instanceof EE_Addon) {
593
+				$addon->initialize_db_if_no_migrations_required();
594
+			}
595
+		}
596
+	}
597
+
598
+
599
+
600
+	/**
601
+	 * Adds the current code version to the saved wp option which stores a list of all ee versions ever installed.
602
+	 *
603
+	 * @param    array  $version_history
604
+	 * @param    string $current_version_to_add version to be added to the version history
605
+	 * @return    boolean success as to whether or not this option was changed
606
+	 */
607
+	public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null)
608
+	{
609
+		if (! $version_history) {
610
+			$version_history = $this->fix_espresso_db_upgrade_option($version_history);
611
+		}
612
+		if ($current_version_to_add === null) {
613
+			$current_version_to_add = espresso_version();
614
+		}
615
+		$version_history[$current_version_to_add][] = date('Y-m-d H:i:s', time());
616
+		// re-save
617
+		return update_option('espresso_db_update', $version_history);
618
+	}
619
+
620
+
621
+
622
+	/**
623
+	 * Detects if the current version indicated in the has existed in the list of
624
+	 * previously-installed versions of EE (espresso_db_update). Does NOT modify it (ie, no side-effect)
625
+	 *
626
+	 * @param array $espresso_db_update array from the wp option stored under the name 'espresso_db_update'.
627
+	 *                                  If not supplied, fetches it from the options table.
628
+	 *                                  Also, caches its result so later parts of the code can also know whether
629
+	 *                                  there's been an update or not. This way we can add the current version to
630
+	 *                                  espresso_db_update, but still know if this is a new install or not
631
+	 * @return int one of the constants on EE_System::req_type_
632
+	 */
633
+	public function detect_req_type($espresso_db_update = null)
634
+	{
635
+		if ($this->_req_type === null) {
636
+			$espresso_db_update = ! empty($espresso_db_update)
637
+				? $espresso_db_update
638
+				: $this->fix_espresso_db_upgrade_option();
639
+			$this->_req_type = EE_System::detect_req_type_given_activation_history(
640
+				$espresso_db_update,
641
+				'ee_espresso_activation', espresso_version()
642
+			);
643
+			$this->_major_version_change = $this->_detect_major_version_change($espresso_db_update);
644
+		}
645
+		return $this->_req_type;
646
+	}
647
+
648
+
649
+
650
+	/**
651
+	 * Returns whether or not there was a non-micro version change (ie, change in either
652
+	 * the first or second number in the version. Eg 4.9.0.rc.001 to 4.10.0.rc.000,
653
+	 * but not 4.9.0.rc.0001 to 4.9.1.rc.0001
654
+	 *
655
+	 * @param $activation_history
656
+	 * @return bool
657
+	 */
658
+	private function _detect_major_version_change($activation_history)
659
+	{
660
+		$previous_version = EE_System::_get_most_recently_active_version_from_activation_history($activation_history);
661
+		$previous_version_parts = explode('.', $previous_version);
662
+		$current_version_parts = explode('.', espresso_version());
663
+		return isset($previous_version_parts[0], $previous_version_parts[1], $current_version_parts[0], $current_version_parts[1])
664
+			   && ($previous_version_parts[0] !== $current_version_parts[0]
665
+				   || $previous_version_parts[1] !== $current_version_parts[1]
666
+			   );
667
+	}
668
+
669
+
670
+
671
+	/**
672
+	 * Returns true if either the major or minor version of EE changed during this request.
673
+	 * Eg 4.9.0.rc.001 to 4.10.0.rc.000, but not 4.9.0.rc.0001 to 4.9.1.rc.0001
674
+	 *
675
+	 * @return bool
676
+	 */
677
+	public function is_major_version_change()
678
+	{
679
+		return $this->_major_version_change;
680
+	}
681
+
682
+
683
+
684
+	/**
685
+	 * Determines the request type for any ee addon, given three piece of info: the current array of activation
686
+	 * histories (for core that' 'espresso_db_update' wp option); the name of the WordPress option which is temporarily
687
+	 * set upon activation of the plugin (for core it's 'ee_espresso_activation'); and the version that this plugin was
688
+	 * just activated to (for core that will always be espresso_version())
689
+	 *
690
+	 * @param array  $activation_history_for_addon     the option's value which stores the activation history for this
691
+	 *                                                 ee plugin. for core that's 'espresso_db_update'
692
+	 * @param string $activation_indicator_option_name the name of the WordPress option that is temporarily set to
693
+	 *                                                 indicate that this plugin was just activated
694
+	 * @param string $version_to_upgrade_to            the version that was just upgraded to (for core that will be
695
+	 *                                                 espresso_version())
696
+	 * @return int one of the constants on EE_System::req_type_*
697
+	 */
698
+	public static function detect_req_type_given_activation_history(
699
+		$activation_history_for_addon,
700
+		$activation_indicator_option_name,
701
+		$version_to_upgrade_to
702
+	) {
703
+		$version_is_higher = self::_new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to);
704
+		if ($activation_history_for_addon) {
705
+			//it exists, so this isn't a completely new install
706
+			//check if this version already in that list of previously installed versions
707
+			if (! isset($activation_history_for_addon[$version_to_upgrade_to])) {
708
+				//it a version we haven't seen before
709
+				if ($version_is_higher === 1) {
710
+					$req_type = EE_System::req_type_upgrade;
711
+				} else {
712
+					$req_type = EE_System::req_type_downgrade;
713
+				}
714
+				delete_option($activation_indicator_option_name);
715
+			} else {
716
+				// its not an update. maybe a reactivation?
717
+				if (get_option($activation_indicator_option_name, false)) {
718
+					if ($version_is_higher === -1) {
719
+						$req_type = EE_System::req_type_downgrade;
720
+					} else if ($version_is_higher === 0) {
721
+						//we've seen this version before, but it's an activation. must be a reactivation
722
+						$req_type = EE_System::req_type_reactivation;
723
+					} else {//$version_is_higher === 1
724
+						$req_type = EE_System::req_type_upgrade;
725
+					}
726
+					delete_option($activation_indicator_option_name);
727
+				} else {
728
+					//we've seen this version before and the activation indicate doesn't show it was just activated
729
+					if ($version_is_higher === -1) {
730
+						$req_type = EE_System::req_type_downgrade;
731
+					} else if ($version_is_higher === 0) {
732
+						//we've seen this version before and it's not an activation. its normal request
733
+						$req_type = EE_System::req_type_normal;
734
+					} else {//$version_is_higher === 1
735
+						$req_type = EE_System::req_type_upgrade;
736
+					}
737
+				}
738
+			}
739
+		} else {
740
+			//brand new install
741
+			$req_type = EE_System::req_type_new_activation;
742
+			delete_option($activation_indicator_option_name);
743
+		}
744
+		return $req_type;
745
+	}
746
+
747
+
748
+
749
+	/**
750
+	 * Detects if the $version_to_upgrade_to is higher than the most recent version in
751
+	 * the $activation_history_for_addon
752
+	 *
753
+	 * @param array  $activation_history_for_addon (keys are versions, values are arrays of times activated,
754
+	 *                                             sometimes containing 'unknown-date'
755
+	 * @param string $version_to_upgrade_to        (current version)
756
+	 * @return int results of version_compare( $version_to_upgrade_to, $most_recently_active_version ).
757
+	 *                                             ie, -1 if $version_to_upgrade_to is LOWER (downgrade);
758
+	 *                                             0 if $version_to_upgrade_to MATCHES (reactivation or normal request);
759
+	 *                                             1 if $version_to_upgrade_to is HIGHER (upgrade) ;
760
+	 */
761
+	private static function _new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to)
762
+	{
763
+		//find the most recently-activated version
764
+		$most_recently_active_version =
765
+			EE_System::_get_most_recently_active_version_from_activation_history($activation_history_for_addon);
766
+		return version_compare($version_to_upgrade_to, $most_recently_active_version);
767
+	}
768
+
769
+
770
+
771
+	/**
772
+	 * Gets the most recently active version listed in the activation history,
773
+	 * and if none are found (ie, it's a brand new install) returns '0.0.0.dev.000'.
774
+	 *
775
+	 * @param array $activation_history  (keys are versions, values are arrays of times activated,
776
+	 *                                   sometimes containing 'unknown-date'
777
+	 * @return string
778
+	 */
779
+	private static function _get_most_recently_active_version_from_activation_history($activation_history)
780
+	{
781
+		$most_recently_active_version_activation = '1970-01-01 00:00:00';
782
+		$most_recently_active_version = '0.0.0.dev.000';
783
+		if (is_array($activation_history)) {
784
+			foreach ($activation_history as $version => $times_activated) {
785
+				//check there is a record of when this version was activated. Otherwise,
786
+				//mark it as unknown
787
+				if (! $times_activated) {
788
+					$times_activated = array('unknown-date');
789
+				}
790
+				if (is_string($times_activated)) {
791
+					$times_activated = array($times_activated);
792
+				}
793
+				foreach ($times_activated as $an_activation) {
794
+					if ($an_activation !== 'unknown-date' && $an_activation > $most_recently_active_version_activation) {
795
+						$most_recently_active_version = $version;
796
+						$most_recently_active_version_activation = $an_activation === 'unknown-date'
797
+							? '1970-01-01 00:00:00'
798
+							: $an_activation;
799
+					}
800
+				}
801
+			}
802
+		}
803
+		return $most_recently_active_version;
804
+	}
805
+
806
+
807
+
808
+	/**
809
+	 * This redirects to the about EE page after activation
810
+	 *
811
+	 * @return void
812
+	 */
813
+	public function redirect_to_about_ee()
814
+	{
815
+		$notices = EE_Error::get_notices(false);
816
+		//if current user is an admin and it's not an ajax or rest request
817
+		if (
818
+			! (defined('DOING_AJAX') && DOING_AJAX)
819
+			&& ! (defined('REST_REQUEST') && REST_REQUEST)
820
+			&& ! isset($notices['errors'])
821
+			&& apply_filters(
822
+				'FHEE__EE_System__redirect_to_about_ee__do_redirect',
823
+				$this->capabilities->current_user_can('manage_options', 'espresso_about_default')
824
+			)
825
+		) {
826
+			$query_params = array('page' => 'espresso_about');
827
+			if (EE_System::instance()->detect_req_type() === EE_System::req_type_new_activation) {
828
+				$query_params['new_activation'] = true;
829
+			}
830
+			if (EE_System::instance()->detect_req_type() === EE_System::req_type_reactivation) {
831
+				$query_params['reactivation'] = true;
832
+			}
833
+			$url = add_query_arg($query_params, admin_url('admin.php'));
834
+			wp_safe_redirect($url);
835
+			exit();
836
+		}
837
+	}
838
+
839
+
840
+
841
+	/**
842
+	 * load_core_configuration
843
+	 * this is hooked into 'AHEE__EE_Bootstrap__load_core_configuration'
844
+	 * which runs during the WP 'plugins_loaded' action at priority 5
845
+	 *
846
+	 * @return void
847
+	 * @throws ReflectionException
848
+	 */
849
+	public function load_core_configuration()
850
+	{
851
+		do_action('AHEE__EE_System__load_core_configuration__begin', $this);
852
+		$this->loader->getShared('EE_Load_Textdomain');
853
+		//load textdomain
854
+		EE_Load_Textdomain::load_textdomain();
855
+		// load and setup EE_Config and EE_Network_Config
856
+		$config = $this->loader->getShared('EE_Config');
857
+		$this->loader->getShared('EE_Network_Config');
858
+		// setup autoloaders
859
+		// enable logging?
860
+		if ($config->admin->use_full_logging) {
861
+			$this->loader->getShared('EE_Log');
862
+		}
863
+		// check for activation errors
864
+		$activation_errors = get_option('ee_plugin_activation_errors', false);
865
+		if ($activation_errors) {
866
+			EE_Error::add_error($activation_errors, __FILE__, __FUNCTION__, __LINE__);
867
+			update_option('ee_plugin_activation_errors', false);
868
+		}
869
+		// get model names
870
+		$this->_parse_model_names();
871
+		//load caf stuff a chance to play during the activation process too.
872
+		$this->_maybe_brew_regular();
873
+		do_action('AHEE__EE_System__load_core_configuration__complete', $this);
874
+	}
875
+
876
+
877
+
878
+	/**
879
+	 * cycles through all of the models/*.model.php files, and assembles an array of model names
880
+	 *
881
+	 * @return void
882
+	 * @throws ReflectionException
883
+	 */
884
+	private function _parse_model_names()
885
+	{
886
+		//get all the files in the EE_MODELS folder that end in .model.php
887
+		$models = glob(EE_MODELS . '*.model.php');
888
+		$model_names = array();
889
+		$non_abstract_db_models = array();
890
+		foreach ($models as $model) {
891
+			// get model classname
892
+			$classname = EEH_File::get_classname_from_filepath_with_standard_filename($model);
893
+			$short_name = str_replace('EEM_', '', $classname);
894
+			$reflectionClass = new ReflectionClass($classname);
895
+			if ($reflectionClass->isSubclassOf('EEM_Base') && ! $reflectionClass->isAbstract()) {
896
+				$non_abstract_db_models[$short_name] = $classname;
897
+			}
898
+			$model_names[$short_name] = $classname;
899
+		}
900
+		$this->registry->models = apply_filters('FHEE__EE_System__parse_model_names', $model_names);
901
+		$this->registry->non_abstract_db_models = apply_filters(
902
+			'FHEE__EE_System__parse_implemented_model_names',
903
+			$non_abstract_db_models
904
+		);
905
+	}
906
+
907
+
908
+
909
+	/**
910
+	 * The purpose of this method is to simply check for a file named "caffeinated/brewing_regular.php" for any hooks
911
+	 * that need to be setup before our EE_System launches.
912
+	 *
913
+	 * @return void
914
+	 */
915
+	private function _maybe_brew_regular()
916
+	{
917
+		if ((! defined('EE_DECAF') || EE_DECAF !== true) && is_readable(EE_CAFF_PATH . 'brewing_regular.php')) {
918
+			require_once EE_CAFF_PATH . 'brewing_regular.php';
919
+		}
920
+	}
921
+
922
+
923
+
924
+	/**
925
+	 * register_shortcodes_modules_and_widgets
926
+	 * generate lists of shortcodes and modules, then verify paths and classes
927
+	 * This is hooked into 'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets'
928
+	 * which runs during the WP 'plugins_loaded' action at priority 7
929
+	 *
930
+	 * @access public
931
+	 * @return void
932
+	 * @throws Exception
933
+	 */
934
+	public function register_shortcodes_modules_and_widgets()
935
+	{
936
+		try {
937
+			// load, register, and add shortcodes the new way
938
+			$this->loader->getShared(
939
+				'EventEspresso\core\services\shortcodes\ShortcodesManager',
940
+				array(
941
+					// and the old way, but we'll put it under control of the new system
942
+					EE_Config::getLegacyShortcodesManager()
943
+				)
944
+			);
945
+		} catch (Exception $exception) {
946
+			new ExceptionStackTraceDisplay($exception);
947
+		}
948
+		do_action('AHEE__EE_System__register_shortcodes_modules_and_widgets');
949
+		// check for addons using old hook point
950
+		if (has_action('AHEE__EE_System__register_shortcodes_modules_and_addons')) {
951
+			$this->_incompatible_addon_error();
952
+		}
953
+	}
954
+
955
+
956
+
957
+	/**
958
+	 * _incompatible_addon_error
959
+	 *
960
+	 * @access public
961
+	 * @return void
962
+	 */
963
+	private function _incompatible_addon_error()
964
+	{
965
+		// get array of classes hooking into here
966
+		$class_names = EEH_Class_Tools::get_class_names_for_all_callbacks_on_hook(
967
+			'AHEE__EE_System__register_shortcodes_modules_and_addons'
968
+		);
969
+		if (! empty($class_names)) {
970
+			$msg = __(
971
+				'The following plugins, addons, or modules appear to be incompatible with this version of Event Espresso and were automatically deactivated to avoid fatal errors:',
972
+				'event_espresso'
973
+			);
974
+			$msg .= '<ul>';
975
+			foreach ($class_names as $class_name) {
976
+				$msg .= '<li><b>Event Espresso - ' . str_replace(
977
+						array('EE_', 'EEM_', 'EED_', 'EES_', 'EEW_'), '',
978
+						$class_name
979
+					) . '</b></li>';
980
+			}
981
+			$msg .= '</ul>';
982
+			$msg .= __(
983
+				'Compatibility issues can be avoided and/or resolved by keeping addons and plugins updated to the latest version.',
984
+				'event_espresso'
985
+			);
986
+			// save list of incompatible addons to wp-options for later use
987
+			add_option('ee_incompatible_addons', $class_names, '', 'no');
988
+			if (is_admin()) {
989
+				EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
990
+			}
991
+		}
992
+	}
993
+
994
+
995
+
996
+	/**
997
+	 * brew_espresso
998
+	 * begins the process of setting hooks for initializing EE in the correct order
999
+	 * This is happening on the 'AHEE__EE_Bootstrap__brew_espresso' hook point
1000
+	 * which runs during the WP 'plugins_loaded' action at priority 9
1001
+	 *
1002
+	 * @return void
1003
+	 */
1004
+	public function brew_espresso()
1005
+	{
1006
+		do_action('AHEE__EE_System__brew_espresso__begin', $this);
1007
+		// load some final core systems
1008
+		add_action('init', array($this, 'set_hooks_for_core'), 1);
1009
+		add_action('init', array($this, 'perform_activations_upgrades_and_migrations'), 3);
1010
+		add_action('init', array($this, 'load_CPTs_and_session'), 5);
1011
+		add_action('init', array($this, 'load_controllers'), 7);
1012
+		add_action('init', array($this, 'core_loaded_and_ready'), 9);
1013
+		add_action('init', array($this, 'initialize'), 10);
1014
+		add_action('init', array($this, 'initialize_last'), 100);
1015
+		if (is_admin() && apply_filters('FHEE__EE_System__brew_espresso__load_pue', true)) {
1016
+			// pew pew pew
1017
+			$this->loader->getShared('EE_PUE');
1018
+			do_action('AHEE__EE_System__brew_espresso__after_pue_init');
1019
+		}
1020
+		do_action('AHEE__EE_System__brew_espresso__complete', $this);
1021
+	}
1022
+
1023
+
1024
+
1025
+	/**
1026
+	 *    set_hooks_for_core
1027
+	 *
1028
+	 * @access public
1029
+	 * @return    void
1030
+	 * @throws EE_Error
1031
+	 */
1032
+	public function set_hooks_for_core()
1033
+	{
1034
+		$this->_deactivate_incompatible_addons();
1035
+		do_action('AHEE__EE_System__set_hooks_for_core');
1036
+		//caps need to be initialized on every request so that capability maps are set.
1037
+		//@see https://events.codebasehq.com/projects/event-espresso/tickets/8674
1038
+		$this->registry->CAP->init_caps();
1039
+	}
1040
+
1041
+
1042
+
1043
+	/**
1044
+	 * Using the information gathered in EE_System::_incompatible_addon_error,
1045
+	 * deactivates any addons considered incompatible with the current version of EE
1046
+	 */
1047
+	private function _deactivate_incompatible_addons()
1048
+	{
1049
+		$incompatible_addons = get_option('ee_incompatible_addons', array());
1050
+		if (! empty($incompatible_addons)) {
1051
+			$active_plugins = get_option('active_plugins', array());
1052
+			foreach ($active_plugins as $active_plugin) {
1053
+				foreach ($incompatible_addons as $incompatible_addon) {
1054
+					if (strpos($active_plugin, $incompatible_addon) !== false) {
1055
+						unset($_GET['activate']);
1056
+						espresso_deactivate_plugin($active_plugin);
1057
+					}
1058
+				}
1059
+			}
1060
+		}
1061
+	}
1062
+
1063
+
1064
+
1065
+	/**
1066
+	 *    perform_activations_upgrades_and_migrations
1067
+	 *
1068
+	 * @access public
1069
+	 * @return    void
1070
+	 */
1071
+	public function perform_activations_upgrades_and_migrations()
1072
+	{
1073
+		//first check if we had previously attempted to setup EE's directories but failed
1074
+		if (EEH_Activation::upload_directories_incomplete()) {
1075
+			EEH_Activation::create_upload_directories();
1076
+		}
1077
+		do_action('AHEE__EE_System__perform_activations_upgrades_and_migrations');
1078
+	}
1079
+
1080
+
1081
+
1082
+	/**
1083
+	 *    load_CPTs_and_session
1084
+	 *
1085
+	 * @access public
1086
+	 * @return    void
1087
+	 */
1088
+	public function load_CPTs_and_session()
1089
+	{
1090
+		do_action('AHEE__EE_System__load_CPTs_and_session__start');
1091
+		// register Custom Post Types
1092
+		$this->loader->getShared('EE_Register_CPTs');
1093
+		do_action('AHEE__EE_System__load_CPTs_and_session__complete');
1094
+	}
1095
+
1096
+
1097
+
1098
+	/**
1099
+	 * load_controllers
1100
+	 * this is the best place to load any additional controllers that needs access to EE core.
1101
+	 * it is expected that all basic core EE systems, that are not dependant on the current request are loaded at this
1102
+	 * time
1103
+	 *
1104
+	 * @access public
1105
+	 * @return void
1106
+	 */
1107
+	public function load_controllers()
1108
+	{
1109
+		do_action('AHEE__EE_System__load_controllers__start');
1110
+		// let's get it started
1111
+		if (! is_admin() && ! $this->maintenance_mode->level()) {
1112
+			do_action('AHEE__EE_System__load_controllers__load_front_controllers');
1113
+			$this->loader->getShared('EE_Front_Controller');
1114
+		} else if (! EE_FRONT_AJAX) {
1115
+			do_action('AHEE__EE_System__load_controllers__load_admin_controllers');
1116
+			$this->loader->getShared('EE_Admin');
1117
+		}
1118
+		do_action('AHEE__EE_System__load_controllers__complete');
1119
+	}
1120
+
1121
+
1122
+
1123
+	/**
1124
+	 * core_loaded_and_ready
1125
+	 * all of the basic EE core should be loaded at this point and available regardless of M-Mode
1126
+	 *
1127
+	 * @access public
1128
+	 * @return void
1129
+	 */
1130
+	public function core_loaded_and_ready()
1131
+	{
1132
+		$this->loader->getShared('EE_Session');
1133
+		do_action('AHEE__EE_System__core_loaded_and_ready');
1134
+		// load_espresso_template_tags
1135
+		if (is_readable(EE_PUBLIC . 'template_tags.php')) {
1136
+			require_once(EE_PUBLIC . 'template_tags.php');
1137
+		}
1138
+		do_action('AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons');
1139
+		$this->loader->getShared('EventEspresso\core\services\assets\Registry');
1140
+	}
1141
+
1142
+
1143
+
1144
+	/**
1145
+	 * initialize
1146
+	 * this is the best place to begin initializing client code
1147
+	 *
1148
+	 * @access public
1149
+	 * @return void
1150
+	 */
1151
+	public function initialize()
1152
+	{
1153
+		do_action('AHEE__EE_System__initialize');
1154
+	}
1155
+
1156
+
1157
+
1158
+	/**
1159
+	 * initialize_last
1160
+	 * this is run really late during the WP init hook point, and ensures that mostly everything else that needs to
1161
+	 * initialize has done so
1162
+	 *
1163
+	 * @access public
1164
+	 * @return void
1165
+	 */
1166
+	public function initialize_last()
1167
+	{
1168
+		do_action('AHEE__EE_System__initialize_last');
1169
+		add_action('admin_bar_init', array($this, 'addEspressoToolbar'));
1170
+	}
1171
+
1172
+
1173
+
1174
+	/**
1175
+	 * @return void
1176
+	 * @throws EE_Error
1177
+	 */
1178
+	public function addEspressoToolbar()
1179
+	{
1180
+		$this->loader->getShared(
1181
+			'EventEspresso\core\domain\services\admin\AdminToolBar',
1182
+			array($this->registry->CAP)
1183
+		);
1184
+	}
1185
+
1186
+
1187
+
1188
+	/**
1189
+	 * do_not_cache
1190
+	 * sets no cache headers and defines no cache constants for WP plugins
1191
+	 *
1192
+	 * @access public
1193
+	 * @return void
1194
+	 */
1195
+	public static function do_not_cache()
1196
+	{
1197
+		// set no cache constants
1198
+		if (! defined('DONOTCACHEPAGE')) {
1199
+			define('DONOTCACHEPAGE', true);
1200
+		}
1201
+		if (! defined('DONOTCACHCEOBJECT')) {
1202
+			define('DONOTCACHCEOBJECT', true);
1203
+		}
1204
+		if (! defined('DONOTCACHEDB')) {
1205
+			define('DONOTCACHEDB', true);
1206
+		}
1207
+		// add no cache headers
1208
+		add_action('send_headers', array('EE_System', 'nocache_headers'), 10);
1209
+		// plus a little extra for nginx and Google Chrome
1210
+		add_filter('nocache_headers', array('EE_System', 'extra_nocache_headers'), 10, 1);
1211
+		// prevent browsers from prefetching of the rel='next' link, because it may contain content that interferes with the registration process
1212
+		remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');
1213
+	}
1214
+
1215
+
1216
+
1217
+	/**
1218
+	 *    extra_nocache_headers
1219
+	 *
1220
+	 * @access    public
1221
+	 * @param $headers
1222
+	 * @return    array
1223
+	 */
1224
+	public static function extra_nocache_headers($headers)
1225
+	{
1226
+		// for NGINX
1227
+		$headers['X-Accel-Expires'] = 0;
1228
+		// plus extra for Google Chrome since it doesn't seem to respect "no-cache", but WILL respect "no-store"
1229
+		$headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0';
1230
+		return $headers;
1231
+	}
1232
+
1233
+
1234
+
1235
+	/**
1236
+	 *    nocache_headers
1237
+	 *
1238
+	 * @access    public
1239
+	 * @return    void
1240
+	 */
1241
+	public static function nocache_headers()
1242
+	{
1243
+		nocache_headers();
1244
+	}
1245
+
1246
+
1247
+
1248
+
1249
+	/**
1250
+	 * simply hooks into "wp_list_pages_exclude" filter (for wp_list_pages method) and makes sure EE critical pages are
1251
+	 * never returned with the function.
1252
+	 *
1253
+	 * @param  array $exclude_array any existing pages being excluded are in this array.
1254
+	 * @return array
1255
+	 */
1256
+	public function remove_pages_from_wp_list_pages($exclude_array)
1257
+	{
1258
+		return array_merge($exclude_array, $this->registry->CFG->core->get_critical_pages_array());
1259
+	}
1260 1260
 
1261 1261
 
1262 1262
 
Please login to merge, or discard this patch.
Spacing   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -132,7 +132,7 @@  discard block
 block discarded – undo
132 132
         EE_Maintenance_Mode $maintenance_mode = null
133 133
     ) {
134 134
         // check if class object is instantiated
135
-        if (! self::$_instance instanceof EE_System) {
135
+        if ( ! self::$_instance instanceof EE_System) {
136 136
             self::$_instance = new self($registry, $loader, $capabilities, $request, $maintenance_mode);
137 137
         }
138 138
         return self::$_instance;
@@ -298,7 +298,7 @@  discard block
 block discarded – undo
298 298
     {
299 299
         // set autoloaders for all of the classes implementing EEI_Plugin_API
300 300
         // which provide helpers for EE plugin authors to more easily register certain components with EE.
301
-        EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'plugin_api');
301
+        EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_LIBRARIES.'plugin_api');
302 302
     }
303 303
 
304 304
 
@@ -317,14 +317,14 @@  discard block
 block discarded – undo
317 317
         $load_callback,
318 318
         $plugin_file_constant
319 319
     ) {
320
-        if (! defined($version_constant)) {
320
+        if ( ! defined($version_constant)) {
321 321
             return;
322 322
         }
323 323
         $addon_version = constant($version_constant);
324 324
         if ($addon_version && version_compare($addon_version, $min_version_required, '<')) {
325 325
             remove_action('AHEE__EE_System__load_espresso_addons', $load_callback);
326
-            if (! function_exists('deactivate_plugins')) {
327
-                require_once ABSPATH . 'wp-admin/includes/plugin.php';
326
+            if ( ! function_exists('deactivate_plugins')) {
327
+                require_once ABSPATH.'wp-admin/includes/plugin.php';
328 328
             }
329 329
             deactivate_plugins(plugin_basename(constant($plugin_file_constant)));
330 330
             unset($_GET['activate'], $_REQUEST['activate'], $_GET['activate-multi'], $_REQUEST['activate-multi']);
@@ -337,7 +337,7 @@  discard block
 block discarded – undo
337 337
                     $addon_name,
338 338
                     $min_version_required
339 339
                 ),
340
-                __FILE__, __FUNCTION__ . "({$addon_name})", __LINE__
340
+                __FILE__, __FUNCTION__."({$addon_name})", __LINE__
341 341
             );
342 342
             EE_Error::get_notices(false, true);
343 343
         }
@@ -389,7 +389,7 @@  discard block
 block discarded – undo
389 389
                 && in_array($_GET['action'], array('activate', 'activate-selected'), true)
390 390
             )
391 391
         ) {
392
-            include_once EE_THIRD_PARTY . 'wp-api-basic-auth' . DS . 'basic-auth.php';
392
+            include_once EE_THIRD_PARTY.'wp-api-basic-auth'.DS.'basic-auth.php';
393 393
         }
394 394
         do_action('AHEE__EE_System__load_espresso_addons__complete');
395 395
     }
@@ -497,11 +497,11 @@  discard block
 block discarded – undo
497 497
     private function fix_espresso_db_upgrade_option($espresso_db_update = null)
498 498
     {
499 499
         do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__begin', $espresso_db_update);
500
-        if (! $espresso_db_update) {
500
+        if ( ! $espresso_db_update) {
501 501
             $espresso_db_update = get_option('espresso_db_update');
502 502
         }
503 503
         // check that option is an array
504
-        if (! is_array($espresso_db_update)) {
504
+        if ( ! is_array($espresso_db_update)) {
505 505
             // if option is FALSE, then it never existed
506 506
             if ($espresso_db_update === false) {
507 507
                 // make $espresso_db_update an array and save option with autoload OFF
@@ -606,7 +606,7 @@  discard block
 block discarded – undo
606 606
      */
607 607
     public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null)
608 608
     {
609
-        if (! $version_history) {
609
+        if ( ! $version_history) {
610 610
             $version_history = $this->fix_espresso_db_upgrade_option($version_history);
611 611
         }
612 612
         if ($current_version_to_add === null) {
@@ -704,7 +704,7 @@  discard block
 block discarded – undo
704 704
         if ($activation_history_for_addon) {
705 705
             //it exists, so this isn't a completely new install
706 706
             //check if this version already in that list of previously installed versions
707
-            if (! isset($activation_history_for_addon[$version_to_upgrade_to])) {
707
+            if ( ! isset($activation_history_for_addon[$version_to_upgrade_to])) {
708 708
                 //it a version we haven't seen before
709 709
                 if ($version_is_higher === 1) {
710 710
                     $req_type = EE_System::req_type_upgrade;
@@ -784,7 +784,7 @@  discard block
 block discarded – undo
784 784
             foreach ($activation_history as $version => $times_activated) {
785 785
                 //check there is a record of when this version was activated. Otherwise,
786 786
                 //mark it as unknown
787
-                if (! $times_activated) {
787
+                if ( ! $times_activated) {
788 788
                     $times_activated = array('unknown-date');
789 789
                 }
790 790
                 if (is_string($times_activated)) {
@@ -884,7 +884,7 @@  discard block
 block discarded – undo
884 884
     private function _parse_model_names()
885 885
     {
886 886
         //get all the files in the EE_MODELS folder that end in .model.php
887
-        $models = glob(EE_MODELS . '*.model.php');
887
+        $models = glob(EE_MODELS.'*.model.php');
888 888
         $model_names = array();
889 889
         $non_abstract_db_models = array();
890 890
         foreach ($models as $model) {
@@ -914,8 +914,8 @@  discard block
 block discarded – undo
914 914
      */
915 915
     private function _maybe_brew_regular()
916 916
     {
917
-        if ((! defined('EE_DECAF') || EE_DECAF !== true) && is_readable(EE_CAFF_PATH . 'brewing_regular.php')) {
918
-            require_once EE_CAFF_PATH . 'brewing_regular.php';
917
+        if (( ! defined('EE_DECAF') || EE_DECAF !== true) && is_readable(EE_CAFF_PATH.'brewing_regular.php')) {
918
+            require_once EE_CAFF_PATH.'brewing_regular.php';
919 919
         }
920 920
     }
921 921
 
@@ -966,17 +966,17 @@  discard block
 block discarded – undo
966 966
         $class_names = EEH_Class_Tools::get_class_names_for_all_callbacks_on_hook(
967 967
             'AHEE__EE_System__register_shortcodes_modules_and_addons'
968 968
         );
969
-        if (! empty($class_names)) {
969
+        if ( ! empty($class_names)) {
970 970
             $msg = __(
971 971
                 'The following plugins, addons, or modules appear to be incompatible with this version of Event Espresso and were automatically deactivated to avoid fatal errors:',
972 972
                 'event_espresso'
973 973
             );
974 974
             $msg .= '<ul>';
975 975
             foreach ($class_names as $class_name) {
976
-                $msg .= '<li><b>Event Espresso - ' . str_replace(
976
+                $msg .= '<li><b>Event Espresso - '.str_replace(
977 977
                         array('EE_', 'EEM_', 'EED_', 'EES_', 'EEW_'), '',
978 978
                         $class_name
979
-                    ) . '</b></li>';
979
+                    ).'</b></li>';
980 980
             }
981 981
             $msg .= '</ul>';
982 982
             $msg .= __(
@@ -1047,7 +1047,7 @@  discard block
 block discarded – undo
1047 1047
     private function _deactivate_incompatible_addons()
1048 1048
     {
1049 1049
         $incompatible_addons = get_option('ee_incompatible_addons', array());
1050
-        if (! empty($incompatible_addons)) {
1050
+        if ( ! empty($incompatible_addons)) {
1051 1051
             $active_plugins = get_option('active_plugins', array());
1052 1052
             foreach ($active_plugins as $active_plugin) {
1053 1053
                 foreach ($incompatible_addons as $incompatible_addon) {
@@ -1108,10 +1108,10 @@  discard block
 block discarded – undo
1108 1108
     {
1109 1109
         do_action('AHEE__EE_System__load_controllers__start');
1110 1110
         // let's get it started
1111
-        if (! is_admin() && ! $this->maintenance_mode->level()) {
1111
+        if ( ! is_admin() && ! $this->maintenance_mode->level()) {
1112 1112
             do_action('AHEE__EE_System__load_controllers__load_front_controllers');
1113 1113
             $this->loader->getShared('EE_Front_Controller');
1114
-        } else if (! EE_FRONT_AJAX) {
1114
+        } else if ( ! EE_FRONT_AJAX) {
1115 1115
             do_action('AHEE__EE_System__load_controllers__load_admin_controllers');
1116 1116
             $this->loader->getShared('EE_Admin');
1117 1117
         }
@@ -1132,8 +1132,8 @@  discard block
 block discarded – undo
1132 1132
         $this->loader->getShared('EE_Session');
1133 1133
         do_action('AHEE__EE_System__core_loaded_and_ready');
1134 1134
         // load_espresso_template_tags
1135
-        if (is_readable(EE_PUBLIC . 'template_tags.php')) {
1136
-            require_once(EE_PUBLIC . 'template_tags.php');
1135
+        if (is_readable(EE_PUBLIC.'template_tags.php')) {
1136
+            require_once(EE_PUBLIC.'template_tags.php');
1137 1137
         }
1138 1138
         do_action('AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons');
1139 1139
         $this->loader->getShared('EventEspresso\core\services\assets\Registry');
@@ -1195,13 +1195,13 @@  discard block
 block discarded – undo
1195 1195
     public static function do_not_cache()
1196 1196
     {
1197 1197
         // set no cache constants
1198
-        if (! defined('DONOTCACHEPAGE')) {
1198
+        if ( ! defined('DONOTCACHEPAGE')) {
1199 1199
             define('DONOTCACHEPAGE', true);
1200 1200
         }
1201
-        if (! defined('DONOTCACHCEOBJECT')) {
1201
+        if ( ! defined('DONOTCACHCEOBJECT')) {
1202 1202
             define('DONOTCACHCEOBJECT', true);
1203 1203
         }
1204
-        if (! defined('DONOTCACHEDB')) {
1204
+        if ( ! defined('DONOTCACHEDB')) {
1205 1205
             define('DONOTCACHEDB', true);
1206 1206
         }
1207 1207
         // add no cache headers
Please login to merge, or discard this patch.
core/helpers/EEH_Template.helper.php 2 patches
Indentation   +930 added lines, -930 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 if (! defined('EVENT_ESPRESSO_VERSION')) {
3
-    exit('NO direct script access allowed');
3
+	exit('NO direct script access allowed');
4 4
 }
5 5
 /**
6 6
  * Event Espresso
@@ -16,35 +16,35 @@  discard block
 block discarded – undo
16 16
 
17 17
 
18 18
 if ( ! function_exists('espresso_get_template_part')) {
19
-    /**
20
-     * espresso_get_template_part
21
-     * basically a copy of the WordPress get_template_part() function but uses EEH_Template::locate_template() instead, and doesn't add base versions of files
22
-     * so not a very useful function at all except that it adds familiarity PLUS filtering based off of the entire template part name
23
-     *
24
-     * @param string $slug The slug name for the generic template.
25
-     * @param string $name The name of the specialised template.
26
-     * @return string        the html output for the formatted money value
27
-     */
28
-    function espresso_get_template_part($slug = null, $name = null)
29
-    {
30
-        EEH_Template::get_template_part($slug, $name);
31
-    }
19
+	/**
20
+	 * espresso_get_template_part
21
+	 * basically a copy of the WordPress get_template_part() function but uses EEH_Template::locate_template() instead, and doesn't add base versions of files
22
+	 * so not a very useful function at all except that it adds familiarity PLUS filtering based off of the entire template part name
23
+	 *
24
+	 * @param string $slug The slug name for the generic template.
25
+	 * @param string $name The name of the specialised template.
26
+	 * @return string        the html output for the formatted money value
27
+	 */
28
+	function espresso_get_template_part($slug = null, $name = null)
29
+	{
30
+		EEH_Template::get_template_part($slug, $name);
31
+	}
32 32
 }
33 33
 
34 34
 
35 35
 if ( ! function_exists('espresso_get_object_css_class')) {
36
-    /**
37
-     * espresso_get_object_css_class - attempts to generate a css class based on the type of EE object passed
38
-     *
39
-     * @param EE_Base_Class $object the EE object the css class is being generated for
40
-     * @param  string       $prefix added to the beginning of the generated class
41
-     * @param  string       $suffix added to the end of the generated class
42
-     * @return string
43
-     */
44
-    function espresso_get_object_css_class($object = null, $prefix = '', $suffix = '')
45
-    {
46
-        return EEH_Template::get_object_css_class($object, $prefix, $suffix);
47
-    }
36
+	/**
37
+	 * espresso_get_object_css_class - attempts to generate a css class based on the type of EE object passed
38
+	 *
39
+	 * @param EE_Base_Class $object the EE object the css class is being generated for
40
+	 * @param  string       $prefix added to the beginning of the generated class
41
+	 * @param  string       $suffix added to the end of the generated class
42
+	 * @return string
43
+	 */
44
+	function espresso_get_object_css_class($object = null, $prefix = '', $suffix = '')
45
+	{
46
+		return EEH_Template::get_object_css_class($object, $prefix, $suffix);
47
+	}
48 48
 }
49 49
 
50 50
 
@@ -59,650 +59,650 @@  discard block
 block discarded – undo
59 59
 class EEH_Template
60 60
 {
61 61
 
62
-    private static $_espresso_themes = array();
63
-
64
-
65
-    /**
66
-     *    is_espresso_theme - returns TRUE or FALSE on whether the currently active WP theme is an espresso theme
67
-     *
68
-     * @return boolean
69
-     */
70
-    public static function is_espresso_theme()
71
-    {
72
-        return wp_get_theme()->get('TextDomain') == 'event_espresso' ? true : false;
73
-    }
74
-
75
-    /**
76
-     *    load_espresso_theme_functions - if current theme is an espresso theme, or uses ee theme template parts, then
77
-     *    load it's functions.php file ( if not already loaded )
78
-     *
79
-     * @return void
80
-     */
81
-    public static function load_espresso_theme_functions()
82
-    {
83
-        if ( ! defined('EE_THEME_FUNCTIONS_LOADED')) {
84
-            if (is_readable(EE_PUBLIC . EE_Config::get_current_theme() . DS . 'functions.php')) {
85
-                require_once(EE_PUBLIC . EE_Config::get_current_theme() . DS . 'functions.php');
86
-            }
87
-        }
88
-    }
89
-
90
-
91
-    /**
92
-     *    get_espresso_themes - returns an array of Espresso Child themes located in the /templates/ directory
93
-     *
94
-     * @return array
95
-     */
96
-    public static function get_espresso_themes()
97
-    {
98
-        if (empty(EEH_Template::$_espresso_themes)) {
99
-            $espresso_themes = glob(EE_PUBLIC . '*', GLOB_ONLYDIR);
100
-            if (empty($espresso_themes)) {
101
-                return array();
102
-            }
103
-            if (($key = array_search('global_assets', $espresso_themes)) !== false) {
104
-                unset($espresso_themes[$key]);
105
-            }
106
-            EEH_Template::$_espresso_themes = array();
107
-            foreach ($espresso_themes as $espresso_theme) {
108
-                EEH_Template::$_espresso_themes[basename($espresso_theme)] = $espresso_theme;
109
-            }
110
-        }
111
-        return EEH_Template::$_espresso_themes;
112
-    }
113
-
114
-
115
-    /**
116
-     * EEH_Template::get_template_part
117
-     * basically a copy of the WordPress get_template_part() function but uses EEH_Template::locate_template() instead,
118
-     * and doesn't add base versions of files so not a very useful function at all except that it adds familiarity PLUS
119
-     * filtering based off of the entire template part name
120
-     *
121
-     * @param string $slug The slug name for the generic template.
122
-     * @param string $name The name of the specialised template.
123
-     * @param array  $template_args
124
-     * @param bool   $return_string
125
-     * @return string        the html output for the formatted money value
126
-     */
127
-    public static function get_template_part(
128
-        $slug = null,
129
-        $name = null,
130
-        $template_args = array(),
131
-        $return_string = false
132
-    ) {
133
-        do_action("get_template_part_{$slug}-{$name}", $slug, $name);
134
-        $templates = array();
135
-        $name      = (string)$name;
136
-        if ($name != '') {
137
-            $templates[] = "{$slug}-{$name}.php";
138
-        }
139
-        // allow template parts to be turned off via something like: add_filter( 'FHEE__content_espresso_events_tickets_template__display_datetimes', '__return_false' );
140
-        if (apply_filters("FHEE__EEH_Template__get_template_part__display__{$slug}_{$name}", true)) {
141
-            EEH_Template::locate_template($templates, $template_args, true, $return_string);
142
-        }
143
-    }
144
-
145
-
146
-    /**
147
-     *    locate_template
148
-     *    locate a template file by looking in the following places, in the following order:
149
-     *        <server path up to>/wp-content/themes/<current active WordPress theme>/
150
-     *        <assumed full absolute server path>
151
-     *        <server path up to>/wp-content/uploads/espresso/templates/<current EE theme>/
152
-     *        <server path up to>/wp-content/uploads/espresso/templates/
153
-     *        <server path up to>/wp-content/plugins/<EE4 folder>/public/<current EE theme>/
154
-     *        <server path up to>/wp-content/plugins/<EE4 folder>/core/templates/<current EE theme>/
155
-     *        <server path up to>/wp-content/plugins/<EE4 folder>/
156
-     *    as soon as the template is found in one of these locations, it will be returned or loaded
157
-     *        Example:
158
-     *          You are using the WordPress Twenty Sixteen theme,
159
-     *        and you want to customize the "some-event.template.php" template,
160
-     *          which is located in the "/relative/path/to/" folder relative to the main EE plugin folder.
161
-     *          Assuming WP is installed on your server in the "/home/public_html/" folder,
162
-     *        EEH_Template::locate_template() will look at the following paths in order until the template is found:
163
-     *        /home/public_html/wp-content/themes/twentysixteen/some-event.template.php
164
-     *        /relative/path/to/some-event.template.php
165
-     *        /home/public_html/wp-content/uploads/espresso/templates/Espresso_Arabica_2014/relative/path/to/some-event.template.php
166
-     *        /home/public_html/wp-content/uploads/espresso/templates/relative/path/to/some-event.template.php
167
-     *        /home/public_html/wp-content/plugins/event-espresso-core-reg/public/Espresso_Arabica_2014/relative/path/to/some-event.template.php
168
-     *        /home/public_html/wp-content/plugins/event-espresso-core-reg/core/templates/Espresso_Arabica_2014/relative/path/to/some-event.template.php
169
-     *        /home/public_html/wp-content/plugins/event-espresso-core-reg/relative/path/to/some-event.template.php
170
-     *          Had you passed an absolute path to your template that was in some other location,
171
-     *        ie: "/absolute/path/to/some-event.template.php"
172
-     *          then the search would have been :
173
-     *        /home/public_html/wp-content/themes/twentysixteen/some-event.template.php
174
-     *        /absolute/path/to/some-event.template.php
175
-     *          and stopped there upon finding it in the second location
176
-     *
177
-     * @param array|string $templates       array of template file names including extension (or just a single string)
178
-     * @param  array       $template_args   an array of arguments to be extracted for use in the template
179
-     * @param  boolean     $load            whether to pass the located template path on to the
180
-     *                                      EEH_Template::display_template() method or simply return it
181
-     * @param  boolean     $return_string   whether to send output immediately to screen, or capture and return as a
182
-     *                                      string
183
-     * @param boolean      $check_if_custom If TRUE, this flags this method to return boolean for whether this will
184
-     *                                      generate a custom template or not. Used in places where you don't actually
185
-     *                                      load the template, you just want to know if there's a custom version of it.
186
-     * @return mixed
187
-     */
188
-    public static function locate_template(
189
-        $templates = array(),
190
-        $template_args = array(),
191
-        $load = true,
192
-        $return_string = true,
193
-        $check_if_custom = false
194
-    ) {
195
-        // first use WP locate_template to check for template in the current theme folder
196
-        $template_path = locate_template($templates);
197
-
198
-        if ($check_if_custom && ! empty($template_path)) {
199
-            return true;
200
-        }
201
-
202
-        // not in the theme
203
-        if (empty($template_path)) {
204
-            // not even a template to look for ?
205
-            if (empty($templates)) {
206
-                // get post_type
207
-                $post_type = EE_Registry::instance()->REQ->get('post_type');
208
-                // get array of EE Custom Post Types
209
-                $EE_CPTs = EE_Register_CPTs::get_CPTs();
210
-                // build template name based on request
211
-                if (isset($EE_CPTs[$post_type])) {
212
-                    $archive_or_single = is_archive() ? 'archive' : '';
213
-                    $archive_or_single = is_single() ? 'single' : $archive_or_single;
214
-                    $templates         = $archive_or_single . '-' . $post_type . '.php';
215
-                }
216
-            }
217
-            // currently active EE template theme
218
-            $current_theme = EE_Config::get_current_theme();
219
-
220
-            // array of paths to folders that may contain templates
221
-            $template_folder_paths = array(
222
-                // first check the /wp-content/uploads/espresso/templates/(current EE theme)/  folder for an EE theme template file
223
-                EVENT_ESPRESSO_TEMPLATE_DIR . $current_theme,
224
-                // then in the root of the /wp-content/uploads/espresso/templates/ folder
225
-                EVENT_ESPRESSO_TEMPLATE_DIR,
226
-            );
227
-
228
-            //add core plugin folders for checking only if we're not $check_if_custom
229
-            if ( ! $check_if_custom) {
230
-                $core_paths            = array(
231
-                    // in the  /wp-content/plugins/(EE4 folder)/public/(current EE theme)/ folder within the plugin
232
-                    EE_PUBLIC . $current_theme,
233
-                    // in the  /wp-content/plugins/(EE4 folder)/core/templates/(current EE theme)/ folder within the plugin
234
-                    EE_TEMPLATES . $current_theme,
235
-                    // or maybe relative from the plugin root: /wp-content/plugins/(EE4 folder)/
236
-                    EE_PLUGIN_DIR_PATH,
237
-                );
238
-                $template_folder_paths = array_merge($template_folder_paths, $core_paths);
239
-            }
240
-
241
-            // now filter that array
242
-            $template_folder_paths = apply_filters('FHEE__EEH_Template__locate_template__template_folder_paths',
243
-                $template_folder_paths);
244
-            $templates             = is_array($templates) ? $templates : array($templates);
245
-            $template_folder_paths = is_array($template_folder_paths) ? $template_folder_paths : array($template_folder_paths);
246
-            // array to hold all possible template paths
247
-            $full_template_paths = array();
248
-
249
-            // loop through $templates
250
-            foreach ($templates as $template) {
251
-                // normalize directory separators
252
-                $template                      = EEH_File::standardise_directory_separators($template);
253
-                $file_name                     = basename($template);
254
-                $template_path_minus_file_name = substr($template, 0, (strlen($file_name) * -1));
255
-                // while looping through all template folder paths
256
-                foreach ($template_folder_paths as $template_folder_path) {
257
-                    // normalize directory separators
258
-                    $template_folder_path = EEH_File::standardise_directory_separators($template_folder_path);
259
-                    // determine if any common base path exists between the two paths
260
-                    $common_base_path = EEH_Template::_find_common_base_path(
261
-                        array($template_folder_path, $template_path_minus_file_name)
262
-                    );
263
-                    if ($common_base_path !== '') {
264
-                        // both paths have a common base, so just tack the filename onto our search path
265
-                        $resolved_path = EEH_File::end_with_directory_separator($template_folder_path) . $file_name;
266
-                    } else {
267
-                        // no common base path, so let's just concatenate
268
-                        $resolved_path = EEH_File::end_with_directory_separator($template_folder_path) . $template;
269
-                    }
270
-                    // build up our template locations array by adding our resolved paths
271
-                    $full_template_paths[] = $resolved_path;
272
-                }
273
-                // if $template is an absolute path, then we'll tack it onto the start of our array so that it gets searched first
274
-                array_unshift($full_template_paths, $template);
275
-                // path to the directory of the current theme: /wp-content/themes/(current WP theme)/
276
-                array_unshift($full_template_paths, get_stylesheet_directory() . DS . $file_name);
277
-            }
278
-            // filter final array of full template paths
279
-            $full_template_paths = apply_filters('FHEE__EEH_Template__locate_template__full_template_paths',
280
-                $full_template_paths, $file_name);
281
-            // now loop through our final array of template location paths and check each location
282
-            foreach ((array)$full_template_paths as $full_template_path) {
283
-                if (is_readable($full_template_path)) {
284
-                    $template_path = str_replace(array('\\', '/'), DIRECTORY_SEPARATOR, $full_template_path);
285
-                    break;
286
-                }
287
-            }
288
-        }
289
-
290
-        // hook that can be used to display the full template path that will be used
291
-        do_action('AHEE__EEH_Template__locate_template__full_template_path', $template_path);
292
-
293
-        // if we got it and you want to see it...
294
-        if ($template_path && $load && ! $check_if_custom) {
295
-            if ($return_string) {
296
-                return EEH_Template::display_template($template_path, $template_args, true);
297
-            } else {
298
-                EEH_Template::display_template($template_path, $template_args, false);
299
-            }
300
-        }
301
-        return $check_if_custom && ! empty($template_path) ? true : $template_path;
302
-    }
303
-
304
-
305
-    /**
306
-     * _find_common_base_path
307
-     * given two paths, this determines if there is a common base path between the two
308
-     *
309
-     * @param array $paths
310
-     * @return string
311
-     */
312
-    protected static function _find_common_base_path($paths)
313
-    {
314
-        $last_offset      = 0;
315
-        $common_base_path = '';
316
-        while (($index = strpos($paths[0], DS, $last_offset)) !== false) {
317
-            $dir_length = $index - $last_offset + 1;
318
-            $directory  = substr($paths[0], $last_offset, $dir_length);
319
-            foreach ($paths as $path) {
320
-                if (substr($path, $last_offset, $dir_length) != $directory) {
321
-                    return $common_base_path;
322
-                }
323
-            }
324
-            $common_base_path .= $directory;
325
-            $last_offset = $index + 1;
326
-        }
327
-        return substr($common_base_path, 0, -1);
328
-    }
329
-
330
-
331
-    /**
332
-     * load and display a template
333
-     *
334
-     * @param bool|string $template_path server path to the file to be loaded, including file name and extension
335
-     * @param  array      $template_args an array of arguments to be extracted for use in the template
336
-     * @param  boolean    $return_string whether to send output immediately to screen, or capture and return as a string
337
-     * @param bool        $throw_exceptions if set to true, will throw an exception if the template is either
338
-     *                                      not found or is not readable
339
-     * @return mixed string
340
-     * @throws \DomainException
341
-     */
62
+	private static $_espresso_themes = array();
63
+
64
+
65
+	/**
66
+	 *    is_espresso_theme - returns TRUE or FALSE on whether the currently active WP theme is an espresso theme
67
+	 *
68
+	 * @return boolean
69
+	 */
70
+	public static function is_espresso_theme()
71
+	{
72
+		return wp_get_theme()->get('TextDomain') == 'event_espresso' ? true : false;
73
+	}
74
+
75
+	/**
76
+	 *    load_espresso_theme_functions - if current theme is an espresso theme, or uses ee theme template parts, then
77
+	 *    load it's functions.php file ( if not already loaded )
78
+	 *
79
+	 * @return void
80
+	 */
81
+	public static function load_espresso_theme_functions()
82
+	{
83
+		if ( ! defined('EE_THEME_FUNCTIONS_LOADED')) {
84
+			if (is_readable(EE_PUBLIC . EE_Config::get_current_theme() . DS . 'functions.php')) {
85
+				require_once(EE_PUBLIC . EE_Config::get_current_theme() . DS . 'functions.php');
86
+			}
87
+		}
88
+	}
89
+
90
+
91
+	/**
92
+	 *    get_espresso_themes - returns an array of Espresso Child themes located in the /templates/ directory
93
+	 *
94
+	 * @return array
95
+	 */
96
+	public static function get_espresso_themes()
97
+	{
98
+		if (empty(EEH_Template::$_espresso_themes)) {
99
+			$espresso_themes = glob(EE_PUBLIC . '*', GLOB_ONLYDIR);
100
+			if (empty($espresso_themes)) {
101
+				return array();
102
+			}
103
+			if (($key = array_search('global_assets', $espresso_themes)) !== false) {
104
+				unset($espresso_themes[$key]);
105
+			}
106
+			EEH_Template::$_espresso_themes = array();
107
+			foreach ($espresso_themes as $espresso_theme) {
108
+				EEH_Template::$_espresso_themes[basename($espresso_theme)] = $espresso_theme;
109
+			}
110
+		}
111
+		return EEH_Template::$_espresso_themes;
112
+	}
113
+
114
+
115
+	/**
116
+	 * EEH_Template::get_template_part
117
+	 * basically a copy of the WordPress get_template_part() function but uses EEH_Template::locate_template() instead,
118
+	 * and doesn't add base versions of files so not a very useful function at all except that it adds familiarity PLUS
119
+	 * filtering based off of the entire template part name
120
+	 *
121
+	 * @param string $slug The slug name for the generic template.
122
+	 * @param string $name The name of the specialised template.
123
+	 * @param array  $template_args
124
+	 * @param bool   $return_string
125
+	 * @return string        the html output for the formatted money value
126
+	 */
127
+	public static function get_template_part(
128
+		$slug = null,
129
+		$name = null,
130
+		$template_args = array(),
131
+		$return_string = false
132
+	) {
133
+		do_action("get_template_part_{$slug}-{$name}", $slug, $name);
134
+		$templates = array();
135
+		$name      = (string)$name;
136
+		if ($name != '') {
137
+			$templates[] = "{$slug}-{$name}.php";
138
+		}
139
+		// allow template parts to be turned off via something like: add_filter( 'FHEE__content_espresso_events_tickets_template__display_datetimes', '__return_false' );
140
+		if (apply_filters("FHEE__EEH_Template__get_template_part__display__{$slug}_{$name}", true)) {
141
+			EEH_Template::locate_template($templates, $template_args, true, $return_string);
142
+		}
143
+	}
144
+
145
+
146
+	/**
147
+	 *    locate_template
148
+	 *    locate a template file by looking in the following places, in the following order:
149
+	 *        <server path up to>/wp-content/themes/<current active WordPress theme>/
150
+	 *        <assumed full absolute server path>
151
+	 *        <server path up to>/wp-content/uploads/espresso/templates/<current EE theme>/
152
+	 *        <server path up to>/wp-content/uploads/espresso/templates/
153
+	 *        <server path up to>/wp-content/plugins/<EE4 folder>/public/<current EE theme>/
154
+	 *        <server path up to>/wp-content/plugins/<EE4 folder>/core/templates/<current EE theme>/
155
+	 *        <server path up to>/wp-content/plugins/<EE4 folder>/
156
+	 *    as soon as the template is found in one of these locations, it will be returned or loaded
157
+	 *        Example:
158
+	 *          You are using the WordPress Twenty Sixteen theme,
159
+	 *        and you want to customize the "some-event.template.php" template,
160
+	 *          which is located in the "/relative/path/to/" folder relative to the main EE plugin folder.
161
+	 *          Assuming WP is installed on your server in the "/home/public_html/" folder,
162
+	 *        EEH_Template::locate_template() will look at the following paths in order until the template is found:
163
+	 *        /home/public_html/wp-content/themes/twentysixteen/some-event.template.php
164
+	 *        /relative/path/to/some-event.template.php
165
+	 *        /home/public_html/wp-content/uploads/espresso/templates/Espresso_Arabica_2014/relative/path/to/some-event.template.php
166
+	 *        /home/public_html/wp-content/uploads/espresso/templates/relative/path/to/some-event.template.php
167
+	 *        /home/public_html/wp-content/plugins/event-espresso-core-reg/public/Espresso_Arabica_2014/relative/path/to/some-event.template.php
168
+	 *        /home/public_html/wp-content/plugins/event-espresso-core-reg/core/templates/Espresso_Arabica_2014/relative/path/to/some-event.template.php
169
+	 *        /home/public_html/wp-content/plugins/event-espresso-core-reg/relative/path/to/some-event.template.php
170
+	 *          Had you passed an absolute path to your template that was in some other location,
171
+	 *        ie: "/absolute/path/to/some-event.template.php"
172
+	 *          then the search would have been :
173
+	 *        /home/public_html/wp-content/themes/twentysixteen/some-event.template.php
174
+	 *        /absolute/path/to/some-event.template.php
175
+	 *          and stopped there upon finding it in the second location
176
+	 *
177
+	 * @param array|string $templates       array of template file names including extension (or just a single string)
178
+	 * @param  array       $template_args   an array of arguments to be extracted for use in the template
179
+	 * @param  boolean     $load            whether to pass the located template path on to the
180
+	 *                                      EEH_Template::display_template() method or simply return it
181
+	 * @param  boolean     $return_string   whether to send output immediately to screen, or capture and return as a
182
+	 *                                      string
183
+	 * @param boolean      $check_if_custom If TRUE, this flags this method to return boolean for whether this will
184
+	 *                                      generate a custom template or not. Used in places where you don't actually
185
+	 *                                      load the template, you just want to know if there's a custom version of it.
186
+	 * @return mixed
187
+	 */
188
+	public static function locate_template(
189
+		$templates = array(),
190
+		$template_args = array(),
191
+		$load = true,
192
+		$return_string = true,
193
+		$check_if_custom = false
194
+	) {
195
+		// first use WP locate_template to check for template in the current theme folder
196
+		$template_path = locate_template($templates);
197
+
198
+		if ($check_if_custom && ! empty($template_path)) {
199
+			return true;
200
+		}
201
+
202
+		// not in the theme
203
+		if (empty($template_path)) {
204
+			// not even a template to look for ?
205
+			if (empty($templates)) {
206
+				// get post_type
207
+				$post_type = EE_Registry::instance()->REQ->get('post_type');
208
+				// get array of EE Custom Post Types
209
+				$EE_CPTs = EE_Register_CPTs::get_CPTs();
210
+				// build template name based on request
211
+				if (isset($EE_CPTs[$post_type])) {
212
+					$archive_or_single = is_archive() ? 'archive' : '';
213
+					$archive_or_single = is_single() ? 'single' : $archive_or_single;
214
+					$templates         = $archive_or_single . '-' . $post_type . '.php';
215
+				}
216
+			}
217
+			// currently active EE template theme
218
+			$current_theme = EE_Config::get_current_theme();
219
+
220
+			// array of paths to folders that may contain templates
221
+			$template_folder_paths = array(
222
+				// first check the /wp-content/uploads/espresso/templates/(current EE theme)/  folder for an EE theme template file
223
+				EVENT_ESPRESSO_TEMPLATE_DIR . $current_theme,
224
+				// then in the root of the /wp-content/uploads/espresso/templates/ folder
225
+				EVENT_ESPRESSO_TEMPLATE_DIR,
226
+			);
227
+
228
+			//add core plugin folders for checking only if we're not $check_if_custom
229
+			if ( ! $check_if_custom) {
230
+				$core_paths            = array(
231
+					// in the  /wp-content/plugins/(EE4 folder)/public/(current EE theme)/ folder within the plugin
232
+					EE_PUBLIC . $current_theme,
233
+					// in the  /wp-content/plugins/(EE4 folder)/core/templates/(current EE theme)/ folder within the plugin
234
+					EE_TEMPLATES . $current_theme,
235
+					// or maybe relative from the plugin root: /wp-content/plugins/(EE4 folder)/
236
+					EE_PLUGIN_DIR_PATH,
237
+				);
238
+				$template_folder_paths = array_merge($template_folder_paths, $core_paths);
239
+			}
240
+
241
+			// now filter that array
242
+			$template_folder_paths = apply_filters('FHEE__EEH_Template__locate_template__template_folder_paths',
243
+				$template_folder_paths);
244
+			$templates             = is_array($templates) ? $templates : array($templates);
245
+			$template_folder_paths = is_array($template_folder_paths) ? $template_folder_paths : array($template_folder_paths);
246
+			// array to hold all possible template paths
247
+			$full_template_paths = array();
248
+
249
+			// loop through $templates
250
+			foreach ($templates as $template) {
251
+				// normalize directory separators
252
+				$template                      = EEH_File::standardise_directory_separators($template);
253
+				$file_name                     = basename($template);
254
+				$template_path_minus_file_name = substr($template, 0, (strlen($file_name) * -1));
255
+				// while looping through all template folder paths
256
+				foreach ($template_folder_paths as $template_folder_path) {
257
+					// normalize directory separators
258
+					$template_folder_path = EEH_File::standardise_directory_separators($template_folder_path);
259
+					// determine if any common base path exists between the two paths
260
+					$common_base_path = EEH_Template::_find_common_base_path(
261
+						array($template_folder_path, $template_path_minus_file_name)
262
+					);
263
+					if ($common_base_path !== '') {
264
+						// both paths have a common base, so just tack the filename onto our search path
265
+						$resolved_path = EEH_File::end_with_directory_separator($template_folder_path) . $file_name;
266
+					} else {
267
+						// no common base path, so let's just concatenate
268
+						$resolved_path = EEH_File::end_with_directory_separator($template_folder_path) . $template;
269
+					}
270
+					// build up our template locations array by adding our resolved paths
271
+					$full_template_paths[] = $resolved_path;
272
+				}
273
+				// if $template is an absolute path, then we'll tack it onto the start of our array so that it gets searched first
274
+				array_unshift($full_template_paths, $template);
275
+				// path to the directory of the current theme: /wp-content/themes/(current WP theme)/
276
+				array_unshift($full_template_paths, get_stylesheet_directory() . DS . $file_name);
277
+			}
278
+			// filter final array of full template paths
279
+			$full_template_paths = apply_filters('FHEE__EEH_Template__locate_template__full_template_paths',
280
+				$full_template_paths, $file_name);
281
+			// now loop through our final array of template location paths and check each location
282
+			foreach ((array)$full_template_paths as $full_template_path) {
283
+				if (is_readable($full_template_path)) {
284
+					$template_path = str_replace(array('\\', '/'), DIRECTORY_SEPARATOR, $full_template_path);
285
+					break;
286
+				}
287
+			}
288
+		}
289
+
290
+		// hook that can be used to display the full template path that will be used
291
+		do_action('AHEE__EEH_Template__locate_template__full_template_path', $template_path);
292
+
293
+		// if we got it and you want to see it...
294
+		if ($template_path && $load && ! $check_if_custom) {
295
+			if ($return_string) {
296
+				return EEH_Template::display_template($template_path, $template_args, true);
297
+			} else {
298
+				EEH_Template::display_template($template_path, $template_args, false);
299
+			}
300
+		}
301
+		return $check_if_custom && ! empty($template_path) ? true : $template_path;
302
+	}
303
+
304
+
305
+	/**
306
+	 * _find_common_base_path
307
+	 * given two paths, this determines if there is a common base path between the two
308
+	 *
309
+	 * @param array $paths
310
+	 * @return string
311
+	 */
312
+	protected static function _find_common_base_path($paths)
313
+	{
314
+		$last_offset      = 0;
315
+		$common_base_path = '';
316
+		while (($index = strpos($paths[0], DS, $last_offset)) !== false) {
317
+			$dir_length = $index - $last_offset + 1;
318
+			$directory  = substr($paths[0], $last_offset, $dir_length);
319
+			foreach ($paths as $path) {
320
+				if (substr($path, $last_offset, $dir_length) != $directory) {
321
+					return $common_base_path;
322
+				}
323
+			}
324
+			$common_base_path .= $directory;
325
+			$last_offset = $index + 1;
326
+		}
327
+		return substr($common_base_path, 0, -1);
328
+	}
329
+
330
+
331
+	/**
332
+	 * load and display a template
333
+	 *
334
+	 * @param bool|string $template_path server path to the file to be loaded, including file name and extension
335
+	 * @param  array      $template_args an array of arguments to be extracted for use in the template
336
+	 * @param  boolean    $return_string whether to send output immediately to screen, or capture and return as a string
337
+	 * @param bool        $throw_exceptions if set to true, will throw an exception if the template is either
338
+	 *                                      not found or is not readable
339
+	 * @return mixed string
340
+	 * @throws \DomainException
341
+	 */
342 342
 	public static function display_template(
343
-        $template_path    = false,
344
-        $template_args    = array(),
345
-        $return_string    = false,
346
-        $throw_exceptions = false
347
-    ) {
348
-
349
-        /**
350
-         * These two filters are intended for last minute changes to templates being loaded and/or template arg
351
-         * modifications.  NOTE... modifying these things can cause breakage as most templates running through
352
-         * the display_template method are templates we DON'T want modified (usually because of js
353
-         * dependencies etc).  So unless you know what you are doing, do NOT filter templates or template args
354
-         * using this.
355
-         *
356
-         * @since 4.6.0
357
-         */
358
-        $template_path = (string) apply_filters('FHEE__EEH_Template__display_template__template_path', $template_path);
359
-        $template_args = (array) apply_filters('FHEE__EEH_Template__display_template__template_args', $template_args);
360
-
361
-        // you gimme nuttin - YOU GET NUTTIN !!
362
-        if ( ! $template_path || ! is_readable($template_path)) {
363
-            return '';
364
-        }
365
-        // if $template_args are not in an array, then make it so
366
-        if ( ! is_array($template_args) && ! is_object($template_args)) {
367
-            $template_args = array($template_args);
368
-        }
369
-        extract( $template_args, EXTR_SKIP );
370
-        // ignore whether template is accessible ?
371
-        if ( $throw_exceptions && ! is_readable( $template_path ) ) {
372
-            throw new \DomainException(
373
-                    esc_html__(
374
-                            'Invalid, unreadable, or missing file.',
375
-                            'event_espresso'
376
-                    )
377
-            );
378
-        }
379
-
380
-
381
-        if ($return_string) {
382
-            // because we want to return a string, we are going to capture the output
383
-            ob_start();
384
-            include($template_path);
385
-            return ob_get_clean();
386
-        } else {
387
-            include($template_path);
388
-        }
389
-        return '';
390
-    }
391
-
392
-
393
-    /**
394
-     * get_object_css_class - attempts to generate a css class based on the type of EE object passed
395
-     *
396
-     * @param EE_Base_Class $object the EE object the css class is being generated for
397
-     * @param  string       $prefix added to the beginning of the generated class
398
-     * @param  string       $suffix added to the end of the generated class
399
-     * @return string
400
-     */
401
-    public static function get_object_css_class($object = null, $prefix = '', $suffix = '')
402
-    {
403
-        // in the beginning...
404
-        $prefix = ! empty($prefix) ? rtrim($prefix, '-') . '-' : '';
405
-        // da muddle
406
-        $class = '';
407
-        // the end
408
-        $suffix = ! empty($suffix) ? '-' . ltrim($suffix, '-') : '';
409
-        // is the passed object an EE object ?
410
-        if ($object instanceof EE_Base_Class) {
411
-            // grab the exact type of object
412
-            $obj_class = get_class($object);
413
-            // depending on the type of object...
414
-            switch ($obj_class) {
415
-                // no specifics just yet...
416
-                default :
417
-                    $class = strtolower(str_replace('_', '-', $obj_class));
418
-                    $class .= method_exists($obj_class, 'name') ? '-' . sanitize_title($object->name()) : '';
419
-
420
-            }
421
-        }
422
-        return $prefix . $class . $suffix;
423
-    }
424
-
425
-
426
-
427
-    /**
428
-     * EEH_Template::format_currency
429
-     * This helper takes a raw float value and formats it according to the default config country currency settings, or
430
-     * the country currency settings from the supplied country ISO code
431
-     *
432
-     * @param  float   $amount       raw money value
433
-     * @param  boolean $return_raw   whether to return the formatted float value only with no currency sign or code
434
-     * @param  boolean $display_code whether to display the country code (USD). Default = TRUE
435
-     * @param string   $CNT_ISO      2 letter ISO code for a country
436
-     * @param string   $cur_code_span_class
437
-     * @return string        the html output for the formatted money value
438
-     * @throws \EE_Error
439
-     */
440
-    public static function format_currency(
441
-        $amount = null,
442
-        $return_raw = false,
443
-        $display_code = true,
444
-        $CNT_ISO = '',
445
-        $cur_code_span_class = 'currency-code'
446
-    ) {
447
-        // ensure amount was received
448
-        if ($amount === null) {
449
-            $msg = __('In order to format currency, an amount needs to be passed.', 'event_espresso');
450
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
451
-            return '';
452
-        }
453
-        //ensure amount is float
454
-        $amount  = apply_filters('FHEE__EEH_Template__format_currency__raw_amount', (float)$amount);
455
-        $CNT_ISO = apply_filters('FHEE__EEH_Template__format_currency__CNT_ISO', $CNT_ISO, $amount);
456
-        // filter raw amount (allows 0.00 to be changed to "free" for example)
457
-        $amount_formatted = apply_filters('FHEE__EEH_Template__format_currency__amount', $amount, $return_raw);
458
-        // still a number or was amount converted to a string like "free" ?
459
-        if (is_float($amount_formatted)) {
460
-            // was a country ISO code passed ? if so generate currency config object for that country
461
-            $mny = $CNT_ISO !== '' ? new EE_Currency_Config($CNT_ISO) : null;
462
-            // verify results
463
-            if ( ! $mny instanceof EE_Currency_Config) {
464
-                // set default config country currency settings
465
-                $mny = EE_Registry::instance()->CFG->currency instanceof EE_Currency_Config
466
-                    ? EE_Registry::instance()->CFG->currency
467
-                    : new EE_Currency_Config();
468
-            }
469
-            // format float
470
-            $amount_formatted = number_format($amount, $mny->dec_plc, $mny->dec_mrk, $mny->thsnds);
471
-            // add formatting ?
472
-            if ( ! $return_raw) {
473
-                // add currency sign
474
-                if ($mny->sign_b4) {
475
-                    if ($amount >= 0) {
476
-                        $amount_formatted = $mny->sign . $amount_formatted;
477
-                    } else {
478
-                        $amount_formatted = '-' . $mny->sign . str_replace('-', '', $amount_formatted);
479
-                    }
480
-
481
-                } else {
482
-                    $amount_formatted = $amount_formatted . $mny->sign;
483
-                }
484
-
485
-                // filter to allow global setting of display_code
486
-                $display_code = apply_filters('FHEE__EEH_Template__format_currency__display_code', $display_code);
487
-
488
-                // add currency code ?
489
-                $amount_formatted = $display_code ? $amount_formatted . ' <span class="' . $cur_code_span_class . '">(' . $mny->code . ')</span>' : $amount_formatted;
490
-            }
491
-            // filter results
492
-            $amount_formatted = apply_filters('FHEE__EEH_Template__format_currency__amount_formatted',
493
-                $amount_formatted, $mny, $return_raw);
494
-        }
495
-        // clean up vars
496
-        unset($mny);
497
-        // return formatted currency amount
498
-        return $amount_formatted;
499
-    }
500
-
501
-
502
-    /**
503
-     * This function is used for outputting the localized label for a given status id in the schema requested (and
504
-     * possibly plural).  The intended use of this function is only for cases where wanting a label outside of a
505
-     * related status model or model object (i.e. in documentation etc.)
506
-     *
507
-     * @param  string  $status_id Status ID matching a registered status in the esp_status table.  If there is no
508
-     *                            match, then 'Unknown' will be returned.
509
-     * @param  boolean $plural    Whether to return plural or not
510
-     * @param  string  $schema    'UPPER', 'lower', or 'Sentence'
511
-     * @return string             The localized label for the status id.
512
-     */
513
-    public static function pretty_status($status_id, $plural = false, $schema = 'upper')
514
-    {
515
-        /** @type EEM_Status $EEM_Status */
516
-        $EEM_Status = EE_Registry::instance()->load_model('Status');
517
-        $status     = $EEM_Status->localized_status(array($status_id => __('unknown', 'event_espresso')), $plural,
518
-            $schema);
519
-        return $status[$status_id];
520
-    }
521
-
522
-
523
-    /**
524
-     * This helper just returns a button or link for the given parameters
525
-     *
526
-     * @param  string $url   the url for the link, note that `esc_url` will be called on it
527
-     * @param  string $label What is the label you want displayed for the button
528
-     * @param  string $class what class is used for the button (defaults to 'button-primary')
529
-     * @param string  $icon
530
-     * @param string  $title
531
-     * @return string the html output for the button
532
-     */
533
-    public static function get_button_or_link($url, $label, $class = 'button-primary', $icon = '', $title = '')
534
-    {
535
-        $icon_html = '';
536
-        if ( ! empty($icon)) {
537
-            $dashicons = preg_split("(ee-icon |dashicons )", $icon);
538
-            $dashicons = array_filter($dashicons);
539
-            $count     = count($dashicons);
540
-            $icon_html .= $count > 1 ? '<span class="ee-composite-dashicon">' : '';
541
-            foreach ($dashicons as $dashicon) {
542
-                $type = strpos($dashicon, 'ee-icon') !== false ? 'ee-icon ' : 'dashicons ';
543
-                $icon_html .= '<span class="' . $type . $dashicon . '"></span>';
544
-            }
545
-            $icon_html .= $count > 1 ? '</span>' : '';
546
-        }
547
-        $label  = ! empty($icon) ? $icon_html . $label : $label;
548
-        $button = '<a id="' . sanitize_title_with_dashes($label) . '" href="' . esc_url($url) . '" class="' . $class . '" title="' . $title . '">' . $label . '</a>';
549
-        return $button;
550
-    }
551
-
552
-
553
-    /**
554
-     * This returns a generated link that will load the related help tab on admin pages.
555
-     *
556
-     * @param  string     $help_tab_id the id for the connected help tab
557
-     * @param bool|string $page        The page identifier for the page the help tab is on
558
-     * @param bool|string $action      The action (route) for the admin page the help tab is on.
559
-     * @param bool|string $icon_style  (optional) include css class for the style you want to use for the help icon.
560
-     * @param bool|string $help_text   (optional) send help text you want to use for the link if default not to be used
561
-     * @return string              generated link
562
-     */
563
-    public static function get_help_tab_link(
564
-        $help_tab_id,
565
-        $page = false,
566
-        $action = false,
567
-        $icon_style = false,
568
-        $help_text = false
569
-    ) {
570
-
571
-        if ( ! $page) {
572
-            $page = isset($_REQUEST['page']) && ! empty($_REQUEST['page']) ? sanitize_key($_REQUEST['page']) : $page;
573
-        }
574
-
575
-        if ( ! $action) {
576
-            $action = isset($_REQUEST['action']) && ! empty($_REQUEST['action']) ? sanitize_key($_REQUEST['action']) : $action;
577
-        }
578
-
579
-        $action = empty($action) ? 'default' : $action;
580
-
581
-
582
-        $help_tab_lnk = $page . '-' . $action . '-' . $help_tab_id;
583
-        $icon         = ! $icon_style ? ' dashicons-editor-help' : $icon_style;
584
-        $help_text    = ! $help_text ? '' : $help_text;
585
-        return '<a id="' . $help_tab_lnk . '" class="ee-clickable dashicons espresso-help-tab-lnk ee-icon-size-22' . $icon . '" title="' . esc_attr__('Click to open the \'Help\' tab for more information about this feature.',
586
-                'event_espresso') . '" > ' . $help_text . ' </a>';
587
-    }
588
-
589
-
590
-    /**
591
-     * This helper generates the html structure for the jquery joyride plugin with the given params.
592
-     *
593
-     * @link http://zurb.com/playground/jquery-joyride-feature-tour-plugin
594
-     * @see  EE_Admin_Page->_stop_callback() for the construct expected for the $stops param.
595
-     * @param EE_Help_Tour
596
-     * @return string         html
597
-     */
598
-    public static function help_tour_stops_generator(EE_Help_Tour $tour)
599
-    {
600
-        $id    = $tour->get_slug();
601
-        $stops = $tour->get_stops();
602
-
603
-        $content = '<ol style="display:none" id="' . $id . '">';
604
-
605
-        foreach ($stops as $stop) {
606
-            $data_id    = ! empty($stop['id']) ? ' data-id="' . $stop['id'] . '"' : '';
607
-            $data_class = empty($data_id) && ! empty($stop['class']) ? ' data-class="' . $stop['class'] . '"' : '';
608
-
609
-            //if container is set to modal then let's make sure we set the options accordingly
610
-            if (empty($data_id) && empty($data_class)) {
611
-                $stop['options']['modal']  = true;
612
-                $stop['options']['expose'] = true;
613
-            }
614
-
615
-            $custom_class  = ! empty($stop['custom_class']) ? ' class="' . $stop['custom_class'] . '"' : '';
616
-            $button_text   = ! empty($stop['button_text']) ? ' data-button="' . $stop['button_text'] . '"' : '';
617
-            $inner_content = isset($stop['content']) ? $stop['content'] : '';
618
-
619
-            //options
620
-            if (isset($stop['options']) && is_array($stop['options'])) {
621
-                $options = ' data-options="';
622
-                foreach ($stop['options'] as $option => $value) {
623
-                    $options .= $option . ':' . $value . ';';
624
-                }
625
-                $options .= '"';
626
-            } else {
627
-                $options = '';
628
-            }
629
-
630
-            //let's put all together
631
-            $content .= '<li' . $data_id . $data_class . $custom_class . $button_text . $options . '>' . $inner_content . '</li>';
632
-        }
633
-
634
-        $content .= '</ol>';
635
-        return $content;
636
-    }
637
-
638
-
639
-    /**
640
-     * This is a helper method to generate a status legend for a given status array.
641
-     * Note this will only work if the incoming statuses have a key in the EEM_Status->localized_status() methods
642
-     * status_array.
643
-     *
644
-     * @param  array  $status_array  array of statuses that will make up the legend. In format:
645
-     *                               array(
646
-     *                               'status_item' => 'status_name'
647
-     *                               )
648
-     * @param  string $active_status This is used to indicate what the active status is IF that is to be highlighted in
649
-     *                               the legend.
650
-     * @throws EE_Error
651
-     * @return string               html structure for status.
652
-     */
653
-    public static function status_legend($status_array, $active_status = '')
654
-    {
655
-        if ( ! is_array($status_array)) {
656
-            throw new EE_Error(esc_html__('The EEH_Template::status_legend helper required the incoming status_array argument to be an array!',
657
-                'event_espresso'));
658
-        }
659
-
660
-        $setup_array = array();
661
-        foreach ($status_array as $item => $status) {
662
-            $setup_array[$item] = array(
663
-                'class'  => 'ee-status-legend ee-status-legend-' . $status,
664
-                'desc'   => EEH_Template::pretty_status($status, false, 'sentence'),
665
-                'status' => $status,
666
-            );
667
-        }
668
-
669
-        $content = '<div class="ee-list-table-legend-container">' . "\n";
670
-        $content .= '<h4 class="status-legend-title">' . esc_html__('Status Legend', 'event_espresso') . '</h4>' . "\n";
671
-        $content .= '<dl class="ee-list-table-legend">' . "\n\t";
672
-        foreach ($setup_array as $item => $details) {
673
-            $active_class = $active_status == $details['status'] ? ' class="ee-is-active-status"' : '';
674
-            $content .= '<dt id="ee-legend-item-tooltip-' . $item . '"' . $active_class . '>' . "\n\t\t";
675
-            $content .= '<span class="' . $details['class'] . '"></span>' . "\n\t\t";
676
-            $content .= '<span class="ee-legend-description">' . $details['desc'] . '</span>' . "\n\t";
677
-            $content .= '</dt>' . "\n";
678
-        }
679
-        $content .= '</dl>' . "\n";
680
-        $content .= '</div>' . "\n";
681
-        return $content;
682
-    }
683
-
684
-
685
-    /**
686
-     * Gets HTML for laying out a deeply-nested array (and objects) in a format
687
-     * that's nice for presenting in the wp admin
688
-     *
689
-     * @param mixed $data
690
-     * @return string
691
-     */
692
-    public static function layout_array_as_table($data)
693
-    {
694
-        if (is_object($data) || $data instanceof __PHP_Incomplete_Class) {
695
-            $data = (array)$data;
696
-        }
697
-        ob_start();
698
-        if (is_array($data)) {
699
-            if (EEH_Array::is_associative_array($data)) {
700
-                ?>
343
+		$template_path    = false,
344
+		$template_args    = array(),
345
+		$return_string    = false,
346
+		$throw_exceptions = false
347
+	) {
348
+
349
+		/**
350
+		 * These two filters are intended for last minute changes to templates being loaded and/or template arg
351
+		 * modifications.  NOTE... modifying these things can cause breakage as most templates running through
352
+		 * the display_template method are templates we DON'T want modified (usually because of js
353
+		 * dependencies etc).  So unless you know what you are doing, do NOT filter templates or template args
354
+		 * using this.
355
+		 *
356
+		 * @since 4.6.0
357
+		 */
358
+		$template_path = (string) apply_filters('FHEE__EEH_Template__display_template__template_path', $template_path);
359
+		$template_args = (array) apply_filters('FHEE__EEH_Template__display_template__template_args', $template_args);
360
+
361
+		// you gimme nuttin - YOU GET NUTTIN !!
362
+		if ( ! $template_path || ! is_readable($template_path)) {
363
+			return '';
364
+		}
365
+		// if $template_args are not in an array, then make it so
366
+		if ( ! is_array($template_args) && ! is_object($template_args)) {
367
+			$template_args = array($template_args);
368
+		}
369
+		extract( $template_args, EXTR_SKIP );
370
+		// ignore whether template is accessible ?
371
+		if ( $throw_exceptions && ! is_readable( $template_path ) ) {
372
+			throw new \DomainException(
373
+					esc_html__(
374
+							'Invalid, unreadable, or missing file.',
375
+							'event_espresso'
376
+					)
377
+			);
378
+		}
379
+
380
+
381
+		if ($return_string) {
382
+			// because we want to return a string, we are going to capture the output
383
+			ob_start();
384
+			include($template_path);
385
+			return ob_get_clean();
386
+		} else {
387
+			include($template_path);
388
+		}
389
+		return '';
390
+	}
391
+
392
+
393
+	/**
394
+	 * get_object_css_class - attempts to generate a css class based on the type of EE object passed
395
+	 *
396
+	 * @param EE_Base_Class $object the EE object the css class is being generated for
397
+	 * @param  string       $prefix added to the beginning of the generated class
398
+	 * @param  string       $suffix added to the end of the generated class
399
+	 * @return string
400
+	 */
401
+	public static function get_object_css_class($object = null, $prefix = '', $suffix = '')
402
+	{
403
+		// in the beginning...
404
+		$prefix = ! empty($prefix) ? rtrim($prefix, '-') . '-' : '';
405
+		// da muddle
406
+		$class = '';
407
+		// the end
408
+		$suffix = ! empty($suffix) ? '-' . ltrim($suffix, '-') : '';
409
+		// is the passed object an EE object ?
410
+		if ($object instanceof EE_Base_Class) {
411
+			// grab the exact type of object
412
+			$obj_class = get_class($object);
413
+			// depending on the type of object...
414
+			switch ($obj_class) {
415
+				// no specifics just yet...
416
+				default :
417
+					$class = strtolower(str_replace('_', '-', $obj_class));
418
+					$class .= method_exists($obj_class, 'name') ? '-' . sanitize_title($object->name()) : '';
419
+
420
+			}
421
+		}
422
+		return $prefix . $class . $suffix;
423
+	}
424
+
425
+
426
+
427
+	/**
428
+	 * EEH_Template::format_currency
429
+	 * This helper takes a raw float value and formats it according to the default config country currency settings, or
430
+	 * the country currency settings from the supplied country ISO code
431
+	 *
432
+	 * @param  float   $amount       raw money value
433
+	 * @param  boolean $return_raw   whether to return the formatted float value only with no currency sign or code
434
+	 * @param  boolean $display_code whether to display the country code (USD). Default = TRUE
435
+	 * @param string   $CNT_ISO      2 letter ISO code for a country
436
+	 * @param string   $cur_code_span_class
437
+	 * @return string        the html output for the formatted money value
438
+	 * @throws \EE_Error
439
+	 */
440
+	public static function format_currency(
441
+		$amount = null,
442
+		$return_raw = false,
443
+		$display_code = true,
444
+		$CNT_ISO = '',
445
+		$cur_code_span_class = 'currency-code'
446
+	) {
447
+		// ensure amount was received
448
+		if ($amount === null) {
449
+			$msg = __('In order to format currency, an amount needs to be passed.', 'event_espresso');
450
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
451
+			return '';
452
+		}
453
+		//ensure amount is float
454
+		$amount  = apply_filters('FHEE__EEH_Template__format_currency__raw_amount', (float)$amount);
455
+		$CNT_ISO = apply_filters('FHEE__EEH_Template__format_currency__CNT_ISO', $CNT_ISO, $amount);
456
+		// filter raw amount (allows 0.00 to be changed to "free" for example)
457
+		$amount_formatted = apply_filters('FHEE__EEH_Template__format_currency__amount', $amount, $return_raw);
458
+		// still a number or was amount converted to a string like "free" ?
459
+		if (is_float($amount_formatted)) {
460
+			// was a country ISO code passed ? if so generate currency config object for that country
461
+			$mny = $CNT_ISO !== '' ? new EE_Currency_Config($CNT_ISO) : null;
462
+			// verify results
463
+			if ( ! $mny instanceof EE_Currency_Config) {
464
+				// set default config country currency settings
465
+				$mny = EE_Registry::instance()->CFG->currency instanceof EE_Currency_Config
466
+					? EE_Registry::instance()->CFG->currency
467
+					: new EE_Currency_Config();
468
+			}
469
+			// format float
470
+			$amount_formatted = number_format($amount, $mny->dec_plc, $mny->dec_mrk, $mny->thsnds);
471
+			// add formatting ?
472
+			if ( ! $return_raw) {
473
+				// add currency sign
474
+				if ($mny->sign_b4) {
475
+					if ($amount >= 0) {
476
+						$amount_formatted = $mny->sign . $amount_formatted;
477
+					} else {
478
+						$amount_formatted = '-' . $mny->sign . str_replace('-', '', $amount_formatted);
479
+					}
480
+
481
+				} else {
482
+					$amount_formatted = $amount_formatted . $mny->sign;
483
+				}
484
+
485
+				// filter to allow global setting of display_code
486
+				$display_code = apply_filters('FHEE__EEH_Template__format_currency__display_code', $display_code);
487
+
488
+				// add currency code ?
489
+				$amount_formatted = $display_code ? $amount_formatted . ' <span class="' . $cur_code_span_class . '">(' . $mny->code . ')</span>' : $amount_formatted;
490
+			}
491
+			// filter results
492
+			$amount_formatted = apply_filters('FHEE__EEH_Template__format_currency__amount_formatted',
493
+				$amount_formatted, $mny, $return_raw);
494
+		}
495
+		// clean up vars
496
+		unset($mny);
497
+		// return formatted currency amount
498
+		return $amount_formatted;
499
+	}
500
+
501
+
502
+	/**
503
+	 * This function is used for outputting the localized label for a given status id in the schema requested (and
504
+	 * possibly plural).  The intended use of this function is only for cases where wanting a label outside of a
505
+	 * related status model or model object (i.e. in documentation etc.)
506
+	 *
507
+	 * @param  string  $status_id Status ID matching a registered status in the esp_status table.  If there is no
508
+	 *                            match, then 'Unknown' will be returned.
509
+	 * @param  boolean $plural    Whether to return plural or not
510
+	 * @param  string  $schema    'UPPER', 'lower', or 'Sentence'
511
+	 * @return string             The localized label for the status id.
512
+	 */
513
+	public static function pretty_status($status_id, $plural = false, $schema = 'upper')
514
+	{
515
+		/** @type EEM_Status $EEM_Status */
516
+		$EEM_Status = EE_Registry::instance()->load_model('Status');
517
+		$status     = $EEM_Status->localized_status(array($status_id => __('unknown', 'event_espresso')), $plural,
518
+			$schema);
519
+		return $status[$status_id];
520
+	}
521
+
522
+
523
+	/**
524
+	 * This helper just returns a button or link for the given parameters
525
+	 *
526
+	 * @param  string $url   the url for the link, note that `esc_url` will be called on it
527
+	 * @param  string $label What is the label you want displayed for the button
528
+	 * @param  string $class what class is used for the button (defaults to 'button-primary')
529
+	 * @param string  $icon
530
+	 * @param string  $title
531
+	 * @return string the html output for the button
532
+	 */
533
+	public static function get_button_or_link($url, $label, $class = 'button-primary', $icon = '', $title = '')
534
+	{
535
+		$icon_html = '';
536
+		if ( ! empty($icon)) {
537
+			$dashicons = preg_split("(ee-icon |dashicons )", $icon);
538
+			$dashicons = array_filter($dashicons);
539
+			$count     = count($dashicons);
540
+			$icon_html .= $count > 1 ? '<span class="ee-composite-dashicon">' : '';
541
+			foreach ($dashicons as $dashicon) {
542
+				$type = strpos($dashicon, 'ee-icon') !== false ? 'ee-icon ' : 'dashicons ';
543
+				$icon_html .= '<span class="' . $type . $dashicon . '"></span>';
544
+			}
545
+			$icon_html .= $count > 1 ? '</span>' : '';
546
+		}
547
+		$label  = ! empty($icon) ? $icon_html . $label : $label;
548
+		$button = '<a id="' . sanitize_title_with_dashes($label) . '" href="' . esc_url($url) . '" class="' . $class . '" title="' . $title . '">' . $label . '</a>';
549
+		return $button;
550
+	}
551
+
552
+
553
+	/**
554
+	 * This returns a generated link that will load the related help tab on admin pages.
555
+	 *
556
+	 * @param  string     $help_tab_id the id for the connected help tab
557
+	 * @param bool|string $page        The page identifier for the page the help tab is on
558
+	 * @param bool|string $action      The action (route) for the admin page the help tab is on.
559
+	 * @param bool|string $icon_style  (optional) include css class for the style you want to use for the help icon.
560
+	 * @param bool|string $help_text   (optional) send help text you want to use for the link if default not to be used
561
+	 * @return string              generated link
562
+	 */
563
+	public static function get_help_tab_link(
564
+		$help_tab_id,
565
+		$page = false,
566
+		$action = false,
567
+		$icon_style = false,
568
+		$help_text = false
569
+	) {
570
+
571
+		if ( ! $page) {
572
+			$page = isset($_REQUEST['page']) && ! empty($_REQUEST['page']) ? sanitize_key($_REQUEST['page']) : $page;
573
+		}
574
+
575
+		if ( ! $action) {
576
+			$action = isset($_REQUEST['action']) && ! empty($_REQUEST['action']) ? sanitize_key($_REQUEST['action']) : $action;
577
+		}
578
+
579
+		$action = empty($action) ? 'default' : $action;
580
+
581
+
582
+		$help_tab_lnk = $page . '-' . $action . '-' . $help_tab_id;
583
+		$icon         = ! $icon_style ? ' dashicons-editor-help' : $icon_style;
584
+		$help_text    = ! $help_text ? '' : $help_text;
585
+		return '<a id="' . $help_tab_lnk . '" class="ee-clickable dashicons espresso-help-tab-lnk ee-icon-size-22' . $icon . '" title="' . esc_attr__('Click to open the \'Help\' tab for more information about this feature.',
586
+				'event_espresso') . '" > ' . $help_text . ' </a>';
587
+	}
588
+
589
+
590
+	/**
591
+	 * This helper generates the html structure for the jquery joyride plugin with the given params.
592
+	 *
593
+	 * @link http://zurb.com/playground/jquery-joyride-feature-tour-plugin
594
+	 * @see  EE_Admin_Page->_stop_callback() for the construct expected for the $stops param.
595
+	 * @param EE_Help_Tour
596
+	 * @return string         html
597
+	 */
598
+	public static function help_tour_stops_generator(EE_Help_Tour $tour)
599
+	{
600
+		$id    = $tour->get_slug();
601
+		$stops = $tour->get_stops();
602
+
603
+		$content = '<ol style="display:none" id="' . $id . '">';
604
+
605
+		foreach ($stops as $stop) {
606
+			$data_id    = ! empty($stop['id']) ? ' data-id="' . $stop['id'] . '"' : '';
607
+			$data_class = empty($data_id) && ! empty($stop['class']) ? ' data-class="' . $stop['class'] . '"' : '';
608
+
609
+			//if container is set to modal then let's make sure we set the options accordingly
610
+			if (empty($data_id) && empty($data_class)) {
611
+				$stop['options']['modal']  = true;
612
+				$stop['options']['expose'] = true;
613
+			}
614
+
615
+			$custom_class  = ! empty($stop['custom_class']) ? ' class="' . $stop['custom_class'] . '"' : '';
616
+			$button_text   = ! empty($stop['button_text']) ? ' data-button="' . $stop['button_text'] . '"' : '';
617
+			$inner_content = isset($stop['content']) ? $stop['content'] : '';
618
+
619
+			//options
620
+			if (isset($stop['options']) && is_array($stop['options'])) {
621
+				$options = ' data-options="';
622
+				foreach ($stop['options'] as $option => $value) {
623
+					$options .= $option . ':' . $value . ';';
624
+				}
625
+				$options .= '"';
626
+			} else {
627
+				$options = '';
628
+			}
629
+
630
+			//let's put all together
631
+			$content .= '<li' . $data_id . $data_class . $custom_class . $button_text . $options . '>' . $inner_content . '</li>';
632
+		}
633
+
634
+		$content .= '</ol>';
635
+		return $content;
636
+	}
637
+
638
+
639
+	/**
640
+	 * This is a helper method to generate a status legend for a given status array.
641
+	 * Note this will only work if the incoming statuses have a key in the EEM_Status->localized_status() methods
642
+	 * status_array.
643
+	 *
644
+	 * @param  array  $status_array  array of statuses that will make up the legend. In format:
645
+	 *                               array(
646
+	 *                               'status_item' => 'status_name'
647
+	 *                               )
648
+	 * @param  string $active_status This is used to indicate what the active status is IF that is to be highlighted in
649
+	 *                               the legend.
650
+	 * @throws EE_Error
651
+	 * @return string               html structure for status.
652
+	 */
653
+	public static function status_legend($status_array, $active_status = '')
654
+	{
655
+		if ( ! is_array($status_array)) {
656
+			throw new EE_Error(esc_html__('The EEH_Template::status_legend helper required the incoming status_array argument to be an array!',
657
+				'event_espresso'));
658
+		}
659
+
660
+		$setup_array = array();
661
+		foreach ($status_array as $item => $status) {
662
+			$setup_array[$item] = array(
663
+				'class'  => 'ee-status-legend ee-status-legend-' . $status,
664
+				'desc'   => EEH_Template::pretty_status($status, false, 'sentence'),
665
+				'status' => $status,
666
+			);
667
+		}
668
+
669
+		$content = '<div class="ee-list-table-legend-container">' . "\n";
670
+		$content .= '<h4 class="status-legend-title">' . esc_html__('Status Legend', 'event_espresso') . '</h4>' . "\n";
671
+		$content .= '<dl class="ee-list-table-legend">' . "\n\t";
672
+		foreach ($setup_array as $item => $details) {
673
+			$active_class = $active_status == $details['status'] ? ' class="ee-is-active-status"' : '';
674
+			$content .= '<dt id="ee-legend-item-tooltip-' . $item . '"' . $active_class . '>' . "\n\t\t";
675
+			$content .= '<span class="' . $details['class'] . '"></span>' . "\n\t\t";
676
+			$content .= '<span class="ee-legend-description">' . $details['desc'] . '</span>' . "\n\t";
677
+			$content .= '</dt>' . "\n";
678
+		}
679
+		$content .= '</dl>' . "\n";
680
+		$content .= '</div>' . "\n";
681
+		return $content;
682
+	}
683
+
684
+
685
+	/**
686
+	 * Gets HTML for laying out a deeply-nested array (and objects) in a format
687
+	 * that's nice for presenting in the wp admin
688
+	 *
689
+	 * @param mixed $data
690
+	 * @return string
691
+	 */
692
+	public static function layout_array_as_table($data)
693
+	{
694
+		if (is_object($data) || $data instanceof __PHP_Incomplete_Class) {
695
+			$data = (array)$data;
696
+		}
697
+		ob_start();
698
+		if (is_array($data)) {
699
+			if (EEH_Array::is_associative_array($data)) {
700
+				?>
701 701
                 <table class="widefat">
702 702
                     <tbody>
703 703
                     <?php
704
-                    foreach ($data as $data_key => $data_values) {
705
-                        ?>
704
+					foreach ($data as $data_key => $data_values) {
705
+						?>
706 706
                         <tr>
707 707
                             <td>
708 708
                                 <?php echo $data_key; ?>
@@ -712,248 +712,248 @@  discard block
 block discarded – undo
712 712
                             </td>
713 713
                         </tr>
714 714
                         <?php
715
-                    } ?>
715
+					} ?>
716 716
                     </tbody>
717 717
                 </table>
718 718
                 <?php
719
-            } else {
720
-                ?>
719
+			} else {
720
+				?>
721 721
                 <ul>
722 722
                     <?php
723
-                    foreach ($data as $datum) {
724
-                        echo "<li>";
725
-                        echo self::layout_array_as_table($datum);
726
-                        echo "</li>";
727
-                    } ?>
723
+					foreach ($data as $datum) {
724
+						echo "<li>";
725
+						echo self::layout_array_as_table($datum);
726
+						echo "</li>";
727
+					} ?>
728 728
                 </ul>
729 729
                 <?php
730
-            }
731
-        } else {
732
-            //simple value
733
-            echo esc_html($data);
734
-        }
735
-        return ob_get_clean();
736
-    }
737
-
738
-
739
-    /**
740
-     * wrapper for self::get_paging_html() that simply echos the generated paging html
741
-     *
742
-     * @since 4.4.0
743
-     * @see   self:get_paging_html() for argument docs.
744
-     * @param        $total_items
745
-     * @param        $current
746
-     * @param        $per_page
747
-     * @param        $url
748
-     * @param bool   $show_num_field
749
-     * @param string $paged_arg_name
750
-     * @param array  $items_label
751
-     * @return string
752
-     */
753
-    public static function paging_html(
754
-        $total_items,
755
-        $current,
756
-        $per_page,
757
-        $url,
758
-        $show_num_field = true,
759
-        $paged_arg_name = 'paged',
760
-        $items_label = array()
761
-    ) {
762
-        echo self::get_paging_html($total_items, $current, $per_page, $url, $show_num_field, $paged_arg_name,
763
-            $items_label);
764
-    }
765
-
766
-
767
-    /**
768
-     * A method for generating paging similar to WP_List_Table
769
-     *
770
-     * @since    4.4.0
771
-     * @see      wp-admin/includes/class-wp-list-table.php WP_List_Table::pagination()
772
-     * @param  integer $total_items     How many total items there are to page.
773
-     * @param  integer $current         What the current page is.
774
-     * @param  integer $per_page        How many items per page.
775
-     * @param  string  $url             What the base url for page links is.
776
-     * @param  boolean $show_num_field  Whether to show the input for changing page number.
777
-     * @param  string  $paged_arg_name  The name of the key for the paged query argument.
778
-     * @param  array   $items_label     An array of singular/plural values for the items label:
779
-     *                                  array(
780
-     *                                  'single' => 'item',
781
-     *                                  'plural' => 'items'
782
-     *                                  )
783
-     * @return  string
784
-     */
785
-    public static function get_paging_html(
786
-        $total_items,
787
-        $current,
788
-        $per_page,
789
-        $url,
790
-        $show_num_field = true,
791
-        $paged_arg_name = 'paged',
792
-        $items_label = array()
793
-    ) {
794
-        $page_links     = array();
795
-        $disable_first  = $disable_last = '';
796
-        $total_items    = (int)$total_items;
797
-        $per_page       = (int)$per_page;
798
-        $current        = (int)$current;
799
-        $paged_arg_name = empty($paged_arg_name) ? 'paged' : sanitize_key($paged_arg_name);
800
-
801
-        //filter items_label
802
-        $items_label = apply_filters(
803
-            'FHEE__EEH_Template__get_paging_html__items_label',
804
-            $items_label
805
-        );
806
-
807
-        if (empty($items_label)
808
-            || ! is_array($items_label)
809
-            || ! isset($items_label['single'])
810
-            || ! isset($items_label['plural'])
811
-        ) {
812
-            $items_label = array(
813
-                'single' => __('1 item', 'event_espresso'),
814
-                'plural' => __('%s items', 'event_espresso'),
815
-            );
816
-        } else {
817
-            $items_label = array(
818
-                'single' => '1 ' . esc_html($items_label['single']),
819
-                'plural' => '%s ' . esc_html($items_label['plural']),
820
-            );
821
-        }
822
-
823
-        $total_pages = ceil($total_items / $per_page);
824
-
825
-        if ($total_pages <= 1) {
826
-            return '';
827
-        }
828
-
829
-        $item_label = $total_items > 1 ? sprintf($items_label['plural'], $total_items) : $items_label['single'];
830
-
831
-        $output = '<span class="displaying-num">' . $item_label . '</span>';
832
-
833
-        if ($current === 1) {
834
-            $disable_first = ' disabled';
835
-        }
836
-        if ($current == $total_pages) {
837
-            $disable_last = ' disabled';
838
-        }
839
-
840
-        $page_links[] = sprintf("<a class='%s' title='%s' href='%s'>%s</a>",
841
-            'first-page' . $disable_first,
842
-            esc_attr__('Go to the first page'),
843
-            esc_url(remove_query_arg($paged_arg_name, $url)),
844
-            '&laquo;'
845
-        );
846
-
847
-        $page_links[] = sprintf(
848
-            '<a class="%s" title="%s" href="%s">%s</a>',
849
-            'prev-page' . $disable_first,
850
-            esc_attr__('Go to the previous page'),
851
-            esc_url(add_query_arg($paged_arg_name, max(1, $current - 1), $url)),
852
-            '&lsaquo;'
853
-        );
854
-
855
-        if ( ! $show_num_field) {
856
-            $html_current_page = $current;
857
-        } else {
858
-            $html_current_page = sprintf("<input class='current-page' title='%s' type='text' name=$paged_arg_name value='%s' size='%d' />",
859
-                esc_attr__('Current page'),
860
-                $current,
861
-                strlen($total_pages)
862
-            );
863
-        }
864
-
865
-        $html_total_pages = sprintf(
866
-            '<span class="total-pages">%s</span>',
867
-            number_format_i18n($total_pages)
868
-        );
869
-        $page_links[]     = sprintf(
870
-            _x('%3$s%1$s of %2$s%4$s', 'paging'),
871
-            $html_current_page,
872
-            $html_total_pages,
873
-            '<span class="paging-input">',
874
-            '</span>'
875
-        );
876
-
877
-        $page_links[] = sprintf(
878
-            '<a class="%s" title="%s" href="%s">%s</a>',
879
-            'next-page' . $disable_last,
880
-            esc_attr__('Go to the next page'),
881
-            esc_url(add_query_arg($paged_arg_name, min($total_pages, $current + 1), $url)),
882
-            '&rsaquo;'
883
-        );
884
-
885
-        $page_links[] = sprintf(
886
-            '<a class="%s" title="%s" href="%s">%s</a>',
887
-            'last-page' . $disable_last,
888
-            esc_attr__('Go to the last page'),
889
-            esc_url(add_query_arg($paged_arg_name, $total_pages, $url)),
890
-            '&raquo;'
891
-        );
892
-
893
-        $output .= "\n" . '<span class="pagination-links">' . join("\n", $page_links) . '</span>';
894
-        // set page class
895
-        if ($total_pages) {
896
-            $page_class = $total_pages < 2 ? ' one-page' : '';
897
-        } else {
898
-            $page_class = ' no-pages';
899
-        }
900
-
901
-        return '<div class="tablenav"><div class="tablenav-pages' . $page_class . '">' . $output . '</div></div>';
902
-    }
903
-
904
-
905
-    /**
906
-     * @param string $wrap_class
907
-     * @param string $wrap_id
908
-     * @return string
909
-     */
910
-    public static function powered_by_event_espresso($wrap_class = '', $wrap_id = '', array $query_args = array())
911
-    {
912
-        $admin = is_admin() && ! (defined('DOING_AJAX') && DOING_AJAX);
913
-        if (
914
-            ! $admin &&
915
-            ! apply_filters(
916
-                'FHEE__EEH_Template__powered_by_event_espresso__show_reg_footer',
917
-                EE_Registry::instance()->CFG->admin->show_reg_footer
918
-            )
919
-        ) {
920
-            return '';
921
-        }
922
-        $tag        = $admin ? 'span' : 'div';
923
-        $attributes = ! empty($wrap_id) ? " id=\"{$wrap_id}\"" : '';
924
-        $wrap_class = $admin ? "{$wrap_class} float-left" : $wrap_class;
925
-        $attributes .= ! empty($wrap_class)
926
-            ? " class=\"{$wrap_class} powered-by-event-espresso-credit\""
927
-            : ' class="powered-by-event-espresso-credit"';
928
-        $query_args = array_merge(
929
-            array(
930
-                'ap_id'        => EE_Registry::instance()->CFG->admin->affiliate_id(),
931
-                'utm_source'   => 'powered_by_event_espresso',
932
-                'utm_medium'   => 'link',
933
-                'utm_campaign' => 'powered_by',
934
-            ),
935
-            $query_args
936
-        );
937
-        $powered_by = apply_filters('FHEE__EEH_Template__powered_by_event_espresso_text',
938
-            $admin ? 'Event Espresso - ' . EVENT_ESPRESSO_VERSION : 'Event Espresso');
939
-        $url        = add_query_arg($query_args, 'https://eventespresso.com/');
940
-        $url        = apply_filters('FHEE__EEH_Template__powered_by_event_espresso__url', $url);
941
-        return (string)apply_filters(
942
-            'FHEE__EEH_Template__powered_by_event_espresso__html',
943
-            sprintf(
944
-                esc_html_x(
945
-                    '%3$s%1$sOnline event registration and ticketing powered by %2$s%3$s',
946
-                    'Online event registration and ticketing powered by [link to eventespresso.com]',
947
-                    'event_espresso'
948
-                ),
949
-                "<{$tag}{$attributes}>",
950
-                "<a href=\"{$url}\" target=\"_blank\" rel=\"nofollow\">{$powered_by}</a></{$tag}>",
951
-                $admin ? '' : '<br />'
952
-            ),
953
-            $wrap_class,
954
-            $wrap_id
955
-        );
956
-    }
730
+			}
731
+		} else {
732
+			//simple value
733
+			echo esc_html($data);
734
+		}
735
+		return ob_get_clean();
736
+	}
737
+
738
+
739
+	/**
740
+	 * wrapper for self::get_paging_html() that simply echos the generated paging html
741
+	 *
742
+	 * @since 4.4.0
743
+	 * @see   self:get_paging_html() for argument docs.
744
+	 * @param        $total_items
745
+	 * @param        $current
746
+	 * @param        $per_page
747
+	 * @param        $url
748
+	 * @param bool   $show_num_field
749
+	 * @param string $paged_arg_name
750
+	 * @param array  $items_label
751
+	 * @return string
752
+	 */
753
+	public static function paging_html(
754
+		$total_items,
755
+		$current,
756
+		$per_page,
757
+		$url,
758
+		$show_num_field = true,
759
+		$paged_arg_name = 'paged',
760
+		$items_label = array()
761
+	) {
762
+		echo self::get_paging_html($total_items, $current, $per_page, $url, $show_num_field, $paged_arg_name,
763
+			$items_label);
764
+	}
765
+
766
+
767
+	/**
768
+	 * A method for generating paging similar to WP_List_Table
769
+	 *
770
+	 * @since    4.4.0
771
+	 * @see      wp-admin/includes/class-wp-list-table.php WP_List_Table::pagination()
772
+	 * @param  integer $total_items     How many total items there are to page.
773
+	 * @param  integer $current         What the current page is.
774
+	 * @param  integer $per_page        How many items per page.
775
+	 * @param  string  $url             What the base url for page links is.
776
+	 * @param  boolean $show_num_field  Whether to show the input for changing page number.
777
+	 * @param  string  $paged_arg_name  The name of the key for the paged query argument.
778
+	 * @param  array   $items_label     An array of singular/plural values for the items label:
779
+	 *                                  array(
780
+	 *                                  'single' => 'item',
781
+	 *                                  'plural' => 'items'
782
+	 *                                  )
783
+	 * @return  string
784
+	 */
785
+	public static function get_paging_html(
786
+		$total_items,
787
+		$current,
788
+		$per_page,
789
+		$url,
790
+		$show_num_field = true,
791
+		$paged_arg_name = 'paged',
792
+		$items_label = array()
793
+	) {
794
+		$page_links     = array();
795
+		$disable_first  = $disable_last = '';
796
+		$total_items    = (int)$total_items;
797
+		$per_page       = (int)$per_page;
798
+		$current        = (int)$current;
799
+		$paged_arg_name = empty($paged_arg_name) ? 'paged' : sanitize_key($paged_arg_name);
800
+
801
+		//filter items_label
802
+		$items_label = apply_filters(
803
+			'FHEE__EEH_Template__get_paging_html__items_label',
804
+			$items_label
805
+		);
806
+
807
+		if (empty($items_label)
808
+			|| ! is_array($items_label)
809
+			|| ! isset($items_label['single'])
810
+			|| ! isset($items_label['plural'])
811
+		) {
812
+			$items_label = array(
813
+				'single' => __('1 item', 'event_espresso'),
814
+				'plural' => __('%s items', 'event_espresso'),
815
+			);
816
+		} else {
817
+			$items_label = array(
818
+				'single' => '1 ' . esc_html($items_label['single']),
819
+				'plural' => '%s ' . esc_html($items_label['plural']),
820
+			);
821
+		}
822
+
823
+		$total_pages = ceil($total_items / $per_page);
824
+
825
+		if ($total_pages <= 1) {
826
+			return '';
827
+		}
828
+
829
+		$item_label = $total_items > 1 ? sprintf($items_label['plural'], $total_items) : $items_label['single'];
830
+
831
+		$output = '<span class="displaying-num">' . $item_label . '</span>';
832
+
833
+		if ($current === 1) {
834
+			$disable_first = ' disabled';
835
+		}
836
+		if ($current == $total_pages) {
837
+			$disable_last = ' disabled';
838
+		}
839
+
840
+		$page_links[] = sprintf("<a class='%s' title='%s' href='%s'>%s</a>",
841
+			'first-page' . $disable_first,
842
+			esc_attr__('Go to the first page'),
843
+			esc_url(remove_query_arg($paged_arg_name, $url)),
844
+			'&laquo;'
845
+		);
846
+
847
+		$page_links[] = sprintf(
848
+			'<a class="%s" title="%s" href="%s">%s</a>',
849
+			'prev-page' . $disable_first,
850
+			esc_attr__('Go to the previous page'),
851
+			esc_url(add_query_arg($paged_arg_name, max(1, $current - 1), $url)),
852
+			'&lsaquo;'
853
+		);
854
+
855
+		if ( ! $show_num_field) {
856
+			$html_current_page = $current;
857
+		} else {
858
+			$html_current_page = sprintf("<input class='current-page' title='%s' type='text' name=$paged_arg_name value='%s' size='%d' />",
859
+				esc_attr__('Current page'),
860
+				$current,
861
+				strlen($total_pages)
862
+			);
863
+		}
864
+
865
+		$html_total_pages = sprintf(
866
+			'<span class="total-pages">%s</span>',
867
+			number_format_i18n($total_pages)
868
+		);
869
+		$page_links[]     = sprintf(
870
+			_x('%3$s%1$s of %2$s%4$s', 'paging'),
871
+			$html_current_page,
872
+			$html_total_pages,
873
+			'<span class="paging-input">',
874
+			'</span>'
875
+		);
876
+
877
+		$page_links[] = sprintf(
878
+			'<a class="%s" title="%s" href="%s">%s</a>',
879
+			'next-page' . $disable_last,
880
+			esc_attr__('Go to the next page'),
881
+			esc_url(add_query_arg($paged_arg_name, min($total_pages, $current + 1), $url)),
882
+			'&rsaquo;'
883
+		);
884
+
885
+		$page_links[] = sprintf(
886
+			'<a class="%s" title="%s" href="%s">%s</a>',
887
+			'last-page' . $disable_last,
888
+			esc_attr__('Go to the last page'),
889
+			esc_url(add_query_arg($paged_arg_name, $total_pages, $url)),
890
+			'&raquo;'
891
+		);
892
+
893
+		$output .= "\n" . '<span class="pagination-links">' . join("\n", $page_links) . '</span>';
894
+		// set page class
895
+		if ($total_pages) {
896
+			$page_class = $total_pages < 2 ? ' one-page' : '';
897
+		} else {
898
+			$page_class = ' no-pages';
899
+		}
900
+
901
+		return '<div class="tablenav"><div class="tablenav-pages' . $page_class . '">' . $output . '</div></div>';
902
+	}
903
+
904
+
905
+	/**
906
+	 * @param string $wrap_class
907
+	 * @param string $wrap_id
908
+	 * @return string
909
+	 */
910
+	public static function powered_by_event_espresso($wrap_class = '', $wrap_id = '', array $query_args = array())
911
+	{
912
+		$admin = is_admin() && ! (defined('DOING_AJAX') && DOING_AJAX);
913
+		if (
914
+			! $admin &&
915
+			! apply_filters(
916
+				'FHEE__EEH_Template__powered_by_event_espresso__show_reg_footer',
917
+				EE_Registry::instance()->CFG->admin->show_reg_footer
918
+			)
919
+		) {
920
+			return '';
921
+		}
922
+		$tag        = $admin ? 'span' : 'div';
923
+		$attributes = ! empty($wrap_id) ? " id=\"{$wrap_id}\"" : '';
924
+		$wrap_class = $admin ? "{$wrap_class} float-left" : $wrap_class;
925
+		$attributes .= ! empty($wrap_class)
926
+			? " class=\"{$wrap_class} powered-by-event-espresso-credit\""
927
+			: ' class="powered-by-event-espresso-credit"';
928
+		$query_args = array_merge(
929
+			array(
930
+				'ap_id'        => EE_Registry::instance()->CFG->admin->affiliate_id(),
931
+				'utm_source'   => 'powered_by_event_espresso',
932
+				'utm_medium'   => 'link',
933
+				'utm_campaign' => 'powered_by',
934
+			),
935
+			$query_args
936
+		);
937
+		$powered_by = apply_filters('FHEE__EEH_Template__powered_by_event_espresso_text',
938
+			$admin ? 'Event Espresso - ' . EVENT_ESPRESSO_VERSION : 'Event Espresso');
939
+		$url        = add_query_arg($query_args, 'https://eventespresso.com/');
940
+		$url        = apply_filters('FHEE__EEH_Template__powered_by_event_espresso__url', $url);
941
+		return (string)apply_filters(
942
+			'FHEE__EEH_Template__powered_by_event_espresso__html',
943
+			sprintf(
944
+				esc_html_x(
945
+					'%3$s%1$sOnline event registration and ticketing powered by %2$s%3$s',
946
+					'Online event registration and ticketing powered by [link to eventespresso.com]',
947
+					'event_espresso'
948
+				),
949
+				"<{$tag}{$attributes}>",
950
+				"<a href=\"{$url}\" target=\"_blank\" rel=\"nofollow\">{$powered_by}</a></{$tag}>",
951
+				$admin ? '' : '<br />'
952
+			),
953
+			$wrap_class,
954
+			$wrap_id
955
+		);
956
+	}
957 957
 
958 958
 
959 959
 } //end EEH_Template class
@@ -962,33 +962,33 @@  discard block
 block discarded – undo
962 962
 
963 963
 
964 964
 if ( ! function_exists('espresso_pagination')) {
965
-    /**
966
-     *    espresso_pagination
967
-     *
968
-     * @access    public
969
-     * @return    void
970
-     */
971
-    function espresso_pagination()
972
-    {
973
-        global $wp_query;
974
-        $big        = 999999999; // need an unlikely integer
975
-        $pagination = paginate_links(
976
-            array(
977
-                'base'         => str_replace($big, '%#%', esc_url(get_pagenum_link($big))),
978
-                'format'       => '?paged=%#%',
979
-                'current'      => max(1, get_query_var('paged')),
980
-                'total'        => $wp_query->max_num_pages,
981
-                'show_all'     => true,
982
-                'end_size'     => 10,
983
-                'mid_size'     => 6,
984
-                'prev_next'    => true,
985
-                'prev_text'    => __('&lsaquo; PREV', 'event_espresso'),
986
-                'next_text'    => __('NEXT &rsaquo;', 'event_espresso'),
987
-                'type'         => 'plain',
988
-                'add_args'     => false,
989
-                'add_fragment' => '',
990
-            )
991
-        );
992
-        echo ! empty($pagination) ? '<div class="ee-pagination-dv ee-clear-float">' . $pagination . '</div>' : '';
993
-    }
965
+	/**
966
+	 *    espresso_pagination
967
+	 *
968
+	 * @access    public
969
+	 * @return    void
970
+	 */
971
+	function espresso_pagination()
972
+	{
973
+		global $wp_query;
974
+		$big        = 999999999; // need an unlikely integer
975
+		$pagination = paginate_links(
976
+			array(
977
+				'base'         => str_replace($big, '%#%', esc_url(get_pagenum_link($big))),
978
+				'format'       => '?paged=%#%',
979
+				'current'      => max(1, get_query_var('paged')),
980
+				'total'        => $wp_query->max_num_pages,
981
+				'show_all'     => true,
982
+				'end_size'     => 10,
983
+				'mid_size'     => 6,
984
+				'prev_next'    => true,
985
+				'prev_text'    => __('&lsaquo; PREV', 'event_espresso'),
986
+				'next_text'    => __('NEXT &rsaquo;', 'event_espresso'),
987
+				'type'         => 'plain',
988
+				'add_args'     => false,
989
+				'add_fragment' => '',
990
+			)
991
+		);
992
+		echo ! empty($pagination) ? '<div class="ee-pagination-dv ee-clear-float">' . $pagination . '</div>' : '';
993
+	}
994 994
 }
995 995
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +65 added lines, -65 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php
2
-if (! defined('EVENT_ESPRESSO_VERSION')) {
2
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
3 3
     exit('NO direct script access allowed');
4 4
 }
5 5
 /**
@@ -81,8 +81,8 @@  discard block
 block discarded – undo
81 81
     public static function load_espresso_theme_functions()
82 82
     {
83 83
         if ( ! defined('EE_THEME_FUNCTIONS_LOADED')) {
84
-            if (is_readable(EE_PUBLIC . EE_Config::get_current_theme() . DS . 'functions.php')) {
85
-                require_once(EE_PUBLIC . EE_Config::get_current_theme() . DS . 'functions.php');
84
+            if (is_readable(EE_PUBLIC.EE_Config::get_current_theme().DS.'functions.php')) {
85
+                require_once(EE_PUBLIC.EE_Config::get_current_theme().DS.'functions.php');
86 86
             }
87 87
         }
88 88
     }
@@ -96,7 +96,7 @@  discard block
 block discarded – undo
96 96
     public static function get_espresso_themes()
97 97
     {
98 98
         if (empty(EEH_Template::$_espresso_themes)) {
99
-            $espresso_themes = glob(EE_PUBLIC . '*', GLOB_ONLYDIR);
99
+            $espresso_themes = glob(EE_PUBLIC.'*', GLOB_ONLYDIR);
100 100
             if (empty($espresso_themes)) {
101 101
                 return array();
102 102
             }
@@ -132,7 +132,7 @@  discard block
 block discarded – undo
132 132
     ) {
133 133
         do_action("get_template_part_{$slug}-{$name}", $slug, $name);
134 134
         $templates = array();
135
-        $name      = (string)$name;
135
+        $name      = (string) $name;
136 136
         if ($name != '') {
137 137
             $templates[] = "{$slug}-{$name}.php";
138 138
         }
@@ -211,7 +211,7 @@  discard block
 block discarded – undo
211 211
                 if (isset($EE_CPTs[$post_type])) {
212 212
                     $archive_or_single = is_archive() ? 'archive' : '';
213 213
                     $archive_or_single = is_single() ? 'single' : $archive_or_single;
214
-                    $templates         = $archive_or_single . '-' . $post_type . '.php';
214
+                    $templates         = $archive_or_single.'-'.$post_type.'.php';
215 215
                 }
216 216
             }
217 217
             // currently active EE template theme
@@ -220,18 +220,18 @@  discard block
 block discarded – undo
220 220
             // array of paths to folders that may contain templates
221 221
             $template_folder_paths = array(
222 222
                 // first check the /wp-content/uploads/espresso/templates/(current EE theme)/  folder for an EE theme template file
223
-                EVENT_ESPRESSO_TEMPLATE_DIR . $current_theme,
223
+                EVENT_ESPRESSO_TEMPLATE_DIR.$current_theme,
224 224
                 // then in the root of the /wp-content/uploads/espresso/templates/ folder
225 225
                 EVENT_ESPRESSO_TEMPLATE_DIR,
226 226
             );
227 227
 
228 228
             //add core plugin folders for checking only if we're not $check_if_custom
229 229
             if ( ! $check_if_custom) {
230
-                $core_paths            = array(
230
+                $core_paths = array(
231 231
                     // in the  /wp-content/plugins/(EE4 folder)/public/(current EE theme)/ folder within the plugin
232
-                    EE_PUBLIC . $current_theme,
232
+                    EE_PUBLIC.$current_theme,
233 233
                     // in the  /wp-content/plugins/(EE4 folder)/core/templates/(current EE theme)/ folder within the plugin
234
-                    EE_TEMPLATES . $current_theme,
234
+                    EE_TEMPLATES.$current_theme,
235 235
                     // or maybe relative from the plugin root: /wp-content/plugins/(EE4 folder)/
236 236
                     EE_PLUGIN_DIR_PATH,
237 237
                 );
@@ -262,10 +262,10 @@  discard block
 block discarded – undo
262 262
                     );
263 263
                     if ($common_base_path !== '') {
264 264
                         // both paths have a common base, so just tack the filename onto our search path
265
-                        $resolved_path = EEH_File::end_with_directory_separator($template_folder_path) . $file_name;
265
+                        $resolved_path = EEH_File::end_with_directory_separator($template_folder_path).$file_name;
266 266
                     } else {
267 267
                         // no common base path, so let's just concatenate
268
-                        $resolved_path = EEH_File::end_with_directory_separator($template_folder_path) . $template;
268
+                        $resolved_path = EEH_File::end_with_directory_separator($template_folder_path).$template;
269 269
                     }
270 270
                     // build up our template locations array by adding our resolved paths
271 271
                     $full_template_paths[] = $resolved_path;
@@ -273,13 +273,13 @@  discard block
 block discarded – undo
273 273
                 // if $template is an absolute path, then we'll tack it onto the start of our array so that it gets searched first
274 274
                 array_unshift($full_template_paths, $template);
275 275
                 // path to the directory of the current theme: /wp-content/themes/(current WP theme)/
276
-                array_unshift($full_template_paths, get_stylesheet_directory() . DS . $file_name);
276
+                array_unshift($full_template_paths, get_stylesheet_directory().DS.$file_name);
277 277
             }
278 278
             // filter final array of full template paths
279 279
             $full_template_paths = apply_filters('FHEE__EEH_Template__locate_template__full_template_paths',
280 280
                 $full_template_paths, $file_name);
281 281
             // now loop through our final array of template location paths and check each location
282
-            foreach ((array)$full_template_paths as $full_template_path) {
282
+            foreach ((array) $full_template_paths as $full_template_path) {
283 283
                 if (is_readable($full_template_path)) {
284 284
                     $template_path = str_replace(array('\\', '/'), DIRECTORY_SEPARATOR, $full_template_path);
285 285
                     break;
@@ -366,9 +366,9 @@  discard block
 block discarded – undo
366 366
         if ( ! is_array($template_args) && ! is_object($template_args)) {
367 367
             $template_args = array($template_args);
368 368
         }
369
-        extract( $template_args, EXTR_SKIP );
369
+        extract($template_args, EXTR_SKIP);
370 370
         // ignore whether template is accessible ?
371
-        if ( $throw_exceptions && ! is_readable( $template_path ) ) {
371
+        if ($throw_exceptions && ! is_readable($template_path)) {
372 372
             throw new \DomainException(
373 373
                     esc_html__(
374 374
                             'Invalid, unreadable, or missing file.',
@@ -401,11 +401,11 @@  discard block
 block discarded – undo
401 401
     public static function get_object_css_class($object = null, $prefix = '', $suffix = '')
402 402
     {
403 403
         // in the beginning...
404
-        $prefix = ! empty($prefix) ? rtrim($prefix, '-') . '-' : '';
404
+        $prefix = ! empty($prefix) ? rtrim($prefix, '-').'-' : '';
405 405
         // da muddle
406 406
         $class = '';
407 407
         // the end
408
-        $suffix = ! empty($suffix) ? '-' . ltrim($suffix, '-') : '';
408
+        $suffix = ! empty($suffix) ? '-'.ltrim($suffix, '-') : '';
409 409
         // is the passed object an EE object ?
410 410
         if ($object instanceof EE_Base_Class) {
411 411
             // grab the exact type of object
@@ -415,11 +415,11 @@  discard block
 block discarded – undo
415 415
                 // no specifics just yet...
416 416
                 default :
417 417
                     $class = strtolower(str_replace('_', '-', $obj_class));
418
-                    $class .= method_exists($obj_class, 'name') ? '-' . sanitize_title($object->name()) : '';
418
+                    $class .= method_exists($obj_class, 'name') ? '-'.sanitize_title($object->name()) : '';
419 419
 
420 420
             }
421 421
         }
422
-        return $prefix . $class . $suffix;
422
+        return $prefix.$class.$suffix;
423 423
     }
424 424
 
425 425
 
@@ -451,7 +451,7 @@  discard block
 block discarded – undo
451 451
             return '';
452 452
         }
453 453
         //ensure amount is float
454
-        $amount  = apply_filters('FHEE__EEH_Template__format_currency__raw_amount', (float)$amount);
454
+        $amount  = apply_filters('FHEE__EEH_Template__format_currency__raw_amount', (float) $amount);
455 455
         $CNT_ISO = apply_filters('FHEE__EEH_Template__format_currency__CNT_ISO', $CNT_ISO, $amount);
456 456
         // filter raw amount (allows 0.00 to be changed to "free" for example)
457 457
         $amount_formatted = apply_filters('FHEE__EEH_Template__format_currency__amount', $amount, $return_raw);
@@ -473,20 +473,20 @@  discard block
 block discarded – undo
473 473
                 // add currency sign
474 474
                 if ($mny->sign_b4) {
475 475
                     if ($amount >= 0) {
476
-                        $amount_formatted = $mny->sign . $amount_formatted;
476
+                        $amount_formatted = $mny->sign.$amount_formatted;
477 477
                     } else {
478
-                        $amount_formatted = '-' . $mny->sign . str_replace('-', '', $amount_formatted);
478
+                        $amount_formatted = '-'.$mny->sign.str_replace('-', '', $amount_formatted);
479 479
                     }
480 480
 
481 481
                 } else {
482
-                    $amount_formatted = $amount_formatted . $mny->sign;
482
+                    $amount_formatted = $amount_formatted.$mny->sign;
483 483
                 }
484 484
 
485 485
                 // filter to allow global setting of display_code
486 486
                 $display_code = apply_filters('FHEE__EEH_Template__format_currency__display_code', $display_code);
487 487
 
488 488
                 // add currency code ?
489
-                $amount_formatted = $display_code ? $amount_formatted . ' <span class="' . $cur_code_span_class . '">(' . $mny->code . ')</span>' : $amount_formatted;
489
+                $amount_formatted = $display_code ? $amount_formatted.' <span class="'.$cur_code_span_class.'">('.$mny->code.')</span>' : $amount_formatted;
490 490
             }
491 491
             // filter results
492 492
             $amount_formatted = apply_filters('FHEE__EEH_Template__format_currency__amount_formatted',
@@ -540,12 +540,12 @@  discard block
 block discarded – undo
540 540
             $icon_html .= $count > 1 ? '<span class="ee-composite-dashicon">' : '';
541 541
             foreach ($dashicons as $dashicon) {
542 542
                 $type = strpos($dashicon, 'ee-icon') !== false ? 'ee-icon ' : 'dashicons ';
543
-                $icon_html .= '<span class="' . $type . $dashicon . '"></span>';
543
+                $icon_html .= '<span class="'.$type.$dashicon.'"></span>';
544 544
             }
545 545
             $icon_html .= $count > 1 ? '</span>' : '';
546 546
         }
547
-        $label  = ! empty($icon) ? $icon_html . $label : $label;
548
-        $button = '<a id="' . sanitize_title_with_dashes($label) . '" href="' . esc_url($url) . '" class="' . $class . '" title="' . $title . '">' . $label . '</a>';
547
+        $label  = ! empty($icon) ? $icon_html.$label : $label;
548
+        $button = '<a id="'.sanitize_title_with_dashes($label).'" href="'.esc_url($url).'" class="'.$class.'" title="'.$title.'">'.$label.'</a>';
549 549
         return $button;
550 550
     }
551 551
 
@@ -579,11 +579,11 @@  discard block
 block discarded – undo
579 579
         $action = empty($action) ? 'default' : $action;
580 580
 
581 581
 
582
-        $help_tab_lnk = $page . '-' . $action . '-' . $help_tab_id;
582
+        $help_tab_lnk = $page.'-'.$action.'-'.$help_tab_id;
583 583
         $icon         = ! $icon_style ? ' dashicons-editor-help' : $icon_style;
584 584
         $help_text    = ! $help_text ? '' : $help_text;
585
-        return '<a id="' . $help_tab_lnk . '" class="ee-clickable dashicons espresso-help-tab-lnk ee-icon-size-22' . $icon . '" title="' . esc_attr__('Click to open the \'Help\' tab for more information about this feature.',
586
-                'event_espresso') . '" > ' . $help_text . ' </a>';
585
+        return '<a id="'.$help_tab_lnk.'" class="ee-clickable dashicons espresso-help-tab-lnk ee-icon-size-22'.$icon.'" title="'.esc_attr__('Click to open the \'Help\' tab for more information about this feature.',
586
+                'event_espresso').'" > '.$help_text.' </a>';
587 587
     }
588 588
 
589 589
 
@@ -600,11 +600,11 @@  discard block
 block discarded – undo
600 600
         $id    = $tour->get_slug();
601 601
         $stops = $tour->get_stops();
602 602
 
603
-        $content = '<ol style="display:none" id="' . $id . '">';
603
+        $content = '<ol style="display:none" id="'.$id.'">';
604 604
 
605 605
         foreach ($stops as $stop) {
606
-            $data_id    = ! empty($stop['id']) ? ' data-id="' . $stop['id'] . '"' : '';
607
-            $data_class = empty($data_id) && ! empty($stop['class']) ? ' data-class="' . $stop['class'] . '"' : '';
606
+            $data_id    = ! empty($stop['id']) ? ' data-id="'.$stop['id'].'"' : '';
607
+            $data_class = empty($data_id) && ! empty($stop['class']) ? ' data-class="'.$stop['class'].'"' : '';
608 608
 
609 609
             //if container is set to modal then let's make sure we set the options accordingly
610 610
             if (empty($data_id) && empty($data_class)) {
@@ -612,15 +612,15 @@  discard block
 block discarded – undo
612 612
                 $stop['options']['expose'] = true;
613 613
             }
614 614
 
615
-            $custom_class  = ! empty($stop['custom_class']) ? ' class="' . $stop['custom_class'] . '"' : '';
616
-            $button_text   = ! empty($stop['button_text']) ? ' data-button="' . $stop['button_text'] . '"' : '';
615
+            $custom_class  = ! empty($stop['custom_class']) ? ' class="'.$stop['custom_class'].'"' : '';
616
+            $button_text   = ! empty($stop['button_text']) ? ' data-button="'.$stop['button_text'].'"' : '';
617 617
             $inner_content = isset($stop['content']) ? $stop['content'] : '';
618 618
 
619 619
             //options
620 620
             if (isset($stop['options']) && is_array($stop['options'])) {
621 621
                 $options = ' data-options="';
622 622
                 foreach ($stop['options'] as $option => $value) {
623
-                    $options .= $option . ':' . $value . ';';
623
+                    $options .= $option.':'.$value.';';
624 624
                 }
625 625
                 $options .= '"';
626 626
             } else {
@@ -628,7 +628,7 @@  discard block
 block discarded – undo
628 628
             }
629 629
 
630 630
             //let's put all together
631
-            $content .= '<li' . $data_id . $data_class . $custom_class . $button_text . $options . '>' . $inner_content . '</li>';
631
+            $content .= '<li'.$data_id.$data_class.$custom_class.$button_text.$options.'>'.$inner_content.'</li>';
632 632
         }
633 633
 
634 634
         $content .= '</ol>';
@@ -660,24 +660,24 @@  discard block
 block discarded – undo
660 660
         $setup_array = array();
661 661
         foreach ($status_array as $item => $status) {
662 662
             $setup_array[$item] = array(
663
-                'class'  => 'ee-status-legend ee-status-legend-' . $status,
663
+                'class'  => 'ee-status-legend ee-status-legend-'.$status,
664 664
                 'desc'   => EEH_Template::pretty_status($status, false, 'sentence'),
665 665
                 'status' => $status,
666 666
             );
667 667
         }
668 668
 
669
-        $content = '<div class="ee-list-table-legend-container">' . "\n";
670
-        $content .= '<h4 class="status-legend-title">' . esc_html__('Status Legend', 'event_espresso') . '</h4>' . "\n";
671
-        $content .= '<dl class="ee-list-table-legend">' . "\n\t";
669
+        $content = '<div class="ee-list-table-legend-container">'."\n";
670
+        $content .= '<h4 class="status-legend-title">'.esc_html__('Status Legend', 'event_espresso').'</h4>'."\n";
671
+        $content .= '<dl class="ee-list-table-legend">'."\n\t";
672 672
         foreach ($setup_array as $item => $details) {
673 673
             $active_class = $active_status == $details['status'] ? ' class="ee-is-active-status"' : '';
674
-            $content .= '<dt id="ee-legend-item-tooltip-' . $item . '"' . $active_class . '>' . "\n\t\t";
675
-            $content .= '<span class="' . $details['class'] . '"></span>' . "\n\t\t";
676
-            $content .= '<span class="ee-legend-description">' . $details['desc'] . '</span>' . "\n\t";
677
-            $content .= '</dt>' . "\n";
674
+            $content .= '<dt id="ee-legend-item-tooltip-'.$item.'"'.$active_class.'>'."\n\t\t";
675
+            $content .= '<span class="'.$details['class'].'"></span>'."\n\t\t";
676
+            $content .= '<span class="ee-legend-description">'.$details['desc'].'</span>'."\n\t";
677
+            $content .= '</dt>'."\n";
678 678
         }
679
-        $content .= '</dl>' . "\n";
680
-        $content .= '</div>' . "\n";
679
+        $content .= '</dl>'."\n";
680
+        $content .= '</div>'."\n";
681 681
         return $content;
682 682
     }
683 683
 
@@ -692,7 +692,7 @@  discard block
 block discarded – undo
692 692
     public static function layout_array_as_table($data)
693 693
     {
694 694
         if (is_object($data) || $data instanceof __PHP_Incomplete_Class) {
695
-            $data = (array)$data;
695
+            $data = (array) $data;
696 696
         }
697 697
         ob_start();
698 698
         if (is_array($data)) {
@@ -793,9 +793,9 @@  discard block
 block discarded – undo
793 793
     ) {
794 794
         $page_links     = array();
795 795
         $disable_first  = $disable_last = '';
796
-        $total_items    = (int)$total_items;
797
-        $per_page       = (int)$per_page;
798
-        $current        = (int)$current;
796
+        $total_items    = (int) $total_items;
797
+        $per_page       = (int) $per_page;
798
+        $current        = (int) $current;
799 799
         $paged_arg_name = empty($paged_arg_name) ? 'paged' : sanitize_key($paged_arg_name);
800 800
 
801 801
         //filter items_label
@@ -815,8 +815,8 @@  discard block
 block discarded – undo
815 815
             );
816 816
         } else {
817 817
             $items_label = array(
818
-                'single' => '1 ' . esc_html($items_label['single']),
819
-                'plural' => '%s ' . esc_html($items_label['plural']),
818
+                'single' => '1 '.esc_html($items_label['single']),
819
+                'plural' => '%s '.esc_html($items_label['plural']),
820 820
             );
821 821
         }
822 822
 
@@ -828,7 +828,7 @@  discard block
 block discarded – undo
828 828
 
829 829
         $item_label = $total_items > 1 ? sprintf($items_label['plural'], $total_items) : $items_label['single'];
830 830
 
831
-        $output = '<span class="displaying-num">' . $item_label . '</span>';
831
+        $output = '<span class="displaying-num">'.$item_label.'</span>';
832 832
 
833 833
         if ($current === 1) {
834 834
             $disable_first = ' disabled';
@@ -838,7 +838,7 @@  discard block
 block discarded – undo
838 838
         }
839 839
 
840 840
         $page_links[] = sprintf("<a class='%s' title='%s' href='%s'>%s</a>",
841
-            'first-page' . $disable_first,
841
+            'first-page'.$disable_first,
842 842
             esc_attr__('Go to the first page'),
843 843
             esc_url(remove_query_arg($paged_arg_name, $url)),
844 844
             '&laquo;'
@@ -846,7 +846,7 @@  discard block
 block discarded – undo
846 846
 
847 847
         $page_links[] = sprintf(
848 848
             '<a class="%s" title="%s" href="%s">%s</a>',
849
-            'prev-page' . $disable_first,
849
+            'prev-page'.$disable_first,
850 850
             esc_attr__('Go to the previous page'),
851 851
             esc_url(add_query_arg($paged_arg_name, max(1, $current - 1), $url)),
852 852
             '&lsaquo;'
@@ -866,7 +866,7 @@  discard block
 block discarded – undo
866 866
             '<span class="total-pages">%s</span>',
867 867
             number_format_i18n($total_pages)
868 868
         );
869
-        $page_links[]     = sprintf(
869
+        $page_links[] = sprintf(
870 870
             _x('%3$s%1$s of %2$s%4$s', 'paging'),
871 871
             $html_current_page,
872 872
             $html_total_pages,
@@ -876,7 +876,7 @@  discard block
 block discarded – undo
876 876
 
877 877
         $page_links[] = sprintf(
878 878
             '<a class="%s" title="%s" href="%s">%s</a>',
879
-            'next-page' . $disable_last,
879
+            'next-page'.$disable_last,
880 880
             esc_attr__('Go to the next page'),
881 881
             esc_url(add_query_arg($paged_arg_name, min($total_pages, $current + 1), $url)),
882 882
             '&rsaquo;'
@@ -884,13 +884,13 @@  discard block
 block discarded – undo
884 884
 
885 885
         $page_links[] = sprintf(
886 886
             '<a class="%s" title="%s" href="%s">%s</a>',
887
-            'last-page' . $disable_last,
887
+            'last-page'.$disable_last,
888 888
             esc_attr__('Go to the last page'),
889 889
             esc_url(add_query_arg($paged_arg_name, $total_pages, $url)),
890 890
             '&raquo;'
891 891
         );
892 892
 
893
-        $output .= "\n" . '<span class="pagination-links">' . join("\n", $page_links) . '</span>';
893
+        $output .= "\n".'<span class="pagination-links">'.join("\n", $page_links).'</span>';
894 894
         // set page class
895 895
         if ($total_pages) {
896 896
             $page_class = $total_pages < 2 ? ' one-page' : '';
@@ -898,7 +898,7 @@  discard block
 block discarded – undo
898 898
             $page_class = ' no-pages';
899 899
         }
900 900
 
901
-        return '<div class="tablenav"><div class="tablenav-pages' . $page_class . '">' . $output . '</div></div>';
901
+        return '<div class="tablenav"><div class="tablenav-pages'.$page_class.'">'.$output.'</div></div>';
902 902
     }
903 903
 
904 904
 
@@ -935,10 +935,10 @@  discard block
 block discarded – undo
935 935
             $query_args
936 936
         );
937 937
         $powered_by = apply_filters('FHEE__EEH_Template__powered_by_event_espresso_text',
938
-            $admin ? 'Event Espresso - ' . EVENT_ESPRESSO_VERSION : 'Event Espresso');
938
+            $admin ? 'Event Espresso - '.EVENT_ESPRESSO_VERSION : 'Event Espresso');
939 939
         $url        = add_query_arg($query_args, 'https://eventespresso.com/');
940 940
         $url        = apply_filters('FHEE__EEH_Template__powered_by_event_espresso__url', $url);
941
-        return (string)apply_filters(
941
+        return (string) apply_filters(
942 942
             'FHEE__EEH_Template__powered_by_event_espresso__html',
943 943
             sprintf(
944 944
                 esc_html_x(
@@ -989,6 +989,6 @@  discard block
 block discarded – undo
989 989
                 'add_fragment' => '',
990 990
             )
991 991
         );
992
-        echo ! empty($pagination) ? '<div class="ee-pagination-dv ee-clear-float">' . $pagination . '</div>' : '';
992
+        echo ! empty($pagination) ? '<div class="ee-pagination-dv ee-clear-float">'.$pagination.'</div>' : '';
993 993
     }
994 994
 }
995 995
\ No newline at end of file
Please login to merge, or discard this patch.
core/libraries/payment_methods/EE_PMT_Base.lib.php 2 patches
Indentation   +718 added lines, -718 removed lines patch added patch discarded remove patch
@@ -21,724 +21,724 @@
 block discarded – undo
21 21
 abstract class EE_PMT_Base
22 22
 {
23 23
 
24
-    const onsite = 'on-site';
25
-    const offsite = 'off-site';
26
-    const offline = 'off-line';
27
-
28
-    /**
29
-     * @var EE_Payment_Method
30
-     */
31
-    protected $_pm_instance = NULL;
32
-
33
-    /**
34
-     * @var boolean
35
-     */
36
-    protected $_requires_https = FALSE;
37
-
38
-    /**
39
-     * @var boolean
40
-     */
41
-    protected $_has_billing_form;
42
-
43
-    /**
44
-     * @var EE_Gateway
45
-     */
46
-    protected $_gateway = NULL;
47
-
48
-    /**
49
-     * @var EE_Payment_Method_Form
50
-     */
51
-    protected $_settings_form = NULL;
52
-
53
-    /**
54
-     * @var EE_Form_Section_Proper
55
-     */
56
-    protected $_billing_form = NULL;
57
-
58
-    /**
59
-     * @var boolean
60
-     */
61
-    protected $_cache_billing_form = TRUE;
62
-
63
-    /**
64
-     * String of the absolute path to the folder containing this file, with a trailing slash.
65
-     * eg '/public_html/wp-site/wp-content/plugins/event-espresso/payment_methods/Invoice/'
66
-     * @var string
67
-     */
68
-    protected $_file_folder = NULL;
69
-
70
-    /**
71
-     * String to the absolute URL to this file (useful for getting its web-accessible resources
72
-     * like images, js, or css)
73
-     * @var string
74
-     */
75
-    protected $_file_url = NULL;
76
-
77
-    /**
78
-     * Pretty name for the payment method
79
-     * @var string
80
-     */
81
-    protected $_pretty_name = NULL;
82
-
83
-    /**
84
-     *
85
-     * @var string
86
-     */
87
-    protected $_default_button_url = NULL;
88
-
89
-    /**
90
-     *
91
-     * @var string
92
-     */
93
-    protected $_default_description = NULL;
94
-
95
-
96
-    /**
97
-     *
98
-     * @param EE_Payment_Method $pm_instance
99
-     * @throws EE_Error
100
-     * @return EE_PMT_Base
101
-     */
102
-    function __construct($pm_instance = NULL)
103
-    {
104
-        if ($pm_instance instanceof EE_Payment_Method) {
105
-            $this->set_instance($pm_instance);
106
-        }
107
-        if ($this->_gateway) {
108
-            $this->_gateway->set_payment_model(EEM_Payment::instance());
109
-            $this->_gateway->set_payment_log(EEM_Change_Log::instance());
110
-            $this->_gateway->set_template_helper(new EEH_Template());
111
-            $this->_gateway->set_line_item_helper(new EEH_Line_Item());
112
-            $this->_gateway->set_money_helper(new EEH_Money());
113
-            $this->_gateway->set_gateway_data_formatter(new GatewayDataFormatter());
114
-            $this->_gateway->set_unsupported_character_remover(new AsciiOnly());
115
-            do_action('AHEE__EE_PMT_Base___construct__done_initializing_gateway_class', $this, $this->_gateway);
116
-        }
117
-        if (!isset($this->_has_billing_form)) {
118
-            // by default, On Site gateways have a billing form
119
-            if ($this->payment_occurs() == EE_PMT_Base::onsite) {
120
-                $this->set_has_billing_form(true);
121
-            } else {
122
-                $this->set_has_billing_form(false);
123
-            }
124
-        }
125
-
126
-        if (!$this->_pretty_name) {
127
-            throw new EE_Error(sprintf(__("You must set the pretty name for the Payment Method Type in the constructor (_pretty_name), and please make it internationalized", "event_espresso")));
128
-        }
129
-        //if the child didn't specify a default button, use the credit card one
130
-        if ($this->_default_button_url === NULL) {
131
-            $this->_default_button_url = EE_PLUGIN_DIR_URL . 'payment_methods' . DS . 'pay-by-credit-card.png';
132
-        }
133
-    }
134
-
135
-
136
-    /**
137
-     * @param boolean $has_billing_form
138
-     */
139
-    public function set_has_billing_form($has_billing_form)
140
-    {
141
-        $this->_has_billing_form = filter_var($has_billing_form, FILTER_VALIDATE_BOOLEAN);
142
-    }
143
-
144
-
145
-    /**
146
-     * sets the file_folder property
147
-     */
148
-    protected function _set_file_folder()
149
-    {
150
-        $reflector = new ReflectionClass(get_class($this));
151
-        $fn = $reflector->getFileName();
152
-        $this->_file_folder = dirname($fn) . DS;
153
-    }
154
-
155
-
156
-    /**
157
-     * sets the file URL with a trailing slash for this PMT
158
-     */
159
-    protected function _set_file_url()
160
-    {
161
-        $plugins_dir_fixed = str_replace('\\', DS, WP_PLUGIN_DIR);
162
-        $file_folder_fixed = str_replace('\\', DS, $this->file_folder());
163
-        $file_path = str_replace($plugins_dir_fixed, WP_PLUGIN_URL, $file_folder_fixed);
164
-        $this->_file_url = $file_path;
165
-    }
166
-
167
-    /**
168
-     * Gets the default description on all payment methods of this type
169
-     * @return string
170
-     */
171
-    public function default_description()
172
-    {
173
-        return $this->_default_description;
174
-    }
175
-
176
-
177
-    /**
178
-     * Returns the folder containing the PMT child class, with a trailing slash
179
-     * @return string
180
-     */
181
-    public function file_folder()
182
-    {
183
-        if (!$this->_file_folder) {
184
-            $this->_set_file_folder();
185
-        }
186
-        return $this->_file_folder;
187
-    }
188
-
189
-
190
-    /**
191
-     * @return string
192
-     */
193
-    public function file_url()
194
-    {
195
-        if (!$this->_file_url) {
196
-            $this->_set_file_url();
197
-        }
198
-        return $this->_file_url;
199
-    }
200
-
201
-
202
-    /**
203
-     * Sets the payment method instance this payment method type is for.
204
-     * Its important teh payment method instance is set before
205
-     * @param EE_Payment_Method $payment_method_instance
206
-     */
207
-    function set_instance($payment_method_instance)
208
-    {
209
-        $this->_pm_instance = $payment_method_instance;
210
-        //if they have already requested the settings form, make sure its
211
-        //data matches this model object
212
-        if ($this->_settings_form) {
213
-            $this->settings_form()->populate_model_obj($payment_method_instance);
214
-        }
215
-        if ($this->_gateway && $this->_gateway instanceof EE_Gateway) {
216
-            $this->_gateway->set_settings($payment_method_instance->settings_array());
217
-        }
218
-    }
219
-
220
-
221
-    /**
222
-     * Gets teh form for displaying to admins where they setup the payment method
223
-     * @return EE_Payment_Method_Form
224
-     */
225
-    function settings_form()
226
-    {
227
-        if (!$this->_settings_form) {
228
-            $this->_settings_form = $this->generate_new_settings_form();
229
-            $this->_settings_form->set_payment_method_type($this);
230
-            //if we have already assigned a model object to this pmt, make
231
-            //sure its reflected in teh form we just generated
232
-            if ($this->_pm_instance) {
233
-                $this->_settings_form->populate_model_obj($this->_pm_instance);
234
-            }
235
-        }
236
-        return $this->_settings_form;
237
-    }
238
-
239
-
240
-    /**
241
-     * Gets the form for all the settings related to this payment method type
242
-     * @return EE_Payment_Method_Form
243
-     */
244
-    abstract function generate_new_settings_form();
245
-
246
-
247
-    /**
248
-     * Sets the form for settings. This may be useful if we have already received
249
-     * a form submission and have form data it in, and want to use it anytime we're showing
250
-     * this payment method type's settings form later in the request
251
-     * @param EE_Payment_Method_Form $form
252
-     */
253
-    public function set_settings_form($form)
254
-    {
255
-        $this->_settings_form = $form;
256
-    }
257
-
258
-
259
-    /**
260
-     * @return boolean
261
-     */
262
-    public function has_billing_form()
263
-    {
264
-        return $this->_has_billing_form;
265
-    }
266
-
267
-
268
-    /**
269
-     * Gets the form for displaying to attendees where they can enter their billing info
270
-     * which will be sent to teh gateway (can be null)
271
-     *
272
-     * @param \EE_Transaction $transaction
273
-     * @param array $extra_args
274
-     * @return \EE_Billing_Attendee_Info_Form|\EE_Billing_Info_Form|null
275
-     */
276
-    public function billing_form(EE_Transaction $transaction = NULL, $extra_args = array())
277
-    {
278
-        // has billing form already been regenerated ? or overwrite cache?
279
-        if (!$this->_billing_form instanceof EE_Billing_Info_Form || !$this->_cache_billing_form) {
280
-            $this->_billing_form = $this->generate_new_billing_form($transaction, $extra_args);
281
-        }
282
-        //if we know who the attendee is, and this is a billing form
283
-        //that uses attendee info, populate it
284
-        if (
285
-        apply_filters(
286
-            'FHEE__populate_billing_form_fields_from_attendee',
287
-            (
288
-                $this->_billing_form instanceof EE_Billing_Attendee_Info_Form
289
-                && $transaction instanceof EE_Transaction
290
-                && $transaction->primary_registration() instanceof EE_Registration
291
-                && $transaction->primary_registration()->attendee() instanceof EE_Attendee
292
-            ),
293
-            $this->_billing_form,
294
-            $transaction
295
-        )
296
-        ) {
297
-            $this->_billing_form->populate_from_attendee($transaction->primary_registration()->attendee());
298
-        }
299
-        return $this->_billing_form;
300
-    }
301
-
302
-
303
-    /**
304
-     * Creates the billing form for this payment method type
305
-     * @param \EE_Transaction $transaction
306
-     * @return \EE_Billing_Info_Form
307
-     */
308
-    abstract function generate_new_billing_form(EE_Transaction $transaction = NULL);
309
-
310
-
311
-    /**
312
-     * apply_billing_form_debug_settings
313
-     * applies debug data to the form
314
-     *
315
-     * @param \EE_Billing_Info_Form $billing_form
316
-     * @return \EE_Billing_Info_Form
317
-     */
318
-    public function apply_billing_form_debug_settings(EE_Billing_Info_Form $billing_form)
319
-    {
320
-        return $billing_form;
321
-    }
322
-
323
-
324
-    /**
325
-     * Sets the billing form for this payment method type. You may want to use this
326
-     * if you have form
327
-     * @param EE_Payment_Method $form
328
-     */
329
-    public function set_billing_form($form)
330
-    {
331
-        $this->_billing_form = $form;
332
-    }
333
-
334
-
335
-    /**
336
-     * Returns whether or not this payment method requires HTTPS to be used
337
-     * @return boolean
338
-     */
339
-    function requires_https()
340
-    {
341
-        return $this->_requires_https;
342
-    }
343
-
344
-
345
-    /**
346
-     *
347
-     * @param EE_Transaction $transaction
348
-     * @param float $amount
349
-     * @param EE_Billing_Info_Form $billing_info
350
-     * @param string $return_url
351
-     * @param string $fail_url
352
-     * @param string $method
353
-     * @param bool $by_admin
354
-     * @return EE_Payment
355
-     * @throws EE_Error
356
-     */
357
-    function process_payment(EE_Transaction $transaction, $amount = null, $billing_info = null, $return_url = null, $fail_url = '', $method = 'CART', $by_admin = false)
358
-    {
359
-        // @todo: add surcharge for the payment method, if any
360
-        if ($this->_gateway) {
361
-            //there is a gateway, so we're going to make a payment object
362
-            //but wait! do they already have a payment in progress that we thought was failed?
363
-            $duplicate_properties = array(
364
-                'STS_ID' => EEM_Payment::status_id_failed,
365
-                'TXN_ID' => $transaction->ID(),
366
-                'PMD_ID' => $this->_pm_instance->ID(),
367
-                'PAY_source' => $method,
368
-                'PAY_amount' => $amount !== null ? $amount : $transaction->remaining(),
369
-                'PAY_gateway_response' => null,
370
-            );
371
-            $payment = EEM_Payment::instance()->get_one(array($duplicate_properties));
372
-            //if we didn't already have a payment in progress for the same thing,
373
-            //then we actually want to make a new payment
374
-            if (!$payment instanceof EE_Payment) {
375
-                $payment = EE_Payment::new_instance(
376
-                    array_merge(
377
-                        $duplicate_properties,
378
-                        array(
379
-                            'PAY_timestamp' => time(),
380
-                            'PAY_txn_id_chq_nmbr' => null,
381
-                            'PAY_po_number' => null,
382
-                            'PAY_extra_accntng' => null,
383
-                            'PAY_details' => null,
384
-                        )
385
-                    )
386
-                );
387
-            }
388
-            //make sure the payment has been saved to show we started it, and so it has an ID should the gateway try to log it
389
-            $payment->save();
390
-            $billing_values = $this->_get_billing_values_from_form($billing_info);
391
-
392
-            //  Offsite Gateway
393
-            if ($this->_gateway instanceof EE_Offsite_Gateway) {
394
-
395
-                $payment = $this->_gateway->set_redirection_info(
396
-                    $payment,
397
-                    $billing_values,
398
-                    $return_url,
399
-                    EE_Config::instance()->core->txn_page_url(
400
-                        array(
401
-                            'e_reg_url_link' => $transaction->primary_registration()->reg_url_link(),
402
-                            'ee_payment_method' => $this->_pm_instance->slug()
403
-                        )
404
-                    ),
405
-                    $fail_url
406
-                );
407
-                $payment->save();
408
-                //  Onsite Gateway
409
-            } elseif ($this->_gateway instanceof EE_Onsite_Gateway) {
410
-
411
-                $payment = $this->_gateway->do_direct_payment($payment, $billing_values);
412
-                $payment->save();
413
-
414
-            } else {
415
-                throw new EE_Error(
416
-                    sprintf(
417
-                        __('Gateway for payment method type "%s" is "%s", not a subclass of either EE_Offsite_Gateway or EE_Onsite_Gateway, or null (to indicate NO gateway)', 'event_espresso'),
418
-                        get_class($this),
419
-                        gettype($this->_gateway)
420
-                    )
421
-                );
422
-            }
423
-
424
-        } else {
425
-            // no gateway provided
426
-            // there is no payment. Must be an offline gateway
427
-            // create a payment object anyways, but dont save it
428
-            $payment = EE_Payment::new_instance(
429
-                array(
430
-                    'STS_ID' => EEM_Payment::status_id_pending,
431
-                    'TXN_ID' => $transaction->ID(),
432
-                    'PMD_ID' => $transaction->payment_method_ID(),
433
-                    'PAY_amount' => 0.00,
434
-                    'PAY_timestamp' => time(),
435
-                )
436
-            );
437
-
438
-        }
439
-
440
-        // if there is billing info, clean it and save it now
441
-        if ($billing_info instanceof EE_Billing_Attendee_Info_Form) {
442
-            $this->_save_billing_info_to_attendee($billing_info, $transaction);
443
-        }
444
-
445
-        return $payment;
446
-    }
447
-
448
-    /**
449
-     * Gets the values we want to pass onto the gateway. Normally these
450
-     * are just the 'pretty' values, but there may be times the data may need
451
-     * a  little massaging. Proper subsections will become arrays of inputs
452
-     * @param EE_Billing_Info_Form $billing_form
453
-     * @return array
454
-     */
455
-    protected function _get_billing_values_from_form($billing_form)
456
-    {
457
-        if ($billing_form instanceof EE_Form_Section_Proper) {
458
-            return $billing_form->input_pretty_values(true);
459
-        } else {
460
-            return NULL;
461
-        }
462
-    }
463
-
464
-
465
-    /**
466
-     * Handles an instant payment notification when the transaction is known (by default).
467
-     * @param array $req_data
468
-     * @param EE_Transaction $transaction
469
-     * @return EE_Payment
470
-     * @throws EE_Error
471
-     */
472
-    public function handle_ipn($req_data, $transaction)
473
-    {
474
-        $transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
475
-        if (!$this->_gateway instanceof EE_Offsite_Gateway) {
476
-            throw new EE_Error(sprintf(__("Could not handle IPN because '%s' is not an offsite gateway", "event_espresso"), print_r($this->_gateway, TRUE)));
477
-
478
-        }
479
-        $payment = $this->_gateway->handle_payment_update($req_data, $transaction);
480
-        return $payment;
481
-    }
482
-
483
-
484
-    /**
485
-     * Saves the billing info onto the attendee of the primary registrant on this transaction, and
486
-     * cleans it first.
487
-     * @param EE_Billing_Attendee_Info_Form $billing_form
488
-     * @param EE_Transaction $transaction
489
-     * @return boolean success
490
-     */
491
-    protected function _save_billing_info_to_attendee($billing_form, $transaction)
492
-    {
493
-        if (!$transaction || !$transaction instanceof EE_Transaction) {
494
-            EE_Error::add_error(__("Cannot save billing info because no transaction was specified", "event_espresso"), __FILE__, __FUNCTION__, __LINE__);
495
-            return false;
496
-        }
497
-        $primary_reg = $transaction->primary_registration();
498
-        if (!$primary_reg) {
499
-            EE_Error::add_error(__("Cannot save billing info because the transaction has no primary registration", "event_espresso"), __FILE__, __FUNCTION__, __LINE__);
500
-            return false;
501
-        }
502
-        $attendee = $primary_reg->attendee();
503
-        if (!$attendee) {
504
-            EE_Error::add_error(__("Cannot save billing info because the transaction's primary registration has no attendee!", "event_espresso"), __FILE__, __FUNCTION__, __LINE__);
505
-            return false;
506
-        }
507
-        return $attendee->save_and_clean_billing_info_for_payment_method($billing_form, $transaction->payment_method());
508
-
509
-    }
510
-
511
-
512
-    /**
513
-     * Gets the payment this IPN is for. Children may often want to
514
-     * override this to inspect the request
515
-     * @param EE_Transaction $transaction
516
-     * @param array $req_data
517
-     * @return EE_Payment
518
-     */
519
-    protected function find_payment_for_ipn(EE_Transaction $transaction, $req_data = array())
520
-    {
521
-        return $transaction->last_payment();
522
-    }
523
-
524
-
525
-    /**
526
-     * In case generic code cannot provide the payment processor with a specific payment method
527
-     * and transaction, it will try calling this method on each activate payment method.
528
-     * If the payment method is able to identify the request as being for it, it should fetch
529
-     * the payment its for and return it. If not, it should throw an EE_Error to indicate it cannot
530
-     * handle the IPN
531
-     * @param array $req_data
532
-     * @return EE_Payment only if this payment method can find the info its needs from $req_data
533
-     * and identifies the IPN as being for this payment method (not just fo ra payment method of this type)
534
-     * @throws EE_Error
535
-     */
536
-    public function handle_unclaimed_ipn($req_data = array())
537
-    {
538
-        throw new EE_Error(sprintf(__("Payment Method '%s' cannot handle unclaimed IPNs", "event_espresso"), get_class($this)));
539
-    }
540
-
541
-
542
-    /**
543
-     * Logic to be accomplished when the payment attempt is complete.
544
-     * Most payment methods don't need to do anything at this point; but some, like Mijireh, do.
545
-     * (Mijireh is an offsite gateway which doesn't send an IPN. So when the user returns to EE from
546
-     * mijireh, this method needs to be called so the Mijireh PM can ping Mijireh to know the status
547
-     * of the payment). Fed a transaction because it's always assumed to be the last payment that
548
-     * we're dealing with. Returns that last payment (if there is one)
549
-     *
550
-     * @param EE_Transaction $transaction
551
-     * @return EE_Payment
552
-     */
553
-    public function finalize_payment_for($transaction)
554
-    {
555
-        return $transaction->last_payment();
556
-    }
557
-
558
-
559
-    /**
560
-     * Whether or not this payment method's gateway supports sending refund requests
561
-     * @return boolean
562
-     */
563
-    public function supports_sending_refunds()
564
-    {
565
-        if ($this->_gateway && $this->_gateway instanceof EE_Gateway) {
566
-            return $this->_gateway->supports_sending_refunds();
567
-        } else {
568
-            return false;
569
-        }
570
-    }
571
-
572
-
573
-    /**
574
-     *
575
-     * @param EE_Payment $payment
576
-     * @param array $refund_info
577
-     * @throws EE_Error
578
-     * @return EE_Payment
579
-     */
580
-    public function process_refund(EE_Payment $payment, $refund_info = array())
581
-    {
582
-        if ($this->_gateway && $this->_gateway instanceof EE_Gateway) {
583
-            return $this->_gateway->do_direct_refund($payment, $refund_info);
584
-        } else {
585
-            throw new EE_Error(
586
-                sprintf(
587
-                    __('Payment Method Type "%s" does not support sending refund requests', 'event_espresso'),
588
-                    get_class($this)
589
-                )
590
-            );
591
-        }
592
-    }
593
-
594
-
595
-    /**
596
-     * Returns one the class's constants onsite,offsite, or offline, depending on this
597
-     * payment method's gateway.
598
-     * @return string
599
-     * @throws EE_Error
600
-     */
601
-    public function payment_occurs()
602
-    {
603
-        if (!$this->_gateway) {
604
-            return EE_PMT_Base::offline;
605
-        } elseif ($this->_gateway instanceof EE_Onsite_Gateway) {
606
-            return EE_PMT_Base::onsite;
607
-        } elseif ($this->_gateway instanceof EE_Offsite_Gateway) {
608
-            return EE_PMT_Base::offsite;
609
-        } else {
610
-            throw new EE_Error(sprintf(__("Payment method type '%s's gateway isn't an instance of EE_Onsite_Gateway, EE_Offsite_Gateway, or null. It must be one of those", "event_espresso"), get_class($this)));
611
-        }
612
-    }
613
-
614
-
615
-    /**
616
-     * For adding any html output ab ove the payment overview.
617
-     * Many gateways won't want ot display anything, so this function just returns an empty string.
618
-     * Other gateways may want to override this, such as offline gateways.
619
-     * @param EE_Payment $payment
620
-     * @return string
621
-     */
622
-    public function payment_overview_content(EE_Payment $payment)
623
-    {
624
-        return EEH_Template::display_template(EE_LIBRARIES . 'payment_methods' . DS . 'templates' . DS . 'payment_details_content.template.php', array('payment_method' => $this->_pm_instance, 'payment' => $payment), true);
625
-    }
626
-
627
-
628
-    /**
629
-     * @return array where keys are the help tab name,
630
-     * values are: array {
631
-     * @type string $title i18n name for the help tab
632
-     * @type string $filename name of the file located in ./help_tabs/ (ie, in a folder next to this file)
633
-     * @type array $template_args any arguments you want passed to the template file while rendering.
634
-     *                Keys will be variable names and values with be their values.
635
-     */
636
-    public function help_tabs_config()
637
-    {
638
-        return array();
639
-    }
640
-
641
-
642
-    /**
643
-     * The system name for this PMT (eg AIM, Paypal_Pro, Invoice... what gets put into
644
-     * the payment method's table's PMT_type column)
645
-     * @return string
646
-     */
647
-    public function system_name()
648
-    {
649
-        $classname = get_class($this);
650
-        return str_replace("EE_PMT_", '', $classname);
651
-    }
652
-
653
-
654
-    /**
655
-     * A pretty i18n version of the PMT name
656
-     * @return string
657
-     */
658
-    public function pretty_name()
659
-    {
660
-        return $this->_pretty_name;
661
-    }
662
-
663
-
664
-    /**
665
-     * Gets the default absolute URL to the payment method type's button
666
-     * @return string
667
-     */
668
-    public function default_button_url()
669
-    {
670
-        return $this->_default_button_url;
671
-    }
672
-
673
-
674
-    /**
675
-     * Gets the gateway used by this payment method (if any)
676
-     * @return EE_Gateway
677
-     */
678
-    public function get_gateway()
679
-    {
680
-        return $this->_gateway;
681
-    }
682
-
683
-
684
-    /**
685
-     * @return string html for the link to a help tab
686
-     */
687
-    public function get_help_tab_link()
688
-    {
689
-        return EEH_Template::get_help_tab_link($this->get_help_tab_name());
690
-    }
691
-
692
-
693
-    /**
694
-     * Returns the name of the help tab for this PMT
695
-     * @return string
696
-     */
697
-    public function get_help_tab_name()
698
-    {
699
-        return 'ee_' . strtolower($this->system_name()) . '_help_tab';
700
-    }
701
-
702
-    /**
703
-     * The name of the wp capability that should be associated with the usage of
704
-     * this PMT by an admin
705
-     * @return string
706
-     */
707
-    public function cap_name()
708
-    {
709
-        return 'ee_payment_method_' . strtolower($this->system_name());
710
-    }
711
-
712
-    /**
713
-     * Called by client code to tell the gateway that if it wants to change
714
-     * the transaction or line items or registrations related to teh payment it already
715
-     * processed (we think, but possibly not) that now's the time to do it.
716
-     * It is expected that gateways will store any info they need for this on the PAY_details,
717
-     * or maybe an extra meta value
718
-     * @param EE_Payment $payment
719
-     * @return void
720
-     */
721
-    public function update_txn_based_on_payment($payment)
722
-    {
723
-        if ($this->_gateway instanceof EE_Gateway) {
724
-            $this->_gateway->update_txn_based_on_payment($payment);
725
-        }
726
-    }
727
-
728
-    /**
729
-     * Returns a string of HTML describing this payment method type for an admin,
730
-     * primarily intended for them to read before activating it.
731
-     * The easiest way to set this is to create a folder 'templates' alongside
732
-     * your EE_PMT_{System_Name} file, and in it create a file named "{system_name}_intro.template.php".
733
-     * Eg, if your payment method file is named "EE_PMT_Foo_Bar.pm.php",
734
-     * then you'd create a file named "templates" in the same folder as it, and name the file
735
-     * "foo_bar_intro.template.php", and its content will be returned by this method
736
-     * @return string
737
-     */
738
-    public function introductory_html()
739
-    {
740
-        return EEH_Template::locate_template($this->file_folder() . 'templates' . DS . strtolower($this->system_name()) . '_intro.template.php', array('pmt_obj' => $this, 'pm_instance' => $this->_pm_instance));
741
-    }
24
+	const onsite = 'on-site';
25
+	const offsite = 'off-site';
26
+	const offline = 'off-line';
27
+
28
+	/**
29
+	 * @var EE_Payment_Method
30
+	 */
31
+	protected $_pm_instance = NULL;
32
+
33
+	/**
34
+	 * @var boolean
35
+	 */
36
+	protected $_requires_https = FALSE;
37
+
38
+	/**
39
+	 * @var boolean
40
+	 */
41
+	protected $_has_billing_form;
42
+
43
+	/**
44
+	 * @var EE_Gateway
45
+	 */
46
+	protected $_gateway = NULL;
47
+
48
+	/**
49
+	 * @var EE_Payment_Method_Form
50
+	 */
51
+	protected $_settings_form = NULL;
52
+
53
+	/**
54
+	 * @var EE_Form_Section_Proper
55
+	 */
56
+	protected $_billing_form = NULL;
57
+
58
+	/**
59
+	 * @var boolean
60
+	 */
61
+	protected $_cache_billing_form = TRUE;
62
+
63
+	/**
64
+	 * String of the absolute path to the folder containing this file, with a trailing slash.
65
+	 * eg '/public_html/wp-site/wp-content/plugins/event-espresso/payment_methods/Invoice/'
66
+	 * @var string
67
+	 */
68
+	protected $_file_folder = NULL;
69
+
70
+	/**
71
+	 * String to the absolute URL to this file (useful for getting its web-accessible resources
72
+	 * like images, js, or css)
73
+	 * @var string
74
+	 */
75
+	protected $_file_url = NULL;
76
+
77
+	/**
78
+	 * Pretty name for the payment method
79
+	 * @var string
80
+	 */
81
+	protected $_pretty_name = NULL;
82
+
83
+	/**
84
+	 *
85
+	 * @var string
86
+	 */
87
+	protected $_default_button_url = NULL;
88
+
89
+	/**
90
+	 *
91
+	 * @var string
92
+	 */
93
+	protected $_default_description = NULL;
94
+
95
+
96
+	/**
97
+	 *
98
+	 * @param EE_Payment_Method $pm_instance
99
+	 * @throws EE_Error
100
+	 * @return EE_PMT_Base
101
+	 */
102
+	function __construct($pm_instance = NULL)
103
+	{
104
+		if ($pm_instance instanceof EE_Payment_Method) {
105
+			$this->set_instance($pm_instance);
106
+		}
107
+		if ($this->_gateway) {
108
+			$this->_gateway->set_payment_model(EEM_Payment::instance());
109
+			$this->_gateway->set_payment_log(EEM_Change_Log::instance());
110
+			$this->_gateway->set_template_helper(new EEH_Template());
111
+			$this->_gateway->set_line_item_helper(new EEH_Line_Item());
112
+			$this->_gateway->set_money_helper(new EEH_Money());
113
+			$this->_gateway->set_gateway_data_formatter(new GatewayDataFormatter());
114
+			$this->_gateway->set_unsupported_character_remover(new AsciiOnly());
115
+			do_action('AHEE__EE_PMT_Base___construct__done_initializing_gateway_class', $this, $this->_gateway);
116
+		}
117
+		if (!isset($this->_has_billing_form)) {
118
+			// by default, On Site gateways have a billing form
119
+			if ($this->payment_occurs() == EE_PMT_Base::onsite) {
120
+				$this->set_has_billing_form(true);
121
+			} else {
122
+				$this->set_has_billing_form(false);
123
+			}
124
+		}
125
+
126
+		if (!$this->_pretty_name) {
127
+			throw new EE_Error(sprintf(__("You must set the pretty name for the Payment Method Type in the constructor (_pretty_name), and please make it internationalized", "event_espresso")));
128
+		}
129
+		//if the child didn't specify a default button, use the credit card one
130
+		if ($this->_default_button_url === NULL) {
131
+			$this->_default_button_url = EE_PLUGIN_DIR_URL . 'payment_methods' . DS . 'pay-by-credit-card.png';
132
+		}
133
+	}
134
+
135
+
136
+	/**
137
+	 * @param boolean $has_billing_form
138
+	 */
139
+	public function set_has_billing_form($has_billing_form)
140
+	{
141
+		$this->_has_billing_form = filter_var($has_billing_form, FILTER_VALIDATE_BOOLEAN);
142
+	}
143
+
144
+
145
+	/**
146
+	 * sets the file_folder property
147
+	 */
148
+	protected function _set_file_folder()
149
+	{
150
+		$reflector = new ReflectionClass(get_class($this));
151
+		$fn = $reflector->getFileName();
152
+		$this->_file_folder = dirname($fn) . DS;
153
+	}
154
+
155
+
156
+	/**
157
+	 * sets the file URL with a trailing slash for this PMT
158
+	 */
159
+	protected function _set_file_url()
160
+	{
161
+		$plugins_dir_fixed = str_replace('\\', DS, WP_PLUGIN_DIR);
162
+		$file_folder_fixed = str_replace('\\', DS, $this->file_folder());
163
+		$file_path = str_replace($plugins_dir_fixed, WP_PLUGIN_URL, $file_folder_fixed);
164
+		$this->_file_url = $file_path;
165
+	}
166
+
167
+	/**
168
+	 * Gets the default description on all payment methods of this type
169
+	 * @return string
170
+	 */
171
+	public function default_description()
172
+	{
173
+		return $this->_default_description;
174
+	}
175
+
176
+
177
+	/**
178
+	 * Returns the folder containing the PMT child class, with a trailing slash
179
+	 * @return string
180
+	 */
181
+	public function file_folder()
182
+	{
183
+		if (!$this->_file_folder) {
184
+			$this->_set_file_folder();
185
+		}
186
+		return $this->_file_folder;
187
+	}
188
+
189
+
190
+	/**
191
+	 * @return string
192
+	 */
193
+	public function file_url()
194
+	{
195
+		if (!$this->_file_url) {
196
+			$this->_set_file_url();
197
+		}
198
+		return $this->_file_url;
199
+	}
200
+
201
+
202
+	/**
203
+	 * Sets the payment method instance this payment method type is for.
204
+	 * Its important teh payment method instance is set before
205
+	 * @param EE_Payment_Method $payment_method_instance
206
+	 */
207
+	function set_instance($payment_method_instance)
208
+	{
209
+		$this->_pm_instance = $payment_method_instance;
210
+		//if they have already requested the settings form, make sure its
211
+		//data matches this model object
212
+		if ($this->_settings_form) {
213
+			$this->settings_form()->populate_model_obj($payment_method_instance);
214
+		}
215
+		if ($this->_gateway && $this->_gateway instanceof EE_Gateway) {
216
+			$this->_gateway->set_settings($payment_method_instance->settings_array());
217
+		}
218
+	}
219
+
220
+
221
+	/**
222
+	 * Gets teh form for displaying to admins where they setup the payment method
223
+	 * @return EE_Payment_Method_Form
224
+	 */
225
+	function settings_form()
226
+	{
227
+		if (!$this->_settings_form) {
228
+			$this->_settings_form = $this->generate_new_settings_form();
229
+			$this->_settings_form->set_payment_method_type($this);
230
+			//if we have already assigned a model object to this pmt, make
231
+			//sure its reflected in teh form we just generated
232
+			if ($this->_pm_instance) {
233
+				$this->_settings_form->populate_model_obj($this->_pm_instance);
234
+			}
235
+		}
236
+		return $this->_settings_form;
237
+	}
238
+
239
+
240
+	/**
241
+	 * Gets the form for all the settings related to this payment method type
242
+	 * @return EE_Payment_Method_Form
243
+	 */
244
+	abstract function generate_new_settings_form();
245
+
246
+
247
+	/**
248
+	 * Sets the form for settings. This may be useful if we have already received
249
+	 * a form submission and have form data it in, and want to use it anytime we're showing
250
+	 * this payment method type's settings form later in the request
251
+	 * @param EE_Payment_Method_Form $form
252
+	 */
253
+	public function set_settings_form($form)
254
+	{
255
+		$this->_settings_form = $form;
256
+	}
257
+
258
+
259
+	/**
260
+	 * @return boolean
261
+	 */
262
+	public function has_billing_form()
263
+	{
264
+		return $this->_has_billing_form;
265
+	}
266
+
267
+
268
+	/**
269
+	 * Gets the form for displaying to attendees where they can enter their billing info
270
+	 * which will be sent to teh gateway (can be null)
271
+	 *
272
+	 * @param \EE_Transaction $transaction
273
+	 * @param array $extra_args
274
+	 * @return \EE_Billing_Attendee_Info_Form|\EE_Billing_Info_Form|null
275
+	 */
276
+	public function billing_form(EE_Transaction $transaction = NULL, $extra_args = array())
277
+	{
278
+		// has billing form already been regenerated ? or overwrite cache?
279
+		if (!$this->_billing_form instanceof EE_Billing_Info_Form || !$this->_cache_billing_form) {
280
+			$this->_billing_form = $this->generate_new_billing_form($transaction, $extra_args);
281
+		}
282
+		//if we know who the attendee is, and this is a billing form
283
+		//that uses attendee info, populate it
284
+		if (
285
+		apply_filters(
286
+			'FHEE__populate_billing_form_fields_from_attendee',
287
+			(
288
+				$this->_billing_form instanceof EE_Billing_Attendee_Info_Form
289
+				&& $transaction instanceof EE_Transaction
290
+				&& $transaction->primary_registration() instanceof EE_Registration
291
+				&& $transaction->primary_registration()->attendee() instanceof EE_Attendee
292
+			),
293
+			$this->_billing_form,
294
+			$transaction
295
+		)
296
+		) {
297
+			$this->_billing_form->populate_from_attendee($transaction->primary_registration()->attendee());
298
+		}
299
+		return $this->_billing_form;
300
+	}
301
+
302
+
303
+	/**
304
+	 * Creates the billing form for this payment method type
305
+	 * @param \EE_Transaction $transaction
306
+	 * @return \EE_Billing_Info_Form
307
+	 */
308
+	abstract function generate_new_billing_form(EE_Transaction $transaction = NULL);
309
+
310
+
311
+	/**
312
+	 * apply_billing_form_debug_settings
313
+	 * applies debug data to the form
314
+	 *
315
+	 * @param \EE_Billing_Info_Form $billing_form
316
+	 * @return \EE_Billing_Info_Form
317
+	 */
318
+	public function apply_billing_form_debug_settings(EE_Billing_Info_Form $billing_form)
319
+	{
320
+		return $billing_form;
321
+	}
322
+
323
+
324
+	/**
325
+	 * Sets the billing form for this payment method type. You may want to use this
326
+	 * if you have form
327
+	 * @param EE_Payment_Method $form
328
+	 */
329
+	public function set_billing_form($form)
330
+	{
331
+		$this->_billing_form = $form;
332
+	}
333
+
334
+
335
+	/**
336
+	 * Returns whether or not this payment method requires HTTPS to be used
337
+	 * @return boolean
338
+	 */
339
+	function requires_https()
340
+	{
341
+		return $this->_requires_https;
342
+	}
343
+
344
+
345
+	/**
346
+	 *
347
+	 * @param EE_Transaction $transaction
348
+	 * @param float $amount
349
+	 * @param EE_Billing_Info_Form $billing_info
350
+	 * @param string $return_url
351
+	 * @param string $fail_url
352
+	 * @param string $method
353
+	 * @param bool $by_admin
354
+	 * @return EE_Payment
355
+	 * @throws EE_Error
356
+	 */
357
+	function process_payment(EE_Transaction $transaction, $amount = null, $billing_info = null, $return_url = null, $fail_url = '', $method = 'CART', $by_admin = false)
358
+	{
359
+		// @todo: add surcharge for the payment method, if any
360
+		if ($this->_gateway) {
361
+			//there is a gateway, so we're going to make a payment object
362
+			//but wait! do they already have a payment in progress that we thought was failed?
363
+			$duplicate_properties = array(
364
+				'STS_ID' => EEM_Payment::status_id_failed,
365
+				'TXN_ID' => $transaction->ID(),
366
+				'PMD_ID' => $this->_pm_instance->ID(),
367
+				'PAY_source' => $method,
368
+				'PAY_amount' => $amount !== null ? $amount : $transaction->remaining(),
369
+				'PAY_gateway_response' => null,
370
+			);
371
+			$payment = EEM_Payment::instance()->get_one(array($duplicate_properties));
372
+			//if we didn't already have a payment in progress for the same thing,
373
+			//then we actually want to make a new payment
374
+			if (!$payment instanceof EE_Payment) {
375
+				$payment = EE_Payment::new_instance(
376
+					array_merge(
377
+						$duplicate_properties,
378
+						array(
379
+							'PAY_timestamp' => time(),
380
+							'PAY_txn_id_chq_nmbr' => null,
381
+							'PAY_po_number' => null,
382
+							'PAY_extra_accntng' => null,
383
+							'PAY_details' => null,
384
+						)
385
+					)
386
+				);
387
+			}
388
+			//make sure the payment has been saved to show we started it, and so it has an ID should the gateway try to log it
389
+			$payment->save();
390
+			$billing_values = $this->_get_billing_values_from_form($billing_info);
391
+
392
+			//  Offsite Gateway
393
+			if ($this->_gateway instanceof EE_Offsite_Gateway) {
394
+
395
+				$payment = $this->_gateway->set_redirection_info(
396
+					$payment,
397
+					$billing_values,
398
+					$return_url,
399
+					EE_Config::instance()->core->txn_page_url(
400
+						array(
401
+							'e_reg_url_link' => $transaction->primary_registration()->reg_url_link(),
402
+							'ee_payment_method' => $this->_pm_instance->slug()
403
+						)
404
+					),
405
+					$fail_url
406
+				);
407
+				$payment->save();
408
+				//  Onsite Gateway
409
+			} elseif ($this->_gateway instanceof EE_Onsite_Gateway) {
410
+
411
+				$payment = $this->_gateway->do_direct_payment($payment, $billing_values);
412
+				$payment->save();
413
+
414
+			} else {
415
+				throw new EE_Error(
416
+					sprintf(
417
+						__('Gateway for payment method type "%s" is "%s", not a subclass of either EE_Offsite_Gateway or EE_Onsite_Gateway, or null (to indicate NO gateway)', 'event_espresso'),
418
+						get_class($this),
419
+						gettype($this->_gateway)
420
+					)
421
+				);
422
+			}
423
+
424
+		} else {
425
+			// no gateway provided
426
+			// there is no payment. Must be an offline gateway
427
+			// create a payment object anyways, but dont save it
428
+			$payment = EE_Payment::new_instance(
429
+				array(
430
+					'STS_ID' => EEM_Payment::status_id_pending,
431
+					'TXN_ID' => $transaction->ID(),
432
+					'PMD_ID' => $transaction->payment_method_ID(),
433
+					'PAY_amount' => 0.00,
434
+					'PAY_timestamp' => time(),
435
+				)
436
+			);
437
+
438
+		}
439
+
440
+		// if there is billing info, clean it and save it now
441
+		if ($billing_info instanceof EE_Billing_Attendee_Info_Form) {
442
+			$this->_save_billing_info_to_attendee($billing_info, $transaction);
443
+		}
444
+
445
+		return $payment;
446
+	}
447
+
448
+	/**
449
+	 * Gets the values we want to pass onto the gateway. Normally these
450
+	 * are just the 'pretty' values, but there may be times the data may need
451
+	 * a  little massaging. Proper subsections will become arrays of inputs
452
+	 * @param EE_Billing_Info_Form $billing_form
453
+	 * @return array
454
+	 */
455
+	protected function _get_billing_values_from_form($billing_form)
456
+	{
457
+		if ($billing_form instanceof EE_Form_Section_Proper) {
458
+			return $billing_form->input_pretty_values(true);
459
+		} else {
460
+			return NULL;
461
+		}
462
+	}
463
+
464
+
465
+	/**
466
+	 * Handles an instant payment notification when the transaction is known (by default).
467
+	 * @param array $req_data
468
+	 * @param EE_Transaction $transaction
469
+	 * @return EE_Payment
470
+	 * @throws EE_Error
471
+	 */
472
+	public function handle_ipn($req_data, $transaction)
473
+	{
474
+		$transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
475
+		if (!$this->_gateway instanceof EE_Offsite_Gateway) {
476
+			throw new EE_Error(sprintf(__("Could not handle IPN because '%s' is not an offsite gateway", "event_espresso"), print_r($this->_gateway, TRUE)));
477
+
478
+		}
479
+		$payment = $this->_gateway->handle_payment_update($req_data, $transaction);
480
+		return $payment;
481
+	}
482
+
483
+
484
+	/**
485
+	 * Saves the billing info onto the attendee of the primary registrant on this transaction, and
486
+	 * cleans it first.
487
+	 * @param EE_Billing_Attendee_Info_Form $billing_form
488
+	 * @param EE_Transaction $transaction
489
+	 * @return boolean success
490
+	 */
491
+	protected function _save_billing_info_to_attendee($billing_form, $transaction)
492
+	{
493
+		if (!$transaction || !$transaction instanceof EE_Transaction) {
494
+			EE_Error::add_error(__("Cannot save billing info because no transaction was specified", "event_espresso"), __FILE__, __FUNCTION__, __LINE__);
495
+			return false;
496
+		}
497
+		$primary_reg = $transaction->primary_registration();
498
+		if (!$primary_reg) {
499
+			EE_Error::add_error(__("Cannot save billing info because the transaction has no primary registration", "event_espresso"), __FILE__, __FUNCTION__, __LINE__);
500
+			return false;
501
+		}
502
+		$attendee = $primary_reg->attendee();
503
+		if (!$attendee) {
504
+			EE_Error::add_error(__("Cannot save billing info because the transaction's primary registration has no attendee!", "event_espresso"), __FILE__, __FUNCTION__, __LINE__);
505
+			return false;
506
+		}
507
+		return $attendee->save_and_clean_billing_info_for_payment_method($billing_form, $transaction->payment_method());
508
+
509
+	}
510
+
511
+
512
+	/**
513
+	 * Gets the payment this IPN is for. Children may often want to
514
+	 * override this to inspect the request
515
+	 * @param EE_Transaction $transaction
516
+	 * @param array $req_data
517
+	 * @return EE_Payment
518
+	 */
519
+	protected function find_payment_for_ipn(EE_Transaction $transaction, $req_data = array())
520
+	{
521
+		return $transaction->last_payment();
522
+	}
523
+
524
+
525
+	/**
526
+	 * In case generic code cannot provide the payment processor with a specific payment method
527
+	 * and transaction, it will try calling this method on each activate payment method.
528
+	 * If the payment method is able to identify the request as being for it, it should fetch
529
+	 * the payment its for and return it. If not, it should throw an EE_Error to indicate it cannot
530
+	 * handle the IPN
531
+	 * @param array $req_data
532
+	 * @return EE_Payment only if this payment method can find the info its needs from $req_data
533
+	 * and identifies the IPN as being for this payment method (not just fo ra payment method of this type)
534
+	 * @throws EE_Error
535
+	 */
536
+	public function handle_unclaimed_ipn($req_data = array())
537
+	{
538
+		throw new EE_Error(sprintf(__("Payment Method '%s' cannot handle unclaimed IPNs", "event_espresso"), get_class($this)));
539
+	}
540
+
541
+
542
+	/**
543
+	 * Logic to be accomplished when the payment attempt is complete.
544
+	 * Most payment methods don't need to do anything at this point; but some, like Mijireh, do.
545
+	 * (Mijireh is an offsite gateway which doesn't send an IPN. So when the user returns to EE from
546
+	 * mijireh, this method needs to be called so the Mijireh PM can ping Mijireh to know the status
547
+	 * of the payment). Fed a transaction because it's always assumed to be the last payment that
548
+	 * we're dealing with. Returns that last payment (if there is one)
549
+	 *
550
+	 * @param EE_Transaction $transaction
551
+	 * @return EE_Payment
552
+	 */
553
+	public function finalize_payment_for($transaction)
554
+	{
555
+		return $transaction->last_payment();
556
+	}
557
+
558
+
559
+	/**
560
+	 * Whether or not this payment method's gateway supports sending refund requests
561
+	 * @return boolean
562
+	 */
563
+	public function supports_sending_refunds()
564
+	{
565
+		if ($this->_gateway && $this->_gateway instanceof EE_Gateway) {
566
+			return $this->_gateway->supports_sending_refunds();
567
+		} else {
568
+			return false;
569
+		}
570
+	}
571
+
572
+
573
+	/**
574
+	 *
575
+	 * @param EE_Payment $payment
576
+	 * @param array $refund_info
577
+	 * @throws EE_Error
578
+	 * @return EE_Payment
579
+	 */
580
+	public function process_refund(EE_Payment $payment, $refund_info = array())
581
+	{
582
+		if ($this->_gateway && $this->_gateway instanceof EE_Gateway) {
583
+			return $this->_gateway->do_direct_refund($payment, $refund_info);
584
+		} else {
585
+			throw new EE_Error(
586
+				sprintf(
587
+					__('Payment Method Type "%s" does not support sending refund requests', 'event_espresso'),
588
+					get_class($this)
589
+				)
590
+			);
591
+		}
592
+	}
593
+
594
+
595
+	/**
596
+	 * Returns one the class's constants onsite,offsite, or offline, depending on this
597
+	 * payment method's gateway.
598
+	 * @return string
599
+	 * @throws EE_Error
600
+	 */
601
+	public function payment_occurs()
602
+	{
603
+		if (!$this->_gateway) {
604
+			return EE_PMT_Base::offline;
605
+		} elseif ($this->_gateway instanceof EE_Onsite_Gateway) {
606
+			return EE_PMT_Base::onsite;
607
+		} elseif ($this->_gateway instanceof EE_Offsite_Gateway) {
608
+			return EE_PMT_Base::offsite;
609
+		} else {
610
+			throw new EE_Error(sprintf(__("Payment method type '%s's gateway isn't an instance of EE_Onsite_Gateway, EE_Offsite_Gateway, or null. It must be one of those", "event_espresso"), get_class($this)));
611
+		}
612
+	}
613
+
614
+
615
+	/**
616
+	 * For adding any html output ab ove the payment overview.
617
+	 * Many gateways won't want ot display anything, so this function just returns an empty string.
618
+	 * Other gateways may want to override this, such as offline gateways.
619
+	 * @param EE_Payment $payment
620
+	 * @return string
621
+	 */
622
+	public function payment_overview_content(EE_Payment $payment)
623
+	{
624
+		return EEH_Template::display_template(EE_LIBRARIES . 'payment_methods' . DS . 'templates' . DS . 'payment_details_content.template.php', array('payment_method' => $this->_pm_instance, 'payment' => $payment), true);
625
+	}
626
+
627
+
628
+	/**
629
+	 * @return array where keys are the help tab name,
630
+	 * values are: array {
631
+	 * @type string $title i18n name for the help tab
632
+	 * @type string $filename name of the file located in ./help_tabs/ (ie, in a folder next to this file)
633
+	 * @type array $template_args any arguments you want passed to the template file while rendering.
634
+	 *                Keys will be variable names and values with be their values.
635
+	 */
636
+	public function help_tabs_config()
637
+	{
638
+		return array();
639
+	}
640
+
641
+
642
+	/**
643
+	 * The system name for this PMT (eg AIM, Paypal_Pro, Invoice... what gets put into
644
+	 * the payment method's table's PMT_type column)
645
+	 * @return string
646
+	 */
647
+	public function system_name()
648
+	{
649
+		$classname = get_class($this);
650
+		return str_replace("EE_PMT_", '', $classname);
651
+	}
652
+
653
+
654
+	/**
655
+	 * A pretty i18n version of the PMT name
656
+	 * @return string
657
+	 */
658
+	public function pretty_name()
659
+	{
660
+		return $this->_pretty_name;
661
+	}
662
+
663
+
664
+	/**
665
+	 * Gets the default absolute URL to the payment method type's button
666
+	 * @return string
667
+	 */
668
+	public function default_button_url()
669
+	{
670
+		return $this->_default_button_url;
671
+	}
672
+
673
+
674
+	/**
675
+	 * Gets the gateway used by this payment method (if any)
676
+	 * @return EE_Gateway
677
+	 */
678
+	public function get_gateway()
679
+	{
680
+		return $this->_gateway;
681
+	}
682
+
683
+
684
+	/**
685
+	 * @return string html for the link to a help tab
686
+	 */
687
+	public function get_help_tab_link()
688
+	{
689
+		return EEH_Template::get_help_tab_link($this->get_help_tab_name());
690
+	}
691
+
692
+
693
+	/**
694
+	 * Returns the name of the help tab for this PMT
695
+	 * @return string
696
+	 */
697
+	public function get_help_tab_name()
698
+	{
699
+		return 'ee_' . strtolower($this->system_name()) . '_help_tab';
700
+	}
701
+
702
+	/**
703
+	 * The name of the wp capability that should be associated with the usage of
704
+	 * this PMT by an admin
705
+	 * @return string
706
+	 */
707
+	public function cap_name()
708
+	{
709
+		return 'ee_payment_method_' . strtolower($this->system_name());
710
+	}
711
+
712
+	/**
713
+	 * Called by client code to tell the gateway that if it wants to change
714
+	 * the transaction or line items or registrations related to teh payment it already
715
+	 * processed (we think, but possibly not) that now's the time to do it.
716
+	 * It is expected that gateways will store any info they need for this on the PAY_details,
717
+	 * or maybe an extra meta value
718
+	 * @param EE_Payment $payment
719
+	 * @return void
720
+	 */
721
+	public function update_txn_based_on_payment($payment)
722
+	{
723
+		if ($this->_gateway instanceof EE_Gateway) {
724
+			$this->_gateway->update_txn_based_on_payment($payment);
725
+		}
726
+	}
727
+
728
+	/**
729
+	 * Returns a string of HTML describing this payment method type for an admin,
730
+	 * primarily intended for them to read before activating it.
731
+	 * The easiest way to set this is to create a folder 'templates' alongside
732
+	 * your EE_PMT_{System_Name} file, and in it create a file named "{system_name}_intro.template.php".
733
+	 * Eg, if your payment method file is named "EE_PMT_Foo_Bar.pm.php",
734
+	 * then you'd create a file named "templates" in the same folder as it, and name the file
735
+	 * "foo_bar_intro.template.php", and its content will be returned by this method
736
+	 * @return string
737
+	 */
738
+	public function introductory_html()
739
+	{
740
+		return EEH_Template::locate_template($this->file_folder() . 'templates' . DS . strtolower($this->system_name()) . '_intro.template.php', array('pmt_obj' => $this, 'pm_instance' => $this->_pm_instance));
741
+	}
742 742
 
743 743
 
744 744
 }
Please login to merge, or discard this patch.
Spacing   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -114,7 +114,7 @@  discard block
 block discarded – undo
114 114
             $this->_gateway->set_unsupported_character_remover(new AsciiOnly());
115 115
             do_action('AHEE__EE_PMT_Base___construct__done_initializing_gateway_class', $this, $this->_gateway);
116 116
         }
117
-        if (!isset($this->_has_billing_form)) {
117
+        if ( ! isset($this->_has_billing_form)) {
118 118
             // by default, On Site gateways have a billing form
119 119
             if ($this->payment_occurs() == EE_PMT_Base::onsite) {
120 120
                 $this->set_has_billing_form(true);
@@ -123,12 +123,12 @@  discard block
 block discarded – undo
123 123
             }
124 124
         }
125 125
 
126
-        if (!$this->_pretty_name) {
126
+        if ( ! $this->_pretty_name) {
127 127
             throw new EE_Error(sprintf(__("You must set the pretty name for the Payment Method Type in the constructor (_pretty_name), and please make it internationalized", "event_espresso")));
128 128
         }
129 129
         //if the child didn't specify a default button, use the credit card one
130 130
         if ($this->_default_button_url === NULL) {
131
-            $this->_default_button_url = EE_PLUGIN_DIR_URL . 'payment_methods' . DS . 'pay-by-credit-card.png';
131
+            $this->_default_button_url = EE_PLUGIN_DIR_URL.'payment_methods'.DS.'pay-by-credit-card.png';
132 132
         }
133 133
     }
134 134
 
@@ -149,7 +149,7 @@  discard block
 block discarded – undo
149 149
     {
150 150
         $reflector = new ReflectionClass(get_class($this));
151 151
         $fn = $reflector->getFileName();
152
-        $this->_file_folder = dirname($fn) . DS;
152
+        $this->_file_folder = dirname($fn).DS;
153 153
     }
154 154
 
155 155
 
@@ -180,7 +180,7 @@  discard block
 block discarded – undo
180 180
      */
181 181
     public function file_folder()
182 182
     {
183
-        if (!$this->_file_folder) {
183
+        if ( ! $this->_file_folder) {
184 184
             $this->_set_file_folder();
185 185
         }
186 186
         return $this->_file_folder;
@@ -192,7 +192,7 @@  discard block
 block discarded – undo
192 192
      */
193 193
     public function file_url()
194 194
     {
195
-        if (!$this->_file_url) {
195
+        if ( ! $this->_file_url) {
196 196
             $this->_set_file_url();
197 197
         }
198 198
         return $this->_file_url;
@@ -224,7 +224,7 @@  discard block
 block discarded – undo
224 224
      */
225 225
     function settings_form()
226 226
     {
227
-        if (!$this->_settings_form) {
227
+        if ( ! $this->_settings_form) {
228 228
             $this->_settings_form = $this->generate_new_settings_form();
229 229
             $this->_settings_form->set_payment_method_type($this);
230 230
             //if we have already assigned a model object to this pmt, make
@@ -276,7 +276,7 @@  discard block
 block discarded – undo
276 276
     public function billing_form(EE_Transaction $transaction = NULL, $extra_args = array())
277 277
     {
278 278
         // has billing form already been regenerated ? or overwrite cache?
279
-        if (!$this->_billing_form instanceof EE_Billing_Info_Form || !$this->_cache_billing_form) {
279
+        if ( ! $this->_billing_form instanceof EE_Billing_Info_Form || ! $this->_cache_billing_form) {
280 280
             $this->_billing_form = $this->generate_new_billing_form($transaction, $extra_args);
281 281
         }
282 282
         //if we know who the attendee is, and this is a billing form
@@ -371,7 +371,7 @@  discard block
 block discarded – undo
371 371
             $payment = EEM_Payment::instance()->get_one(array($duplicate_properties));
372 372
             //if we didn't already have a payment in progress for the same thing,
373 373
             //then we actually want to make a new payment
374
-            if (!$payment instanceof EE_Payment) {
374
+            if ( ! $payment instanceof EE_Payment) {
375 375
                 $payment = EE_Payment::new_instance(
376 376
                     array_merge(
377 377
                         $duplicate_properties,
@@ -472,7 +472,7 @@  discard block
 block discarded – undo
472 472
     public function handle_ipn($req_data, $transaction)
473 473
     {
474 474
         $transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
475
-        if (!$this->_gateway instanceof EE_Offsite_Gateway) {
475
+        if ( ! $this->_gateway instanceof EE_Offsite_Gateway) {
476 476
             throw new EE_Error(sprintf(__("Could not handle IPN because '%s' is not an offsite gateway", "event_espresso"), print_r($this->_gateway, TRUE)));
477 477
 
478 478
         }
@@ -490,17 +490,17 @@  discard block
 block discarded – undo
490 490
      */
491 491
     protected function _save_billing_info_to_attendee($billing_form, $transaction)
492 492
     {
493
-        if (!$transaction || !$transaction instanceof EE_Transaction) {
493
+        if ( ! $transaction || ! $transaction instanceof EE_Transaction) {
494 494
             EE_Error::add_error(__("Cannot save billing info because no transaction was specified", "event_espresso"), __FILE__, __FUNCTION__, __LINE__);
495 495
             return false;
496 496
         }
497 497
         $primary_reg = $transaction->primary_registration();
498
-        if (!$primary_reg) {
498
+        if ( ! $primary_reg) {
499 499
             EE_Error::add_error(__("Cannot save billing info because the transaction has no primary registration", "event_espresso"), __FILE__, __FUNCTION__, __LINE__);
500 500
             return false;
501 501
         }
502 502
         $attendee = $primary_reg->attendee();
503
-        if (!$attendee) {
503
+        if ( ! $attendee) {
504 504
             EE_Error::add_error(__("Cannot save billing info because the transaction's primary registration has no attendee!", "event_espresso"), __FILE__, __FUNCTION__, __LINE__);
505 505
             return false;
506 506
         }
@@ -600,7 +600,7 @@  discard block
 block discarded – undo
600 600
      */
601 601
     public function payment_occurs()
602 602
     {
603
-        if (!$this->_gateway) {
603
+        if ( ! $this->_gateway) {
604 604
             return EE_PMT_Base::offline;
605 605
         } elseif ($this->_gateway instanceof EE_Onsite_Gateway) {
606 606
             return EE_PMT_Base::onsite;
@@ -621,7 +621,7 @@  discard block
 block discarded – undo
621 621
      */
622 622
     public function payment_overview_content(EE_Payment $payment)
623 623
     {
624
-        return EEH_Template::display_template(EE_LIBRARIES . 'payment_methods' . DS . 'templates' . DS . 'payment_details_content.template.php', array('payment_method' => $this->_pm_instance, 'payment' => $payment), true);
624
+        return EEH_Template::display_template(EE_LIBRARIES.'payment_methods'.DS.'templates'.DS.'payment_details_content.template.php', array('payment_method' => $this->_pm_instance, 'payment' => $payment), true);
625 625
     }
626 626
 
627 627
 
@@ -696,7 +696,7 @@  discard block
 block discarded – undo
696 696
      */
697 697
     public function get_help_tab_name()
698 698
     {
699
-        return 'ee_' . strtolower($this->system_name()) . '_help_tab';
699
+        return 'ee_'.strtolower($this->system_name()).'_help_tab';
700 700
     }
701 701
 
702 702
     /**
@@ -706,7 +706,7 @@  discard block
 block discarded – undo
706 706
      */
707 707
     public function cap_name()
708 708
     {
709
-        return 'ee_payment_method_' . strtolower($this->system_name());
709
+        return 'ee_payment_method_'.strtolower($this->system_name());
710 710
     }
711 711
 
712 712
     /**
@@ -737,7 +737,7 @@  discard block
 block discarded – undo
737 737
      */
738 738
     public function introductory_html()
739 739
     {
740
-        return EEH_Template::locate_template($this->file_folder() . 'templates' . DS . strtolower($this->system_name()) . '_intro.template.php', array('pmt_obj' => $this, 'pm_instance' => $this->_pm_instance));
740
+        return EEH_Template::locate_template($this->file_folder().'templates'.DS.strtolower($this->system_name()).'_intro.template.php', array('pmt_obj' => $this, 'pm_instance' => $this->_pm_instance));
741 741
     }
742 742
 
743 743
 
Please login to merge, or discard this patch.
core/helpers/EEH_Money.helper.php 2 patches
Indentation   +200 added lines, -200 removed lines patch added patch discarded remove patch
@@ -15,214 +15,214 @@
 block discarded – undo
15 15
 class EEH_Money extends EEH_Base
16 16
 {
17 17
 
18
-    /**
19
-     * This removes all localized money formatting from the incoming value
20
-     * Note: uses this site's currency settings for deciding what is considered a
21
-     * "thousands separator" (usually the character "," )
22
-     * and what is a "decimal mark" (usually the character ".")
23
-     *
24
-     * @param int|float|string $money_value
25
-     * @param string           $CNT_ISO
26
-     * @return float
27
-     * @throws EE_Error
28
-     */
29
-    public static function strip_localized_money_formatting($money_value, $CNT_ISO = '')
30
-    {
31
-        $currency_config = EEH_Money::get_currency_config($CNT_ISO);
32
-        $money_value     = str_replace(
33
-            array(
34
-                $currency_config->thsnds,
35
-                $currency_config->dec_mrk,
36
-            ),
37
-            array(
38
-                '', // remove thousands separator
39
-                '.', // convert decimal mark to what PHP expects
40
-            ),
41
-            $money_value
42
-        );
43
-        $money_value     = filter_var(
44
-            $money_value,
45
-            FILTER_SANITIZE_NUMBER_FLOAT,
46
-            FILTER_FLAG_ALLOW_FRACTION
47
-        );
48
-        return $money_value;
49
-    }
18
+	/**
19
+	 * This removes all localized money formatting from the incoming value
20
+	 * Note: uses this site's currency settings for deciding what is considered a
21
+	 * "thousands separator" (usually the character "," )
22
+	 * and what is a "decimal mark" (usually the character ".")
23
+	 *
24
+	 * @param int|float|string $money_value
25
+	 * @param string           $CNT_ISO
26
+	 * @return float
27
+	 * @throws EE_Error
28
+	 */
29
+	public static function strip_localized_money_formatting($money_value, $CNT_ISO = '')
30
+	{
31
+		$currency_config = EEH_Money::get_currency_config($CNT_ISO);
32
+		$money_value     = str_replace(
33
+			array(
34
+				$currency_config->thsnds,
35
+				$currency_config->dec_mrk,
36
+			),
37
+			array(
38
+				'', // remove thousands separator
39
+				'.', // convert decimal mark to what PHP expects
40
+			),
41
+			$money_value
42
+		);
43
+		$money_value     = filter_var(
44
+			$money_value,
45
+			FILTER_SANITIZE_NUMBER_FLOAT,
46
+			FILTER_FLAG_ALLOW_FRACTION
47
+		);
48
+		return $money_value;
49
+	}
50 50
 
51 51
 
52
-    /**
53
-     * This converts an incoming localized money value into a standard float item (to three decimal places)
54
-     * Only use this if you know the $money_value follows your currency configuration's
55
-     * settings. Note: this uses this site's currency settings for deciding what is considered a
56
-     * "thousands separator" (usually the character "," )
57
-     * and what is a "decimal mark" (usually the character ".")
58
-     *
59
-     * @param int|string $money_value
60
-     * @return float
61
-     * @throws EE_Error
62
-     */
63
-    public static function convert_to_float_from_localized_money($money_value)
64
-    {
65
-        //float it! and round to three decimal places
66
-        return round((float) EEH_Money::strip_localized_money_formatting($money_value), 3);
67
-    }
52
+	/**
53
+	 * This converts an incoming localized money value into a standard float item (to three decimal places)
54
+	 * Only use this if you know the $money_value follows your currency configuration's
55
+	 * settings. Note: this uses this site's currency settings for deciding what is considered a
56
+	 * "thousands separator" (usually the character "," )
57
+	 * and what is a "decimal mark" (usually the character ".")
58
+	 *
59
+	 * @param int|string $money_value
60
+	 * @return float
61
+	 * @throws EE_Error
62
+	 */
63
+	public static function convert_to_float_from_localized_money($money_value)
64
+	{
65
+		//float it! and round to three decimal places
66
+		return round((float) EEH_Money::strip_localized_money_formatting($money_value), 3);
67
+	}
68 68
 
69 69
 
70
-    /**
71
-     * For comparing floats. Default operator is '=', but see the $operator below for all options.
72
-     * This should be used to compare floats instead of normal '==' because floats
73
-     * are inherently imprecise, and so you can sometimes have two floats that appear to be identical
74
-     * but actually differ by 0.00000001.
75
-     *
76
-     * @see http://biostall.com/php-function-to-compare-floating-point-numbers
77
-     * @param float  $float1
78
-     * @param float  $float2
79
-     * @param string $operator The operator. Valid options are =, <=, <, >=, >, <>, eq, lt, lte, gt, gte, ne
80
-     * @return bool whether the equation is true or false
81
-     * @throws EE_Error
82
-     */
83
-    public static function compare_floats($float1, $float2, $operator = '=')
84
-    {
85
-        // Check numbers to 5 digits of precision
86
-        $epsilon = 0.00001;
87
-        $float1 = (float) $float1;
88
-        $float2 = (float) $float2;
89
-        switch ($operator) {
90
-            // equal
91
-            case "=":
92
-            case "==":
93
-            case "===":
94
-            case "eq":
95
-                if (abs($float1 - $float2) < $epsilon) {
96
-                    return true;
97
-                }
98
-                break;
99
-            // less than
100
-            case "<":
101
-            case "lt":
102
-                if (abs($float1 - $float2) < $epsilon) {
103
-                    return false;
104
-                } else {
105
-                    if ($float1 < $float2) {
106
-                        return true;
107
-                    }
108
-                }
109
-                break;
110
-            // less than or equal
111
-            case "<=":
112
-            case "lte":
113
-                if (self::compare_floats($float1, $float2, '<') || self::compare_floats($float1, $float2, '=')) {
114
-                    return true;
115
-                }
116
-                break;
117
-            // greater than
118
-            case ">":
119
-            case "gt":
120
-                if (abs($float1 - $float2) < $epsilon) {
121
-                    return false;
122
-                } else {
123
-                    if ($float1 > $float2) {
124
-                        return true;
125
-                    }
126
-                }
127
-                break;
128
-            // greater than or equal
129
-            case ">=":
130
-            case "gte":
131
-                if (self::compare_floats($float1, $float2, '>') || self::compare_floats($float1, $float2, '=')) {
132
-                    return true;
133
-                }
134
-                break;
135
-            case "<>":
136
-            case "!=":
137
-            case "ne":
138
-                if (abs($float1 - $float2) > $epsilon) {
139
-                    return true;
140
-                }
141
-                break;
142
-            default:
143
-                throw new EE_Error(__("Unknown operator '" . $operator . "' in EEH_Money::compare_floats()",
144
-                    'event_espresso'));
145
-        }
146
-        return false;
147
-    }
70
+	/**
71
+	 * For comparing floats. Default operator is '=', but see the $operator below for all options.
72
+	 * This should be used to compare floats instead of normal '==' because floats
73
+	 * are inherently imprecise, and so you can sometimes have two floats that appear to be identical
74
+	 * but actually differ by 0.00000001.
75
+	 *
76
+	 * @see http://biostall.com/php-function-to-compare-floating-point-numbers
77
+	 * @param float  $float1
78
+	 * @param float  $float2
79
+	 * @param string $operator The operator. Valid options are =, <=, <, >=, >, <>, eq, lt, lte, gt, gte, ne
80
+	 * @return bool whether the equation is true or false
81
+	 * @throws EE_Error
82
+	 */
83
+	public static function compare_floats($float1, $float2, $operator = '=')
84
+	{
85
+		// Check numbers to 5 digits of precision
86
+		$epsilon = 0.00001;
87
+		$float1 = (float) $float1;
88
+		$float2 = (float) $float2;
89
+		switch ($operator) {
90
+			// equal
91
+			case "=":
92
+			case "==":
93
+			case "===":
94
+			case "eq":
95
+				if (abs($float1 - $float2) < $epsilon) {
96
+					return true;
97
+				}
98
+				break;
99
+			// less than
100
+			case "<":
101
+			case "lt":
102
+				if (abs($float1 - $float2) < $epsilon) {
103
+					return false;
104
+				} else {
105
+					if ($float1 < $float2) {
106
+						return true;
107
+					}
108
+				}
109
+				break;
110
+			// less than or equal
111
+			case "<=":
112
+			case "lte":
113
+				if (self::compare_floats($float1, $float2, '<') || self::compare_floats($float1, $float2, '=')) {
114
+					return true;
115
+				}
116
+				break;
117
+			// greater than
118
+			case ">":
119
+			case "gt":
120
+				if (abs($float1 - $float2) < $epsilon) {
121
+					return false;
122
+				} else {
123
+					if ($float1 > $float2) {
124
+						return true;
125
+					}
126
+				}
127
+				break;
128
+			// greater than or equal
129
+			case ">=":
130
+			case "gte":
131
+				if (self::compare_floats($float1, $float2, '>') || self::compare_floats($float1, $float2, '=')) {
132
+					return true;
133
+				}
134
+				break;
135
+			case "<>":
136
+			case "!=":
137
+			case "ne":
138
+				if (abs($float1 - $float2) > $epsilon) {
139
+					return true;
140
+				}
141
+				break;
142
+			default:
143
+				throw new EE_Error(__("Unknown operator '" . $operator . "' in EEH_Money::compare_floats()",
144
+					'event_espresso'));
145
+		}
146
+		return false;
147
+	}
148 148
 
149 149
 
150
-    /**
151
-     * This returns a localized format string suitable for jQplot.
152
-     *
153
-     * @param string $CNT_ISO  If this is provided, then will attempt to get the currency settings for the country.
154
-     *                         Otherwise will use currency settings for current active country on site.
155
-     * @return string
156
-     * @throws EE_Error
157
-     */
158
-    public static function get_format_for_jqplot($CNT_ISO = '')
159
-    {
160
-        //default format
161
-        $format          = 'f';
162
-        $currency_config = $currency_config = EEH_Money::get_currency_config($CNT_ISO);
163
-        //first get the decimal place and number of places
164
-        $format = "%'." . $currency_config->dec_plc . $format;
165
-        //currency symbol on right side.
166
-        $format = $currency_config->sign_b4 ? $currency_config->sign . $format : $format . $currency_config->sign;
167
-        return $format;
168
-    }
150
+	/**
151
+	 * This returns a localized format string suitable for jQplot.
152
+	 *
153
+	 * @param string $CNT_ISO  If this is provided, then will attempt to get the currency settings for the country.
154
+	 *                         Otherwise will use currency settings for current active country on site.
155
+	 * @return string
156
+	 * @throws EE_Error
157
+	 */
158
+	public static function get_format_for_jqplot($CNT_ISO = '')
159
+	{
160
+		//default format
161
+		$format          = 'f';
162
+		$currency_config = $currency_config = EEH_Money::get_currency_config($CNT_ISO);
163
+		//first get the decimal place and number of places
164
+		$format = "%'." . $currency_config->dec_plc . $format;
165
+		//currency symbol on right side.
166
+		$format = $currency_config->sign_b4 ? $currency_config->sign . $format : $format . $currency_config->sign;
167
+		return $format;
168
+	}
169 169
 
170 170
 
171
-    /**
172
-     * This returns a localized format string suitable for usage with the Google Charts API format param.
173
-     *
174
-     * @param string $CNT_ISO  If this is provided, then will attempt to get the currency settings for the country.
175
-     *                         Otherwise will use currency settings for current active country on site.
176
-     *                         Note: GoogleCharts uses ICU pattern set
177
-     *                         (@see http://icu-project.org/apiref/icu4c/classDecimalFormat.html#_details)
178
-     * @return string
179
-     * @throws EE_Error
180
-     */
181
-    public static function get_format_for_google_charts($CNT_ISO = '')
182
-    {
183
-        $currency_config            = EEH_Money::get_currency_config($CNT_ISO);
184
-        $decimal_places_placeholder = str_pad('', $currency_config->dec_plc, '0');
185
-        //first get the decimal place and number of places
186
-        $format = '#,##0.' . $decimal_places_placeholder;
187
-        //currency symbol on right side.
188
-        $format          = $currency_config->sign_b4
189
-            ? $currency_config->sign . $format
190
-            : $format
191
-              . $currency_config->sign;
192
-        $formatterObject = array(
193
-            'decimalSymbol'  => $currency_config->dec_mrk,
194
-            'groupingSymbol' => $currency_config->thsnds,
195
-            'fractionDigits' => $currency_config->dec_plc,
196
-        );
197
-        if ($currency_config->sign_b4) {
198
-            $formatterObject['prefix'] = $currency_config->sign;
199
-        } else {
200
-            $formatterObject['suffix'] = $currency_config->sign;
201
-        }
202
-        return array(
203
-            'format'          => $format,
204
-            'formatterObject' => $formatterObject,
205
-        );
206
-    }
171
+	/**
172
+	 * This returns a localized format string suitable for usage with the Google Charts API format param.
173
+	 *
174
+	 * @param string $CNT_ISO  If this is provided, then will attempt to get the currency settings for the country.
175
+	 *                         Otherwise will use currency settings for current active country on site.
176
+	 *                         Note: GoogleCharts uses ICU pattern set
177
+	 *                         (@see http://icu-project.org/apiref/icu4c/classDecimalFormat.html#_details)
178
+	 * @return string
179
+	 * @throws EE_Error
180
+	 */
181
+	public static function get_format_for_google_charts($CNT_ISO = '')
182
+	{
183
+		$currency_config            = EEH_Money::get_currency_config($CNT_ISO);
184
+		$decimal_places_placeholder = str_pad('', $currency_config->dec_plc, '0');
185
+		//first get the decimal place and number of places
186
+		$format = '#,##0.' . $decimal_places_placeholder;
187
+		//currency symbol on right side.
188
+		$format          = $currency_config->sign_b4
189
+			? $currency_config->sign . $format
190
+			: $format
191
+			  . $currency_config->sign;
192
+		$formatterObject = array(
193
+			'decimalSymbol'  => $currency_config->dec_mrk,
194
+			'groupingSymbol' => $currency_config->thsnds,
195
+			'fractionDigits' => $currency_config->dec_plc,
196
+		);
197
+		if ($currency_config->sign_b4) {
198
+			$formatterObject['prefix'] = $currency_config->sign;
199
+		} else {
200
+			$formatterObject['suffix'] = $currency_config->sign;
201
+		}
202
+		return array(
203
+			'format'          => $format,
204
+			'formatterObject' => $formatterObject,
205
+		);
206
+	}
207 207
 
208 208
 
209
-    /**
210
-     * @param string $CNT_ISO
211
-     * @return EE_Currency_Config|null
212
-     * @throws EE_Error
213
-     */
214
-    public static function get_currency_config($CNT_ISO = '')
215
-    {
216
-        //if CNT_ISO passed lets try to get currency settings for it.
217
-        $currency_config = $CNT_ISO !== ''
218
-            ? new EE_Currency_Config($CNT_ISO)
219
-            : null;
220
-        //default currency settings for site if not set
221
-        if (! $currency_config instanceof EE_Currency_Config) {
222
-            $currency_config = EE_Registry::instance()->CFG->currency instanceof EE_Currency_Config
223
-                ? EE_Registry::instance()->CFG->currency
224
-                : new EE_Currency_Config();
225
-        }
226
-        return $currency_config;
227
-    }
209
+	/**
210
+	 * @param string $CNT_ISO
211
+	 * @return EE_Currency_Config|null
212
+	 * @throws EE_Error
213
+	 */
214
+	public static function get_currency_config($CNT_ISO = '')
215
+	{
216
+		//if CNT_ISO passed lets try to get currency settings for it.
217
+		$currency_config = $CNT_ISO !== ''
218
+			? new EE_Currency_Config($CNT_ISO)
219
+			: null;
220
+		//default currency settings for site if not set
221
+		if (! $currency_config instanceof EE_Currency_Config) {
222
+			$currency_config = EE_Registry::instance()->CFG->currency instanceof EE_Currency_Config
223
+				? EE_Registry::instance()->CFG->currency
224
+				: new EE_Currency_Config();
225
+		}
226
+		return $currency_config;
227
+	}
228 228
 } //end class EEH_Money
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -40,7 +40,7 @@  discard block
 block discarded – undo
40 40
             ),
41 41
             $money_value
42 42
         );
43
-        $money_value     = filter_var(
43
+        $money_value = filter_var(
44 44
             $money_value,
45 45
             FILTER_SANITIZE_NUMBER_FLOAT,
46 46
             FILTER_FLAG_ALLOW_FRACTION
@@ -140,7 +140,7 @@  discard block
 block discarded – undo
140 140
                 }
141 141
                 break;
142 142
             default:
143
-                throw new EE_Error(__("Unknown operator '" . $operator . "' in EEH_Money::compare_floats()",
143
+                throw new EE_Error(__("Unknown operator '".$operator."' in EEH_Money::compare_floats()",
144 144
                     'event_espresso'));
145 145
         }
146 146
         return false;
@@ -161,9 +161,9 @@  discard block
 block discarded – undo
161 161
         $format          = 'f';
162 162
         $currency_config = $currency_config = EEH_Money::get_currency_config($CNT_ISO);
163 163
         //first get the decimal place and number of places
164
-        $format = "%'." . $currency_config->dec_plc . $format;
164
+        $format = "%'.".$currency_config->dec_plc.$format;
165 165
         //currency symbol on right side.
166
-        $format = $currency_config->sign_b4 ? $currency_config->sign . $format : $format . $currency_config->sign;
166
+        $format = $currency_config->sign_b4 ? $currency_config->sign.$format : $format.$currency_config->sign;
167 167
         return $format;
168 168
     }
169 169
 
@@ -183,10 +183,10 @@  discard block
 block discarded – undo
183 183
         $currency_config            = EEH_Money::get_currency_config($CNT_ISO);
184 184
         $decimal_places_placeholder = str_pad('', $currency_config->dec_plc, '0');
185 185
         //first get the decimal place and number of places
186
-        $format = '#,##0.' . $decimal_places_placeholder;
186
+        $format = '#,##0.'.$decimal_places_placeholder;
187 187
         //currency symbol on right side.
188
-        $format          = $currency_config->sign_b4
189
-            ? $currency_config->sign . $format
188
+        $format = $currency_config->sign_b4
189
+            ? $currency_config->sign.$format
190 190
             : $format
191 191
               . $currency_config->sign;
192 192
         $formatterObject = array(
@@ -218,7 +218,7 @@  discard block
 block discarded – undo
218 218
             ? new EE_Currency_Config($CNT_ISO)
219 219
             : null;
220 220
         //default currency settings for site if not set
221
-        if (! $currency_config instanceof EE_Currency_Config) {
221
+        if ( ! $currency_config instanceof EE_Currency_Config) {
222 222
             $currency_config = EE_Registry::instance()->CFG->currency instanceof EE_Currency_Config
223 223
                 ? EE_Registry::instance()->CFG->currency
224 224
                 : new EE_Currency_Config();
Please login to merge, or discard this patch.
modules/ticket_sales_monitor/EED_Ticket_Sales_Monitor.module.php 1 patch
Indentation   +969 added lines, -969 removed lines patch added patch discarded remove patch
@@ -3,7 +3,7 @@  discard block
 block discarded – undo
3 3
 use EventEspresso\core\exceptions\UnexpectedEntityException;
4 4
 
5 5
 if (! defined('EVENT_ESPRESSO_VERSION')) {
6
-    exit('No direct script access allowed');
6
+	exit('No direct script access allowed');
7 7
 }
8 8
 
9 9
 
@@ -22,975 +22,975 @@  discard block
 block discarded – undo
22 22
 class EED_Ticket_Sales_Monitor extends EED_Module
23 23
 {
24 24
 
25
-    const debug = false;    //	true false
26
-
27
-    /**
28
-     * an array of raw ticket data from EED_Ticket_Selector
29
-     *
30
-     * @var array $ticket_selections
31
-     */
32
-    protected $ticket_selections = array();
33
-
34
-    /**
35
-     * the raw ticket data from EED_Ticket_Selector is organized in rows
36
-     * according to how they are displayed in the actual Ticket_Selector
37
-     * this tracks the current row being processed
38
-     *
39
-     * @var int $current_row
40
-     */
41
-    protected $current_row = 0;
42
-
43
-    /**
44
-     * an array for tracking names of tickets that have sold out
45
-     *
46
-     * @var array $sold_out_tickets
47
-     */
48
-    protected $sold_out_tickets = array();
49
-
50
-    /**
51
-     * an array for tracking names of tickets that have had their quantities reduced
52
-     *
53
-     * @var array $decremented_tickets
54
-     */
55
-    protected $decremented_tickets = array();
56
-
57
-
58
-
59
-    /**
60
-     * set_hooks - for hooking into EE Core, other modules, etc
61
-     *
62
-     * @return    void
63
-     */
64
-    public static function set_hooks()
65
-    {
66
-        // release tickets for expired carts
67
-        add_action(
68
-            'EED_Ticket_Selector__process_ticket_selections__before',
69
-            array('EED_Ticket_Sales_Monitor', 'release_tickets_for_expired_carts'),
70
-            1
71
-        );
72
-        // check ticket reserves AFTER MER does it's check (hence priority 20)
73
-        add_filter(
74
-            'FHEE__EE_Ticket_Selector___add_ticket_to_cart__ticket_qty',
75
-            array('EED_Ticket_Sales_Monitor', 'validate_ticket_sale'),
76
-            20,
77
-            3
78
-        );
79
-        // add notices for sold out tickets
80
-        add_action(
81
-            'AHEE__EE_Ticket_Selector__process_ticket_selections__after_tickets_added_to_cart',
82
-            array('EED_Ticket_Sales_Monitor', 'post_notices'),
83
-            10
84
-        );
85
-        // handle ticket quantities adjusted in cart
86
-        //add_action(
87
-        //	'FHEE__EED_Multi_Event_Registration__adjust_line_item_quantity__line_item_quantity_updated',
88
-        //	array( 'EED_Ticket_Sales_Monitor', 'ticket_quantity_updated' ),
89
-        //	10, 2
90
-        //);
91
-        // handle tickets deleted from cart
92
-        add_action(
93
-            'FHEE__EED_Multi_Event_Registration__delete_ticket__ticket_removed_from_cart',
94
-            array('EED_Ticket_Sales_Monitor', 'ticket_removed_from_cart'),
95
-            10,
96
-            2
97
-        );
98
-        // handle emptied carts
99
-        add_action(
100
-            'AHEE__EE_Session__reset_cart__before_reset',
101
-            array('EED_Ticket_Sales_Monitor', 'session_cart_reset'),
102
-            10,
103
-            1
104
-        );
105
-        add_action(
106
-            'AHEE__EED_Multi_Event_Registration__empty_event_cart__before_delete_cart',
107
-            array('EED_Ticket_Sales_Monitor', 'session_cart_reset'),
108
-            10,
109
-            1
110
-        );
111
-        // handle cancelled registrations
112
-        add_action(
113
-            'AHEE__EE_Session__reset_checkout__before_reset',
114
-            array('EED_Ticket_Sales_Monitor', 'session_checkout_reset'),
115
-            10,
116
-            1
117
-        );
118
-        // cron tasks
119
-        add_action(
120
-            'AHEE__EE_Cron_Tasks__process_expired_transactions__abandoned_transaction',
121
-            array('EED_Ticket_Sales_Monitor', 'process_abandoned_transactions'),
122
-            10,
123
-            1
124
-        );
125
-        add_action(
126
-            'AHEE__EE_Cron_Tasks__process_expired_transactions__incomplete_transaction',
127
-            array('EED_Ticket_Sales_Monitor', 'process_abandoned_transactions'),
128
-            10,
129
-            1
130
-        );
131
-        add_action(
132
-            'AHEE__EE_Cron_Tasks__process_expired_transactions__failed_transaction',
133
-            array('EED_Ticket_Sales_Monitor', 'process_failed_transactions'),
134
-            10,
135
-            1
136
-        );
137
-    }
138
-
139
-
140
-
141
-    /**
142
-     * set_hooks_admin - for hooking into EE Admin Core, other modules, etc
143
-     *
144
-     * @return void
145
-     */
146
-    public static function set_hooks_admin()
147
-    {
148
-        EED_Ticket_Sales_Monitor::set_hooks();
149
-    }
150
-
151
-
152
-
153
-    /**
154
-     * @return EED_Ticket_Sales_Monitor|EED_Module
155
-     */
156
-    public static function instance()
157
-    {
158
-        return parent::get_instance(__CLASS__);
159
-    }
160
-
161
-
162
-
163
-    /**
164
-     * @param WP_Query $WP_Query
165
-     * @return    void
166
-     */
167
-    public function run($WP_Query)
168
-    {
169
-    }
170
-
171
-
172
-
173
-    /********************************** PRE_TICKET_SALES  **********************************/
174
-
175
-
176
-
177
-    /**
178
-     * Retrieves grand totals from the line items that have no TXN ID
179
-     * and timestamps less than the current time minus the session lifespan.
180
-     * These are carts that have been abandoned before the "registrant" even attempted to checkout.
181
-     * We're going to release the tickets for these line items before attempting to add more to the cart.
182
-     *
183
-     * @return void
184
-     * @throws EE_Error
185
-     * @throws InvalidArgumentException
186
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
187
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
188
-     */
189
-    public static function release_tickets_for_expired_carts()
190
-    {
191
-        do_action('AHEE__EED_Ticket_Sales_Monitor__release_tickets_for_expired_carts__begin');
192
-        $expired_ticket_IDs      = array();
193
-        $valid_ticket_line_items = array();
194
-        $total_line_items        = EEM_Line_Item::instance()->get_total_line_items_with_no_transaction();
195
-        if (empty($total_line_items)) {
196
-            do_action(
197
-                'AHEE__EED_Ticket_Sales_Monitor__release_tickets_for_expired_carts__end',
198
-                $total_line_items,
199
-                $valid_ticket_line_items,
200
-                $expired_ticket_IDs
201
-            );
202
-            return;
203
-        }
204
-        $expired = current_time('timestamp') - EE_Registry::instance()->SSN->lifespan();
205
-        foreach ($total_line_items as $total_line_item) {
206
-            /** @var EE_Line_Item $total_line_item */
207
-            $ticket_line_items = EED_Ticket_Sales_Monitor::get_ticket_line_items_for_grand_total($total_line_item);
208
-            foreach ($ticket_line_items as $ticket_line_item) {
209
-                if (! $ticket_line_item instanceof EE_Line_Item) {
210
-                    continue;
211
-                }
212
-                if ($total_line_item->timestamp(true) <= $expired) {
213
-                    $expired_ticket_IDs[$ticket_line_item->OBJ_ID()] = $ticket_line_item->OBJ_ID();
214
-                } else {
215
-                    $valid_ticket_line_items[$ticket_line_item->OBJ_ID()] = $ticket_line_item;
216
-                }
217
-            }
218
-        }
219
-        if (! empty($expired_ticket_IDs)) {
220
-            EED_Ticket_Sales_Monitor::release_reservations_for_tickets(
221
-                \EEM_Ticket::instance()->get_tickets_with_IDs($expired_ticket_IDs),
222
-                $valid_ticket_line_items
223
-            );
224
-            // let's get rid of expired line items so that they can't interfere with tracking
225
-            add_action(
226
-                'shutdown',
227
-                array('EED_Ticket_Sales_Monitor', 'clear_expired_line_items_with_no_transaction'),
228
-                999
229
-            );
230
-        }
231
-        do_action(
232
-            'AHEE__EED_Ticket_Sales_Monitor__release_tickets_for_expired_carts__end',
233
-            $total_line_items,
234
-            $valid_ticket_line_items,
235
-            $expired_ticket_IDs
236
-        );
237
-    }
238
-
239
-
240
-
241
-    /********************************** VALIDATE_TICKET_SALE  **********************************/
242
-
243
-
244
-
245
-    /**
246
-     * callback for 'FHEE__EED_Ticket_Selector__process_ticket_selections__valid_post_data'
247
-     *
248
-     * @param int       $qty
249
-     * @param EE_Ticket $ticket
250
-     * @return bool
251
-     * @throws UnexpectedEntityException
252
-     * @throws EE_Error
253
-     */
254
-    public static function validate_ticket_sale($qty = 1, EE_Ticket $ticket)
255
-    {
256
-        $qty = absint($qty);
257
-        if ($qty > 0) {
258
-            $qty = EED_Ticket_Sales_Monitor::instance()->_validate_ticket_sale($ticket, $qty);
259
-        }
260
-        if (self::debug) {
261
-            echo '<br /><br /> ' . __LINE__ . ') ' . __METHOD__ . '()';
262
-            echo '<br /><br /><b> RETURNED QTY: ' . $qty . '</b>';
263
-        }
264
-        return $qty;
265
-    }
266
-
267
-
268
-
269
-    /**
270
-     * checks whether an individual ticket is available for purchase based on datetime, and ticket details
271
-     *
272
-     * @param   EE_Ticket $ticket
273
-     * @param int         $qty
274
-     * @return int
275
-     * @throws UnexpectedEntityException
276
-     * @throws EE_Error
277
-     */
278
-    protected function _validate_ticket_sale(EE_Ticket $ticket, $qty = 1)
279
-    {
280
-        if (self::debug) {
281
-            echo '<br /><br /> ' . __LINE__ . ') ' . __METHOD__ . '() ';
282
-        }
283
-        if (! $ticket instanceof EE_Ticket) {
284
-            return 0;
285
-        }
286
-        if (self::debug) {
287
-            echo '<br /><b> . ticket->ID: ' . $ticket->ID() . '</b>';
288
-            echo '<br /> . original ticket->reserved: ' . $ticket->reserved();
289
-        }
290
-        $ticket->refresh_from_db();
291
-        // first let's determine the ticket availability based on sales
292
-        $available = $ticket->qty('saleable');
293
-        if (self::debug) {
294
-            echo '<br /> . . . ticket->qty: ' . $ticket->qty();
295
-            echo '<br /> . . . ticket->sold: ' . $ticket->sold();
296
-            echo '<br /> . . . ticket->reserved: ' . $ticket->reserved();
297
-            echo '<br /> . . . ticket->qty(saleable): ' . $ticket->qty('saleable');
298
-            echo '<br /> . . . available: ' . $available;
299
-        }
300
-        if ($available < 1) {
301
-            $this->_ticket_sold_out($ticket);
302
-            return 0;
303
-        }
304
-        if (self::debug) {
305
-            echo '<br /> . . . qty: ' . $qty;
306
-        }
307
-        if ($available < $qty) {
308
-            $qty = $available;
309
-            if (self::debug) {
310
-                echo '<br /> . . . QTY ADJUSTED: ' . $qty;
311
-            }
312
-            $this->_ticket_quantity_decremented($ticket);
313
-        }
314
-        $this->_reserve_ticket($ticket, $qty);
315
-        return $qty;
316
-    }
317
-
318
-
319
-
320
-    /**
321
-     * increments ticket reserved based on quantity passed
322
-     *
323
-     * @param    EE_Ticket $ticket
324
-     * @param int          $quantity
325
-     * @return bool
326
-     * @throws EE_Error
327
-     */
328
-    protected function _reserve_ticket(EE_Ticket $ticket, $quantity = 1)
329
-    {
330
-        if (self::debug) {
331
-            echo '<br /><br /> . . . INCREASE RESERVED: ' . $quantity;
332
-        }
333
-        $ticket->increase_reserved($quantity);
334
-        return $ticket->save();
335
-    }
336
-
337
-
338
-
339
-    /**
340
-     * @param  EE_Ticket $ticket
341
-     * @param  int       $quantity
342
-     * @return bool
343
-     * @throws EE_Error
344
-     */
345
-    protected function _release_reserved_ticket(EE_Ticket $ticket, $quantity = 1)
346
-    {
347
-        if (self::debug) {
348
-            echo '<br /> . . . ticket->ID: ' . $ticket->ID();
349
-            echo '<br /> . . . ticket->reserved: ' . $ticket->reserved();
350
-        }
351
-        $ticket->decrease_reserved($quantity);
352
-        if (self::debug) {
353
-            echo '<br /> . . . ticket->reserved: ' . $ticket->reserved();
354
-        }
355
-        return $ticket->save() ? 1 : 0;
356
-    }
357
-
358
-
359
-
360
-    /**
361
-     * removes quantities within the ticket selector based on zero ticket availability
362
-     *
363
-     * @param    EE_Ticket $ticket
364
-     * @return    void
365
-     * @throws UnexpectedEntityException
366
-     * @throws EE_Error
367
-     */
368
-    protected function _ticket_sold_out(EE_Ticket $ticket)
369
-    {
370
-        if (self::debug) {
371
-            echo '<br /><br /> ' . __LINE__ . ') ' . __METHOD__ . '() ';
372
-            echo '<br /> . . ticket->name: ' . $this->_get_ticket_and_event_name($ticket);
373
-        }
374
-        $this->sold_out_tickets[] = $this->_get_ticket_and_event_name($ticket);
375
-    }
376
-
377
-
378
-
379
-    /**
380
-     * adjusts quantities within the ticket selector based on decreased ticket availability
381
-     *
382
-     * @param    EE_Ticket $ticket
383
-     * @return void
384
-     * @throws UnexpectedEntityException
385
-     * @throws EE_Error
386
-     */
387
-    protected function _ticket_quantity_decremented(EE_Ticket $ticket)
388
-    {
389
-        if (self::debug) {
390
-            echo '<br /><br /> ' . __LINE__ . ') ' . __METHOD__ . '() ';
391
-            echo '<br /> . . ticket->name: ' . $this->_get_ticket_and_event_name($ticket);
392
-        }
393
-        $this->decremented_tickets[] = $this->_get_ticket_and_event_name($ticket);
394
-    }
395
-
396
-
397
-
398
-    /**
399
-     * builds string out of ticket and event name
400
-     *
401
-     * @param    EE_Ticket $ticket
402
-     * @return string
403
-     * @throws UnexpectedEntityException
404
-     * @throws EE_Error
405
-     */
406
-    protected function _get_ticket_and_event_name(EE_Ticket $ticket)
407
-    {
408
-        $event = $ticket->get_related_event();
409
-        if ($event instanceof EE_Event) {
410
-            $ticket_name = sprintf(
411
-                _x('%1$s for %2$s', 'ticket name for event name', 'event_espresso'),
412
-                $ticket->name(),
413
-                $event->name()
414
-            );
415
-        } else {
416
-            $ticket_name = $ticket->name();
417
-        }
418
-        return $ticket_name;
419
-    }
420
-
421
-
422
-
423
-    /********************************** EVENT CART  **********************************/
424
-
425
-
426
-
427
-    /**
428
-     * releases or reserves ticket(s) based on quantity passed
429
-     *
430
-     * @param  EE_Line_Item $line_item
431
-     * @param  int          $quantity
432
-     * @return void
433
-     * @throws EE_Error
434
-     * @throws InvalidArgumentException
435
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
436
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
437
-     */
438
-    public static function ticket_quantity_updated(EE_Line_Item $line_item, $quantity = 1)
439
-    {
440
-        $ticket = EEM_Ticket::instance()->get_one_by_ID(absint($line_item->OBJ_ID()));
441
-        if ($ticket instanceof EE_Ticket) {
442
-            if ($quantity > 0) {
443
-                EED_Ticket_Sales_Monitor::instance()->_reserve_ticket($ticket, $quantity);
444
-            } else {
445
-                EED_Ticket_Sales_Monitor::instance()->_release_reserved_ticket($ticket, $quantity);
446
-            }
447
-        }
448
-    }
449
-
450
-
451
-
452
-    /**
453
-     * releases reserved ticket(s) based on quantity passed
454
-     *
455
-     * @param  EE_Ticket $ticket
456
-     * @param  int       $quantity
457
-     * @return void
458
-     * @throws EE_Error
459
-     */
460
-    public static function ticket_removed_from_cart(EE_Ticket $ticket, $quantity = 1)
461
-    {
462
-        EED_Ticket_Sales_Monitor::instance()->_release_reserved_ticket($ticket, $quantity);
463
-    }
464
-
465
-
466
-
467
-    /********************************** POST_NOTICES  **********************************/
468
-
469
-
470
-
471
-    /**
472
-     * @return void
473
-     * @throws EE_Error
474
-     * @throws InvalidArgumentException
475
-     * @throws ReflectionException
476
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
477
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
478
-     */
479
-    public static function post_notices()
480
-    {
481
-        EED_Ticket_Sales_Monitor::instance()->_post_notices();
482
-    }
483
-
484
-
485
-
486
-    /**
487
-     * @return void
488
-     * @throws EE_Error
489
-     * @throws InvalidArgumentException
490
-     * @throws ReflectionException
491
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
492
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
493
-     */
494
-    protected function _post_notices()
495
-    {
496
-        if (self::debug) {
497
-            echo '<br /><br /> ' . __LINE__ . ') ' . __METHOD__ . '() ';
498
-        }
499
-        $refresh_msg    = '';
500
-        $none_added_msg = '';
501
-        if (defined('DOING_AJAX') && DOING_AJAX) {
502
-            $refresh_msg    = __(
503
-                'Please refresh the page to view updated ticket quantities.',
504
-                'event_espresso'
505
-            );
506
-            $none_added_msg = __('No tickets were added for the event.', 'event_espresso');
507
-        }
508
-        if (! empty($this->sold_out_tickets)) {
509
-            EE_Error::add_attention(
510
-                sprintf(
511
-                    apply_filters(
512
-                        'FHEE__EED_Ticket_Sales_Monitor___post_notices__sold_out_tickets_notice',
513
-                        __(
514
-                            'We\'re sorry...%1$sThe following items have sold out since you first viewed this page, and can no longer be registered for:%1$s%1$s%2$s%1$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.%1$s%1$s%3$s%1$s%4$s%1$s',
515
-                            'event_espresso'
516
-                        )
517
-                    ),
518
-                    '<br />',
519
-                    implode('<br />', $this->sold_out_tickets),
520
-                    $none_added_msg,
521
-                    $refresh_msg
522
-                )
523
-            );
524
-            // alter code flow in the Ticket Selector for better UX
525
-            add_filter('FHEE__EED_Ticket_Selector__process_ticket_selections__tckts_slctd', '__return_true');
526
-            add_filter('FHEE__EED_Ticket_Selector__process_ticket_selections__success', '__return_false');
527
-            $this->sold_out_tickets = array();
528
-            // and reset the cart
529
-            EED_Ticket_Sales_Monitor::session_cart_reset(EE_Registry::instance()->SSN);
530
-        }
531
-        if (! empty($this->decremented_tickets)) {
532
-            EE_Error::add_attention(
533
-                sprintf(
534
-                    apply_filters(
535
-                        'FHEE__EED_Ticket_Sales_Monitor___ticket_quantity_decremented__notice',
536
-                        __(
537
-                            'We\'re sorry...%1$sDue to sales that have occurred since you first viewed the last page, the following items have had their quantities adjusted to match the current available amount:%1$s%1$s%2$s%1$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.%1$s%1$s%3$s%1$s%4$s%1$s',
538
-                            'event_espresso'
539
-                        )
540
-                    ),
541
-                    '<br />',
542
-                    implode('<br />', $this->decremented_tickets),
543
-                    $none_added_msg,
544
-                    $refresh_msg
545
-                )
546
-            );
547
-            $this->decremented_tickets = array();
548
-        }
549
-    }
550
-
551
-
552
-
553
-    /********************************** RELEASE_ALL_RESERVED_TICKETS_FOR_TRANSACTION  **********************************/
554
-
555
-
556
-
557
-    /**
558
-     * releases reserved tickets for all registrations of an EE_Transaction
559
-     * by default, will NOT release tickets for finalized transactions
560
-     *
561
-     * @param    EE_Transaction $transaction
562
-     * @return int
563
-     * @throws EE_Error
564
-     * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
565
-     */
566
-    protected function _release_all_reserved_tickets_for_transaction(EE_Transaction $transaction)
567
-    {
568
-        if (self::debug) {
569
-            echo '<br /><br /> ' . __LINE__ . ') ' . __METHOD__ . '() ';
570
-            echo '<br /> . transaction->ID: ' . $transaction->ID();
571
-        }
572
-        // check if 'finalize_registration' step has been completed...
573
-        $finalized = $transaction->reg_step_completed('finalize_registration');
574
-        if (self::debug) {
575
-            // DEBUG LOG
576
-            EEH_Debug_Tools::log(
577
-                __CLASS__,
578
-                __FUNCTION__,
579
-                __LINE__,
580
-                array('finalized' => $finalized),
581
-                false,
582
-                'EE_Transaction: ' . $transaction->ID()
583
-            );
584
-        }
585
-        // how many tickets were released
586
-        $count = 0;
587
-        if (self::debug) {
588
-            echo '<br /> . . . finalized: ' . $finalized;
589
-        }
590
-        $release_tickets_with_TXN_status = array(
591
-            EEM_Transaction::failed_status_code,
592
-            EEM_Transaction::abandoned_status_code,
593
-            EEM_Transaction::incomplete_status_code,
594
-        );
595
-        // if the session is getting cleared BEFORE the TXN has been finalized
596
-        if (! $finalized || in_array($transaction->status_ID(), $release_tickets_with_TXN_status, true)) {
597
-            // let's cancel any reserved tickets
598
-            $registrations = $transaction->registrations();
599
-            if (! empty($registrations)) {
600
-                foreach ($registrations as $registration) {
601
-                    if ($registration instanceof EE_Registration) {
602
-                        $count += $this->_release_reserved_ticket_for_registration($registration, $transaction);
603
-                    }
604
-                }
605
-            }
606
-        }
607
-        return $count;
608
-    }
609
-
610
-
611
-
612
-    /**
613
-     * releases reserved tickets for an EE_Registration
614
-     * by default, will NOT release tickets for APPROVED registrations
615
-     *
616
-     * @param    EE_Registration $registration
617
-     * @param    EE_Transaction  $transaction
618
-     * @return    int
619
-     * @throws    EE_Error
620
-     */
621
-    protected function _release_reserved_ticket_for_registration(
622
-        EE_Registration $registration,
623
-        EE_Transaction $transaction
624
-    ) {
625
-        $STS_ID = $transaction->status_ID();
626
-        if (self::debug) {
627
-            echo '<br /><br /> ' . __LINE__ . ') ' . __METHOD__ . '() ';
628
-            echo '<br /> . . registration->ID: ' . $registration->ID();
629
-            echo '<br /> . . registration->status_ID: ' . $registration->status_ID();
630
-            echo '<br /> . . transaction->status_ID(): ' . $STS_ID;
631
-        }
632
-        if (
633
-            // release Tickets for Failed Transactions and Abandoned Transactions
634
-            $STS_ID === EEM_Transaction::failed_status_code
635
-            || $STS_ID === EEM_Transaction::abandoned_status_code
636
-            || (
637
-                // also release Tickets for Incomplete Transactions, but ONLY if the Registrations are NOT Approved
638
-                $STS_ID === EEM_Transaction::incomplete_status_code
639
-                && $registration->status_ID() !== EEM_Registration::status_id_approved
640
-            )
641
-        ) {
642
-            $ticket = $registration->ticket();
643
-            if ($ticket instanceof EE_Ticket) {
644
-                return $this->_release_reserved_ticket($ticket);
645
-            }
646
-        }
647
-        return 0;
648
-    }
649
-
650
-
651
-
652
-    /********************************** SESSION_CART_RESET  **********************************/
653
-
654
-
655
-
656
-    /**
657
-     * callback hooked into 'AHEE__EE_Session__reset_cart__before_reset'
658
-     *
659
-     * @param    EE_Session $session
660
-     * @return void
661
-     * @throws EE_Error
662
-     * @throws InvalidArgumentException
663
-     * @throws ReflectionException
664
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
665
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
666
-     */
667
-    public static function session_cart_reset(EE_Session $session)
668
-    {
669
-        if (self::debug) {
670
-            echo '<br /><br /> ' . __LINE__ . ') ' . __METHOD__ . '() ';
671
-        }
672
-        $cart = $session->cart();
673
-        if ($cart instanceof EE_Cart) {
674
-            if (self::debug) {
675
-                echo '<br /><br /> cart instance of EE_Cart: ';
676
-            }
677
-            EED_Ticket_Sales_Monitor::instance()->_session_cart_reset($cart);
678
-        } else {
679
-            if (self::debug) {
680
-                echo '<br /><br /> invalid EE_Cart: ';
681
-                var_export($cart, true);
682
-            }
683
-        }
684
-    }
685
-
686
-
687
-
688
-    /**
689
-     * releases reserved tickets in the EE_Cart
690
-     *
691
-     * @param    EE_Cart $cart
692
-     * @return void
693
-     * @throws EE_Error
694
-     * @throws InvalidArgumentException
695
-     * @throws ReflectionException
696
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
697
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
698
-     */
699
-    protected function _session_cart_reset(EE_Cart $cart)
700
-    {
701
-        if (self::debug) {
702
-            echo '<br /><br /> ' . __LINE__ . ') ' . __METHOD__ . '() ';
703
-        }
704
-        EE_Registry::instance()->load_helper('Line_Item');
705
-        $ticket_line_items = $cart->get_tickets();
706
-        if (empty($ticket_line_items)) {
707
-            return;
708
-        }
709
-        foreach ($ticket_line_items as $ticket_line_item) {
710
-            if (self::debug) {
711
-                echo '<br /> . ticket_line_item->ID(): ' . $ticket_line_item->ID();
712
-            }
713
-            if ($ticket_line_item instanceof EE_Line_Item && $ticket_line_item->OBJ_type() === 'Ticket') {
714
-                if (self::debug) {
715
-                    echo '<br /> . . ticket_line_item->OBJ_ID(): ' . $ticket_line_item->OBJ_ID();
716
-                }
717
-                $ticket = EEM_Ticket::instance()->get_one_by_ID($ticket_line_item->OBJ_ID());
718
-                if ($ticket instanceof EE_Ticket) {
719
-                    if (self::debug) {
720
-                        echo '<br /> . . ticket->ID(): ' . $ticket->ID();
721
-                        echo '<br /> . . ticket_line_item->quantity(): ' . $ticket_line_item->quantity();
722
-                    }
723
-                    $this->_release_reserved_ticket($ticket, $ticket_line_item->quantity());
724
-                }
725
-            }
726
-        }
727
-        if (self::debug) {
728
-            echo '<br /><br /> RESET COMPLETED ';
729
-        }
730
-    }
731
-
732
-
733
-
734
-    /********************************** SESSION_CHECKOUT_RESET  **********************************/
735
-
736
-
737
-
738
-    /**
739
-     * callback hooked into 'AHEE__EE_Session__reset_checkout__before_reset'
740
-     *
741
-     * @param    EE_Session $session
742
-     * @return void
743
-     * @throws EE_Error
744
-     * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
745
-     */
746
-    public static function session_checkout_reset(EE_Session $session)
747
-    {
748
-        $checkout = $session->checkout();
749
-        if ($checkout instanceof EE_Checkout) {
750
-            EED_Ticket_Sales_Monitor::instance()->_session_checkout_reset($checkout);
751
-        }
752
-    }
753
-
754
-
755
-
756
-    /**
757
-     * releases reserved tickets for the EE_Checkout->transaction
758
-     *
759
-     * @param    EE_Checkout $checkout
760
-     * @return void
761
-     * @throws EE_Error
762
-     * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
763
-     */
764
-    protected function _session_checkout_reset(EE_Checkout $checkout)
765
-    {
766
-        if (self::debug) {
767
-            echo '<br /><br /> ' . __LINE__ . ') ' . __METHOD__ . '() ';
768
-        }
769
-        // we want to release the each registration's reserved tickets if the session was cleared, but not if this is a revisit
770
-        if ($checkout->revisit || ! $checkout->transaction instanceof EE_Transaction) {
771
-            return;
772
-        }
773
-        $this->_release_all_reserved_tickets_for_transaction($checkout->transaction);
774
-    }
775
-
776
-
777
-
778
-    /********************************** SESSION_EXPIRED_RESET  **********************************/
779
-
780
-
781
-
782
-    /**
783
-     * @param    EE_Session $session
784
-     * @return    void
785
-     */
786
-    public static function session_expired_reset(EE_Session $session)
787
-    {
788
-    }
789
-
790
-
791
-
792
-    /********************************** PROCESS_ABANDONED_TRANSACTIONS  **********************************/
793
-
794
-
795
-
796
-    /**
797
-     * releases reserved tickets for all registrations of an ABANDONED EE_Transaction
798
-     * by default, will NOT release tickets for free transactions, or any that have received a payment
799
-     *
800
-     * @param    EE_Transaction $transaction
801
-     * @return void
802
-     * @throws EE_Error
803
-     * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
804
-     */
805
-    public static function process_abandoned_transactions(EE_Transaction $transaction)
806
-    {
807
-        // is this TXN free or has any money been paid towards this TXN? If so, then leave it alone
808
-        if ($transaction->is_free() || $transaction->paid() > 0) {
809
-            if (self::debug) {
810
-                // DEBUG LOG
811
-                EEH_Debug_Tools::log(
812
-                    __CLASS__,
813
-                    __FUNCTION__,
814
-                    __LINE__,
815
-                    array($transaction),
816
-                    false,
817
-                    'EE_Transaction: ' . $transaction->ID()
818
-                );
819
-            }
820
-            return;
821
-        }
822
-        // have their been any successful payments made ?
823
-        $payments = $transaction->payments();
824
-        foreach ($payments as $payment) {
825
-            if ($payment instanceof EE_Payment && $payment->status() === EEM_Payment::status_id_approved) {
826
-                if (self::debug) {
827
-                    // DEBUG LOG
828
-                    EEH_Debug_Tools::log(
829
-                        __CLASS__,
830
-                        __FUNCTION__,
831
-                        __LINE__,
832
-                        array($payment),
833
-                        false,
834
-                        'EE_Transaction: ' . $transaction->ID()
835
-                    );
836
-                }
837
-                return;
838
-            }
839
-        }
840
-        // since you haven't even attempted to pay for your ticket...
841
-        EED_Ticket_Sales_Monitor::instance()->_release_all_reserved_tickets_for_transaction($transaction);
842
-    }
843
-
844
-
845
-
846
-    /********************************** PROCESS_FAILED_TRANSACTIONS  **********************************/
847
-
848
-
849
-
850
-    /**
851
-     * releases reserved tickets for absolutely ALL registrations of a FAILED EE_Transaction
852
-     *
853
-     * @param    EE_Transaction $transaction
854
-     * @return void
855
-     * @throws EE_Error
856
-     * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
857
-     */
858
-    public static function process_failed_transactions(EE_Transaction $transaction)
859
-    {
860
-        // since you haven't even attempted to pay for your ticket...
861
-        EED_Ticket_Sales_Monitor::instance()->_release_all_reserved_tickets_for_transaction($transaction);
862
-    }
863
-
864
-
865
-
866
-    /********************************** RESET RESERVATION COUNTS  *********************************/
867
-    /**
868
-     * Resets all ticket and datetime reserved counts to zero
869
-     * Tickets that are currently associated with a Transaction that is in progress
870
-     *
871
-     * @throws \EE_Error
872
-     * @throws \DomainException
873
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
874
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
875
-     * @throws \InvalidArgumentException
876
-     */
877
-    public static function reset_reservation_counts()
878
-    {
879
-        /** @var EE_Line_Item[] $valid_reserved_tickets */
880
-        $valid_reserved_tickets   = array();
881
-        $transactions_in_progress = EEM_Transaction::instance()->get_transactions_in_progress();
882
-        foreach ($transactions_in_progress as $transaction_in_progress) {
883
-            // if this TXN has been fully completed, then skip it
884
-            if ($transaction_in_progress->reg_step_completed('finalize_registration')) {
885
-                continue;
886
-            }
887
-            /** @var EE_Transaction $transaction_in_progress */
888
-            $total_line_item = $transaction_in_progress->total_line_item();
889
-            // $transaction_in_progress->line
890
-            if (! $total_line_item instanceof EE_Line_Item) {
891
-                throw new DomainException(
892
-                    esc_html__(
893
-                        'Transaction does not have a valid Total Line Item associated with it.',
894
-                        'event_espresso'
895
-                    )
896
-                );
897
-            }
898
-            $valid_reserved_tickets += EED_Ticket_Sales_Monitor::get_ticket_line_items_for_grand_total(
899
-                $total_line_item
900
-            );
901
-        }
902
-        $total_line_items = EEM_Line_Item::instance()->get_total_line_items_for_active_carts();
903
-        foreach ($total_line_items as $total_line_item) {
904
-            $valid_reserved_tickets += EED_Ticket_Sales_Monitor::get_ticket_line_items_for_grand_total(
905
-                $total_line_item
906
-            );
907
-        }
908
-        return EED_Ticket_Sales_Monitor::release_reservations_for_tickets(
909
-            EEM_Ticket::instance()->get_tickets_with_reservations(),
910
-            $valid_reserved_tickets
911
-        );
912
-    }
913
-
914
-
915
-
916
-    /**
917
-     * @param EE_Line_Item $total_line_item
918
-     * @return EE_Line_Item[]
919
-     */
920
-    private static function get_ticket_line_items_for_grand_total(EE_Line_Item $total_line_item)
921
-    {
922
-        /** @var EE_Line_Item[] $valid_reserved_tickets */
923
-        $valid_reserved_tickets = array();
924
-        $ticket_line_items      = EEH_Line_Item::get_ticket_line_items($total_line_item);
925
-        foreach ($ticket_line_items as $ticket_line_item) {
926
-            if ($ticket_line_item instanceof EE_Line_Item) {
927
-                $valid_reserved_tickets[] = $ticket_line_item;
928
-            }
929
-        }
930
-        return $valid_reserved_tickets;
931
-    }
932
-
933
-
934
-
935
-    /**
936
-     * @param EE_Ticket[]    $tickets_with_reservations
937
-     * @param EE_Line_Item[] $valid_reserved_ticket_line_items
938
-     * @return int
939
-     * @throws \EE_Error
940
-     */
941
-    private static function release_reservations_for_tickets(
942
-        array $tickets_with_reservations,
943
-        $valid_reserved_ticket_line_items = array()
944
-    ) {
945
-        $total_tickets_released = 0;
946
-        foreach ($tickets_with_reservations as $ticket_with_reservations) {
947
-            if (! $ticket_with_reservations instanceof EE_Ticket) {
948
-                continue;
949
-            }
950
-            $reserved_qty = $ticket_with_reservations->reserved();
951
-            foreach ($valid_reserved_ticket_line_items as $valid_reserved_ticket_line_item) {
952
-                if (
953
-                    $valid_reserved_ticket_line_item instanceof EE_Line_Item
954
-                    && $valid_reserved_ticket_line_item->OBJ_ID() === $ticket_with_reservations->ID()
955
-                ) {
956
-                    $reserved_qty -= $valid_reserved_ticket_line_item->quantity();
957
-                }
958
-            }
959
-            if ($reserved_qty > 0) {
960
-                $ticket_with_reservations->decrease_reserved($reserved_qty);
961
-                $ticket_with_reservations->save();
962
-                $total_tickets_released += $reserved_qty;
963
-            }
964
-        }
965
-        return $total_tickets_released;
966
-    }
967
-
968
-
969
-
970
-    /********************************** SHUTDOWN  **********************************/
971
-
972
-
973
-
974
-    /**
975
-     * @return false|int
976
-     * @throws EE_Error
977
-     * @throws InvalidArgumentException
978
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
979
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
980
-     */
981
-    public static function clear_expired_line_items_with_no_transaction()
982
-    {
983
-        /** @type WPDB $wpdb */
984
-        global $wpdb;
985
-        return $wpdb->query(
986
-            $wpdb->prepare(
987
-                'DELETE FROM ' . EEM_Line_Item::instance()->table() . '
25
+	const debug = false;    //	true false
26
+
27
+	/**
28
+	 * an array of raw ticket data from EED_Ticket_Selector
29
+	 *
30
+	 * @var array $ticket_selections
31
+	 */
32
+	protected $ticket_selections = array();
33
+
34
+	/**
35
+	 * the raw ticket data from EED_Ticket_Selector is organized in rows
36
+	 * according to how they are displayed in the actual Ticket_Selector
37
+	 * this tracks the current row being processed
38
+	 *
39
+	 * @var int $current_row
40
+	 */
41
+	protected $current_row = 0;
42
+
43
+	/**
44
+	 * an array for tracking names of tickets that have sold out
45
+	 *
46
+	 * @var array $sold_out_tickets
47
+	 */
48
+	protected $sold_out_tickets = array();
49
+
50
+	/**
51
+	 * an array for tracking names of tickets that have had their quantities reduced
52
+	 *
53
+	 * @var array $decremented_tickets
54
+	 */
55
+	protected $decremented_tickets = array();
56
+
57
+
58
+
59
+	/**
60
+	 * set_hooks - for hooking into EE Core, other modules, etc
61
+	 *
62
+	 * @return    void
63
+	 */
64
+	public static function set_hooks()
65
+	{
66
+		// release tickets for expired carts
67
+		add_action(
68
+			'EED_Ticket_Selector__process_ticket_selections__before',
69
+			array('EED_Ticket_Sales_Monitor', 'release_tickets_for_expired_carts'),
70
+			1
71
+		);
72
+		// check ticket reserves AFTER MER does it's check (hence priority 20)
73
+		add_filter(
74
+			'FHEE__EE_Ticket_Selector___add_ticket_to_cart__ticket_qty',
75
+			array('EED_Ticket_Sales_Monitor', 'validate_ticket_sale'),
76
+			20,
77
+			3
78
+		);
79
+		// add notices for sold out tickets
80
+		add_action(
81
+			'AHEE__EE_Ticket_Selector__process_ticket_selections__after_tickets_added_to_cart',
82
+			array('EED_Ticket_Sales_Monitor', 'post_notices'),
83
+			10
84
+		);
85
+		// handle ticket quantities adjusted in cart
86
+		//add_action(
87
+		//	'FHEE__EED_Multi_Event_Registration__adjust_line_item_quantity__line_item_quantity_updated',
88
+		//	array( 'EED_Ticket_Sales_Monitor', 'ticket_quantity_updated' ),
89
+		//	10, 2
90
+		//);
91
+		// handle tickets deleted from cart
92
+		add_action(
93
+			'FHEE__EED_Multi_Event_Registration__delete_ticket__ticket_removed_from_cart',
94
+			array('EED_Ticket_Sales_Monitor', 'ticket_removed_from_cart'),
95
+			10,
96
+			2
97
+		);
98
+		// handle emptied carts
99
+		add_action(
100
+			'AHEE__EE_Session__reset_cart__before_reset',
101
+			array('EED_Ticket_Sales_Monitor', 'session_cart_reset'),
102
+			10,
103
+			1
104
+		);
105
+		add_action(
106
+			'AHEE__EED_Multi_Event_Registration__empty_event_cart__before_delete_cart',
107
+			array('EED_Ticket_Sales_Monitor', 'session_cart_reset'),
108
+			10,
109
+			1
110
+		);
111
+		// handle cancelled registrations
112
+		add_action(
113
+			'AHEE__EE_Session__reset_checkout__before_reset',
114
+			array('EED_Ticket_Sales_Monitor', 'session_checkout_reset'),
115
+			10,
116
+			1
117
+		);
118
+		// cron tasks
119
+		add_action(
120
+			'AHEE__EE_Cron_Tasks__process_expired_transactions__abandoned_transaction',
121
+			array('EED_Ticket_Sales_Monitor', 'process_abandoned_transactions'),
122
+			10,
123
+			1
124
+		);
125
+		add_action(
126
+			'AHEE__EE_Cron_Tasks__process_expired_transactions__incomplete_transaction',
127
+			array('EED_Ticket_Sales_Monitor', 'process_abandoned_transactions'),
128
+			10,
129
+			1
130
+		);
131
+		add_action(
132
+			'AHEE__EE_Cron_Tasks__process_expired_transactions__failed_transaction',
133
+			array('EED_Ticket_Sales_Monitor', 'process_failed_transactions'),
134
+			10,
135
+			1
136
+		);
137
+	}
138
+
139
+
140
+
141
+	/**
142
+	 * set_hooks_admin - for hooking into EE Admin Core, other modules, etc
143
+	 *
144
+	 * @return void
145
+	 */
146
+	public static function set_hooks_admin()
147
+	{
148
+		EED_Ticket_Sales_Monitor::set_hooks();
149
+	}
150
+
151
+
152
+
153
+	/**
154
+	 * @return EED_Ticket_Sales_Monitor|EED_Module
155
+	 */
156
+	public static function instance()
157
+	{
158
+		return parent::get_instance(__CLASS__);
159
+	}
160
+
161
+
162
+
163
+	/**
164
+	 * @param WP_Query $WP_Query
165
+	 * @return    void
166
+	 */
167
+	public function run($WP_Query)
168
+	{
169
+	}
170
+
171
+
172
+
173
+	/********************************** PRE_TICKET_SALES  **********************************/
174
+
175
+
176
+
177
+	/**
178
+	 * Retrieves grand totals from the line items that have no TXN ID
179
+	 * and timestamps less than the current time minus the session lifespan.
180
+	 * These are carts that have been abandoned before the "registrant" even attempted to checkout.
181
+	 * We're going to release the tickets for these line items before attempting to add more to the cart.
182
+	 *
183
+	 * @return void
184
+	 * @throws EE_Error
185
+	 * @throws InvalidArgumentException
186
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
187
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
188
+	 */
189
+	public static function release_tickets_for_expired_carts()
190
+	{
191
+		do_action('AHEE__EED_Ticket_Sales_Monitor__release_tickets_for_expired_carts__begin');
192
+		$expired_ticket_IDs      = array();
193
+		$valid_ticket_line_items = array();
194
+		$total_line_items        = EEM_Line_Item::instance()->get_total_line_items_with_no_transaction();
195
+		if (empty($total_line_items)) {
196
+			do_action(
197
+				'AHEE__EED_Ticket_Sales_Monitor__release_tickets_for_expired_carts__end',
198
+				$total_line_items,
199
+				$valid_ticket_line_items,
200
+				$expired_ticket_IDs
201
+			);
202
+			return;
203
+		}
204
+		$expired = current_time('timestamp') - EE_Registry::instance()->SSN->lifespan();
205
+		foreach ($total_line_items as $total_line_item) {
206
+			/** @var EE_Line_Item $total_line_item */
207
+			$ticket_line_items = EED_Ticket_Sales_Monitor::get_ticket_line_items_for_grand_total($total_line_item);
208
+			foreach ($ticket_line_items as $ticket_line_item) {
209
+				if (! $ticket_line_item instanceof EE_Line_Item) {
210
+					continue;
211
+				}
212
+				if ($total_line_item->timestamp(true) <= $expired) {
213
+					$expired_ticket_IDs[$ticket_line_item->OBJ_ID()] = $ticket_line_item->OBJ_ID();
214
+				} else {
215
+					$valid_ticket_line_items[$ticket_line_item->OBJ_ID()] = $ticket_line_item;
216
+				}
217
+			}
218
+		}
219
+		if (! empty($expired_ticket_IDs)) {
220
+			EED_Ticket_Sales_Monitor::release_reservations_for_tickets(
221
+				\EEM_Ticket::instance()->get_tickets_with_IDs($expired_ticket_IDs),
222
+				$valid_ticket_line_items
223
+			);
224
+			// let's get rid of expired line items so that they can't interfere with tracking
225
+			add_action(
226
+				'shutdown',
227
+				array('EED_Ticket_Sales_Monitor', 'clear_expired_line_items_with_no_transaction'),
228
+				999
229
+			);
230
+		}
231
+		do_action(
232
+			'AHEE__EED_Ticket_Sales_Monitor__release_tickets_for_expired_carts__end',
233
+			$total_line_items,
234
+			$valid_ticket_line_items,
235
+			$expired_ticket_IDs
236
+		);
237
+	}
238
+
239
+
240
+
241
+	/********************************** VALIDATE_TICKET_SALE  **********************************/
242
+
243
+
244
+
245
+	/**
246
+	 * callback for 'FHEE__EED_Ticket_Selector__process_ticket_selections__valid_post_data'
247
+	 *
248
+	 * @param int       $qty
249
+	 * @param EE_Ticket $ticket
250
+	 * @return bool
251
+	 * @throws UnexpectedEntityException
252
+	 * @throws EE_Error
253
+	 */
254
+	public static function validate_ticket_sale($qty = 1, EE_Ticket $ticket)
255
+	{
256
+		$qty = absint($qty);
257
+		if ($qty > 0) {
258
+			$qty = EED_Ticket_Sales_Monitor::instance()->_validate_ticket_sale($ticket, $qty);
259
+		}
260
+		if (self::debug) {
261
+			echo '<br /><br /> ' . __LINE__ . ') ' . __METHOD__ . '()';
262
+			echo '<br /><br /><b> RETURNED QTY: ' . $qty . '</b>';
263
+		}
264
+		return $qty;
265
+	}
266
+
267
+
268
+
269
+	/**
270
+	 * checks whether an individual ticket is available for purchase based on datetime, and ticket details
271
+	 *
272
+	 * @param   EE_Ticket $ticket
273
+	 * @param int         $qty
274
+	 * @return int
275
+	 * @throws UnexpectedEntityException
276
+	 * @throws EE_Error
277
+	 */
278
+	protected function _validate_ticket_sale(EE_Ticket $ticket, $qty = 1)
279
+	{
280
+		if (self::debug) {
281
+			echo '<br /><br /> ' . __LINE__ . ') ' . __METHOD__ . '() ';
282
+		}
283
+		if (! $ticket instanceof EE_Ticket) {
284
+			return 0;
285
+		}
286
+		if (self::debug) {
287
+			echo '<br /><b> . ticket->ID: ' . $ticket->ID() . '</b>';
288
+			echo '<br /> . original ticket->reserved: ' . $ticket->reserved();
289
+		}
290
+		$ticket->refresh_from_db();
291
+		// first let's determine the ticket availability based on sales
292
+		$available = $ticket->qty('saleable');
293
+		if (self::debug) {
294
+			echo '<br /> . . . ticket->qty: ' . $ticket->qty();
295
+			echo '<br /> . . . ticket->sold: ' . $ticket->sold();
296
+			echo '<br /> . . . ticket->reserved: ' . $ticket->reserved();
297
+			echo '<br /> . . . ticket->qty(saleable): ' . $ticket->qty('saleable');
298
+			echo '<br /> . . . available: ' . $available;
299
+		}
300
+		if ($available < 1) {
301
+			$this->_ticket_sold_out($ticket);
302
+			return 0;
303
+		}
304
+		if (self::debug) {
305
+			echo '<br /> . . . qty: ' . $qty;
306
+		}
307
+		if ($available < $qty) {
308
+			$qty = $available;
309
+			if (self::debug) {
310
+				echo '<br /> . . . QTY ADJUSTED: ' . $qty;
311
+			}
312
+			$this->_ticket_quantity_decremented($ticket);
313
+		}
314
+		$this->_reserve_ticket($ticket, $qty);
315
+		return $qty;
316
+	}
317
+
318
+
319
+
320
+	/**
321
+	 * increments ticket reserved based on quantity passed
322
+	 *
323
+	 * @param    EE_Ticket $ticket
324
+	 * @param int          $quantity
325
+	 * @return bool
326
+	 * @throws EE_Error
327
+	 */
328
+	protected function _reserve_ticket(EE_Ticket $ticket, $quantity = 1)
329
+	{
330
+		if (self::debug) {
331
+			echo '<br /><br /> . . . INCREASE RESERVED: ' . $quantity;
332
+		}
333
+		$ticket->increase_reserved($quantity);
334
+		return $ticket->save();
335
+	}
336
+
337
+
338
+
339
+	/**
340
+	 * @param  EE_Ticket $ticket
341
+	 * @param  int       $quantity
342
+	 * @return bool
343
+	 * @throws EE_Error
344
+	 */
345
+	protected function _release_reserved_ticket(EE_Ticket $ticket, $quantity = 1)
346
+	{
347
+		if (self::debug) {
348
+			echo '<br /> . . . ticket->ID: ' . $ticket->ID();
349
+			echo '<br /> . . . ticket->reserved: ' . $ticket->reserved();
350
+		}
351
+		$ticket->decrease_reserved($quantity);
352
+		if (self::debug) {
353
+			echo '<br /> . . . ticket->reserved: ' . $ticket->reserved();
354
+		}
355
+		return $ticket->save() ? 1 : 0;
356
+	}
357
+
358
+
359
+
360
+	/**
361
+	 * removes quantities within the ticket selector based on zero ticket availability
362
+	 *
363
+	 * @param    EE_Ticket $ticket
364
+	 * @return    void
365
+	 * @throws UnexpectedEntityException
366
+	 * @throws EE_Error
367
+	 */
368
+	protected function _ticket_sold_out(EE_Ticket $ticket)
369
+	{
370
+		if (self::debug) {
371
+			echo '<br /><br /> ' . __LINE__ . ') ' . __METHOD__ . '() ';
372
+			echo '<br /> . . ticket->name: ' . $this->_get_ticket_and_event_name($ticket);
373
+		}
374
+		$this->sold_out_tickets[] = $this->_get_ticket_and_event_name($ticket);
375
+	}
376
+
377
+
378
+
379
+	/**
380
+	 * adjusts quantities within the ticket selector based on decreased ticket availability
381
+	 *
382
+	 * @param    EE_Ticket $ticket
383
+	 * @return void
384
+	 * @throws UnexpectedEntityException
385
+	 * @throws EE_Error
386
+	 */
387
+	protected function _ticket_quantity_decremented(EE_Ticket $ticket)
388
+	{
389
+		if (self::debug) {
390
+			echo '<br /><br /> ' . __LINE__ . ') ' . __METHOD__ . '() ';
391
+			echo '<br /> . . ticket->name: ' . $this->_get_ticket_and_event_name($ticket);
392
+		}
393
+		$this->decremented_tickets[] = $this->_get_ticket_and_event_name($ticket);
394
+	}
395
+
396
+
397
+
398
+	/**
399
+	 * builds string out of ticket and event name
400
+	 *
401
+	 * @param    EE_Ticket $ticket
402
+	 * @return string
403
+	 * @throws UnexpectedEntityException
404
+	 * @throws EE_Error
405
+	 */
406
+	protected function _get_ticket_and_event_name(EE_Ticket $ticket)
407
+	{
408
+		$event = $ticket->get_related_event();
409
+		if ($event instanceof EE_Event) {
410
+			$ticket_name = sprintf(
411
+				_x('%1$s for %2$s', 'ticket name for event name', 'event_espresso'),
412
+				$ticket->name(),
413
+				$event->name()
414
+			);
415
+		} else {
416
+			$ticket_name = $ticket->name();
417
+		}
418
+		return $ticket_name;
419
+	}
420
+
421
+
422
+
423
+	/********************************** EVENT CART  **********************************/
424
+
425
+
426
+
427
+	/**
428
+	 * releases or reserves ticket(s) based on quantity passed
429
+	 *
430
+	 * @param  EE_Line_Item $line_item
431
+	 * @param  int          $quantity
432
+	 * @return void
433
+	 * @throws EE_Error
434
+	 * @throws InvalidArgumentException
435
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
436
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
437
+	 */
438
+	public static function ticket_quantity_updated(EE_Line_Item $line_item, $quantity = 1)
439
+	{
440
+		$ticket = EEM_Ticket::instance()->get_one_by_ID(absint($line_item->OBJ_ID()));
441
+		if ($ticket instanceof EE_Ticket) {
442
+			if ($quantity > 0) {
443
+				EED_Ticket_Sales_Monitor::instance()->_reserve_ticket($ticket, $quantity);
444
+			} else {
445
+				EED_Ticket_Sales_Monitor::instance()->_release_reserved_ticket($ticket, $quantity);
446
+			}
447
+		}
448
+	}
449
+
450
+
451
+
452
+	/**
453
+	 * releases reserved ticket(s) based on quantity passed
454
+	 *
455
+	 * @param  EE_Ticket $ticket
456
+	 * @param  int       $quantity
457
+	 * @return void
458
+	 * @throws EE_Error
459
+	 */
460
+	public static function ticket_removed_from_cart(EE_Ticket $ticket, $quantity = 1)
461
+	{
462
+		EED_Ticket_Sales_Monitor::instance()->_release_reserved_ticket($ticket, $quantity);
463
+	}
464
+
465
+
466
+
467
+	/********************************** POST_NOTICES  **********************************/
468
+
469
+
470
+
471
+	/**
472
+	 * @return void
473
+	 * @throws EE_Error
474
+	 * @throws InvalidArgumentException
475
+	 * @throws ReflectionException
476
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
477
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
478
+	 */
479
+	public static function post_notices()
480
+	{
481
+		EED_Ticket_Sales_Monitor::instance()->_post_notices();
482
+	}
483
+
484
+
485
+
486
+	/**
487
+	 * @return void
488
+	 * @throws EE_Error
489
+	 * @throws InvalidArgumentException
490
+	 * @throws ReflectionException
491
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
492
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
493
+	 */
494
+	protected function _post_notices()
495
+	{
496
+		if (self::debug) {
497
+			echo '<br /><br /> ' . __LINE__ . ') ' . __METHOD__ . '() ';
498
+		}
499
+		$refresh_msg    = '';
500
+		$none_added_msg = '';
501
+		if (defined('DOING_AJAX') && DOING_AJAX) {
502
+			$refresh_msg    = __(
503
+				'Please refresh the page to view updated ticket quantities.',
504
+				'event_espresso'
505
+			);
506
+			$none_added_msg = __('No tickets were added for the event.', 'event_espresso');
507
+		}
508
+		if (! empty($this->sold_out_tickets)) {
509
+			EE_Error::add_attention(
510
+				sprintf(
511
+					apply_filters(
512
+						'FHEE__EED_Ticket_Sales_Monitor___post_notices__sold_out_tickets_notice',
513
+						__(
514
+							'We\'re sorry...%1$sThe following items have sold out since you first viewed this page, and can no longer be registered for:%1$s%1$s%2$s%1$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.%1$s%1$s%3$s%1$s%4$s%1$s',
515
+							'event_espresso'
516
+						)
517
+					),
518
+					'<br />',
519
+					implode('<br />', $this->sold_out_tickets),
520
+					$none_added_msg,
521
+					$refresh_msg
522
+				)
523
+			);
524
+			// alter code flow in the Ticket Selector for better UX
525
+			add_filter('FHEE__EED_Ticket_Selector__process_ticket_selections__tckts_slctd', '__return_true');
526
+			add_filter('FHEE__EED_Ticket_Selector__process_ticket_selections__success', '__return_false');
527
+			$this->sold_out_tickets = array();
528
+			// and reset the cart
529
+			EED_Ticket_Sales_Monitor::session_cart_reset(EE_Registry::instance()->SSN);
530
+		}
531
+		if (! empty($this->decremented_tickets)) {
532
+			EE_Error::add_attention(
533
+				sprintf(
534
+					apply_filters(
535
+						'FHEE__EED_Ticket_Sales_Monitor___ticket_quantity_decremented__notice',
536
+						__(
537
+							'We\'re sorry...%1$sDue to sales that have occurred since you first viewed the last page, the following items have had their quantities adjusted to match the current available amount:%1$s%1$s%2$s%1$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.%1$s%1$s%3$s%1$s%4$s%1$s',
538
+							'event_espresso'
539
+						)
540
+					),
541
+					'<br />',
542
+					implode('<br />', $this->decremented_tickets),
543
+					$none_added_msg,
544
+					$refresh_msg
545
+				)
546
+			);
547
+			$this->decremented_tickets = array();
548
+		}
549
+	}
550
+
551
+
552
+
553
+	/********************************** RELEASE_ALL_RESERVED_TICKETS_FOR_TRANSACTION  **********************************/
554
+
555
+
556
+
557
+	/**
558
+	 * releases reserved tickets for all registrations of an EE_Transaction
559
+	 * by default, will NOT release tickets for finalized transactions
560
+	 *
561
+	 * @param    EE_Transaction $transaction
562
+	 * @return int
563
+	 * @throws EE_Error
564
+	 * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
565
+	 */
566
+	protected function _release_all_reserved_tickets_for_transaction(EE_Transaction $transaction)
567
+	{
568
+		if (self::debug) {
569
+			echo '<br /><br /> ' . __LINE__ . ') ' . __METHOD__ . '() ';
570
+			echo '<br /> . transaction->ID: ' . $transaction->ID();
571
+		}
572
+		// check if 'finalize_registration' step has been completed...
573
+		$finalized = $transaction->reg_step_completed('finalize_registration');
574
+		if (self::debug) {
575
+			// DEBUG LOG
576
+			EEH_Debug_Tools::log(
577
+				__CLASS__,
578
+				__FUNCTION__,
579
+				__LINE__,
580
+				array('finalized' => $finalized),
581
+				false,
582
+				'EE_Transaction: ' . $transaction->ID()
583
+			);
584
+		}
585
+		// how many tickets were released
586
+		$count = 0;
587
+		if (self::debug) {
588
+			echo '<br /> . . . finalized: ' . $finalized;
589
+		}
590
+		$release_tickets_with_TXN_status = array(
591
+			EEM_Transaction::failed_status_code,
592
+			EEM_Transaction::abandoned_status_code,
593
+			EEM_Transaction::incomplete_status_code,
594
+		);
595
+		// if the session is getting cleared BEFORE the TXN has been finalized
596
+		if (! $finalized || in_array($transaction->status_ID(), $release_tickets_with_TXN_status, true)) {
597
+			// let's cancel any reserved tickets
598
+			$registrations = $transaction->registrations();
599
+			if (! empty($registrations)) {
600
+				foreach ($registrations as $registration) {
601
+					if ($registration instanceof EE_Registration) {
602
+						$count += $this->_release_reserved_ticket_for_registration($registration, $transaction);
603
+					}
604
+				}
605
+			}
606
+		}
607
+		return $count;
608
+	}
609
+
610
+
611
+
612
+	/**
613
+	 * releases reserved tickets for an EE_Registration
614
+	 * by default, will NOT release tickets for APPROVED registrations
615
+	 *
616
+	 * @param    EE_Registration $registration
617
+	 * @param    EE_Transaction  $transaction
618
+	 * @return    int
619
+	 * @throws    EE_Error
620
+	 */
621
+	protected function _release_reserved_ticket_for_registration(
622
+		EE_Registration $registration,
623
+		EE_Transaction $transaction
624
+	) {
625
+		$STS_ID = $transaction->status_ID();
626
+		if (self::debug) {
627
+			echo '<br /><br /> ' . __LINE__ . ') ' . __METHOD__ . '() ';
628
+			echo '<br /> . . registration->ID: ' . $registration->ID();
629
+			echo '<br /> . . registration->status_ID: ' . $registration->status_ID();
630
+			echo '<br /> . . transaction->status_ID(): ' . $STS_ID;
631
+		}
632
+		if (
633
+			// release Tickets for Failed Transactions and Abandoned Transactions
634
+			$STS_ID === EEM_Transaction::failed_status_code
635
+			|| $STS_ID === EEM_Transaction::abandoned_status_code
636
+			|| (
637
+				// also release Tickets for Incomplete Transactions, but ONLY if the Registrations are NOT Approved
638
+				$STS_ID === EEM_Transaction::incomplete_status_code
639
+				&& $registration->status_ID() !== EEM_Registration::status_id_approved
640
+			)
641
+		) {
642
+			$ticket = $registration->ticket();
643
+			if ($ticket instanceof EE_Ticket) {
644
+				return $this->_release_reserved_ticket($ticket);
645
+			}
646
+		}
647
+		return 0;
648
+	}
649
+
650
+
651
+
652
+	/********************************** SESSION_CART_RESET  **********************************/
653
+
654
+
655
+
656
+	/**
657
+	 * callback hooked into 'AHEE__EE_Session__reset_cart__before_reset'
658
+	 *
659
+	 * @param    EE_Session $session
660
+	 * @return void
661
+	 * @throws EE_Error
662
+	 * @throws InvalidArgumentException
663
+	 * @throws ReflectionException
664
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
665
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
666
+	 */
667
+	public static function session_cart_reset(EE_Session $session)
668
+	{
669
+		if (self::debug) {
670
+			echo '<br /><br /> ' . __LINE__ . ') ' . __METHOD__ . '() ';
671
+		}
672
+		$cart = $session->cart();
673
+		if ($cart instanceof EE_Cart) {
674
+			if (self::debug) {
675
+				echo '<br /><br /> cart instance of EE_Cart: ';
676
+			}
677
+			EED_Ticket_Sales_Monitor::instance()->_session_cart_reset($cart);
678
+		} else {
679
+			if (self::debug) {
680
+				echo '<br /><br /> invalid EE_Cart: ';
681
+				var_export($cart, true);
682
+			}
683
+		}
684
+	}
685
+
686
+
687
+
688
+	/**
689
+	 * releases reserved tickets in the EE_Cart
690
+	 *
691
+	 * @param    EE_Cart $cart
692
+	 * @return void
693
+	 * @throws EE_Error
694
+	 * @throws InvalidArgumentException
695
+	 * @throws ReflectionException
696
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
697
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
698
+	 */
699
+	protected function _session_cart_reset(EE_Cart $cart)
700
+	{
701
+		if (self::debug) {
702
+			echo '<br /><br /> ' . __LINE__ . ') ' . __METHOD__ . '() ';
703
+		}
704
+		EE_Registry::instance()->load_helper('Line_Item');
705
+		$ticket_line_items = $cart->get_tickets();
706
+		if (empty($ticket_line_items)) {
707
+			return;
708
+		}
709
+		foreach ($ticket_line_items as $ticket_line_item) {
710
+			if (self::debug) {
711
+				echo '<br /> . ticket_line_item->ID(): ' . $ticket_line_item->ID();
712
+			}
713
+			if ($ticket_line_item instanceof EE_Line_Item && $ticket_line_item->OBJ_type() === 'Ticket') {
714
+				if (self::debug) {
715
+					echo '<br /> . . ticket_line_item->OBJ_ID(): ' . $ticket_line_item->OBJ_ID();
716
+				}
717
+				$ticket = EEM_Ticket::instance()->get_one_by_ID($ticket_line_item->OBJ_ID());
718
+				if ($ticket instanceof EE_Ticket) {
719
+					if (self::debug) {
720
+						echo '<br /> . . ticket->ID(): ' . $ticket->ID();
721
+						echo '<br /> . . ticket_line_item->quantity(): ' . $ticket_line_item->quantity();
722
+					}
723
+					$this->_release_reserved_ticket($ticket, $ticket_line_item->quantity());
724
+				}
725
+			}
726
+		}
727
+		if (self::debug) {
728
+			echo '<br /><br /> RESET COMPLETED ';
729
+		}
730
+	}
731
+
732
+
733
+
734
+	/********************************** SESSION_CHECKOUT_RESET  **********************************/
735
+
736
+
737
+
738
+	/**
739
+	 * callback hooked into 'AHEE__EE_Session__reset_checkout__before_reset'
740
+	 *
741
+	 * @param    EE_Session $session
742
+	 * @return void
743
+	 * @throws EE_Error
744
+	 * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
745
+	 */
746
+	public static function session_checkout_reset(EE_Session $session)
747
+	{
748
+		$checkout = $session->checkout();
749
+		if ($checkout instanceof EE_Checkout) {
750
+			EED_Ticket_Sales_Monitor::instance()->_session_checkout_reset($checkout);
751
+		}
752
+	}
753
+
754
+
755
+
756
+	/**
757
+	 * releases reserved tickets for the EE_Checkout->transaction
758
+	 *
759
+	 * @param    EE_Checkout $checkout
760
+	 * @return void
761
+	 * @throws EE_Error
762
+	 * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
763
+	 */
764
+	protected function _session_checkout_reset(EE_Checkout $checkout)
765
+	{
766
+		if (self::debug) {
767
+			echo '<br /><br /> ' . __LINE__ . ') ' . __METHOD__ . '() ';
768
+		}
769
+		// we want to release the each registration's reserved tickets if the session was cleared, but not if this is a revisit
770
+		if ($checkout->revisit || ! $checkout->transaction instanceof EE_Transaction) {
771
+			return;
772
+		}
773
+		$this->_release_all_reserved_tickets_for_transaction($checkout->transaction);
774
+	}
775
+
776
+
777
+
778
+	/********************************** SESSION_EXPIRED_RESET  **********************************/
779
+
780
+
781
+
782
+	/**
783
+	 * @param    EE_Session $session
784
+	 * @return    void
785
+	 */
786
+	public static function session_expired_reset(EE_Session $session)
787
+	{
788
+	}
789
+
790
+
791
+
792
+	/********************************** PROCESS_ABANDONED_TRANSACTIONS  **********************************/
793
+
794
+
795
+
796
+	/**
797
+	 * releases reserved tickets for all registrations of an ABANDONED EE_Transaction
798
+	 * by default, will NOT release tickets for free transactions, or any that have received a payment
799
+	 *
800
+	 * @param    EE_Transaction $transaction
801
+	 * @return void
802
+	 * @throws EE_Error
803
+	 * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
804
+	 */
805
+	public static function process_abandoned_transactions(EE_Transaction $transaction)
806
+	{
807
+		// is this TXN free or has any money been paid towards this TXN? If so, then leave it alone
808
+		if ($transaction->is_free() || $transaction->paid() > 0) {
809
+			if (self::debug) {
810
+				// DEBUG LOG
811
+				EEH_Debug_Tools::log(
812
+					__CLASS__,
813
+					__FUNCTION__,
814
+					__LINE__,
815
+					array($transaction),
816
+					false,
817
+					'EE_Transaction: ' . $transaction->ID()
818
+				);
819
+			}
820
+			return;
821
+		}
822
+		// have their been any successful payments made ?
823
+		$payments = $transaction->payments();
824
+		foreach ($payments as $payment) {
825
+			if ($payment instanceof EE_Payment && $payment->status() === EEM_Payment::status_id_approved) {
826
+				if (self::debug) {
827
+					// DEBUG LOG
828
+					EEH_Debug_Tools::log(
829
+						__CLASS__,
830
+						__FUNCTION__,
831
+						__LINE__,
832
+						array($payment),
833
+						false,
834
+						'EE_Transaction: ' . $transaction->ID()
835
+					);
836
+				}
837
+				return;
838
+			}
839
+		}
840
+		// since you haven't even attempted to pay for your ticket...
841
+		EED_Ticket_Sales_Monitor::instance()->_release_all_reserved_tickets_for_transaction($transaction);
842
+	}
843
+
844
+
845
+
846
+	/********************************** PROCESS_FAILED_TRANSACTIONS  **********************************/
847
+
848
+
849
+
850
+	/**
851
+	 * releases reserved tickets for absolutely ALL registrations of a FAILED EE_Transaction
852
+	 *
853
+	 * @param    EE_Transaction $transaction
854
+	 * @return void
855
+	 * @throws EE_Error
856
+	 * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
857
+	 */
858
+	public static function process_failed_transactions(EE_Transaction $transaction)
859
+	{
860
+		// since you haven't even attempted to pay for your ticket...
861
+		EED_Ticket_Sales_Monitor::instance()->_release_all_reserved_tickets_for_transaction($transaction);
862
+	}
863
+
864
+
865
+
866
+	/********************************** RESET RESERVATION COUNTS  *********************************/
867
+	/**
868
+	 * Resets all ticket and datetime reserved counts to zero
869
+	 * Tickets that are currently associated with a Transaction that is in progress
870
+	 *
871
+	 * @throws \EE_Error
872
+	 * @throws \DomainException
873
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
874
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
875
+	 * @throws \InvalidArgumentException
876
+	 */
877
+	public static function reset_reservation_counts()
878
+	{
879
+		/** @var EE_Line_Item[] $valid_reserved_tickets */
880
+		$valid_reserved_tickets   = array();
881
+		$transactions_in_progress = EEM_Transaction::instance()->get_transactions_in_progress();
882
+		foreach ($transactions_in_progress as $transaction_in_progress) {
883
+			// if this TXN has been fully completed, then skip it
884
+			if ($transaction_in_progress->reg_step_completed('finalize_registration')) {
885
+				continue;
886
+			}
887
+			/** @var EE_Transaction $transaction_in_progress */
888
+			$total_line_item = $transaction_in_progress->total_line_item();
889
+			// $transaction_in_progress->line
890
+			if (! $total_line_item instanceof EE_Line_Item) {
891
+				throw new DomainException(
892
+					esc_html__(
893
+						'Transaction does not have a valid Total Line Item associated with it.',
894
+						'event_espresso'
895
+					)
896
+				);
897
+			}
898
+			$valid_reserved_tickets += EED_Ticket_Sales_Monitor::get_ticket_line_items_for_grand_total(
899
+				$total_line_item
900
+			);
901
+		}
902
+		$total_line_items = EEM_Line_Item::instance()->get_total_line_items_for_active_carts();
903
+		foreach ($total_line_items as $total_line_item) {
904
+			$valid_reserved_tickets += EED_Ticket_Sales_Monitor::get_ticket_line_items_for_grand_total(
905
+				$total_line_item
906
+			);
907
+		}
908
+		return EED_Ticket_Sales_Monitor::release_reservations_for_tickets(
909
+			EEM_Ticket::instance()->get_tickets_with_reservations(),
910
+			$valid_reserved_tickets
911
+		);
912
+	}
913
+
914
+
915
+
916
+	/**
917
+	 * @param EE_Line_Item $total_line_item
918
+	 * @return EE_Line_Item[]
919
+	 */
920
+	private static function get_ticket_line_items_for_grand_total(EE_Line_Item $total_line_item)
921
+	{
922
+		/** @var EE_Line_Item[] $valid_reserved_tickets */
923
+		$valid_reserved_tickets = array();
924
+		$ticket_line_items      = EEH_Line_Item::get_ticket_line_items($total_line_item);
925
+		foreach ($ticket_line_items as $ticket_line_item) {
926
+			if ($ticket_line_item instanceof EE_Line_Item) {
927
+				$valid_reserved_tickets[] = $ticket_line_item;
928
+			}
929
+		}
930
+		return $valid_reserved_tickets;
931
+	}
932
+
933
+
934
+
935
+	/**
936
+	 * @param EE_Ticket[]    $tickets_with_reservations
937
+	 * @param EE_Line_Item[] $valid_reserved_ticket_line_items
938
+	 * @return int
939
+	 * @throws \EE_Error
940
+	 */
941
+	private static function release_reservations_for_tickets(
942
+		array $tickets_with_reservations,
943
+		$valid_reserved_ticket_line_items = array()
944
+	) {
945
+		$total_tickets_released = 0;
946
+		foreach ($tickets_with_reservations as $ticket_with_reservations) {
947
+			if (! $ticket_with_reservations instanceof EE_Ticket) {
948
+				continue;
949
+			}
950
+			$reserved_qty = $ticket_with_reservations->reserved();
951
+			foreach ($valid_reserved_ticket_line_items as $valid_reserved_ticket_line_item) {
952
+				if (
953
+					$valid_reserved_ticket_line_item instanceof EE_Line_Item
954
+					&& $valid_reserved_ticket_line_item->OBJ_ID() === $ticket_with_reservations->ID()
955
+				) {
956
+					$reserved_qty -= $valid_reserved_ticket_line_item->quantity();
957
+				}
958
+			}
959
+			if ($reserved_qty > 0) {
960
+				$ticket_with_reservations->decrease_reserved($reserved_qty);
961
+				$ticket_with_reservations->save();
962
+				$total_tickets_released += $reserved_qty;
963
+			}
964
+		}
965
+		return $total_tickets_released;
966
+	}
967
+
968
+
969
+
970
+	/********************************** SHUTDOWN  **********************************/
971
+
972
+
973
+
974
+	/**
975
+	 * @return false|int
976
+	 * @throws EE_Error
977
+	 * @throws InvalidArgumentException
978
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
979
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
980
+	 */
981
+	public static function clear_expired_line_items_with_no_transaction()
982
+	{
983
+		/** @type WPDB $wpdb */
984
+		global $wpdb;
985
+		return $wpdb->query(
986
+			$wpdb->prepare(
987
+				'DELETE FROM ' . EEM_Line_Item::instance()->table() . '
988 988
                 WHERE TXN_ID = 0 AND LIN_timestamp <= %s',
989
-                // use GMT time because that's what LIN_timestamps are in
990
-                date('Y-m-d H:i:s', time() - EE_Registry::instance()->SSN->lifespan())
991
-            )
992
-        );
993
-    }
989
+				// use GMT time because that's what LIN_timestamps are in
990
+				date('Y-m-d H:i:s', time() - EE_Registry::instance()->SSN->lifespan())
991
+			)
992
+		);
993
+	}
994 994
 
995 995
 }
996 996
 // End of file EED_Ticket_Sales_Monitor.module.php
Please login to merge, or discard this patch.
modules/ticket_selector/ProcessTicketSelector.php 3 patches
Doc Comments   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -41,7 +41,7 @@  discard block
 block discarded – undo
41 41
     /**
42 42
      * cancelTicketSelections
43 43
      *
44
-     * @return        string
44
+     * @return        false|null
45 45
      * @throws EE_Error
46 46
      * @throws InvalidArgumentException
47 47
      * @throws InvalidInterfaceException
@@ -113,7 +113,7 @@  discard block
 block discarded – undo
113 113
     /**
114 114
      * process_ticket_selections
115 115
      *
116
-     * @return array|bool
116
+     * @return boolean|null
117 117
      * @throws \ReflectionException
118 118
      * @throws InvalidArgumentException
119 119
      * @throws InvalidInterfaceException
@@ -287,7 +287,7 @@  discard block
 block discarded – undo
287 287
      * validate_post_data
288 288
      *
289 289
      * @param int $id
290
-     * @return array|FALSE
290
+     * @return string
291 291
      * @throws \ReflectionException
292 292
      * @throws InvalidArgumentException
293 293
      * @throws InvalidInterfaceException
@@ -410,7 +410,7 @@  discard block
 block discarded – undo
410 410
      *
411 411
      * @param EE_Ticket $ticket
412 412
      * @param int        $qty
413
-     * @return TRUE on success, FALSE on fail
413
+     * @return boolean on success, FALSE on fail
414 414
      * @throws InvalidArgumentException
415 415
      * @throws InvalidInterfaceException
416 416
      * @throws InvalidDataTypeException
Please login to merge, or discard this patch.
Indentation   +569 added lines, -569 removed lines patch added patch discarded remove patch
@@ -13,7 +13,7 @@  discard block
 block discarded – undo
13 13
 use InvalidArgumentException;
14 14
 
15 15
 if (! defined('EVENT_ESPRESSO_VERSION')) {
16
-    exit('No direct script access allowed');
16
+	exit('No direct script access allowed');
17 17
 }
18 18
 
19 19
 
@@ -30,592 +30,592 @@  discard block
 block discarded – undo
30 30
 class ProcessTicketSelector
31 31
 {
32 32
 
33
-    /**
34
-     * array of datetimes and the spaces available for them
35
-     *
36
-     * @var array[][]
37
-     */
38
-    private static $_available_spaces = array();
33
+	/**
34
+	 * array of datetimes and the spaces available for them
35
+	 *
36
+	 * @var array[][]
37
+	 */
38
+	private static $_available_spaces = array();
39 39
 
40 40
 
41
-    /**
42
-     * cancelTicketSelections
43
-     *
44
-     * @return        string
45
-     * @throws EE_Error
46
-     * @throws InvalidArgumentException
47
-     * @throws InvalidInterfaceException
48
-     * @throws InvalidDataTypeException
49
-     */
50
-    public function cancelTicketSelections()
51
-    {
52
-        // check nonce
53
-        if (! $this->processTicketSelectorNonce('cancel_ticket_selections')) {
54
-            return false;
55
-        }
56
-        EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
57
-        if (EE_Registry::instance()->REQ->is_set('event_id')) {
58
-            wp_safe_redirect(
59
-                EEH_Event_View::event_link_url(
60
-                    EE_Registry::instance()->REQ->get('event_id')
61
-                )
62
-            );
63
-        } else {
64
-            wp_safe_redirect(
65
-                site_url('/' . EE_Registry::instance()->CFG->core->event_cpt_slug . '/')
66
-            );
67
-        }
68
-        exit();
69
-    }
41
+	/**
42
+	 * cancelTicketSelections
43
+	 *
44
+	 * @return        string
45
+	 * @throws EE_Error
46
+	 * @throws InvalidArgumentException
47
+	 * @throws InvalidInterfaceException
48
+	 * @throws InvalidDataTypeException
49
+	 */
50
+	public function cancelTicketSelections()
51
+	{
52
+		// check nonce
53
+		if (! $this->processTicketSelectorNonce('cancel_ticket_selections')) {
54
+			return false;
55
+		}
56
+		EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
57
+		if (EE_Registry::instance()->REQ->is_set('event_id')) {
58
+			wp_safe_redirect(
59
+				EEH_Event_View::event_link_url(
60
+					EE_Registry::instance()->REQ->get('event_id')
61
+				)
62
+			);
63
+		} else {
64
+			wp_safe_redirect(
65
+				site_url('/' . EE_Registry::instance()->CFG->core->event_cpt_slug . '/')
66
+			);
67
+		}
68
+		exit();
69
+	}
70 70
 
71 71
 
72
-    /**
73
-     * processTicketSelectorNonce
74
-     *
75
-     * @param  string $nonce_name
76
-     * @param string  $id
77
-     * @return bool
78
-     * @throws InvalidArgumentException
79
-     * @throws InvalidInterfaceException
80
-     * @throws InvalidDataTypeException
81
-     */
82
-    private function processTicketSelectorNonce($nonce_name, $id = '')
83
-    {
84
-        $nonce_name_with_id = ! empty($id) ? "{$nonce_name}_nonce_{$id}" : "{$nonce_name}_nonce";
85
-        if (
86
-            ! is_admin()
87
-            && (
88
-                ! EE_Registry::instance()->REQ->is_set($nonce_name_with_id)
89
-                || ! wp_verify_nonce(
90
-                    EE_Registry::instance()->REQ->get($nonce_name_with_id),
91
-                    $nonce_name
92
-                )
93
-            )
94
-        ) {
95
-            EE_Error::add_error(
96
-                sprintf(
97
-                    __(
98
-                        'We\'re sorry but your request failed to pass a security check.%sPlease click the back button on your browser and try again.',
99
-                        'event_espresso'
100
-                    ),
101
-                    '<br/>'
102
-                ),
103
-                __FILE__,
104
-                __FUNCTION__,
105
-                __LINE__
106
-            );
107
-            return false;
108
-        }
109
-        return true;
110
-    }
72
+	/**
73
+	 * processTicketSelectorNonce
74
+	 *
75
+	 * @param  string $nonce_name
76
+	 * @param string  $id
77
+	 * @return bool
78
+	 * @throws InvalidArgumentException
79
+	 * @throws InvalidInterfaceException
80
+	 * @throws InvalidDataTypeException
81
+	 */
82
+	private function processTicketSelectorNonce($nonce_name, $id = '')
83
+	{
84
+		$nonce_name_with_id = ! empty($id) ? "{$nonce_name}_nonce_{$id}" : "{$nonce_name}_nonce";
85
+		if (
86
+			! is_admin()
87
+			&& (
88
+				! EE_Registry::instance()->REQ->is_set($nonce_name_with_id)
89
+				|| ! wp_verify_nonce(
90
+					EE_Registry::instance()->REQ->get($nonce_name_with_id),
91
+					$nonce_name
92
+				)
93
+			)
94
+		) {
95
+			EE_Error::add_error(
96
+				sprintf(
97
+					__(
98
+						'We\'re sorry but your request failed to pass a security check.%sPlease click the back button on your browser and try again.',
99
+						'event_espresso'
100
+					),
101
+					'<br/>'
102
+				),
103
+				__FILE__,
104
+				__FUNCTION__,
105
+				__LINE__
106
+			);
107
+			return false;
108
+		}
109
+		return true;
110
+	}
111 111
 
112 112
 
113
-    /**
114
-     * process_ticket_selections
115
-     *
116
-     * @return array|bool
117
-     * @throws \ReflectionException
118
-     * @throws InvalidArgumentException
119
-     * @throws InvalidInterfaceException
120
-     * @throws InvalidDataTypeException
121
-     * @throws EE_Error
122
-     */
123
-    public function processTicketSelections()
124
-    {
125
-        do_action('EED_Ticket_Selector__process_ticket_selections__before');
126
-        // do we have an event id?
127
-        if (! EE_Registry::instance()->REQ->is_set('tkt-slctr-event-id')) {
128
-            // $_POST['tkt-slctr-event-id'] was not set ?!?!?!?
129
-            EE_Error::add_error(
130
-                sprintf(
131
-                    __(
132
-                        'An event id was not provided or was not received.%sPlease click the back button on your browser and try again.',
133
-                        'event_espresso'
134
-                    ),
135
-                    '<br/>'
136
-                ),
137
-                __FILE__,
138
-                __FUNCTION__,
139
-                __LINE__
140
-            );
141
-        }
142
-        //if event id is valid
143
-        $id = absint(EE_Registry::instance()->REQ->get('tkt-slctr-event-id'));
144
-        //		d( \EE_Registry::instance()->REQ );
145
-        self::$_available_spaces = array(
146
-            'tickets'   => array(),
147
-            'datetimes' => array(),
148
-        );
149
-        //we should really only have 1 registration in the works now (ie, no MER) so clear any previous items in the cart.
150
-        // When MER happens this will probably need to be tweaked, possibly wrapped in a conditional checking for some constant defined in MER etc.
151
-        EE_Registry::instance()->load_core('Session');
152
-        // unless otherwise requested, clear the session
153
-        if (apply_filters('FHEE__EE_Ticket_Selector__process_ticket_selections__clear_session', true)) {
154
-            EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
155
-        }
156
-        //d( \EE_Registry::instance()->SSN );
157
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
158
-        // validate/sanitize data
159
-        $valid = $this->validatePostData($id);
160
-        //EEH_Debug_Tools::printr( $_REQUEST, '$_REQUEST', __FILE__, __LINE__ );
161
-        //EEH_Debug_Tools::printr( $valid, '$valid', __FILE__, __LINE__ );
162
-        //EEH_Debug_Tools::printr( $valid[ 'total_tickets' ], 'total_tickets', __FILE__, __LINE__ );
163
-        //EEH_Debug_Tools::printr( $valid[ 'max_atndz' ], 'max_atndz', __FILE__, __LINE__ );
164
-        //check total tickets ordered vs max number of attendees that can register
165
-        if ($valid['total_tickets'] > $valid['max_atndz']) {
166
-            // ordering too many tickets !!!
167
-            $total_tickets_string = _n(
168
-                'You have attempted to purchase %s ticket.',
169
-                'You have attempted to purchase %s tickets.',
170
-                $valid['total_tickets'],
171
-                'event_espresso'
172
-            );
173
-            $limit_error_1        = sprintf($total_tickets_string, $valid['total_tickets']);
174
-            // dev only message
175
-            $max_atndz_string = _n(
176
-                'The registration limit for this event is %s ticket per registration, therefore the total number of tickets you may purchase at a time can not exceed %s.',
177
-                'The registration limit for this event is %s tickets per registration, therefore the total number of tickets you may purchase at a time can not exceed %s.',
178
-                $valid['max_atndz'],
179
-                'event_espresso'
180
-            );
181
-            $limit_error_2    = sprintf($max_atndz_string, $valid['max_atndz'], $valid['max_atndz']);
182
-            EE_Error::add_error($limit_error_1 . '<br/>' . $limit_error_2, __FILE__, __FUNCTION__, __LINE__);
183
-        } else {
184
-            // all data appears to be valid
185
-            $tckts_slctd   = false;
186
-            $tickets_added = 0;
187
-            $valid         = apply_filters('FHEE__EED_Ticket_Selector__process_ticket_selections__valid_post_data',
188
-                $valid);
189
-            if ($valid['total_tickets'] > 0) {
190
-                // load cart
191
-                EE_Registry::instance()->load_core('Cart');
192
-                // cycle thru the number of data rows sent from the event listing
193
-                for ($x = 0; $x < $valid['rows']; $x++) {
194
-                    // does this row actually contain a ticket quantity?
195
-                    if (isset($valid['qty'][ $x ]) && $valid['qty'][ $x ] > 0) {
196
-                        // YES we have a ticket quantity
197
-                        $tckts_slctd = true;
198
-                        //						d( $valid['ticket_obj'][$x] );
199
-                        if ($valid['ticket_obj'][ $x ] instanceof EE_Ticket) {
200
-                            // then add ticket to cart
201
-                            $tickets_added += $this->addTicketToCart(
202
-                                $valid['ticket_obj'][ $x ],
203
-                                $valid['qty'][ $x ]
204
-                            );
205
-                            if (EE_Error::has_error()) {
206
-                                break;
207
-                            }
208
-                        } else {
209
-                            // nothing added to cart retrieved
210
-                            EE_Error::add_error(
211
-                                sprintf(
212
-                                    __(
213
-                                        'A valid ticket could not be retrieved for the event.%sPlease click the back button on your browser and try again.',
214
-                                        'event_espresso'
215
-                                    ),
216
-                                    '<br/>'
217
-                                ),
218
-                                __FILE__, __FUNCTION__, __LINE__
219
-                            );
220
-                        }
221
-                    }
222
-                }
223
-            }
224
-            do_action(
225
-                'AHEE__EE_Ticket_Selector__process_ticket_selections__after_tickets_added_to_cart',
226
-                EE_Registry::instance()->CART,
227
-                $this
228
-            );
229
-            //d( \EE_Registry::instance()->CART );
230
-            //die(); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< KILL REDIRECT HERE BEFORE CART UPDATE
231
-            if (apply_filters('FHEE__EED_Ticket_Selector__process_ticket_selections__tckts_slctd', $tckts_slctd)) {
232
-                if (apply_filters('FHEE__EED_Ticket_Selector__process_ticket_selections__success', $tickets_added)) {
233
-                    do_action(
234
-                        'FHEE__EE_Ticket_Selector__process_ticket_selections__before_redirecting_to_checkout',
235
-                        EE_Registry::instance()->CART,
236
-                        $this
237
-                    );
238
-                    EE_Registry::instance()->CART->recalculate_all_cart_totals();
239
-                    EE_Registry::instance()->CART->save_cart(false);
240
-                    // exit('KILL REDIRECT AFTER CART UPDATE'); // <<<<<<<<  OR HERE TO KILL REDIRECT AFTER CART UPDATE
241
-                    // just return TRUE for registrations being made from admin
242
-                    if (is_admin()) {
243
-                        return true;
244
-                    }
245
-                    EE_Error::get_notices(false, true);
246
-                    wp_safe_redirect(
247
-                        apply_filters(
248
-                            'FHEE__EE_Ticket_Selector__process_ticket_selections__success_redirect_url',
249
-                            EE_Registry::instance()->CFG->core->reg_page_url()
250
-                        )
251
-                    );
252
-                    exit();
253
-                } else {
254
-                    if (! EE_Error::has_error() && ! EE_Error::has_error(true, 'attention')) {
255
-                        // nothing added to cart
256
-                        EE_Error::add_attention(__('No tickets were added for the event', 'event_espresso'),
257
-                            __FILE__, __FUNCTION__, __LINE__);
258
-                    }
259
-                }
260
-            } else {
261
-                // no ticket quantities were selected
262
-                EE_Error::add_error(__('You need to select a ticket quantity before you can proceed.',
263
-                    'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
264
-            }
265
-        }
266
-        //die(); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< KILL BEFORE REDIRECT
267
-        // at this point, just return if registration is being made from admin
268
-        if (is_admin()) {
269
-            return false;
270
-        }
271
-        if ($valid['return_url']) {
272
-            EE_Error::get_notices(false, true);
273
-            wp_safe_redirect($valid['return_url']);
274
-            exit();
275
-        } elseif (isset($event_to_add['id'])) {
276
-            EE_Error::get_notices(false, true);
277
-            wp_safe_redirect(get_permalink($event_to_add['id']));
278
-            exit();
279
-        } else {
280
-            echo EE_Error::get_notices();
281
-        }
282
-        return false;
283
-    }
113
+	/**
114
+	 * process_ticket_selections
115
+	 *
116
+	 * @return array|bool
117
+	 * @throws \ReflectionException
118
+	 * @throws InvalidArgumentException
119
+	 * @throws InvalidInterfaceException
120
+	 * @throws InvalidDataTypeException
121
+	 * @throws EE_Error
122
+	 */
123
+	public function processTicketSelections()
124
+	{
125
+		do_action('EED_Ticket_Selector__process_ticket_selections__before');
126
+		// do we have an event id?
127
+		if (! EE_Registry::instance()->REQ->is_set('tkt-slctr-event-id')) {
128
+			// $_POST['tkt-slctr-event-id'] was not set ?!?!?!?
129
+			EE_Error::add_error(
130
+				sprintf(
131
+					__(
132
+						'An event id was not provided or was not received.%sPlease click the back button on your browser and try again.',
133
+						'event_espresso'
134
+					),
135
+					'<br/>'
136
+				),
137
+				__FILE__,
138
+				__FUNCTION__,
139
+				__LINE__
140
+			);
141
+		}
142
+		//if event id is valid
143
+		$id = absint(EE_Registry::instance()->REQ->get('tkt-slctr-event-id'));
144
+		//		d( \EE_Registry::instance()->REQ );
145
+		self::$_available_spaces = array(
146
+			'tickets'   => array(),
147
+			'datetimes' => array(),
148
+		);
149
+		//we should really only have 1 registration in the works now (ie, no MER) so clear any previous items in the cart.
150
+		// When MER happens this will probably need to be tweaked, possibly wrapped in a conditional checking for some constant defined in MER etc.
151
+		EE_Registry::instance()->load_core('Session');
152
+		// unless otherwise requested, clear the session
153
+		if (apply_filters('FHEE__EE_Ticket_Selector__process_ticket_selections__clear_session', true)) {
154
+			EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
155
+		}
156
+		//d( \EE_Registry::instance()->SSN );
157
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
158
+		// validate/sanitize data
159
+		$valid = $this->validatePostData($id);
160
+		//EEH_Debug_Tools::printr( $_REQUEST, '$_REQUEST', __FILE__, __LINE__ );
161
+		//EEH_Debug_Tools::printr( $valid, '$valid', __FILE__, __LINE__ );
162
+		//EEH_Debug_Tools::printr( $valid[ 'total_tickets' ], 'total_tickets', __FILE__, __LINE__ );
163
+		//EEH_Debug_Tools::printr( $valid[ 'max_atndz' ], 'max_atndz', __FILE__, __LINE__ );
164
+		//check total tickets ordered vs max number of attendees that can register
165
+		if ($valid['total_tickets'] > $valid['max_atndz']) {
166
+			// ordering too many tickets !!!
167
+			$total_tickets_string = _n(
168
+				'You have attempted to purchase %s ticket.',
169
+				'You have attempted to purchase %s tickets.',
170
+				$valid['total_tickets'],
171
+				'event_espresso'
172
+			);
173
+			$limit_error_1        = sprintf($total_tickets_string, $valid['total_tickets']);
174
+			// dev only message
175
+			$max_atndz_string = _n(
176
+				'The registration limit for this event is %s ticket per registration, therefore the total number of tickets you may purchase at a time can not exceed %s.',
177
+				'The registration limit for this event is %s tickets per registration, therefore the total number of tickets you may purchase at a time can not exceed %s.',
178
+				$valid['max_atndz'],
179
+				'event_espresso'
180
+			);
181
+			$limit_error_2    = sprintf($max_atndz_string, $valid['max_atndz'], $valid['max_atndz']);
182
+			EE_Error::add_error($limit_error_1 . '<br/>' . $limit_error_2, __FILE__, __FUNCTION__, __LINE__);
183
+		} else {
184
+			// all data appears to be valid
185
+			$tckts_slctd   = false;
186
+			$tickets_added = 0;
187
+			$valid         = apply_filters('FHEE__EED_Ticket_Selector__process_ticket_selections__valid_post_data',
188
+				$valid);
189
+			if ($valid['total_tickets'] > 0) {
190
+				// load cart
191
+				EE_Registry::instance()->load_core('Cart');
192
+				// cycle thru the number of data rows sent from the event listing
193
+				for ($x = 0; $x < $valid['rows']; $x++) {
194
+					// does this row actually contain a ticket quantity?
195
+					if (isset($valid['qty'][ $x ]) && $valid['qty'][ $x ] > 0) {
196
+						// YES we have a ticket quantity
197
+						$tckts_slctd = true;
198
+						//						d( $valid['ticket_obj'][$x] );
199
+						if ($valid['ticket_obj'][ $x ] instanceof EE_Ticket) {
200
+							// then add ticket to cart
201
+							$tickets_added += $this->addTicketToCart(
202
+								$valid['ticket_obj'][ $x ],
203
+								$valid['qty'][ $x ]
204
+							);
205
+							if (EE_Error::has_error()) {
206
+								break;
207
+							}
208
+						} else {
209
+							// nothing added to cart retrieved
210
+							EE_Error::add_error(
211
+								sprintf(
212
+									__(
213
+										'A valid ticket could not be retrieved for the event.%sPlease click the back button on your browser and try again.',
214
+										'event_espresso'
215
+									),
216
+									'<br/>'
217
+								),
218
+								__FILE__, __FUNCTION__, __LINE__
219
+							);
220
+						}
221
+					}
222
+				}
223
+			}
224
+			do_action(
225
+				'AHEE__EE_Ticket_Selector__process_ticket_selections__after_tickets_added_to_cart',
226
+				EE_Registry::instance()->CART,
227
+				$this
228
+			);
229
+			//d( \EE_Registry::instance()->CART );
230
+			//die(); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< KILL REDIRECT HERE BEFORE CART UPDATE
231
+			if (apply_filters('FHEE__EED_Ticket_Selector__process_ticket_selections__tckts_slctd', $tckts_slctd)) {
232
+				if (apply_filters('FHEE__EED_Ticket_Selector__process_ticket_selections__success', $tickets_added)) {
233
+					do_action(
234
+						'FHEE__EE_Ticket_Selector__process_ticket_selections__before_redirecting_to_checkout',
235
+						EE_Registry::instance()->CART,
236
+						$this
237
+					);
238
+					EE_Registry::instance()->CART->recalculate_all_cart_totals();
239
+					EE_Registry::instance()->CART->save_cart(false);
240
+					// exit('KILL REDIRECT AFTER CART UPDATE'); // <<<<<<<<  OR HERE TO KILL REDIRECT AFTER CART UPDATE
241
+					// just return TRUE for registrations being made from admin
242
+					if (is_admin()) {
243
+						return true;
244
+					}
245
+					EE_Error::get_notices(false, true);
246
+					wp_safe_redirect(
247
+						apply_filters(
248
+							'FHEE__EE_Ticket_Selector__process_ticket_selections__success_redirect_url',
249
+							EE_Registry::instance()->CFG->core->reg_page_url()
250
+						)
251
+					);
252
+					exit();
253
+				} else {
254
+					if (! EE_Error::has_error() && ! EE_Error::has_error(true, 'attention')) {
255
+						// nothing added to cart
256
+						EE_Error::add_attention(__('No tickets were added for the event', 'event_espresso'),
257
+							__FILE__, __FUNCTION__, __LINE__);
258
+					}
259
+				}
260
+			} else {
261
+				// no ticket quantities were selected
262
+				EE_Error::add_error(__('You need to select a ticket quantity before you can proceed.',
263
+					'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
264
+			}
265
+		}
266
+		//die(); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< KILL BEFORE REDIRECT
267
+		// at this point, just return if registration is being made from admin
268
+		if (is_admin()) {
269
+			return false;
270
+		}
271
+		if ($valid['return_url']) {
272
+			EE_Error::get_notices(false, true);
273
+			wp_safe_redirect($valid['return_url']);
274
+			exit();
275
+		} elseif (isset($event_to_add['id'])) {
276
+			EE_Error::get_notices(false, true);
277
+			wp_safe_redirect(get_permalink($event_to_add['id']));
278
+			exit();
279
+		} else {
280
+			echo EE_Error::get_notices();
281
+		}
282
+		return false;
283
+	}
284 284
 
285 285
 
286
-    /**
287
-     * validate_post_data
288
-     *
289
-     * @param int $id
290
-     * @return array|FALSE
291
-     * @throws \ReflectionException
292
-     * @throws InvalidArgumentException
293
-     * @throws InvalidInterfaceException
294
-     * @throws InvalidDataTypeException
295
-     * @throws EE_Error
296
-     */
297
-    private function validatePostData($id = 0)
298
-    {
299
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
300
-        if (! $id) {
301
-            EE_Error::add_error(
302
-                __('The event id provided was not valid.', 'event_espresso'),
303
-                __FILE__,
304
-                __FUNCTION__,
305
-                __LINE__
306
-            );
307
-            return false;
308
-        }
309
-        // start with an empty array()
310
-        $valid_data = array();
311
-        // grab valid id
312
-        $valid_data['id'] = $id;
313
-        // array of other form names
314
-        $inputs_to_clean = array(
315
-            'event_id'   => 'tkt-slctr-event-id',
316
-            'max_atndz'  => 'tkt-slctr-max-atndz-',
317
-            'rows'       => 'tkt-slctr-rows-',
318
-            'qty'        => 'tkt-slctr-qty-',
319
-            'ticket_id'  => 'tkt-slctr-ticket-id-',
320
-            'return_url' => 'tkt-slctr-return-url-',
321
-        );
322
-        // let's track the total number of tickets ordered.'
323
-        $valid_data['total_tickets'] = 0;
324
-        // cycle through $inputs_to_clean array
325
-        foreach ($inputs_to_clean as $what => $input_to_clean) {
326
-            // check for POST data
327
-            if (EE_Registry::instance()->REQ->is_set($input_to_clean . $id)) {
328
-                // grab value
329
-                $input_value = EE_Registry::instance()->REQ->get($input_to_clean . $id);
330
-                switch ($what) {
331
-                    // integers
332
-                    case 'event_id':
333
-                        $valid_data[ $what ] = absint($input_value);
334
-                        // get event via the event id we put in the form
335
-                        $valid_data['event'] = EE_Registry::instance()
336
-                                                           ->load_model('Event')
337
-                                                           ->get_one_by_ID($valid_data['event_id']);
338
-                        break;
339
-                    case 'rows':
340
-                    case 'max_atndz':
341
-                        $valid_data[ $what ] = absint($input_value);
342
-                        break;
343
-                    // arrays of integers
344
-                    case 'qty':
345
-                        /** @var array $row_qty */
346
-                        $row_qty = $input_value;
347
-                        // if qty is coming from a radio button input, then we need to assemble an array of rows
348
-                        if (! is_array($row_qty)) {
349
-                            // get number of rows
350
-                            $rows = EE_Registry::instance()->REQ->is_set('tkt-slctr-rows-' . $id)
351
-                                ? absint(EE_Registry::instance()->REQ->get('tkt-slctr-rows-' . $id))
352
-                                : 1;
353
-                            // explode ints by the dash
354
-                            $row_qty = explode('-', $row_qty);
355
-                            $row     = isset($row_qty[0]) ? absint($row_qty[0]) : 1;
356
-                            $qty     = isset($row_qty[1]) ? absint($row_qty[1]) : 0;
357
-                            $row_qty = array($row => $qty);
358
-                            for ($x = 1; $x <= $rows; $x++) {
359
-                                if (! isset($row_qty[ $x ])) {
360
-                                    $row_qty[ $x ] = 0;
361
-                                }
362
-                            }
363
-                        }
364
-                        ksort($row_qty);
365
-                        // cycle thru values
366
-                        foreach ($row_qty as $qty) {
367
-                            $qty = absint($qty);
368
-                            // sanitize as integers
369
-                            $valid_data[ $what ][]       = $qty;
370
-                            $valid_data['total_tickets'] += $qty;
371
-                        }
372
-                        break;
373
-                    // array of integers
374
-                    case 'ticket_id':
375
-                        $value_array = array();
376
-                        // cycle thru values
377
-                        foreach ((array) $input_value as $key => $value) {
378
-                            // allow only numbers, letters,  spaces, commas and dashes
379
-                            $value_array[ $key ] = wp_strip_all_tags($value);
380
-                            // get ticket via the ticket id we put in the form
381
-                            $ticket_obj                       = EE_Registry::instance()
382
-                                                                            ->load_model('Ticket')
383
-                                                                            ->get_one_by_ID($value);
384
-                            $valid_data['ticket_obj'][ $key ] = $ticket_obj;
385
-                        }
386
-                        $valid_data[ $what ] = $value_array;
387
-                        break;
388
-                    case 'return_url' :
389
-                        // grab and sanitize return-url
390
-                        $input_value = esc_url_raw($input_value);
391
-                        // was the request coming from an iframe ? if so, then:
392
-                        if (strpos($input_value, 'event_list=iframe')) {
393
-                            // get anchor fragment
394
-                            $input_value = explode('#', $input_value);
395
-                            $input_value = end($input_value);
396
-                            // use event list url instead, but append anchor
397
-                            $input_value = EEH_Event_View::event_archive_url() . '#' . $input_value;
398
-                        }
399
-                        $valid_data[ $what ] = $input_value;
400
-                        break;
401
-                }    // end switch $what
402
-            }
403
-        }    // end foreach $inputs_to_clean
404
-        return $valid_data;
405
-    }
286
+	/**
287
+	 * validate_post_data
288
+	 *
289
+	 * @param int $id
290
+	 * @return array|FALSE
291
+	 * @throws \ReflectionException
292
+	 * @throws InvalidArgumentException
293
+	 * @throws InvalidInterfaceException
294
+	 * @throws InvalidDataTypeException
295
+	 * @throws EE_Error
296
+	 */
297
+	private function validatePostData($id = 0)
298
+	{
299
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
300
+		if (! $id) {
301
+			EE_Error::add_error(
302
+				__('The event id provided was not valid.', 'event_espresso'),
303
+				__FILE__,
304
+				__FUNCTION__,
305
+				__LINE__
306
+			);
307
+			return false;
308
+		}
309
+		// start with an empty array()
310
+		$valid_data = array();
311
+		// grab valid id
312
+		$valid_data['id'] = $id;
313
+		// array of other form names
314
+		$inputs_to_clean = array(
315
+			'event_id'   => 'tkt-slctr-event-id',
316
+			'max_atndz'  => 'tkt-slctr-max-atndz-',
317
+			'rows'       => 'tkt-slctr-rows-',
318
+			'qty'        => 'tkt-slctr-qty-',
319
+			'ticket_id'  => 'tkt-slctr-ticket-id-',
320
+			'return_url' => 'tkt-slctr-return-url-',
321
+		);
322
+		// let's track the total number of tickets ordered.'
323
+		$valid_data['total_tickets'] = 0;
324
+		// cycle through $inputs_to_clean array
325
+		foreach ($inputs_to_clean as $what => $input_to_clean) {
326
+			// check for POST data
327
+			if (EE_Registry::instance()->REQ->is_set($input_to_clean . $id)) {
328
+				// grab value
329
+				$input_value = EE_Registry::instance()->REQ->get($input_to_clean . $id);
330
+				switch ($what) {
331
+					// integers
332
+					case 'event_id':
333
+						$valid_data[ $what ] = absint($input_value);
334
+						// get event via the event id we put in the form
335
+						$valid_data['event'] = EE_Registry::instance()
336
+														   ->load_model('Event')
337
+														   ->get_one_by_ID($valid_data['event_id']);
338
+						break;
339
+					case 'rows':
340
+					case 'max_atndz':
341
+						$valid_data[ $what ] = absint($input_value);
342
+						break;
343
+					// arrays of integers
344
+					case 'qty':
345
+						/** @var array $row_qty */
346
+						$row_qty = $input_value;
347
+						// if qty is coming from a radio button input, then we need to assemble an array of rows
348
+						if (! is_array($row_qty)) {
349
+							// get number of rows
350
+							$rows = EE_Registry::instance()->REQ->is_set('tkt-slctr-rows-' . $id)
351
+								? absint(EE_Registry::instance()->REQ->get('tkt-slctr-rows-' . $id))
352
+								: 1;
353
+							// explode ints by the dash
354
+							$row_qty = explode('-', $row_qty);
355
+							$row     = isset($row_qty[0]) ? absint($row_qty[0]) : 1;
356
+							$qty     = isset($row_qty[1]) ? absint($row_qty[1]) : 0;
357
+							$row_qty = array($row => $qty);
358
+							for ($x = 1; $x <= $rows; $x++) {
359
+								if (! isset($row_qty[ $x ])) {
360
+									$row_qty[ $x ] = 0;
361
+								}
362
+							}
363
+						}
364
+						ksort($row_qty);
365
+						// cycle thru values
366
+						foreach ($row_qty as $qty) {
367
+							$qty = absint($qty);
368
+							// sanitize as integers
369
+							$valid_data[ $what ][]       = $qty;
370
+							$valid_data['total_tickets'] += $qty;
371
+						}
372
+						break;
373
+					// array of integers
374
+					case 'ticket_id':
375
+						$value_array = array();
376
+						// cycle thru values
377
+						foreach ((array) $input_value as $key => $value) {
378
+							// allow only numbers, letters,  spaces, commas and dashes
379
+							$value_array[ $key ] = wp_strip_all_tags($value);
380
+							// get ticket via the ticket id we put in the form
381
+							$ticket_obj                       = EE_Registry::instance()
382
+																			->load_model('Ticket')
383
+																			->get_one_by_ID($value);
384
+							$valid_data['ticket_obj'][ $key ] = $ticket_obj;
385
+						}
386
+						$valid_data[ $what ] = $value_array;
387
+						break;
388
+					case 'return_url' :
389
+						// grab and sanitize return-url
390
+						$input_value = esc_url_raw($input_value);
391
+						// was the request coming from an iframe ? if so, then:
392
+						if (strpos($input_value, 'event_list=iframe')) {
393
+							// get anchor fragment
394
+							$input_value = explode('#', $input_value);
395
+							$input_value = end($input_value);
396
+							// use event list url instead, but append anchor
397
+							$input_value = EEH_Event_View::event_archive_url() . '#' . $input_value;
398
+						}
399
+						$valid_data[ $what ] = $input_value;
400
+						break;
401
+				}    // end switch $what
402
+			}
403
+		}    // end foreach $inputs_to_clean
404
+		return $valid_data;
405
+	}
406 406
 
407 407
 
408
-    /**
409
-     * adds a ticket to the cart
410
-     *
411
-     * @param EE_Ticket $ticket
412
-     * @param int        $qty
413
-     * @return TRUE on success, FALSE on fail
414
-     * @throws InvalidArgumentException
415
-     * @throws InvalidInterfaceException
416
-     * @throws InvalidDataTypeException
417
-     * @throws EE_Error
418
-     */
419
-    private function addTicketToCart(EE_Ticket $ticket = null, $qty = 1)
420
-    {
421
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
422
-        // get the number of spaces left for this datetime ticket
423
-        $available_spaces = $this->ticketDatetimeAvailability($ticket);
424
-        // compare available spaces against the number of tickets being purchased
425
-        if ($available_spaces >= $qty) {
426
-            // allow addons to prevent a ticket from being added to cart
427
-            if (
428
-            ! apply_filters(
429
-                'FHEE__EE_Ticket_Selector___add_ticket_to_cart__allow_add_to_cart',
430
-                true,
431
-                $ticket,
432
-                $qty,
433
-                $available_spaces
434
-            )
435
-            ) {
436
-                return false;
437
-            }
438
-            $qty = absint(apply_filters('FHEE__EE_Ticket_Selector___add_ticket_to_cart__ticket_qty', $qty, $ticket));
439
-            // add event to cart
440
-            if (EE_Registry::instance()->CART->add_ticket_to_cart($ticket, $qty)) {
441
-                $this->recalculateTicketDatetimeAvailability($ticket, $qty);
442
-                return true;
443
-            }
444
-            return false;
445
-        }
446
-        // tickets can not be purchased but let's find the exact number left
447
-        // for the last ticket selected PRIOR to subtracting tickets
448
-        $available_spaces = $this->ticketDatetimeAvailability($ticket, true);
449
-        // greedy greedy greedy eh?
450
-        if ($available_spaces > 0) {
451
-            if (
452
-            apply_filters(
453
-                'FHEE__EE_Ticket_Selector___add_ticket_to_cart__allow_display_availability_error',
454
-                true,
455
-                $ticket,
456
-                $qty,
457
-                $available_spaces
458
-            )
459
-            ) {
460
-                $this->displayAvailabilityError($available_spaces);
461
-            }
462
-        } else {
463
-            EE_Error::add_error(
464
-                __(
465
-                    'We\'re sorry, but there are no available spaces left for this event at this particular date and time.',
466
-                    'event_espresso'
467
-                ),
468
-                __FILE__, __FUNCTION__, __LINE__
469
-            );
470
-        }
471
-        return false;
472
-    }
408
+	/**
409
+	 * adds a ticket to the cart
410
+	 *
411
+	 * @param EE_Ticket $ticket
412
+	 * @param int        $qty
413
+	 * @return TRUE on success, FALSE on fail
414
+	 * @throws InvalidArgumentException
415
+	 * @throws InvalidInterfaceException
416
+	 * @throws InvalidDataTypeException
417
+	 * @throws EE_Error
418
+	 */
419
+	private function addTicketToCart(EE_Ticket $ticket = null, $qty = 1)
420
+	{
421
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
422
+		// get the number of spaces left for this datetime ticket
423
+		$available_spaces = $this->ticketDatetimeAvailability($ticket);
424
+		// compare available spaces against the number of tickets being purchased
425
+		if ($available_spaces >= $qty) {
426
+			// allow addons to prevent a ticket from being added to cart
427
+			if (
428
+			! apply_filters(
429
+				'FHEE__EE_Ticket_Selector___add_ticket_to_cart__allow_add_to_cart',
430
+				true,
431
+				$ticket,
432
+				$qty,
433
+				$available_spaces
434
+			)
435
+			) {
436
+				return false;
437
+			}
438
+			$qty = absint(apply_filters('FHEE__EE_Ticket_Selector___add_ticket_to_cart__ticket_qty', $qty, $ticket));
439
+			// add event to cart
440
+			if (EE_Registry::instance()->CART->add_ticket_to_cart($ticket, $qty)) {
441
+				$this->recalculateTicketDatetimeAvailability($ticket, $qty);
442
+				return true;
443
+			}
444
+			return false;
445
+		}
446
+		// tickets can not be purchased but let's find the exact number left
447
+		// for the last ticket selected PRIOR to subtracting tickets
448
+		$available_spaces = $this->ticketDatetimeAvailability($ticket, true);
449
+		// greedy greedy greedy eh?
450
+		if ($available_spaces > 0) {
451
+			if (
452
+			apply_filters(
453
+				'FHEE__EE_Ticket_Selector___add_ticket_to_cart__allow_display_availability_error',
454
+				true,
455
+				$ticket,
456
+				$qty,
457
+				$available_spaces
458
+			)
459
+			) {
460
+				$this->displayAvailabilityError($available_spaces);
461
+			}
462
+		} else {
463
+			EE_Error::add_error(
464
+				__(
465
+					'We\'re sorry, but there are no available spaces left for this event at this particular date and time.',
466
+					'event_espresso'
467
+				),
468
+				__FILE__, __FUNCTION__, __LINE__
469
+			);
470
+		}
471
+		return false;
472
+	}
473 473
 
474 474
 
475
-    /**
476
-     * @param int $available_spaces
477
-     * @throws InvalidArgumentException
478
-     * @throws InvalidInterfaceException
479
-     * @throws InvalidDataTypeException
480
-     * @throws EE_Error
481
-     */
482
-    private function displayAvailabilityError($available_spaces = 1)
483
-    {
484
-        // add error messaging - we're using the _n function that will generate
485
-        // the appropriate singular or plural message based on the number of $available_spaces
486
-        if (EE_Registry::instance()->CART->all_ticket_quantity_count()) {
487
-            $msg = sprintf(
488
-                _n(
489
-                    'We\'re sorry, but there is only %1$s available space left for this event at this particular date and time. Please select a different number (or different combination) of tickets by cancelling the current selection and choosing again, or proceed to registration.',
490
-                    'We\'re sorry, but there are only %1$s available spaces left for this event at this particular date and time. Please select a different number (or different combination) of tickets by cancelling the current selection and choosing again, or proceed to registration.',
491
-                    $available_spaces,
492
-                    'event_espresso'
493
-                ),
494
-                $available_spaces,
495
-                '<br />'
496
-            );
497
-        } else {
498
-            $msg = sprintf(
499
-                _n(
500
-                    'We\'re sorry, but there is only %1$s available space left for this event at this particular date and time. Please select a different number (or different combination) of tickets.',
501
-                    'We\'re sorry, but there are only %1$s available spaces left for this event at this particular date and time. Please select a different number (or different combination) of tickets.',
502
-                    $available_spaces,
503
-                    'event_espresso'
504
-                ),
505
-                $available_spaces,
506
-                '<br />'
507
-            );
508
-        }
509
-        EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
510
-    }
475
+	/**
476
+	 * @param int $available_spaces
477
+	 * @throws InvalidArgumentException
478
+	 * @throws InvalidInterfaceException
479
+	 * @throws InvalidDataTypeException
480
+	 * @throws EE_Error
481
+	 */
482
+	private function displayAvailabilityError($available_spaces = 1)
483
+	{
484
+		// add error messaging - we're using the _n function that will generate
485
+		// the appropriate singular or plural message based on the number of $available_spaces
486
+		if (EE_Registry::instance()->CART->all_ticket_quantity_count()) {
487
+			$msg = sprintf(
488
+				_n(
489
+					'We\'re sorry, but there is only %1$s available space left for this event at this particular date and time. Please select a different number (or different combination) of tickets by cancelling the current selection and choosing again, or proceed to registration.',
490
+					'We\'re sorry, but there are only %1$s available spaces left for this event at this particular date and time. Please select a different number (or different combination) of tickets by cancelling the current selection and choosing again, or proceed to registration.',
491
+					$available_spaces,
492
+					'event_espresso'
493
+				),
494
+				$available_spaces,
495
+				'<br />'
496
+			);
497
+		} else {
498
+			$msg = sprintf(
499
+				_n(
500
+					'We\'re sorry, but there is only %1$s available space left for this event at this particular date and time. Please select a different number (or different combination) of tickets.',
501
+					'We\'re sorry, but there are only %1$s available spaces left for this event at this particular date and time. Please select a different number (or different combination) of tickets.',
502
+					$available_spaces,
503
+					'event_espresso'
504
+				),
505
+				$available_spaces,
506
+				'<br />'
507
+			);
508
+		}
509
+		EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
510
+	}
511 511
 
512 512
 
513
-    /**
514
-     * ticketDatetimeAvailability
515
-     * creates an array of tickets plus all of the datetimes available to each ticket
516
-     * and tracks the spaces remaining for each of those datetimes
517
-     *
518
-     * @param EE_Ticket $ticket - selected ticket
519
-     * @param bool      $get_original_ticket_spaces
520
-     * @return int
521
-     * @throws InvalidArgumentException
522
-     * @throws InvalidInterfaceException
523
-     * @throws InvalidDataTypeException
524
-     * @throws EE_Error
525
-     */
526
-    private function ticketDatetimeAvailability(EE_Ticket $ticket, $get_original_ticket_spaces = false)
527
-    {
528
-        // if the $_available_spaces array has not been set up yet...
529
-        if (! isset(self::$_available_spaces['tickets'][ $ticket->ID() ])) {
530
-            $this->setInitialTicketDatetimeAvailability($ticket);
531
-        }
532
-        $available_spaces = $ticket->qty() - $ticket->sold();
533
-        if (isset(self::$_available_spaces['tickets'][ $ticket->ID() ])) {
534
-            // loop thru tickets, which will ALSO include individual ticket records AND a total
535
-            foreach (self::$_available_spaces['tickets'][ $ticket->ID() ] as $DTD_ID => $spaces) {
536
-                // if we want the original datetime availability BEFORE we started subtracting tickets ?
537
-                if ($get_original_ticket_spaces) {
538
-                    // then grab the available spaces from the "tickets" array
539
-                    // and compare with the above to get the lowest number
540
-                    $available_spaces = min(
541
-                        $available_spaces,
542
-                        self::$_available_spaces['tickets'][ $ticket->ID() ][ $DTD_ID ]
543
-                    );
544
-                } else {
545
-                    // we want the updated ticket availability as stored in the "datetimes" array
546
-                    $available_spaces = min($available_spaces, self::$_available_spaces['datetimes'][ $DTD_ID ]);
547
-                }
548
-            }
549
-        }
550
-        return $available_spaces;
551
-    }
513
+	/**
514
+	 * ticketDatetimeAvailability
515
+	 * creates an array of tickets plus all of the datetimes available to each ticket
516
+	 * and tracks the spaces remaining for each of those datetimes
517
+	 *
518
+	 * @param EE_Ticket $ticket - selected ticket
519
+	 * @param bool      $get_original_ticket_spaces
520
+	 * @return int
521
+	 * @throws InvalidArgumentException
522
+	 * @throws InvalidInterfaceException
523
+	 * @throws InvalidDataTypeException
524
+	 * @throws EE_Error
525
+	 */
526
+	private function ticketDatetimeAvailability(EE_Ticket $ticket, $get_original_ticket_spaces = false)
527
+	{
528
+		// if the $_available_spaces array has not been set up yet...
529
+		if (! isset(self::$_available_spaces['tickets'][ $ticket->ID() ])) {
530
+			$this->setInitialTicketDatetimeAvailability($ticket);
531
+		}
532
+		$available_spaces = $ticket->qty() - $ticket->sold();
533
+		if (isset(self::$_available_spaces['tickets'][ $ticket->ID() ])) {
534
+			// loop thru tickets, which will ALSO include individual ticket records AND a total
535
+			foreach (self::$_available_spaces['tickets'][ $ticket->ID() ] as $DTD_ID => $spaces) {
536
+				// if we want the original datetime availability BEFORE we started subtracting tickets ?
537
+				if ($get_original_ticket_spaces) {
538
+					// then grab the available spaces from the "tickets" array
539
+					// and compare with the above to get the lowest number
540
+					$available_spaces = min(
541
+						$available_spaces,
542
+						self::$_available_spaces['tickets'][ $ticket->ID() ][ $DTD_ID ]
543
+					);
544
+				} else {
545
+					// we want the updated ticket availability as stored in the "datetimes" array
546
+					$available_spaces = min($available_spaces, self::$_available_spaces['datetimes'][ $DTD_ID ]);
547
+				}
548
+			}
549
+		}
550
+		return $available_spaces;
551
+	}
552 552
 
553 553
 
554
-    /**
555
-     * @param EE_Ticket $ticket
556
-     * @return void
557
-     * @throws InvalidArgumentException
558
-     * @throws InvalidInterfaceException
559
-     * @throws InvalidDataTypeException
560
-     * @throws EE_Error
561
-     */
562
-    private function setInitialTicketDatetimeAvailability(EE_Ticket $ticket)
563
-    {
564
-        // first, get all of the datetimes that are available to this ticket
565
-        $datetimes = $ticket->get_many_related(
566
-            'Datetime',
567
-            array(
568
-                array(
569
-                    'DTT_EVT_end' => array(
570
-                        '>=',
571
-                        EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end'),
572
-                    ),
573
-                ),
574
-                'order_by' => array('DTT_EVT_start' => 'ASC'),
575
-            )
576
-        );
577
-        if (! empty($datetimes)) {
578
-            // now loop thru all of the datetimes
579
-            foreach ($datetimes as $datetime) {
580
-                if ($datetime instanceof EE_Datetime) {
581
-                    // the number of spaces available for the datetime without considering individual ticket quantities
582
-                    $spaces_remaining = $datetime->spaces_remaining();
583
-                    // save the total available spaces ( the lesser of the ticket qty minus the number of tickets sold
584
-                    // or the datetime spaces remaining) to this ticket using the datetime ID as the key
585
-                    self::$_available_spaces['tickets'][ $ticket->ID() ][ $datetime->ID() ] = min(
586
-                        $ticket->qty() - $ticket->sold(),
587
-                        $spaces_remaining
588
-                    );
589
-                    // if the remaining spaces for this datetime is already set,
590
-                    // then compare that against the datetime spaces remaining, and take the lowest number,
591
-                    // else just take the datetime spaces remaining, and assign to the datetimes array
592
-                    self::$_available_spaces['datetimes'][ $datetime->ID() ] = isset(
593
-                        self::$_available_spaces['datetimes'][ $datetime->ID() ]
594
-                    )
595
-                        ? min(self::$_available_spaces['datetimes'][ $datetime->ID() ], $spaces_remaining)
596
-                        : $spaces_remaining;
597
-                }
598
-            }
599
-        }
600
-    }
554
+	/**
555
+	 * @param EE_Ticket $ticket
556
+	 * @return void
557
+	 * @throws InvalidArgumentException
558
+	 * @throws InvalidInterfaceException
559
+	 * @throws InvalidDataTypeException
560
+	 * @throws EE_Error
561
+	 */
562
+	private function setInitialTicketDatetimeAvailability(EE_Ticket $ticket)
563
+	{
564
+		// first, get all of the datetimes that are available to this ticket
565
+		$datetimes = $ticket->get_many_related(
566
+			'Datetime',
567
+			array(
568
+				array(
569
+					'DTT_EVT_end' => array(
570
+						'>=',
571
+						EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end'),
572
+					),
573
+				),
574
+				'order_by' => array('DTT_EVT_start' => 'ASC'),
575
+			)
576
+		);
577
+		if (! empty($datetimes)) {
578
+			// now loop thru all of the datetimes
579
+			foreach ($datetimes as $datetime) {
580
+				if ($datetime instanceof EE_Datetime) {
581
+					// the number of spaces available for the datetime without considering individual ticket quantities
582
+					$spaces_remaining = $datetime->spaces_remaining();
583
+					// save the total available spaces ( the lesser of the ticket qty minus the number of tickets sold
584
+					// or the datetime spaces remaining) to this ticket using the datetime ID as the key
585
+					self::$_available_spaces['tickets'][ $ticket->ID() ][ $datetime->ID() ] = min(
586
+						$ticket->qty() - $ticket->sold(),
587
+						$spaces_remaining
588
+					);
589
+					// if the remaining spaces for this datetime is already set,
590
+					// then compare that against the datetime spaces remaining, and take the lowest number,
591
+					// else just take the datetime spaces remaining, and assign to the datetimes array
592
+					self::$_available_spaces['datetimes'][ $datetime->ID() ] = isset(
593
+						self::$_available_spaces['datetimes'][ $datetime->ID() ]
594
+					)
595
+						? min(self::$_available_spaces['datetimes'][ $datetime->ID() ], $spaces_remaining)
596
+						: $spaces_remaining;
597
+				}
598
+			}
599
+		}
600
+	}
601 601
 
602 602
 
603
-    /**
604
-     * @param    EE_Ticket $ticket
605
-     * @param    int        $qty
606
-     * @return    void
607
-     * @throws EE_Error
608
-     */
609
-    private function recalculateTicketDatetimeAvailability(EE_Ticket $ticket, $qty = 0)
610
-    {
611
-        if (isset(self::$_available_spaces['tickets'][ $ticket->ID() ])) {
612
-            // loop thru tickets, which will ALSO include individual ticket records AND a total
613
-            foreach (self::$_available_spaces['tickets'][ $ticket->ID() ] as $DTD_ID => $spaces) {
614
-                // subtract the qty of selected tickets from each datetime's available spaces this ticket has access to,
615
-                self::$_available_spaces['datetimes'][ $DTD_ID ] -= $qty;
616
-            }
617
-        }
618
-    }
603
+	/**
604
+	 * @param    EE_Ticket $ticket
605
+	 * @param    int        $qty
606
+	 * @return    void
607
+	 * @throws EE_Error
608
+	 */
609
+	private function recalculateTicketDatetimeAvailability(EE_Ticket $ticket, $qty = 0)
610
+	{
611
+		if (isset(self::$_available_spaces['tickets'][ $ticket->ID() ])) {
612
+			// loop thru tickets, which will ALSO include individual ticket records AND a total
613
+			foreach (self::$_available_spaces['tickets'][ $ticket->ID() ] as $DTD_ID => $spaces) {
614
+				// subtract the qty of selected tickets from each datetime's available spaces this ticket has access to,
615
+				self::$_available_spaces['datetimes'][ $DTD_ID ] -= $qty;
616
+			}
617
+		}
618
+	}
619 619
 }
620 620
 // End of file ProcessTicketSelector.php
621 621
 // Location: /ProcessTicketSelector.php
Please login to merge, or discard this patch.
Spacing   +41 added lines, -41 removed lines patch added patch discarded remove patch
@@ -12,7 +12,7 @@  discard block
 block discarded – undo
12 12
 use EventEspresso\core\exceptions\InvalidInterfaceException;
13 13
 use InvalidArgumentException;
14 14
 
15
-if (! defined('EVENT_ESPRESSO_VERSION')) {
15
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
16 16
     exit('No direct script access allowed');
17 17
 }
18 18
 
@@ -50,7 +50,7 @@  discard block
 block discarded – undo
50 50
     public function cancelTicketSelections()
51 51
     {
52 52
         // check nonce
53
-        if (! $this->processTicketSelectorNonce('cancel_ticket_selections')) {
53
+        if ( ! $this->processTicketSelectorNonce('cancel_ticket_selections')) {
54 54
             return false;
55 55
         }
56 56
         EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
@@ -62,7 +62,7 @@  discard block
 block discarded – undo
62 62
             );
63 63
         } else {
64 64
             wp_safe_redirect(
65
-                site_url('/' . EE_Registry::instance()->CFG->core->event_cpt_slug . '/')
65
+                site_url('/'.EE_Registry::instance()->CFG->core->event_cpt_slug.'/')
66 66
             );
67 67
         }
68 68
         exit();
@@ -124,7 +124,7 @@  discard block
 block discarded – undo
124 124
     {
125 125
         do_action('EED_Ticket_Selector__process_ticket_selections__before');
126 126
         // do we have an event id?
127
-        if (! EE_Registry::instance()->REQ->is_set('tkt-slctr-event-id')) {
127
+        if ( ! EE_Registry::instance()->REQ->is_set('tkt-slctr-event-id')) {
128 128
             // $_POST['tkt-slctr-event-id'] was not set ?!?!?!?
129 129
             EE_Error::add_error(
130 130
                 sprintf(
@@ -170,7 +170,7 @@  discard block
 block discarded – undo
170 170
                 $valid['total_tickets'],
171 171
                 'event_espresso'
172 172
             );
173
-            $limit_error_1        = sprintf($total_tickets_string, $valid['total_tickets']);
173
+            $limit_error_1 = sprintf($total_tickets_string, $valid['total_tickets']);
174 174
             // dev only message
175 175
             $max_atndz_string = _n(
176 176
                 'The registration limit for this event is %s ticket per registration, therefore the total number of tickets you may purchase at a time can not exceed %s.',
@@ -178,8 +178,8 @@  discard block
 block discarded – undo
178 178
                 $valid['max_atndz'],
179 179
                 'event_espresso'
180 180
             );
181
-            $limit_error_2    = sprintf($max_atndz_string, $valid['max_atndz'], $valid['max_atndz']);
182
-            EE_Error::add_error($limit_error_1 . '<br/>' . $limit_error_2, __FILE__, __FUNCTION__, __LINE__);
181
+            $limit_error_2 = sprintf($max_atndz_string, $valid['max_atndz'], $valid['max_atndz']);
182
+            EE_Error::add_error($limit_error_1.'<br/>'.$limit_error_2, __FILE__, __FUNCTION__, __LINE__);
183 183
         } else {
184 184
             // all data appears to be valid
185 185
             $tckts_slctd   = false;
@@ -192,15 +192,15 @@  discard block
 block discarded – undo
192 192
                 // cycle thru the number of data rows sent from the event listing
193 193
                 for ($x = 0; $x < $valid['rows']; $x++) {
194 194
                     // does this row actually contain a ticket quantity?
195
-                    if (isset($valid['qty'][ $x ]) && $valid['qty'][ $x ] > 0) {
195
+                    if (isset($valid['qty'][$x]) && $valid['qty'][$x] > 0) {
196 196
                         // YES we have a ticket quantity
197 197
                         $tckts_slctd = true;
198 198
                         //						d( $valid['ticket_obj'][$x] );
199
-                        if ($valid['ticket_obj'][ $x ] instanceof EE_Ticket) {
199
+                        if ($valid['ticket_obj'][$x] instanceof EE_Ticket) {
200 200
                             // then add ticket to cart
201 201
                             $tickets_added += $this->addTicketToCart(
202
-                                $valid['ticket_obj'][ $x ],
203
-                                $valid['qty'][ $x ]
202
+                                $valid['ticket_obj'][$x],
203
+                                $valid['qty'][$x]
204 204
                             );
205 205
                             if (EE_Error::has_error()) {
206 206
                                 break;
@@ -251,7 +251,7 @@  discard block
 block discarded – undo
251 251
                     );
252 252
                     exit();
253 253
                 } else {
254
-                    if (! EE_Error::has_error() && ! EE_Error::has_error(true, 'attention')) {
254
+                    if ( ! EE_Error::has_error() && ! EE_Error::has_error(true, 'attention')) {
255 255
                         // nothing added to cart
256 256
                         EE_Error::add_attention(__('No tickets were added for the event', 'event_espresso'),
257 257
                             __FILE__, __FUNCTION__, __LINE__);
@@ -297,7 +297,7 @@  discard block
 block discarded – undo
297 297
     private function validatePostData($id = 0)
298 298
     {
299 299
         do_action('AHEE_log', __FILE__, __FUNCTION__, '');
300
-        if (! $id) {
300
+        if ( ! $id) {
301 301
             EE_Error::add_error(
302 302
                 __('The event id provided was not valid.', 'event_espresso'),
303 303
                 __FILE__,
@@ -324,13 +324,13 @@  discard block
 block discarded – undo
324 324
         // cycle through $inputs_to_clean array
325 325
         foreach ($inputs_to_clean as $what => $input_to_clean) {
326 326
             // check for POST data
327
-            if (EE_Registry::instance()->REQ->is_set($input_to_clean . $id)) {
327
+            if (EE_Registry::instance()->REQ->is_set($input_to_clean.$id)) {
328 328
                 // grab value
329
-                $input_value = EE_Registry::instance()->REQ->get($input_to_clean . $id);
329
+                $input_value = EE_Registry::instance()->REQ->get($input_to_clean.$id);
330 330
                 switch ($what) {
331 331
                     // integers
332 332
                     case 'event_id':
333
-                        $valid_data[ $what ] = absint($input_value);
333
+                        $valid_data[$what] = absint($input_value);
334 334
                         // get event via the event id we put in the form
335 335
                         $valid_data['event'] = EE_Registry::instance()
336 336
                                                            ->load_model('Event')
@@ -338,17 +338,17 @@  discard block
 block discarded – undo
338 338
                         break;
339 339
                     case 'rows':
340 340
                     case 'max_atndz':
341
-                        $valid_data[ $what ] = absint($input_value);
341
+                        $valid_data[$what] = absint($input_value);
342 342
                         break;
343 343
                     // arrays of integers
344 344
                     case 'qty':
345 345
                         /** @var array $row_qty */
346 346
                         $row_qty = $input_value;
347 347
                         // if qty is coming from a radio button input, then we need to assemble an array of rows
348
-                        if (! is_array($row_qty)) {
348
+                        if ( ! is_array($row_qty)) {
349 349
                             // get number of rows
350
-                            $rows = EE_Registry::instance()->REQ->is_set('tkt-slctr-rows-' . $id)
351
-                                ? absint(EE_Registry::instance()->REQ->get('tkt-slctr-rows-' . $id))
350
+                            $rows = EE_Registry::instance()->REQ->is_set('tkt-slctr-rows-'.$id)
351
+                                ? absint(EE_Registry::instance()->REQ->get('tkt-slctr-rows-'.$id))
352 352
                                 : 1;
353 353
                             // explode ints by the dash
354 354
                             $row_qty = explode('-', $row_qty);
@@ -356,8 +356,8 @@  discard block
 block discarded – undo
356 356
                             $qty     = isset($row_qty[1]) ? absint($row_qty[1]) : 0;
357 357
                             $row_qty = array($row => $qty);
358 358
                             for ($x = 1; $x <= $rows; $x++) {
359
-                                if (! isset($row_qty[ $x ])) {
360
-                                    $row_qty[ $x ] = 0;
359
+                                if ( ! isset($row_qty[$x])) {
360
+                                    $row_qty[$x] = 0;
361 361
                                 }
362 362
                             }
363 363
                         }
@@ -366,7 +366,7 @@  discard block
 block discarded – undo
366 366
                         foreach ($row_qty as $qty) {
367 367
                             $qty = absint($qty);
368 368
                             // sanitize as integers
369
-                            $valid_data[ $what ][]       = $qty;
369
+                            $valid_data[$what][] = $qty;
370 370
                             $valid_data['total_tickets'] += $qty;
371 371
                         }
372 372
                         break;
@@ -376,14 +376,14 @@  discard block
 block discarded – undo
376 376
                         // cycle thru values
377 377
                         foreach ((array) $input_value as $key => $value) {
378 378
                             // allow only numbers, letters,  spaces, commas and dashes
379
-                            $value_array[ $key ] = wp_strip_all_tags($value);
379
+                            $value_array[$key] = wp_strip_all_tags($value);
380 380
                             // get ticket via the ticket id we put in the form
381 381
                             $ticket_obj                       = EE_Registry::instance()
382 382
                                                                             ->load_model('Ticket')
383 383
                                                                             ->get_one_by_ID($value);
384
-                            $valid_data['ticket_obj'][ $key ] = $ticket_obj;
384
+                            $valid_data['ticket_obj'][$key] = $ticket_obj;
385 385
                         }
386
-                        $valid_data[ $what ] = $value_array;
386
+                        $valid_data[$what] = $value_array;
387 387
                         break;
388 388
                     case 'return_url' :
389 389
                         // grab and sanitize return-url
@@ -394,9 +394,9 @@  discard block
 block discarded – undo
394 394
                             $input_value = explode('#', $input_value);
395 395
                             $input_value = end($input_value);
396 396
                             // use event list url instead, but append anchor
397
-                            $input_value = EEH_Event_View::event_archive_url() . '#' . $input_value;
397
+                            $input_value = EEH_Event_View::event_archive_url().'#'.$input_value;
398 398
                         }
399
-                        $valid_data[ $what ] = $input_value;
399
+                        $valid_data[$what] = $input_value;
400 400
                         break;
401 401
                 }    // end switch $what
402 402
             }
@@ -526,24 +526,24 @@  discard block
 block discarded – undo
526 526
     private function ticketDatetimeAvailability(EE_Ticket $ticket, $get_original_ticket_spaces = false)
527 527
     {
528 528
         // if the $_available_spaces array has not been set up yet...
529
-        if (! isset(self::$_available_spaces['tickets'][ $ticket->ID() ])) {
529
+        if ( ! isset(self::$_available_spaces['tickets'][$ticket->ID()])) {
530 530
             $this->setInitialTicketDatetimeAvailability($ticket);
531 531
         }
532 532
         $available_spaces = $ticket->qty() - $ticket->sold();
533
-        if (isset(self::$_available_spaces['tickets'][ $ticket->ID() ])) {
533
+        if (isset(self::$_available_spaces['tickets'][$ticket->ID()])) {
534 534
             // loop thru tickets, which will ALSO include individual ticket records AND a total
535
-            foreach (self::$_available_spaces['tickets'][ $ticket->ID() ] as $DTD_ID => $spaces) {
535
+            foreach (self::$_available_spaces['tickets'][$ticket->ID()] as $DTD_ID => $spaces) {
536 536
                 // if we want the original datetime availability BEFORE we started subtracting tickets ?
537 537
                 if ($get_original_ticket_spaces) {
538 538
                     // then grab the available spaces from the "tickets" array
539 539
                     // and compare with the above to get the lowest number
540 540
                     $available_spaces = min(
541 541
                         $available_spaces,
542
-                        self::$_available_spaces['tickets'][ $ticket->ID() ][ $DTD_ID ]
542
+                        self::$_available_spaces['tickets'][$ticket->ID()][$DTD_ID]
543 543
                     );
544 544
                 } else {
545 545
                     // we want the updated ticket availability as stored in the "datetimes" array
546
-                    $available_spaces = min($available_spaces, self::$_available_spaces['datetimes'][ $DTD_ID ]);
546
+                    $available_spaces = min($available_spaces, self::$_available_spaces['datetimes'][$DTD_ID]);
547 547
                 }
548 548
             }
549 549
         }
@@ -574,7 +574,7 @@  discard block
 block discarded – undo
574 574
                 'order_by' => array('DTT_EVT_start' => 'ASC'),
575 575
             )
576 576
         );
577
-        if (! empty($datetimes)) {
577
+        if ( ! empty($datetimes)) {
578 578
             // now loop thru all of the datetimes
579 579
             foreach ($datetimes as $datetime) {
580 580
                 if ($datetime instanceof EE_Datetime) {
@@ -582,17 +582,17 @@  discard block
 block discarded – undo
582 582
                     $spaces_remaining = $datetime->spaces_remaining();
583 583
                     // save the total available spaces ( the lesser of the ticket qty minus the number of tickets sold
584 584
                     // or the datetime spaces remaining) to this ticket using the datetime ID as the key
585
-                    self::$_available_spaces['tickets'][ $ticket->ID() ][ $datetime->ID() ] = min(
585
+                    self::$_available_spaces['tickets'][$ticket->ID()][$datetime->ID()] = min(
586 586
                         $ticket->qty() - $ticket->sold(),
587 587
                         $spaces_remaining
588 588
                     );
589 589
                     // if the remaining spaces for this datetime is already set,
590 590
                     // then compare that against the datetime spaces remaining, and take the lowest number,
591 591
                     // else just take the datetime spaces remaining, and assign to the datetimes array
592
-                    self::$_available_spaces['datetimes'][ $datetime->ID() ] = isset(
593
-                        self::$_available_spaces['datetimes'][ $datetime->ID() ]
592
+                    self::$_available_spaces['datetimes'][$datetime->ID()] = isset(
593
+                        self::$_available_spaces['datetimes'][$datetime->ID()]
594 594
                     )
595
-                        ? min(self::$_available_spaces['datetimes'][ $datetime->ID() ], $spaces_remaining)
595
+                        ? min(self::$_available_spaces['datetimes'][$datetime->ID()], $spaces_remaining)
596 596
                         : $spaces_remaining;
597 597
                 }
598 598
             }
@@ -608,11 +608,11 @@  discard block
 block discarded – undo
608 608
      */
609 609
     private function recalculateTicketDatetimeAvailability(EE_Ticket $ticket, $qty = 0)
610 610
     {
611
-        if (isset(self::$_available_spaces['tickets'][ $ticket->ID() ])) {
611
+        if (isset(self::$_available_spaces['tickets'][$ticket->ID()])) {
612 612
             // loop thru tickets, which will ALSO include individual ticket records AND a total
613
-            foreach (self::$_available_spaces['tickets'][ $ticket->ID() ] as $DTD_ID => $spaces) {
613
+            foreach (self::$_available_spaces['tickets'][$ticket->ID()] as $DTD_ID => $spaces) {
614 614
                 // subtract the qty of selected tickets from each datetime's available spaces this ticket has access to,
615
-                self::$_available_spaces['datetimes'][ $DTD_ID ] -= $qty;
615
+                self::$_available_spaces['datetimes'][$DTD_ID] -= $qty;
616 616
             }
617 617
         }
618 618
     }
Please login to merge, or discard this patch.
espresso.php 1 patch
Indentation   +191 added lines, -191 removed lines patch added patch discarded remove patch
@@ -38,216 +38,216 @@
 block discarded – undo
38 38
  * @since       4.0
39 39
  */
40 40
 if (function_exists('espresso_version')) {
41
-    if (! function_exists('espresso_duplicate_plugin_error')) {
42
-        /**
43
-         *    espresso_duplicate_plugin_error
44
-         *    displays if more than one version of EE is activated at the same time
45
-         */
46
-        function espresso_duplicate_plugin_error()
47
-        {
48
-            ?>
41
+	if (! function_exists('espresso_duplicate_plugin_error')) {
42
+		/**
43
+		 *    espresso_duplicate_plugin_error
44
+		 *    displays if more than one version of EE is activated at the same time
45
+		 */
46
+		function espresso_duplicate_plugin_error()
47
+		{
48
+			?>
49 49
             <div class="error">
50 50
                 <p>
51 51
                     <?php
52
-                    echo esc_html__(
53
-                        'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
54
-                        'event_espresso'
55
-                    ); ?>
52
+					echo esc_html__(
53
+						'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
54
+						'event_espresso'
55
+					); ?>
56 56
                 </p>
57 57
             </div>
58 58
             <?php
59
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
60
-        }
61
-    }
62
-    add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
59
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
60
+		}
61
+	}
62
+	add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
63 63
 
64 64
 } else {
65
-    define('EE_MIN_PHP_VER_REQUIRED', '5.3.9');
66
-    if (! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
67
-        /**
68
-         * espresso_minimum_php_version_error
69
-         * @return void
70
-         */
71
-        function espresso_minimum_php_version_error()
72
-        {
73
-            ?>
65
+	define('EE_MIN_PHP_VER_REQUIRED', '5.3.9');
66
+	if (! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
67
+		/**
68
+		 * espresso_minimum_php_version_error
69
+		 * @return void
70
+		 */
71
+		function espresso_minimum_php_version_error()
72
+		{
73
+			?>
74 74
             <div class="error">
75 75
                 <p>
76 76
                     <?php
77
-                    printf(
78
-                        esc_html__(
79
-                            'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
80
-                            'event_espresso'
81
-                        ),
82
-                        EE_MIN_PHP_VER_REQUIRED,
83
-                        PHP_VERSION,
84
-                        '<br/>',
85
-                        '<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
86
-                    );
87
-                    ?>
77
+					printf(
78
+						esc_html__(
79
+							'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
80
+							'event_espresso'
81
+						),
82
+						EE_MIN_PHP_VER_REQUIRED,
83
+						PHP_VERSION,
84
+						'<br/>',
85
+						'<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
86
+					);
87
+					?>
88 88
                 </p>
89 89
             </div>
90 90
             <?php
91
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
92
-        }
91
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
92
+		}
93 93
 
94
-        add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
95
-    } else {
96
-        define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
97
-        /**
98
-         * espresso_version
99
-         * Returns the plugin version
100
-         *
101
-         * @return string
102
-         */
103
-        function espresso_version()
104
-        {
105
-            return apply_filters('FHEE__espresso__espresso_version', '4.9.56.rc.012');
106
-        }
94
+		add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
95
+	} else {
96
+		define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
97
+		/**
98
+		 * espresso_version
99
+		 * Returns the plugin version
100
+		 *
101
+		 * @return string
102
+		 */
103
+		function espresso_version()
104
+		{
105
+			return apply_filters('FHEE__espresso__espresso_version', '4.9.56.rc.012');
106
+		}
107 107
 
108
-        /**
109
-         * espresso_plugin_activation
110
-         * adds a wp-option to indicate that EE has been activated via the WP admin plugins page
111
-         */
112
-        function espresso_plugin_activation()
113
-        {
114
-            update_option('ee_espresso_activation', true);
115
-        }
108
+		/**
109
+		 * espresso_plugin_activation
110
+		 * adds a wp-option to indicate that EE has been activated via the WP admin plugins page
111
+		 */
112
+		function espresso_plugin_activation()
113
+		{
114
+			update_option('ee_espresso_activation', true);
115
+		}
116 116
 
117
-        register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
118
-        /**
119
-         *    espresso_load_error_handling
120
-         *    this function loads EE's class for handling exceptions and errors
121
-         */
122
-        function espresso_load_error_handling()
123
-        {
124
-            static $error_handling_loaded = false;
125
-            if ($error_handling_loaded) {
126
-                return;
127
-            }
128
-            // load debugging tools
129
-            if (WP_DEBUG === true && is_readable(EE_HELPERS . 'EEH_Debug_Tools.helper.php')) {
130
-                require_once   EE_HELPERS . 'EEH_Debug_Tools.helper.php';
131
-                \EEH_Debug_Tools::instance();
132
-            }
133
-            // load error handling
134
-            if (is_readable(EE_CORE . 'EE_Error.core.php')) {
135
-                require_once EE_CORE . 'EE_Error.core.php';
136
-            } else {
137
-                wp_die(esc_html__('The EE_Error core class could not be loaded.', 'event_espresso'));
138
-            }
139
-            $error_handling_loaded = true;
140
-        }
117
+		register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
118
+		/**
119
+		 *    espresso_load_error_handling
120
+		 *    this function loads EE's class for handling exceptions and errors
121
+		 */
122
+		function espresso_load_error_handling()
123
+		{
124
+			static $error_handling_loaded = false;
125
+			if ($error_handling_loaded) {
126
+				return;
127
+			}
128
+			// load debugging tools
129
+			if (WP_DEBUG === true && is_readable(EE_HELPERS . 'EEH_Debug_Tools.helper.php')) {
130
+				require_once   EE_HELPERS . 'EEH_Debug_Tools.helper.php';
131
+				\EEH_Debug_Tools::instance();
132
+			}
133
+			// load error handling
134
+			if (is_readable(EE_CORE . 'EE_Error.core.php')) {
135
+				require_once EE_CORE . 'EE_Error.core.php';
136
+			} else {
137
+				wp_die(esc_html__('The EE_Error core class could not be loaded.', 'event_espresso'));
138
+			}
139
+			$error_handling_loaded = true;
140
+		}
141 141
 
142
-        /**
143
-         *    espresso_load_required
144
-         *    given a class name and path, this function will load that file or throw an exception
145
-         *
146
-         * @param    string $classname
147
-         * @param    string $full_path_to_file
148
-         * @throws    EE_Error
149
-         */
150
-        function espresso_load_required($classname, $full_path_to_file)
151
-        {
152
-            if (is_readable($full_path_to_file)) {
153
-                require_once $full_path_to_file;
154
-            } else {
155
-                throw new \EE_Error (
156
-                    sprintf(
157
-                        esc_html__(
158
-                            'The %s class file could not be located or is not readable due to file permissions.',
159
-                            'event_espresso'
160
-                        ),
161
-                        $classname
162
-                    )
163
-                );
164
-            }
165
-        }
142
+		/**
143
+		 *    espresso_load_required
144
+		 *    given a class name and path, this function will load that file or throw an exception
145
+		 *
146
+		 * @param    string $classname
147
+		 * @param    string $full_path_to_file
148
+		 * @throws    EE_Error
149
+		 */
150
+		function espresso_load_required($classname, $full_path_to_file)
151
+		{
152
+			if (is_readable($full_path_to_file)) {
153
+				require_once $full_path_to_file;
154
+			} else {
155
+				throw new \EE_Error (
156
+					sprintf(
157
+						esc_html__(
158
+							'The %s class file could not be located or is not readable due to file permissions.',
159
+							'event_espresso'
160
+						),
161
+						$classname
162
+					)
163
+				);
164
+			}
165
+		}
166 166
 
167
-        /**
168
-         * @since 4.9.27
169
-         * @throws \EE_Error
170
-         * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
171
-         * @throws \EventEspresso\core\exceptions\InvalidEntityException
172
-         * @throws \EventEspresso\core\exceptions\InvalidIdentifierException
173
-         * @throws \EventEspresso\core\exceptions\InvalidClassException
174
-         * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
175
-         * @throws \EventEspresso\core\services\container\exceptions\ServiceExistsException
176
-         * @throws \EventEspresso\core\services\container\exceptions\ServiceNotFoundException
177
-         * @throws \OutOfBoundsException
178
-         */
179
-        function bootstrap_espresso()
180
-        {
181
-            require_once __DIR__ . '/core/espresso_definitions.php';
182
-            try {
183
-                espresso_load_error_handling();
184
-                espresso_load_required(
185
-                    'EEH_Base',
186
-                    EE_CORE . 'helpers' . DS . 'EEH_Base.helper.php'
187
-                );
188
-                espresso_load_required(
189
-                    'EEH_File',
190
-                    EE_CORE . 'interfaces' . DS . 'EEHI_File.interface.php'
191
-                );
192
-                espresso_load_required(
193
-                    'EEH_File',
194
-                    EE_CORE . 'helpers' . DS . 'EEH_File.helper.php'
195
-                );
196
-                espresso_load_required(
197
-                    'EEH_Array',
198
-                    EE_CORE . 'helpers' . DS . 'EEH_Array.helper.php'
199
-                );
200
-                // instantiate and configure PSR4 autoloader
201
-                espresso_load_required(
202
-                    'Psr4Autoloader',
203
-                    EE_CORE . 'Psr4Autoloader.php'
204
-                );
205
-                espresso_load_required(
206
-                    'EE_Psr4AutoloaderInit',
207
-                    EE_CORE . 'EE_Psr4AutoloaderInit.core.php'
208
-                );
209
-                $AutoloaderInit = new EE_Psr4AutoloaderInit();
210
-                $AutoloaderInit->initializeAutoloader();
211
-                espresso_load_required(
212
-                    'EE_Request',
213
-                    EE_CORE . 'request_stack' . DS . 'EE_Request.core.php'
214
-                );
215
-                espresso_load_required(
216
-                    'EE_Response',
217
-                    EE_CORE . 'request_stack' . DS . 'EE_Response.core.php'
218
-                );
219
-                espresso_load_required(
220
-                    'EE_Bootstrap',
221
-                    EE_CORE . 'EE_Bootstrap.core.php'
222
-                );
223
-                // bootstrap EE and the request stack
224
-                new EE_Bootstrap(
225
-                    new EE_Request($_GET, $_POST, $_COOKIE),
226
-                    new EE_Response()
227
-                );
228
-            } catch (Exception $e) {
229
-                require_once EE_CORE . 'exceptions' . DS . 'ExceptionStackTraceDisplay.php';
230
-                new EventEspresso\core\exceptions\ExceptionStackTraceDisplay($e);
231
-            }
232
-        }
233
-        bootstrap_espresso();
234
-    }
167
+		/**
168
+		 * @since 4.9.27
169
+		 * @throws \EE_Error
170
+		 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
171
+		 * @throws \EventEspresso\core\exceptions\InvalidEntityException
172
+		 * @throws \EventEspresso\core\exceptions\InvalidIdentifierException
173
+		 * @throws \EventEspresso\core\exceptions\InvalidClassException
174
+		 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
175
+		 * @throws \EventEspresso\core\services\container\exceptions\ServiceExistsException
176
+		 * @throws \EventEspresso\core\services\container\exceptions\ServiceNotFoundException
177
+		 * @throws \OutOfBoundsException
178
+		 */
179
+		function bootstrap_espresso()
180
+		{
181
+			require_once __DIR__ . '/core/espresso_definitions.php';
182
+			try {
183
+				espresso_load_error_handling();
184
+				espresso_load_required(
185
+					'EEH_Base',
186
+					EE_CORE . 'helpers' . DS . 'EEH_Base.helper.php'
187
+				);
188
+				espresso_load_required(
189
+					'EEH_File',
190
+					EE_CORE . 'interfaces' . DS . 'EEHI_File.interface.php'
191
+				);
192
+				espresso_load_required(
193
+					'EEH_File',
194
+					EE_CORE . 'helpers' . DS . 'EEH_File.helper.php'
195
+				);
196
+				espresso_load_required(
197
+					'EEH_Array',
198
+					EE_CORE . 'helpers' . DS . 'EEH_Array.helper.php'
199
+				);
200
+				// instantiate and configure PSR4 autoloader
201
+				espresso_load_required(
202
+					'Psr4Autoloader',
203
+					EE_CORE . 'Psr4Autoloader.php'
204
+				);
205
+				espresso_load_required(
206
+					'EE_Psr4AutoloaderInit',
207
+					EE_CORE . 'EE_Psr4AutoloaderInit.core.php'
208
+				);
209
+				$AutoloaderInit = new EE_Psr4AutoloaderInit();
210
+				$AutoloaderInit->initializeAutoloader();
211
+				espresso_load_required(
212
+					'EE_Request',
213
+					EE_CORE . 'request_stack' . DS . 'EE_Request.core.php'
214
+				);
215
+				espresso_load_required(
216
+					'EE_Response',
217
+					EE_CORE . 'request_stack' . DS . 'EE_Response.core.php'
218
+				);
219
+				espresso_load_required(
220
+					'EE_Bootstrap',
221
+					EE_CORE . 'EE_Bootstrap.core.php'
222
+				);
223
+				// bootstrap EE and the request stack
224
+				new EE_Bootstrap(
225
+					new EE_Request($_GET, $_POST, $_COOKIE),
226
+					new EE_Response()
227
+				);
228
+			} catch (Exception $e) {
229
+				require_once EE_CORE . 'exceptions' . DS . 'ExceptionStackTraceDisplay.php';
230
+				new EventEspresso\core\exceptions\ExceptionStackTraceDisplay($e);
231
+			}
232
+		}
233
+		bootstrap_espresso();
234
+	}
235 235
 }
236 236
 if (! function_exists('espresso_deactivate_plugin')) {
237
-    /**
238
-     *    deactivate_plugin
239
-     * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
240
-     *
241
-     * @access public
242
-     * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
243
-     * @return    void
244
-     */
245
-    function espresso_deactivate_plugin($plugin_basename = '')
246
-    {
247
-        if (! function_exists('deactivate_plugins')) {
248
-            require_once ABSPATH . 'wp-admin/includes/plugin.php';
249
-        }
250
-        unset($_GET['activate'], $_REQUEST['activate']);
251
-        deactivate_plugins($plugin_basename);
252
-    }
237
+	/**
238
+	 *    deactivate_plugin
239
+	 * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
240
+	 *
241
+	 * @access public
242
+	 * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
243
+	 * @return    void
244
+	 */
245
+	function espresso_deactivate_plugin($plugin_basename = '')
246
+	{
247
+		if (! function_exists('deactivate_plugins')) {
248
+			require_once ABSPATH . 'wp-admin/includes/plugin.php';
249
+		}
250
+		unset($_GET['activate'], $_REQUEST['activate']);
251
+		deactivate_plugins($plugin_basename);
252
+	}
253 253
 }
Please login to merge, or discard this patch.