Completed
Branch FET-10768-extract-admin-bar (277687)
by
unknown
116:39 queued 104:25
created

EE_System::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 71
Code Lines 49

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 49
nc 1
nop 5
dl 0
loc 71
rs 9.1369
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
use EventEspresso\core\exceptions\ExceptionStackTraceDisplay;
4
use EventEspresso\core\interfaces\ResettableInterface;
5
use EventEspresso\core\services\loaders\LoaderInterface;
6
use EventEspresso\core\services\shortcodes\ShortcodesManager;
7
8
defined('EVENT_ESPRESSO_VERSION') || exit('No direct script access allowed');
9
10
11
12
/**
13
 * EE_System
14
 * The backbone of the core application that the rest of the system builds off of once bootstrapping is complete
15
 *
16
 * @package        Event Espresso
17
 * @subpackage     core/
18
 * @author         Brent Christensen, Michael Nelson
19
 */
20
final class EE_System implements ResettableInterface
21
{
22
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);
0 ignored issues
show
Bug introduced by
It seems like $registry defined by parameter $registry on line 128 can be null; however, EE_System::__construct() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
Bug introduced by
It seems like $loader defined by parameter $loader on line 129 can be null; however, EE_System::__construct() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
Bug introduced by
It seems like $capabilities defined by parameter $capabilities on line 130 can be null; however, EE_System::__construct() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
Bug introduced by
It seems like $request defined by parameter $request on line 131 can be null; however, EE_System::__construct() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
Bug introduced by
It seems like $maintenance_mode defined by parameter $maintenance_mode on line 132 can be null; however, EE_System::__construct() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
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->registry->load_core('EE_Capabilities');
256
        add_action(
257
            'AHEE__EE_Capabilities__init_caps__before_initialization',
258
            function() {
259
                EE_Registry::instance()->load_lib('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->registry->create(
277
            'CommandBusInterface',
278
            array(
279
                null,
280
                apply_filters(
281
                    'FHEE__EE_Load_Espresso_Core__handle_request__CommandBus_middleware',
282
                    array(
283
                        $this->registry->create('CapChecker'),
284
                        $this->registry->create('AddActionHook'),
285
                    )
286
                ),
287
            ),
288
            true
289
        );
290
    }
291
292
293
294
    /**
295
     * @return void
296
     * @throws EE_Error
297
     */
298
    public function loadPluginApi()
299
    {
300
        // set autoloaders for all of the classes implementing EEI_Plugin_API
301
        // which provide helpers for EE plugin authors to more easily register certain components with EE.
302
        EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'plugin_api');
303
    }
304
305
306
307
    /**
308
     * load_espresso_addons
309
     * allow addons to load first so that they can set hooks for running DMS's, etc
310
     * this is hooked into both:
311
     *    'AHEE__EE_Bootstrap__load_core_configuration'
312
     *        which runs during the WP 'plugins_loaded' action at priority 5
313
     *    and the WP 'activate_plugin' hook point
314
     *
315
     * @access public
316
     * @return void
317
     * @throws EE_Error
318
     */
319
    public function load_espresso_addons()
320
    {
321
        do_action('AHEE__EE_System__load_espresso_addons');
322
        //if the WP API basic auth plugin isn't already loaded, load it now.
323
        //We want it for mobile apps. Just include the entire plugin
324
        //also, don't load the basic auth when a plugin is getting activated, because
325
        //it could be the basic auth plugin, and it doesn't check if its methods are already defined
326
        //and causes a fatal error
327
        if (
328
            ! (
329
                isset($_GET['activate'])
330
                && $_GET['activate'] === 'true'
331
            )
332
            && ! function_exists('json_basic_auth_handler')
333
            && ! function_exists('json_basic_auth_error')
334
            && ! (
335
                isset($_GET['action'])
336
                && in_array($_GET['action'], array('activate', 'activate-selected'), true)
337
            )
338
        ) {
339
            include_once EE_THIRD_PARTY . 'wp-api-basic-auth' . DS . 'basic-auth.php';
340
        }
341
        do_action('AHEE__EE_System__load_espresso_addons__complete');
342
    }
343
344
345
346
    /**
347
     * detect_activations_or_upgrades
348
     * Checks for activation or upgrade of core first;
349
     * then also checks if any registered addons have been activated or upgraded
350
     * This is hooked into 'AHEE__EE_Bootstrap__detect_activations_or_upgrades'
351
     * which runs during the WP 'plugins_loaded' action at priority 3
352
     *
353
     * @access public
354
     * @return void
355
     */
356
    public function detect_activations_or_upgrades()
357
    {
358
        //first off: let's make sure to handle core
359
        $this->detect_if_activation_or_upgrade();
360
        foreach ($this->registry->addons as $addon) {
361
            if ($addon instanceof EE_Addon) {
362
                //detect teh request type for that addon
363
                $addon->detect_activation_or_upgrade();
364
            }
365
        }
366
    }
367
368
369
370
    /**
371
     * detect_if_activation_or_upgrade
372
     * Takes care of detecting whether this is a brand new install or code upgrade,
373
     * and either setting up the DB or setting up maintenance mode etc.
374
     *
375
     * @access public
376
     * @return void
377
     */
378
    public function detect_if_activation_or_upgrade()
379
    {
380
        do_action('AHEE__EE_System___detect_if_activation_or_upgrade__begin');
381
        // check if db has been updated, or if its a brand-new installation
382
        $espresso_db_update = $this->fix_espresso_db_upgrade_option();
383
        $request_type = $this->detect_req_type($espresso_db_update);
384
        //EEH_Debug_Tools::printr( $request_type, '$request_type', __FILE__, __LINE__ );
385
        switch ($request_type) {
386
            case EE_System::req_type_new_activation:
387
                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__new_activation');
388
                $this->_handle_core_version_change($espresso_db_update);
389
                break;
390
            case EE_System::req_type_reactivation:
391
                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__reactivation');
392
                $this->_handle_core_version_change($espresso_db_update);
393
                break;
394
            case EE_System::req_type_upgrade:
395
                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__upgrade');
396
                //migrations may be required now that we've upgraded
397
                $this->maintenance_mode->set_maintenance_mode_if_db_old();
398
                $this->_handle_core_version_change($espresso_db_update);
399
                //				echo "done upgrade";die;
400
                break;
401
            case EE_System::req_type_downgrade:
402
                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__downgrade');
403
                //its possible migrations are no longer required
404
                $this->maintenance_mode->set_maintenance_mode_if_db_old();
405
                $this->_handle_core_version_change($espresso_db_update);
406
                break;
407
            case EE_System::req_type_normal:
408
            default:
409
                //				$this->_maybe_redirect_to_ee_about();
410
                break;
411
        }
412
        do_action('AHEE__EE_System__detect_if_activation_or_upgrade__complete');
413
    }
414
415
416
417
    /**
418
     * Updates the list of installed versions and sets hooks for
419
     * initializing the database later during the request
420
     *
421
     * @param array $espresso_db_update
422
     */
423
    private function _handle_core_version_change($espresso_db_update)
424
    {
425
        $this->update_list_of_installed_versions($espresso_db_update);
426
        //get ready to verify the DB is ok (provided we aren't in maintenance mode, of course)
427
        add_action(
428
            'AHEE__EE_System__perform_activations_upgrades_and_migrations',
429
            array($this, 'initialize_db_if_no_migrations_required')
430
        );
431
    }
432
433
434
435
    /**
436
     * standardizes the wp option 'espresso_db_upgrade' which actually stores
437
     * information about what versions of EE have been installed and activated,
438
     * NOT necessarily the state of the database
439
     *
440
     * @param mixed $espresso_db_update the value of the WordPress option.
441
     *                                            If not supplied, fetches it from the options table
442
     * @return array the correct value of 'espresso_db_upgrade', after saving it, if it needed correction
443
     */
444
    private function fix_espresso_db_upgrade_option($espresso_db_update = null)
445
    {
446
        do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__begin', $espresso_db_update);
447
        if (! $espresso_db_update) {
448
            $espresso_db_update = get_option('espresso_db_update');
449
        }
450
        // check that option is an array
451
        if (! is_array($espresso_db_update)) {
452
            // if option is FALSE, then it never existed
453
            if ($espresso_db_update === false) {
454
                // make $espresso_db_update an array and save option with autoload OFF
455
                $espresso_db_update = array();
456
                add_option('espresso_db_update', $espresso_db_update, '', 'no');
457
            } else {
458
                // option is NOT FALSE but also is NOT an array, so make it an array and save it
459
                $espresso_db_update = array($espresso_db_update => array());
460
                update_option('espresso_db_update', $espresso_db_update);
461
            }
462
        } else {
463
            $corrected_db_update = array();
464
            //if IS an array, but is it an array where KEYS are version numbers, and values are arrays?
465
            foreach ($espresso_db_update as $should_be_version_string => $should_be_array) {
466
                if (is_int($should_be_version_string) && ! is_array($should_be_array)) {
467
                    //the key is an int, and the value IS NOT an array
468
                    //so it must be numerically-indexed, where values are versions installed...
469
                    //fix it!
470
                    $version_string = $should_be_array;
471
                    $corrected_db_update[$version_string] = array('unknown-date');
472
                } else {
473
                    //ok it checks out
474
                    $corrected_db_update[$should_be_version_string] = $should_be_array;
475
                }
476
            }
477
            $espresso_db_update = $corrected_db_update;
478
            update_option('espresso_db_update', $espresso_db_update);
479
        }
480
        do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__complete', $espresso_db_update);
481
        return $espresso_db_update;
482
    }
483
484
485
486
    /**
487
     * Does the traditional work of setting up the plugin's database and adding default data.
488
     * If migration script/process did not exist, this is what would happen on every activation/reactivation/upgrade.
489
     * NOTE: if we're in maintenance mode (which would be the case if we detect there are data
490
     * migration scripts that need to be run and a version change happens), enqueues core for database initialization,
491
     * so that it will be done when migrations are finished
492
     *
493
     * @param boolean $initialize_addons_too if true, we double-check addons' database tables etc too;
494
     * @param boolean $verify_schema         if true will re-check the database tables have the correct schema.
495
     *                                       This is a resource-intensive job
496
     *                                       so we prefer to only do it when necessary
497
     * @return void
498
     * @throws EE_Error
499
     */
500
    public function initialize_db_if_no_migrations_required($initialize_addons_too = false, $verify_schema = true)
501
    {
502
        $request_type = $this->detect_req_type();
503
        //only initialize system if we're not in maintenance mode.
504
        if ($this->maintenance_mode->level() !== EE_Maintenance_Mode::level_2_complete_maintenance) {
505
            update_option('ee_flush_rewrite_rules', true);
506
            if ($verify_schema) {
507
                EEH_Activation::initialize_db_and_folders();
508
            }
509
            EEH_Activation::initialize_db_content();
510
            EEH_Activation::system_initialization();
511
            if ($initialize_addons_too) {
512
                $this->initialize_addons();
513
            }
514
        } else {
515
            EE_Data_Migration_Manager::instance()->enqueue_db_initialization_for('Core');
516
        }
517
        if ($request_type === EE_System::req_type_new_activation
518
            || $request_type === EE_System::req_type_reactivation
519
            || (
520
                $request_type === EE_System::req_type_upgrade
521
                && $this->is_major_version_change()
522
            )
523
        ) {
524
            add_action('AHEE__EE_System__initialize_last', array($this, 'redirect_to_about_ee'), 9);
525
        }
526
    }
527
528
529
530
    /**
531
     * Initializes the db for all registered addons
532
     *
533
     * @throws EE_Error
534
     */
535
    public function initialize_addons()
536
    {
537
        //foreach registered addon, make sure its db is up-to-date too
538
        foreach ($this->registry->addons as $addon) {
539
            if ($addon instanceof EE_Addon) {
540
                $addon->initialize_db_if_no_migrations_required();
541
            }
542
        }
543
    }
544
545
546
547
    /**
548
     * Adds the current code version to the saved wp option which stores a list of all ee versions ever installed.
549
     *
550
     * @param    array  $version_history
551
     * @param    string $current_version_to_add version to be added to the version history
552
     * @return    boolean success as to whether or not this option was changed
553
     */
554
    public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null)
555
    {
556
        if (! $version_history) {
557
            $version_history = $this->fix_espresso_db_upgrade_option($version_history);
558
        }
559
        if ($current_version_to_add === null) {
560
            $current_version_to_add = espresso_version();
561
        }
562
        $version_history[$current_version_to_add][] = date('Y-m-d H:i:s', time());
563
        // re-save
564
        return update_option('espresso_db_update', $version_history);
565
    }
566
567
568
569
    /**
570
     * Detects if the current version indicated in the has existed in the list of
571
     * previously-installed versions of EE (espresso_db_update). Does NOT modify it (ie, no side-effect)
572
     *
573
     * @param array $espresso_db_update array from the wp option stored under the name 'espresso_db_update'.
574
     *                                  If not supplied, fetches it from the options table.
575
     *                                  Also, caches its result so later parts of the code can also know whether
576
     *                                  there's been an update or not. This way we can add the current version to
577
     *                                  espresso_db_update, but still know if this is a new install or not
578
     * @return int one of the constants on EE_System::req_type_
579
     */
580
    public function detect_req_type($espresso_db_update = null)
581
    {
582
        if ($this->_req_type === null) {
583
            $espresso_db_update = ! empty($espresso_db_update)
584
                ? $espresso_db_update
585
                : $this->fix_espresso_db_upgrade_option();
586
            $this->_req_type = EE_System::detect_req_type_given_activation_history(
587
                $espresso_db_update,
588
                'ee_espresso_activation', espresso_version()
589
            );
590
            $this->_major_version_change = $this->_detect_major_version_change($espresso_db_update);
591
        }
592
        return $this->_req_type;
593
    }
594
595
596
597
    /**
598
     * Returns whether or not there was a non-micro version change (ie, change in either
599
     * the first or second number in the version. Eg 4.9.0.rc.001 to 4.10.0.rc.000,
600
     * but not 4.9.0.rc.0001 to 4.9.1.rc.0001
601
     *
602
     * @param $activation_history
603
     * @return bool
604
     */
605
    private function _detect_major_version_change($activation_history)
606
    {
607
        $previous_version = EE_System::_get_most_recently_active_version_from_activation_history($activation_history);
608
        $previous_version_parts = explode('.', $previous_version);
609
        $current_version_parts = explode('.', espresso_version());
610
        return isset($previous_version_parts[0], $previous_version_parts[1], $current_version_parts[0], $current_version_parts[1])
611
               && ($previous_version_parts[0] !== $current_version_parts[0]
612
                   || $previous_version_parts[1] !== $current_version_parts[1]
613
               );
614
    }
615
616
617
618
    /**
619
     * Returns true if either the major or minor version of EE changed during this request.
620
     * 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
621
     *
622
     * @return bool
623
     */
624
    public function is_major_version_change()
625
    {
626
        return $this->_major_version_change;
627
    }
628
629
630
631
    /**
632
     * Determines the request type for any ee addon, given three piece of info: the current array of activation
633
     * histories (for core that' 'espresso_db_update' wp option); the name of the WordPress option which is temporarily
634
     * set upon activation of the plugin (for core it's 'ee_espresso_activation'); and the version that this plugin was
635
     * just activated to (for core that will always be espresso_version())
636
     *
637
     * @param array  $activation_history_for_addon     the option's value which stores the activation history for this
638
     *                                                 ee plugin. for core that's 'espresso_db_update'
639
     * @param string $activation_indicator_option_name the name of the WordPress option that is temporarily set to
640
     *                                                 indicate that this plugin was just activated
641
     * @param string $version_to_upgrade_to            the version that was just upgraded to (for core that will be
642
     *                                                 espresso_version())
643
     * @return int one of the constants on EE_System::req_type_*
644
     */
645
    public static function detect_req_type_given_activation_history(
646
        $activation_history_for_addon,
647
        $activation_indicator_option_name,
648
        $version_to_upgrade_to
649
    ) {
650
        $version_is_higher = self::_new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to);
651
        if ($activation_history_for_addon) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $activation_history_for_addon of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
652
            //it exists, so this isn't a completely new install
653
            //check if this version already in that list of previously installed versions
654
            if (! isset($activation_history_for_addon[$version_to_upgrade_to])) {
655
                //it a version we haven't seen before
656
                if ($version_is_higher === 1) {
657
                    $req_type = EE_System::req_type_upgrade;
658
                } else {
659
                    $req_type = EE_System::req_type_downgrade;
660
                }
661
                delete_option($activation_indicator_option_name);
662
            } else {
663
                // its not an update. maybe a reactivation?
664
                if (get_option($activation_indicator_option_name, false)) {
665 View Code Duplication
                    if ($version_is_higher === -1) {
666
                        $req_type = EE_System::req_type_downgrade;
667
                    } else if ($version_is_higher === 0) {
668
                        //we've seen this version before, but it's an activation. must be a reactivation
669
                        $req_type = EE_System::req_type_reactivation;
670
                    } else {//$version_is_higher === 1
671
                        $req_type = EE_System::req_type_upgrade;
672
                    }
673
                    delete_option($activation_indicator_option_name);
674 View Code Duplication
                } else {
675
                    //we've seen this version before and the activation indicate doesn't show it was just activated
676
                    if ($version_is_higher === -1) {
677
                        $req_type = EE_System::req_type_downgrade;
678
                    } else if ($version_is_higher === 0) {
679
                        //we've seen this version before and it's not an activation. its normal request
680
                        $req_type = EE_System::req_type_normal;
681
                    } else {//$version_is_higher === 1
682
                        $req_type = EE_System::req_type_upgrade;
683
                    }
684
                }
685
            }
686
        } else {
687
            //brand new install
688
            $req_type = EE_System::req_type_new_activation;
689
            delete_option($activation_indicator_option_name);
690
        }
691
        return $req_type;
692
    }
693
694
695
696
    /**
697
     * Detects if the $version_to_upgrade_to is higher than the most recent version in
698
     * the $activation_history_for_addon
699
     *
700
     * @param array  $activation_history_for_addon (keys are versions, values are arrays of times activated,
701
     *                                             sometimes containing 'unknown-date'
702
     * @param string $version_to_upgrade_to        (current version)
703
     * @return int results of version_compare( $version_to_upgrade_to, $most_recently_active_version ).
704
     *                                             ie, -1 if $version_to_upgrade_to is LOWER (downgrade);
705
     *                                             0 if $version_to_upgrade_to MATCHES (reactivation or normal request);
706
     *                                             1 if $version_to_upgrade_to is HIGHER (upgrade) ;
707
     */
708
    private static function _new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to)
709
    {
710
        //find the most recently-activated version
711
        $most_recently_active_version =
712
            EE_System::_get_most_recently_active_version_from_activation_history($activation_history_for_addon);
713
        return version_compare($version_to_upgrade_to, $most_recently_active_version);
714
    }
715
716
717
718
    /**
719
     * Gets the most recently active version listed in the activation history,
720
     * and if none are found (ie, it's a brand new install) returns '0.0.0.dev.000'.
721
     *
722
     * @param array $activation_history  (keys are versions, values are arrays of times activated,
723
     *                                   sometimes containing 'unknown-date'
724
     * @return string
725
     */
726
    private static function _get_most_recently_active_version_from_activation_history($activation_history)
727
    {
728
        $most_recently_active_version_activation = '1970-01-01 00:00:00';
729
        $most_recently_active_version = '0.0.0.dev.000';
730
        if (is_array($activation_history)) {
731
            foreach ($activation_history as $version => $times_activated) {
732
                //check there is a record of when this version was activated. Otherwise,
733
                //mark it as unknown
734
                if (! $times_activated) {
735
                    $times_activated = array('unknown-date');
736
                }
737
                if (is_string($times_activated)) {
738
                    $times_activated = array($times_activated);
739
                }
740
                foreach ($times_activated as $an_activation) {
741
                    if ($an_activation !== 'unknown-date' && $an_activation > $most_recently_active_version_activation) {
742
                        $most_recently_active_version = $version;
743
                        $most_recently_active_version_activation = $an_activation === 'unknown-date'
744
                            ? '1970-01-01 00:00:00'
745
                            : $an_activation;
746
                    }
747
                }
748
            }
749
        }
750
        return $most_recently_active_version;
751
    }
752
753
754
755
    /**
756
     * This redirects to the about EE page after activation
757
     *
758
     * @return void
759
     */
760
    public function redirect_to_about_ee()
761
    {
762
        $notices = EE_Error::get_notices(false);
763
        //if current user is an admin and it's not an ajax or rest request
764
        if (
765
            ! (defined('DOING_AJAX') && DOING_AJAX)
766
            && ! (defined('REST_REQUEST') && REST_REQUEST)
767
            && ! isset($notices['errors'])
768
            && apply_filters(
769
                'FHEE__EE_System__redirect_to_about_ee__do_redirect',
770
                $this->capabilities->current_user_can('manage_options', 'espresso_about_default')
771
            )
772
        ) {
773
            $query_params = array('page' => 'espresso_about');
774
            if (EE_System::instance()->detect_req_type() === EE_System::req_type_new_activation) {
775
                $query_params['new_activation'] = true;
776
            }
777
            if (EE_System::instance()->detect_req_type() === EE_System::req_type_reactivation) {
778
                $query_params['reactivation'] = true;
779
            }
780
            $url = add_query_arg($query_params, admin_url('admin.php'));
781
            wp_safe_redirect($url);
782
            exit();
783
        }
784
    }
785
786
787
788
    /**
789
     * load_core_configuration
790
     * this is hooked into 'AHEE__EE_Bootstrap__load_core_configuration'
791
     * which runs during the WP 'plugins_loaded' action at priority 5
792
     *
793
     * @return void
794
     * @throws ReflectionException
795
     */
796
    public function load_core_configuration()
797
    {
798
        do_action('AHEE__EE_System__load_core_configuration__begin', $this);
799
        $this->loader->getShared('EE_Load_Textdomain');
800
        //load textdomain
801
        EE_Load_Textdomain::load_textdomain();
802
        // load and setup EE_Config and EE_Network_Config
803
        $config = $this->loader->getShared('EE_Config');
804
        $this->loader->getShared('EE_Network_Config');
805
        // setup autoloaders
806
        // enable logging?
807
        if ($config->admin->use_full_logging) {
808
            $this->loader->getShared('EE_Log');
809
        }
810
        // check for activation errors
811
        $activation_errors = get_option('ee_plugin_activation_errors', false);
812
        if ($activation_errors) {
813
            EE_Error::add_error($activation_errors, __FILE__, __FUNCTION__, __LINE__);
814
            update_option('ee_plugin_activation_errors', false);
815
        }
816
        // get model names
817
        $this->_parse_model_names();
818
        //load caf stuff a chance to play during the activation process too.
819
        $this->_maybe_brew_regular();
820
        do_action('AHEE__EE_System__load_core_configuration__complete', $this);
821
    }
822
823
824
825
    /**
826
     * cycles through all of the models/*.model.php files, and assembles an array of model names
827
     *
828
     * @return void
829
     * @throws ReflectionException
830
     */
831
    private function _parse_model_names()
832
    {
833
        //get all the files in the EE_MODELS folder that end in .model.php
834
        $models = glob(EE_MODELS . '*.model.php');
835
        $model_names = array();
836
        $non_abstract_db_models = array();
837
        foreach ($models as $model) {
838
            // get model classname
839
            $classname = EEH_File::get_classname_from_filepath_with_standard_filename($model);
840
            $short_name = str_replace('EEM_', '', $classname);
841
            $reflectionClass = new ReflectionClass($classname);
842
            if ($reflectionClass->isSubclassOf('EEM_Base') && ! $reflectionClass->isAbstract()) {
843
                $non_abstract_db_models[$short_name] = $classname;
844
            }
845
            $model_names[$short_name] = $classname;
846
        }
847
        $this->registry->models = apply_filters('FHEE__EE_System__parse_model_names', $model_names);
848
        $this->registry->non_abstract_db_models = apply_filters(
849
            'FHEE__EE_System__parse_implemented_model_names',
850
            $non_abstract_db_models
851
        );
852
    }
853
854
855
856
    /**
857
     * The purpose of this method is to simply check for a file named "caffeinated/brewing_regular.php" for any hooks
858
     * that need to be setup before our EE_System launches.
859
     *
860
     * @return void
861
     */
862
    private function _maybe_brew_regular()
863
    {
864
        if ((! defined('EE_DECAF') || EE_DECAF !== true) && is_readable(EE_CAFF_PATH . 'brewing_regular.php')) {
865
            require_once EE_CAFF_PATH . 'brewing_regular.php';
866
        }
867
    }
868
869
870
871
    /**
872
     * register_shortcodes_modules_and_widgets
873
     * generate lists of shortcodes and modules, then verify paths and classes
874
     * This is hooked into 'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets'
875
     * which runs during the WP 'plugins_loaded' action at priority 7
876
     *
877
     * @access public
878
     * @return void
879
     * @throws Exception
880
     */
881
    public function register_shortcodes_modules_and_widgets()
882
    {
883
        try {
884
            // load, register, and add shortcodes the new way
885
            new ShortcodesManager(
886
            // and the old way, but we'll put it under control of the new system
887
                EE_Config::getLegacyShortcodesManager()
888
            );
889
        } catch (Exception $exception) {
890
            new ExceptionStackTraceDisplay($exception);
891
        }
892
        do_action('AHEE__EE_System__register_shortcodes_modules_and_widgets');
893
        // check for addons using old hook point
894
        if (has_action('AHEE__EE_System__register_shortcodes_modules_and_addons')) {
895
            $this->_incompatible_addon_error();
896
        }
897
    }
898
899
900
901
    /**
902
     * _incompatible_addon_error
903
     *
904
     * @access public
905
     * @return void
906
     */
907
    private function _incompatible_addon_error()
908
    {
909
        // get array of classes hooking into here
910
        $class_names = EEH_Class_Tools::get_class_names_for_all_callbacks_on_hook(
911
            'AHEE__EE_System__register_shortcodes_modules_and_addons'
912
        );
913
        if (! empty($class_names)) {
914
            $msg = __(
915
                'The following plugins, addons, or modules appear to be incompatible with this version of Event Espresso and were automatically deactivated to avoid fatal errors:',
916
                'event_espresso'
917
            );
918
            $msg .= '<ul>';
919
            foreach ($class_names as $class_name) {
920
                $msg .= '<li><b>Event Espresso - ' . str_replace(
921
                        array('EE_', 'EEM_', 'EED_', 'EES_', 'EEW_'), '',
922
                        $class_name
923
                    ) . '</b></li>';
924
            }
925
            $msg .= '</ul>';
926
            $msg .= __(
927
                'Compatibility issues can be avoided and/or resolved by keeping addons and plugins updated to the latest version.',
928
                'event_espresso'
929
            );
930
            // save list of incompatible addons to wp-options for later use
931
            add_option('ee_incompatible_addons', $class_names, '', 'no');
932
            if (is_admin()) {
933
                EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
934
            }
935
        }
936
    }
937
938
939
940
    /**
941
     * brew_espresso
942
     * begins the process of setting hooks for initializing EE in the correct order
943
     * This is happening on the 'AHEE__EE_Bootstrap__brew_espresso' hook point
944
     * which runs during the WP 'plugins_loaded' action at priority 9
945
     *
946
     * @return void
947
     */
948
    public function brew_espresso()
949
    {
950
        do_action('AHEE__EE_System__brew_espresso__begin', $this);
951
        // load some final core systems
952
        add_action('init', array($this, 'set_hooks_for_core'), 1);
953
        add_action('init', array($this, 'perform_activations_upgrades_and_migrations'), 3);
954
        add_action('init', array($this, 'load_CPTs_and_session'), 5);
955
        add_action('init', array($this, 'load_controllers'), 7);
956
        add_action('init', array($this, 'core_loaded_and_ready'), 9);
957
        add_action('init', array($this, 'initialize'), 10);
958
        add_action('init', array($this, 'initialize_last'), 100);
959
        if (is_admin() && apply_filters('FHEE__EE_System__brew_espresso__load_pue', true)) {
960
            // pew pew pew
961
            $this->loader->getShared('EE_PUE');
962
            do_action('AHEE__EE_System__brew_espresso__after_pue_init');
963
        }
964
        do_action('AHEE__EE_System__brew_espresso__complete', $this);
965
    }
966
967
968
969
    /**
970
     *    set_hooks_for_core
971
     *
972
     * @access public
973
     * @return    void
974
     * @throws EE_Error
975
     */
976
    public function set_hooks_for_core()
977
    {
978
        $this->_deactivate_incompatible_addons();
979
        do_action('AHEE__EE_System__set_hooks_for_core');
980
        //caps need to be initialized on every request so that capability maps are set.
981
        //@see https://events.codebasehq.com/projects/event-espresso/tickets/8674
982
        $this->registry->CAP->init_caps();
983
    }
984
985
986
987
    /**
988
     * Using the information gathered in EE_System::_incompatible_addon_error,
989
     * deactivates any addons considered incompatible with the current version of EE
990
     */
991
    private function _deactivate_incompatible_addons()
992
    {
993
        $incompatible_addons = get_option('ee_incompatible_addons', array());
994
        if (! empty($incompatible_addons)) {
995
            $active_plugins = get_option('active_plugins', array());
996
            foreach ($active_plugins as $active_plugin) {
997
                foreach ($incompatible_addons as $incompatible_addon) {
998
                    if (strpos($active_plugin, $incompatible_addon) !== false) {
999
                        unset($_GET['activate']);
1000
                        espresso_deactivate_plugin($active_plugin);
1001
                    }
1002
                }
1003
            }
1004
        }
1005
    }
1006
1007
1008
1009
    /**
1010
     *    perform_activations_upgrades_and_migrations
1011
     *
1012
     * @access public
1013
     * @return    void
1014
     */
1015
    public function perform_activations_upgrades_and_migrations()
1016
    {
1017
        //first check if we had previously attempted to setup EE's directories but failed
1018
        if (EEH_Activation::upload_directories_incomplete()) {
1019
            EEH_Activation::create_upload_directories();
1020
        }
1021
        do_action('AHEE__EE_System__perform_activations_upgrades_and_migrations');
1022
    }
1023
1024
1025
1026
    /**
1027
     *    load_CPTs_and_session
1028
     *
1029
     * @access public
1030
     * @return    void
1031
     */
1032
    public function load_CPTs_and_session()
1033
    {
1034
        do_action('AHEE__EE_System__load_CPTs_and_session__start');
1035
        // register Custom Post Types
1036
        $this->loader->getShared('EE_Register_CPTs');
1037
        do_action('AHEE__EE_System__load_CPTs_and_session__complete');
1038
    }
1039
1040
1041
1042
    /**
1043
     * load_controllers
1044
     * this is the best place to load any additional controllers that needs access to EE core.
1045
     * it is expected that all basic core EE systems, that are not dependant on the current request are loaded at this
1046
     * time
1047
     *
1048
     * @access public
1049
     * @return void
1050
     */
1051
    public function load_controllers()
1052
    {
1053
        do_action('AHEE__EE_System__load_controllers__start');
1054
        // let's get it started
1055
        if (! is_admin() && ! $this->maintenance_mode->level()) {
1056
            do_action('AHEE__EE_System__load_controllers__load_front_controllers');
1057
            $this->loader->getShared('EE_Front_Controller');
1058
        } else if (! EE_FRONT_AJAX) {
1059
            do_action('AHEE__EE_System__load_controllers__load_admin_controllers');
1060
            $this->loader->getShared('EE_Admin');
1061
        }
1062
        do_action('AHEE__EE_System__load_controllers__complete');
1063
    }
1064
1065
1066
1067
    /**
1068
     * core_loaded_and_ready
1069
     * all of the basic EE core should be loaded at this point and available regardless of M-Mode
1070
     *
1071
     * @access public
1072
     * @return void
1073
     */
1074
    public function core_loaded_and_ready()
1075
    {
1076
        $this->loader->getShared('EE_Session');
1077
        do_action('AHEE__EE_System__core_loaded_and_ready');
1078
        // load_espresso_template_tags
1079
        if (is_readable(EE_PUBLIC . 'template_tags.php')) {
1080
            require_once(EE_PUBLIC . 'template_tags.php');
1081
        }
1082
        do_action('AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons');
1083
        $this->loader->getShared('EventEspresso\core\services\assets\Registry');
1084
    }
1085
1086
1087
1088
    /**
1089
     * initialize
1090
     * this is the best place to begin initializing client code
1091
     *
1092
     * @access public
1093
     * @return void
1094
     */
1095
    public function initialize()
1096
    {
1097
        do_action('AHEE__EE_System__initialize');
1098
    }
1099
1100
1101
1102
    /**
1103
     * initialize_last
1104
     * this is run really late during the WP init hook point, and ensures that mostly everything else that needs to
1105
     * initialize has done so
1106
     *
1107
     * @access public
1108
     * @return void
1109
     */
1110
    public function initialize_last()
1111
    {
1112
        do_action('AHEE__EE_System__initialize_last');
1113
        add_action('admin_bar_init', array($this, 'addEspressoToolbar'));
1114
    }
1115
1116
1117
1118
    /**
1119
     * @return void
1120
     * @throws EE_Error
1121
     */
1122
    public function addEspressoToolbar()
1123
    {
1124
        $this->registry->create(
1125
            'EventEspresso\core\domain\services\admin\AdminToolBar',
1126
            array($this->registry->CAP)
1127
        );
1128
    }
1129
1130
1131
1132
    /**
1133
     * do_not_cache
1134
     * sets no cache headers and defines no cache constants for WP plugins
1135
     *
1136
     * @access public
1137
     * @return void
1138
     */
1139
    public static function do_not_cache()
1140
    {
1141
        // set no cache constants
1142
        if (! defined('DONOTCACHEPAGE')) {
1143
            define('DONOTCACHEPAGE', true);
1144
        }
1145
        if (! defined('DONOTCACHCEOBJECT')) {
1146
            define('DONOTCACHCEOBJECT', true);
1147
        }
1148
        if (! defined('DONOTCACHEDB')) {
1149
            define('DONOTCACHEDB', true);
1150
        }
1151
        // add no cache headers
1152
        add_action('send_headers', array('EE_System', 'nocache_headers'), 10);
1153
        // plus a little extra for nginx and Google Chrome
1154
        add_filter('nocache_headers', array('EE_System', 'extra_nocache_headers'), 10, 1);
1155
        // prevent browsers from prefetching of the rel='next' link, because it may contain content that interferes with the registration process
1156
        remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');
1157
    }
1158
1159
1160
1161
    /**
1162
     *    extra_nocache_headers
1163
     *
1164
     * @access    public
1165
     * @param $headers
1166
     * @return    array
1167
     */
1168
    public static function extra_nocache_headers($headers)
1169
    {
1170
        // for NGINX
1171
        $headers['X-Accel-Expires'] = 0;
1172
        // plus extra for Google Chrome since it doesn't seem to respect "no-cache", but WILL respect "no-store"
1173
        $headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0';
1174
        return $headers;
1175
    }
1176
1177
1178
1179
    /**
1180
     *    nocache_headers
1181
     *
1182
     * @access    public
1183
     * @return    void
1184
     */
1185
    public static function nocache_headers()
1186
    {
1187
        nocache_headers();
1188
    }
1189
1190
1191
1192
1193
    /**
1194
     * simply hooks into "wp_list_pages_exclude" filter (for wp_list_pages method) and makes sure EE critical pages are
1195
     * never returned with the function.
1196
     *
1197
     * @param  array $exclude_array any existing pages being excluded are in this array.
1198
     * @return array
1199
     */
1200
    public function remove_pages_from_wp_list_pages($exclude_array)
1201
    {
1202
        return array_merge($exclude_array, $this->registry->CFG->core->get_critical_pages_array());
1203
    }
1204
1205
1206
1207
}
1208
// End of file EE_System.core.php
1209
// Location: /core/EE_System.core.php
1210