Completed
Branch FET-11146-improve-messages-dat... (304d27)
by
unknown
113:38 queued 102:27
created
modules/add_new_state/EED_Add_New_State.module.php 2 patches
Indentation   +738 added lines, -738 removed lines patch added patch discarded remove patch
@@ -22,744 +22,744 @@
 block discarded – undo
22 22
 
23 23
 
24 24
 
25
-    /**
26
-     * @return EED_Module|EED_Add_New_State
27
-     */
28
-    public static function instance()
29
-    {
30
-        return parent::get_instance(__CLASS__);
31
-    }
32
-
33
-
34
-
35
-    /**
36
-     * set_hooks - for hooking into EE Core, other modules, etc
37
-     *
38
-     * @return void
39
-     */
40
-    public static function set_hooks()
41
-    {
42
-        add_action('wp_loaded', array('EED_Add_New_State', 'set_definitions'), 2);
43
-        add_action('wp_enqueue_scripts', array('EED_Add_New_State', 'translate_js_strings'), 0);
44
-        add_action('wp_enqueue_scripts', array('EED_Add_New_State', 'wp_enqueue_scripts'), 10);
45
-        add_filter('FHEE__EE_SPCO_Reg_Step_Attendee_Information___question_group_reg_form__question_group_reg_form',
46
-            array('EED_Add_New_State', 'display_add_new_state_micro_form'), 1, 1);
47
-        add_filter('FHEE__EE_SPCO_Reg_Step_Payment_Options___get_billing_form_for_payment_method__billing_form',
48
-            array('EED_Add_New_State', 'display_add_new_state_micro_form'), 1, 1);
49
-        add_filter('FHEE__EE_Single_Page_Checkout__process_attendee_information__valid_data_line_item',
50
-            array('EED_Add_New_State', 'unset_new_state_request_params'), 10, 1);
51
-        add_filter('FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__state_options',
52
-            array('EED_Add_New_State', 'inject_new_reg_state_into_options'), 10, 5);
53
-        add_filter('FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__country_options',
54
-            array('EED_Add_New_State', 'inject_new_reg_country_into_options'), 10, 5);
55
-        add_filter('FHEE__EE_State_Select_Input____construct__state_options',
56
-            array('EED_Add_New_State', 'state_options'), 10, 1);
57
-        add_filter('FHEE__EE_Country_Select_Input____construct__country_options',
58
-            array('EED_Add_New_State', 'country_options'), 10, 1);
59
-    }
60
-
61
-
62
-
63
-    /**
64
-     * set_hooks_admin - for hooking into EE Admin Core, other modules, etc
65
-     *
66
-     * @return void
67
-     */
68
-    public static function set_hooks_admin()
69
-    {
70
-        add_action('wp_loaded', array('EED_Add_New_State', 'set_definitions'), 2);
71
-        add_filter('FHEE__EE_SPCO_Reg_Step_Attendee_Information___question_group_reg_form__question_group_reg_form',
72
-            array('EED_Add_New_State', 'display_add_new_state_micro_form'), 1, 1);
73
-        add_filter('FHEE__EE_SPCO_Reg_Step_Payment_Options___get_billing_form_for_payment_method__billing_form',
74
-            array('EED_Add_New_State', 'display_add_new_state_micro_form'), 1, 1);
75
-        add_action('wp_ajax_espresso_add_new_state', array('EED_Add_New_State', 'add_new_state'));
76
-        add_action('wp_ajax_nopriv_espresso_add_new_state', array('EED_Add_New_State', 'add_new_state'));
77
-        add_filter('FHEE__EE_Single_Page_Checkout__process_attendee_information__valid_data_line_item',
78
-            array('EED_Add_New_State', 'unset_new_state_request_params'), 10, 1);
79
-        add_action('AHEE__General_Settings_Admin_Page__update_country_settings__state_saved',
80
-            array('EED_Add_New_State', 'update_country_settings'), 10, 3);
81
-        add_action('AHEE__General_Settings_Admin_Page__delete_state__state_deleted',
82
-            array('EED_Add_New_State', 'update_country_settings'), 10, 3);
83
-        add_filter('FHEE__EE_State_Select_Input____construct__state_options',
84
-            array('EED_Add_New_State', 'state_options'), 10, 1);
85
-        add_filter('FHEE__EE_Country_Select_Input____construct__country_options',
86
-            array('EED_Add_New_State', 'country_options'), 10, 1);
87
-        add_filter('FHEE__EE_Form_Section_Proper__receive_form_submission__request_data',
88
-            array('EED_Add_New_State', 'filter_checkout_request_params'), 10, 1);
89
-        add_filter('FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__state_options',
90
-            array('EED_Add_New_State', 'inject_new_reg_state_into_options'), 10, 5);
91
-        add_filter('FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__country_options',
92
-            array('EED_Add_New_State', 'inject_new_reg_country_into_options'), 10, 5);
93
-    }
94
-
95
-
96
-
97
-    /**
98
-     * @return void
99
-     */
100
-    public static function set_definitions()
101
-    {
102
-        define('ANS_ASSETS_URL', plugin_dir_url(__FILE__) . 'assets' . DS);
103
-        define('ANS_TEMPLATES_PATH', str_replace(
104
-                                         '\\',
105
-                                         DS,
106
-                                         plugin_dir_path(__FILE__)) . 'templates' . DS
107
-        );
108
-    }
109
-
110
-
111
-
112
-    /**
113
-     * @param WP $WP
114
-     * @return void
115
-     */
116
-    public function run($WP)
117
-    {
118
-    }
119
-
120
-
121
-
122
-    /**
123
-     * @return void
124
-     */
125
-    public static function translate_js_strings()
126
-    {
127
-        EE_Registry::$i18n_js_strings['ans_no_country']        = esc_html__(
128
-            'In order to proceed, you need to select the Country that your State/Province belongs to.',
129
-            'event_espresso'
130
-        );
131
-        EE_Registry::$i18n_js_strings['ans_no_name']           = esc_html__(
132
-            'In order to proceed, you need to enter the name of your State/Province.',
133
-            'event_espresso'
134
-        );
135
-        EE_Registry::$i18n_js_strings['ans_no_abbreviation']   = esc_html__(
136
-            'In order to proceed, you need to enter an abbreviation for the name of your State/Province.',
137
-            'event_espresso'
138
-        );
139
-        EE_Registry::$i18n_js_strings['ans_save_success']      = esc_html__(
140
-            'The new state was successfully saved to the database.',
141
-            'event_espresso'
142
-        );
143
-        EE_Registry::$i18n_js_strings['ans_server_save_error'] = esc_html__(
144
-            'An unknown error has occurred on the server while saving the new state to the database.',
145
-            'event_espresso'
146
-        );
147
-    }
148
-
149
-
150
-
151
-    /**
152
-     * @return void
153
-     */
154
-    public static function wp_enqueue_scripts()
155
-    {
156
-        if (apply_filters('EED_Single_Page_Checkout__SPCO_active', false)) {
157
-            wp_register_script('add_new_state', ANS_ASSETS_URL . 'add_new_state.js',
158
-                array('espresso_core', 'single_page_checkout'), EVENT_ESPRESSO_VERSION, true);
159
-            wp_enqueue_script('add_new_state');
160
-        }
161
-    }
162
-
163
-
164
-
165
-    /**
166
-     * display_add_new_state_micro_form
167
-     *
168
-     * @param EE_Form_Section_Proper $question_group_reg_form
169
-     * @return string
170
-     * @throws EE_Error
171
-     * @throws InvalidArgumentException
172
-     * @throws InvalidDataTypeException
173
-     * @throws InvalidInterfaceException
174
-     */
175
-    //	public static function display_add_new_state_micro_form( $html, EE_Form_Input_With_Options_Base $input ){
176
-    public static function display_add_new_state_micro_form(EE_Form_Section_Proper $question_group_reg_form)
177
-    {
178
-        // only add the 'new_state_micro_form' when displaying reg forms,
179
-        // not during processing since we process the 'new_state_micro_form' in it's own AJAX request
180
-        $action = EE_Registry::instance()->REQ->get('action', '');
181
-        // is the "state" question in this form section?
182
-        $input = $question_group_reg_form->get_subsection('state');
183
-        if ($action === 'process_reg_step' || $action === 'update_reg_step') {
184
-            //ok then all we need to do is make sure the input's HTML name is consistent
185
-            //by forcing it to set it now, like it did while getting the form for display
186
-            if ($input instanceof EE_State_Select_Input) {
187
-                $input->html_name();
188
-            }
189
-            return $question_group_reg_form;
190
-        }
191
-        // we're only doing this for state select inputs
192
-        if ($input instanceof EE_State_Select_Input) {
193
-            // grab any set values from the request
194
-            $country_name        = str_replace('state', 'nsmf_new_state_country', $input->html_name());
195
-            $state_name          = str_replace('state', 'nsmf_new_state_name', $input->html_name());
196
-            $abbrv_name          = str_replace('state', 'nsmf_new_state_abbrv', $input->html_name());
197
-            $new_state_submit_id = str_replace('state', 'new_state', $input->html_id());
198
-            $country_options     = array();
199
-            $countries           = EEM_Country::instance()->get_all_countries();
200
-            if (! empty($countries)) {
201
-                foreach ($countries as $country) {
202
-                    if ($country instanceof EE_Country) {
203
-                        $country_options[$country->ID()] = $country->name();
204
-                    }
205
-                }
206
-            }
207
-            $new_state_micro_form = new EE_Form_Section_Proper(
208
-                array(
209
-                    'name'            => 'new_state_micro_form',
210
-                    'html_id'         => 'new_state_micro_form',
211
-                    'layout_strategy' => new EE_Div_Per_Section_Layout(),
212
-                    'subsections'     => array(
213
-                        // add hidden input to indicate that a new state is being added
214
-                        'add_new_state'               => new EE_Hidden_Input(
215
-                            array(
216
-                                'html_name' => str_replace(
217
-                                    'state',
218
-                                    'nsmf_add_new_state',
219
-                                    $input->html_name()
220
-                                ),
221
-                                'html_id'   => str_replace(
222
-                                    'state',
223
-                                    'nsmf_add_new_state',
224
-                                    $input->html_id()
225
-                                ),
226
-                                'default'   => 0,
227
-                            )
228
-                        ),
229
-                        // add link for displaying hidden container
230
-                        'click_here_link'             => new EE_Form_Section_HTML(
231
-                            apply_filters(
232
-                                'FHEE__EED_Add_New_State__display_add_new_state_micro_form__click_here_link',
233
-                                EEH_HTML::link(
234
-                                    '',
235
-                                    esc_html__('click here to add a new state/province', 'event_espresso'),
236
-                                    '',
237
-                                    'display-' . $input->html_id(),
238
-                                    'ee-form-add-new-state-lnk display-the-hidden smaller-text hide-if-no-js',
239
-                                    '',
240
-                                    'data-target="' . $input->html_id() . '"'
241
-                                )
242
-                            )
243
-                        ),
244
-                        // add initial html for hidden container
245
-                        'add_new_state_micro_form'    => new EE_Form_Section_HTML(
246
-                            apply_filters(
247
-                                'FHEE__EED_Add_New_State__display_add_new_state_micro_form__add_new_state_micro_form',
248
-                                EEH_HTML::div('', $input->html_id() . '-dv', 'ee-form-add-new-state-dv',
249
-                                    'display: none;') .
250
-                                EEH_HTML::h6(
251
-                                    esc_html__(
252
-                                        'Is your state/province missing from the dropdown menu above? You can add it by completing the following steps:',
253
-                                        'event_espresso'
254
-                                    )
255
-                                ) .
256
-                                EEH_HTML::ul() .
257
-                                EEH_HTML::li(
258
-                                    esc_html__(
259
-                                        'first select the Country that your State/Province belongs to',
260
-                                        'event_espresso'
261
-                                    )
262
-                                ) .
263
-                                EEH_HTML::li(
264
-                                    esc_html__('enter the name of your State/Province', 'event_espresso')
265
-                                ) .
266
-                                EEH_HTML::li(
267
-                                    esc_html__(
268
-                                        'enter a two to six letter abbreviation for the name of your State/Province',
269
-                                        'event_espresso'
270
-                                    )
271
-                                ) .
272
-                                EEH_HTML::li(esc_html__('click the ADD button', 'event_espresso')) .
273
-                                EEH_HTML::ulx()
274
-                            )
275
-                        ),
276
-                        // NEW STATE COUNTRY
277
-                        'new_state_country'           => new EE_Country_Select_Input(
278
-                            $country_options,
279
-                            array(
280
-                                'html_name'       => $country_name,
281
-                                'html_id'         => str_replace(
282
-                                    'state',
283
-                                    'nsmf_new_state_country', $input->html_id()
284
-                                ),
285
-                                'html_class'      => $input->html_class() . ' new-state-country',
286
-                                'html_label_text' => esc_html__('New State/Province Country', 'event_espresso'),
287
-                                'default'         => EE_Registry::instance()->REQ->get($country_name, ''),
288
-                                'required'        => false,
289
-                            )
290
-                        ),
291
-                        // NEW STATE NAME
292
-                        'new_state_name'              => new EE_Text_Input(
293
-                            array(
294
-                                'html_name'       => $state_name,
295
-                                'html_id'         => str_replace(
296
-                                    'state',
297
-                                    'nsmf_new_state_name', $input->html_id()
298
-                                ),
299
-                                'html_class'      => $input->html_class() . ' new-state-state',
300
-                                'html_label_text' => esc_html__('New State/Province Name',
301
-                                    'event_espresso'),
302
-                                'default'         => EE_Registry::instance()->REQ->get($state_name, ''),
303
-                                'required'        => false,
304
-                            )
305
-                        ),
306
-                        'spacer'                      => new EE_Form_Section_HTML(EEH_HTML::br()),
307
-                        // NEW STATE NAME
308
-                        'new_state_abbrv'             => new EE_Text_Input(
309
-                            array(
310
-                                'html_name'             => $abbrv_name,
311
-                                'html_id'               => str_replace('state', 'nsmf_new_state_abbrv',
312
-                                    $input->html_id()),
313
-                                'html_class'            => $input->html_class() . ' new-state-abbrv',
314
-                                'html_label_text'       => esc_html__(
315
-                                                               'New State/Province Abbreviation',
316
-                                                               'event_espresso'
317
-                                                           ) . ' *',
318
-                                'html_other_attributes' => 'size="24"',
319
-                                'default'               => EE_Registry::instance()->REQ->get($abbrv_name, ''),
320
-                                'required'              => false,
321
-                            )
322
-                        ),
323
-                        // "submit" button
324
-                        'add_new_state_submit_button' => new EE_Form_Section_HTML(
325
-                            apply_filters(
326
-                                'FHEE__EED_Add_New_State__display_add_new_state_micro_form__add_new_state_submit_button',
327
-                                EEH_HTML::nbsp(3) .
328
-                                EEH_HTML::link(
329
-                                    '',
330
-                                    esc_html__('ADD', 'event_espresso'),
331
-                                    '',
332
-                                    'submit-' . $new_state_submit_id,
333
-                                    'ee-form-add-new-state-submit button button-secondary',
334
-                                    '',
335
-                                    'data-target="' . $new_state_submit_id . '"'
336
-                                )
337
-                            )
338
-                        ),
339
-                        // extra info
340
-                        'add_new_state_extra'         => new EE_Form_Section_HTML(
341
-                            apply_filters(
342
-                                'FHEE__EED_Add_New_State__display_add_new_state_micro_form__add_new_state_extra',
343
-                                EEH_HTML::br(2)
344
-                                .
345
-                                EEH_HTML::div('', '', 'small-text')
346
-                                .
347
-                                EEH_HTML::strong(
348
-                                    '* ' .
349
-                                    esc_html__(
350
-                                        'Don\'t know your State/Province Abbreviation?',
351
-                                        'event_espresso'
352
-                                    )
353
-                                )
354
-                                .
355
-                                EEH_HTML::br()
356
-                                .
357
-                                sprintf(
358
-                                    esc_html__(
359
-                                        'You can look here: %s, for a list of Countries and links to their State/Province Abbreviations ("Subdivisions assigned codes" column).',
360
-                                        'event_espresso'
361
-                                    ),
362
-                                    EEH_HTML::link(
363
-                                        'http://en.wikipedia.org/wiki/ISO_3166-2',
364
-                                        'http://en.wikipedia.org/wiki/ISO_3166-2',
365
-                                        '',
366
-                                        '',
367
-                                        'ee-form-add-new-state-wiki-lnk',
368
-                                        '',
369
-                                        'target="_blank"'
370
-                                    )
371
-                                )
372
-                                .
373
-                                EEH_HTML::divx()
374
-                                .
375
-                                EEH_HTML::br()
376
-                                .
377
-                                EEH_HTML::link(
378
-                                    '',
379
-                                    esc_html__('cancel new State/Province', 'event_espresso'),
380
-                                    '',
381
-                                    'hide-' . $input->html_id(),
382
-                                    'ee-form-cancel-new-state-lnk smaller-text',
383
-                                    '',
384
-                                    'data-target="' . $input->html_id() . '"'
385
-                                )
386
-                                .
387
-                                EEH_HTML::divx()
388
-                                .
389
-                                EEH_HTML::br()
390
-                            )
391
-                        ),
392
-                    ),
393
-                )
394
-            );
395
-            $question_group_reg_form->add_subsections(
396
-                array('new_state_micro_form' => $new_state_micro_form),
397
-                'state',
398
-                false
399
-            );
400
-        }
401
-        return $question_group_reg_form;
402
-    }
403
-
404
-
405
-
406
-    /**
407
-     * set_new_state_input_width
408
-     *
409
-     * @return int|string
410
-     * @throws EE_Error
411
-     * @throws InvalidArgumentException
412
-     * @throws InvalidDataTypeException
413
-     * @throws InvalidInterfaceException
414
-     * @throws ReflectionException
415
-     */
416
-    public static function add_new_state()
417
-    {
418
-        $REQ = EE_Registry::instance()->load_core('Request_Handler');
419
-        if (absint($REQ->get('nsmf_add_new_state')) === 1) {
420
-            EE_Registry::instance()->load_model('State');
421
-            // grab country ISO code, new state name, and new state abbreviation
422
-            $state_country = $REQ->is_set('nsmf_new_state_country')
423
-                ? sanitize_text_field($REQ->get('nsmf_new_state_country'))
424
-                : false;
425
-            $state_name    = $REQ->is_set('nsmf_new_state_name')
426
-                ? sanitize_text_field($REQ->get('nsmf_new_state_name'))
427
-                : false;
428
-            $state_abbr    = $REQ->is_set('nsmf_new_state_abbrv')
429
-                ? sanitize_text_field($REQ->get('nsmf_new_state_abbrv'))
430
-                : false;
431
-            if ($state_country && $state_name && $state_abbr) {
432
-                $new_state = EED_Add_New_State::save_new_state_to_db(array(
433
-                    'CNT_ISO'    => strtoupper($state_country),
434
-                    'STA_abbrev' => strtoupper($state_abbr),
435
-                    'STA_name'   => ucwords($state_name),
436
-                    'STA_active' => false,
437
-                ));
438
-                if ($new_state instanceof EE_State) {
439
-                    // clean house
440
-                    EE_Registry::instance()->REQ->un_set('nsmf_add_new_state');
441
-                    EE_Registry::instance()->REQ->un_set('nsmf_new_state_country');
442
-                    EE_Registry::instance()->REQ->un_set('nsmf_new_state_name');
443
-                    EE_Registry::instance()->REQ->un_set('nsmf_new_state_abbrv');
444
-                    // get any existing new states
445
-                    $new_states                   = EE_Registry::instance()->SSN->get_session_data(
446
-                        'nsmf_new_states'
447
-                    );
448
-                    $new_states[$new_state->ID()] = $new_state;
449
-                    EE_Registry::instance()->SSN->set_session_data(
450
-                        array('nsmf_new_states' => $new_states)
451
-                    );
452
-                    if (EE_Registry::instance()->REQ->ajax) {
453
-                        echo wp_json_encode(array(
454
-                            'success'      => true,
455
-                            'id'           => $new_state->ID(),
456
-                            'name'         => $new_state->name(),
457
-                            'abbrev'       => $new_state->abbrev(),
458
-                            'country_iso'  => $new_state->country_iso(),
459
-                            'country_name' => $new_state->country()->name(),
460
-                        ));
461
-                        exit();
462
-                    }
463
-                    return $new_state->ID();
464
-                }
465
-            } else {
466
-                $error = esc_html__(
467
-                    'A new State/Province could not be added because invalid or missing data was received.',
468
-                    'event_espresso'
469
-                );
470
-                if (EE_Registry::instance()->REQ->ajax) {
471
-                    echo wp_json_encode(array('error' => $error));
472
-                    exit();
473
-                }
474
-                EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
475
-            }
476
-        }
477
-        return false;
478
-    }
479
-
480
-
481
-
482
-    /**
483
-     * recursively drills down through request params to remove any that were added by this module
484
-     *
485
-     * @param array $request_params
486
-     * @return array
487
-     */
488
-    public static function filter_checkout_request_params($request_params)
489
-    {
490
-        foreach ($request_params as $form_section) {
491
-            if (is_array($form_section)) {
492
-                EED_Add_New_State::unset_new_state_request_params($form_section);
493
-                EED_Add_New_State::filter_checkout_request_params($form_section);
494
-            }
495
-        }
496
-        return $request_params;
497
-    }
498
-
499
-
500
-
501
-    /**
502
-     * @param array $request_params
503
-     * @return array
504
-     */
505
-    public static function unset_new_state_request_params($request_params)
506
-    {
507
-        unset(
508
-            $request_params['new_state_micro_form'],
509
-            $request_params['new_state_micro_add_new_state'],
510
-            $request_params['new_state_micro_new_state_country'],
511
-            $request_params['new_state_micro_new_state_name'],
512
-            $request_params['new_state_micro_new_state_abbrv']
513
-        );
514
-        return $request_params;
515
-    }
516
-
517
-
518
-
519
-    /**
520
-     * @param array $props_n_values
521
-     * @return bool
522
-     * @throws EE_Error
523
-     * @throws InvalidArgumentException
524
-     * @throws InvalidDataTypeException
525
-     * @throws InvalidInterfaceException
526
-     */
527
-    public static function save_new_state_to_db($props_n_values = array())
528
-    {
529
-        $existing_state = EEM_State::instance()->get_all(array($props_n_values, 'limit' => 1));
530
-        if (! empty($existing_state)) {
531
-            return array_pop($existing_state);
532
-        }
533
-        $new_state = EE_State::new_instance($props_n_values);
534
-        if ($new_state instanceof EE_State) {
535
-            $country_settings_url = add_query_arg(
536
-                array(
537
-                    'page'    => 'espresso_general_settings',
538
-                    'action'  => 'country_settings',
539
-                    'country' => $new_state->country_iso(),
540
-                ),
541
-                admin_url('admin.php')
542
-            );
543
-            // if not non-ajax admin
544
-            new PersistentAdminNotice(
545
-                'new-state-added-' . $new_state->country_iso() . '-' . $new_state->abbrev(),
546
-                sprintf(
547
-                    esc_html__(
548
-                        'A new State named "%1$s (%2$s)" was dynamically added from an Event Espresso form for the Country of "%3$s".%5$sTo verify, edit, and/or delete this new State, please go to the %4$s and update the States / Provinces section.%5$sCheck "Yes" to have this new State added to dropdown select lists in forms.',
549
-                        'event_espresso'
550
-                    ),
551
-                    '<b>' . $new_state->name() . '</b>',
552
-                    '<b>' . $new_state->abbrev() . '</b>',
553
-                    '<b>' . $new_state->country()->name() . '</b>',
554
-                    '<a href="'
555
-                    . $country_settings_url
556
-                    . '">'
557
-                    . esc_html__('Event Espresso - General Settings > Countries Tab',
558
-                        'event_espresso')
559
-                    . '</a>',
560
-                    '<br />'
561
-                )
562
-            );
563
-            $new_state->save();
564
-            EEM_State::instance()->reset_cached_states();
565
-            return $new_state;
566
-        }
567
-        return false;
568
-    }
569
-
570
-
571
-
572
-    /**
573
-     * @param string $CNT_ISO
574
-     * @param string $STA_ID
575
-     * @param array  $cols_n_values
576
-     * @return void
577
-     * @throws DomainException
578
-     * @throws EE_Error
579
-     * @throws InvalidArgumentException
580
-     * @throws InvalidDataTypeException
581
-     * @throws InvalidInterfaceException
582
-     */
583
-    public static function update_country_settings($CNT_ISO = '', $STA_ID = '', $cols_n_values = array())
584
-    {
585
-        if (! $CNT_ISO) {
586
-            EE_Error::add_error(
587
-                esc_html__('An invalid or missing Country ISO Code was received.', 'event_espresso'),
588
-                __FILE__,
589
-                __FUNCTION__,
590
-                __LINE__
591
-            );
592
-        }
593
-        $STA_abbrev = is_array($cols_n_values) && isset($cols_n_values['STA_abbrev']) ? $cols_n_values['STA_abbrev']
594
-            : false;
595
-        if (! $STA_abbrev && ! empty($STA_ID)) {
596
-            $state = EEM_State::instance()->get_one_by_ID($STA_ID);
597
-            if ($state instanceof EE_State) {
598
-                $STA_abbrev = $state->abbrev();
599
-            }
600
-        }
601
-        if (! $STA_abbrev) {
602
-            EE_Error::add_error(
603
-                esc_html__('An invalid or missing State Abbreviation was received.', 'event_espresso'),
604
-                __FILE__,
605
-                __FUNCTION__,
606
-                __LINE__
607
-            );
608
-        }
609
-        /** @var PersistentAdminNoticeManager $persistent_admin_notice_manager */
610
-        $persistent_admin_notice_manager = LoaderFactory::getLoader()->getShared(
611
-            'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
612
-        );
613
-        $persistent_admin_notice_manager->dismissNotice($CNT_ISO . '-' . $STA_abbrev, true, true);
614
-    }
615
-
616
-
617
-
618
-    /**
619
-     * @param EE_State[]                            $state_options
620
-     * @param EE_SPCO_Reg_Step_Attendee_Information $reg_step
621
-     * @param EE_Registration                       $registration
622
-     * @param EE_Question                           $question
623
-     * @param                                       $answer
624
-     * @return array
625
-     * @throws EE_Error
626
-     * @throws InvalidArgumentException
627
-     * @throws InvalidDataTypeException
628
-     * @throws InvalidInterfaceException
629
-     */
630
-    public static function inject_new_reg_state_into_options(
631
-        $state_options = array(),
632
-        EE_SPCO_Reg_Step_Attendee_Information $reg_step,
633
-        EE_Registration $registration,
634
-        EE_Question $question,
635
-        $answer
636
-    ) {
637
-        if ($answer instanceof EE_Answer && $question instanceof EE_Question
638
-            && $question->type() === EEM_Question::QST_type_state
639
-        ) {
640
-            $STA_ID = $answer->value();
641
-            if (! empty($STA_ID)) {
642
-                $state = EEM_State::instance()->get_one_by_ID($STA_ID);
643
-                if ($state instanceof EE_State) {
644
-                    $country = $state->country();
645
-                    if ($country instanceof EE_Country) {
646
-                        if (! isset($state_options[$country->name()])) {
647
-                            $state_options[$country->name()] = array();
648
-                        }
649
-                        if (! isset($state_options[$country->name()][$STA_ID])) {
650
-                            $state_options[$country->name()][$STA_ID] = $state->name();
651
-                        }
652
-                    }
653
-                }
654
-            }
655
-        }
656
-        return $state_options;
657
-    }
658
-
659
-
660
-
661
-    /**
662
-     * @param EE_Country[]                          $country_options
663
-     * @param EE_SPCO_Reg_Step_Attendee_Information $reg_step
664
-     * @param EE_Registration                       $registration
665
-     * @param EE_Question                           $question
666
-     * @param                                       $answer
667
-     * @return array
668
-     * @throws EE_Error
669
-     * @throws InvalidArgumentException
670
-     * @throws InvalidDataTypeException
671
-     * @throws InvalidInterfaceException
672
-     */
673
-    public static function inject_new_reg_country_into_options(
674
-        $country_options = array(),
675
-        EE_SPCO_Reg_Step_Attendee_Information $reg_step,
676
-        EE_Registration $registration,
677
-        EE_Question $question,
678
-        $answer
679
-    ) {
680
-        if ($answer instanceof EE_Answer && $question instanceof EE_Question
681
-            && $question->type()
682
-               === EEM_Question::QST_type_country
683
-        ) {
684
-            $CNT_ISO = $answer->value();
685
-            if (! empty($CNT_ISO)) {
686
-                $country = EEM_Country::instance()->get_one_by_ID($CNT_ISO);
687
-                if ($country instanceof EE_Country) {
688
-                    if (! isset($country_options[$CNT_ISO])) {
689
-                        $country_options[$CNT_ISO] = $country->name();
690
-                    }
691
-                }
692
-            }
693
-        }
694
-        return $country_options;
695
-    }
696
-
697
-
698
-
699
-    /**
700
-     * @param EE_State[] $state_options
701
-     * @return array
702
-     * @throws EE_Error
703
-     * @throws InvalidArgumentException
704
-     * @throws InvalidDataTypeException
705
-     * @throws InvalidInterfaceException
706
-     */
707
-    public static function state_options($state_options = array())
708
-    {
709
-        $new_states = EED_Add_New_State::_get_new_states();
710
-        foreach ($new_states as $new_state) {
711
-            if (
712
-                $new_state instanceof EE_State
713
-                && $new_state->country() instanceof EE_Country
714
-            ) {
715
-                $state_options[$new_state->country()->name()][$new_state->ID()] = $new_state->name();
716
-            }
717
-        }
718
-        return $state_options;
719
-    }
720
-
721
-
722
-
723
-    /**
724
-     * @return array
725
-     * @throws InvalidArgumentException
726
-     * @throws InvalidDataTypeException
727
-     * @throws InvalidInterfaceException
728
-     */
729
-    protected static function _get_new_states()
730
-    {
731
-        $new_states = array();
732
-        if (EE_Registry::instance()->SSN instanceof EE_Session) {
733
-            $new_states = EE_Registry::instance()->SSN->get_session_data(
734
-                'nsmf_new_states'
735
-            );
736
-        }
737
-        return is_array($new_states) ? $new_states : array();
738
-    }
739
-
740
-
741
-
742
-    /**
743
-     * @param EE_Country[] $country_options
744
-     * @return array
745
-     * @throws EE_Error
746
-     * @throws InvalidArgumentException
747
-     * @throws InvalidDataTypeException
748
-     * @throws InvalidInterfaceException
749
-     */
750
-    public static function country_options($country_options = array())
751
-    {
752
-        $new_states = EED_Add_New_State::_get_new_states();
753
-        foreach ($new_states as $new_state) {
754
-            if (
755
-                $new_state instanceof EE_State
756
-                && $new_state->country() instanceof EE_Country
757
-            ) {
758
-                $country_options[$new_state->country()->ID()] = $new_state->country()->name();
759
-            }
760
-        }
761
-        return $country_options;
762
-    }
25
+	/**
26
+	 * @return EED_Module|EED_Add_New_State
27
+	 */
28
+	public static function instance()
29
+	{
30
+		return parent::get_instance(__CLASS__);
31
+	}
32
+
33
+
34
+
35
+	/**
36
+	 * set_hooks - for hooking into EE Core, other modules, etc
37
+	 *
38
+	 * @return void
39
+	 */
40
+	public static function set_hooks()
41
+	{
42
+		add_action('wp_loaded', array('EED_Add_New_State', 'set_definitions'), 2);
43
+		add_action('wp_enqueue_scripts', array('EED_Add_New_State', 'translate_js_strings'), 0);
44
+		add_action('wp_enqueue_scripts', array('EED_Add_New_State', 'wp_enqueue_scripts'), 10);
45
+		add_filter('FHEE__EE_SPCO_Reg_Step_Attendee_Information___question_group_reg_form__question_group_reg_form',
46
+			array('EED_Add_New_State', 'display_add_new_state_micro_form'), 1, 1);
47
+		add_filter('FHEE__EE_SPCO_Reg_Step_Payment_Options___get_billing_form_for_payment_method__billing_form',
48
+			array('EED_Add_New_State', 'display_add_new_state_micro_form'), 1, 1);
49
+		add_filter('FHEE__EE_Single_Page_Checkout__process_attendee_information__valid_data_line_item',
50
+			array('EED_Add_New_State', 'unset_new_state_request_params'), 10, 1);
51
+		add_filter('FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__state_options',
52
+			array('EED_Add_New_State', 'inject_new_reg_state_into_options'), 10, 5);
53
+		add_filter('FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__country_options',
54
+			array('EED_Add_New_State', 'inject_new_reg_country_into_options'), 10, 5);
55
+		add_filter('FHEE__EE_State_Select_Input____construct__state_options',
56
+			array('EED_Add_New_State', 'state_options'), 10, 1);
57
+		add_filter('FHEE__EE_Country_Select_Input____construct__country_options',
58
+			array('EED_Add_New_State', 'country_options'), 10, 1);
59
+	}
60
+
61
+
62
+
63
+	/**
64
+	 * set_hooks_admin - for hooking into EE Admin Core, other modules, etc
65
+	 *
66
+	 * @return void
67
+	 */
68
+	public static function set_hooks_admin()
69
+	{
70
+		add_action('wp_loaded', array('EED_Add_New_State', 'set_definitions'), 2);
71
+		add_filter('FHEE__EE_SPCO_Reg_Step_Attendee_Information___question_group_reg_form__question_group_reg_form',
72
+			array('EED_Add_New_State', 'display_add_new_state_micro_form'), 1, 1);
73
+		add_filter('FHEE__EE_SPCO_Reg_Step_Payment_Options___get_billing_form_for_payment_method__billing_form',
74
+			array('EED_Add_New_State', 'display_add_new_state_micro_form'), 1, 1);
75
+		add_action('wp_ajax_espresso_add_new_state', array('EED_Add_New_State', 'add_new_state'));
76
+		add_action('wp_ajax_nopriv_espresso_add_new_state', array('EED_Add_New_State', 'add_new_state'));
77
+		add_filter('FHEE__EE_Single_Page_Checkout__process_attendee_information__valid_data_line_item',
78
+			array('EED_Add_New_State', 'unset_new_state_request_params'), 10, 1);
79
+		add_action('AHEE__General_Settings_Admin_Page__update_country_settings__state_saved',
80
+			array('EED_Add_New_State', 'update_country_settings'), 10, 3);
81
+		add_action('AHEE__General_Settings_Admin_Page__delete_state__state_deleted',
82
+			array('EED_Add_New_State', 'update_country_settings'), 10, 3);
83
+		add_filter('FHEE__EE_State_Select_Input____construct__state_options',
84
+			array('EED_Add_New_State', 'state_options'), 10, 1);
85
+		add_filter('FHEE__EE_Country_Select_Input____construct__country_options',
86
+			array('EED_Add_New_State', 'country_options'), 10, 1);
87
+		add_filter('FHEE__EE_Form_Section_Proper__receive_form_submission__request_data',
88
+			array('EED_Add_New_State', 'filter_checkout_request_params'), 10, 1);
89
+		add_filter('FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__state_options',
90
+			array('EED_Add_New_State', 'inject_new_reg_state_into_options'), 10, 5);
91
+		add_filter('FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__country_options',
92
+			array('EED_Add_New_State', 'inject_new_reg_country_into_options'), 10, 5);
93
+	}
94
+
95
+
96
+
97
+	/**
98
+	 * @return void
99
+	 */
100
+	public static function set_definitions()
101
+	{
102
+		define('ANS_ASSETS_URL', plugin_dir_url(__FILE__) . 'assets' . DS);
103
+		define('ANS_TEMPLATES_PATH', str_replace(
104
+										 '\\',
105
+										 DS,
106
+										 plugin_dir_path(__FILE__)) . 'templates' . DS
107
+		);
108
+	}
109
+
110
+
111
+
112
+	/**
113
+	 * @param WP $WP
114
+	 * @return void
115
+	 */
116
+	public function run($WP)
117
+	{
118
+	}
119
+
120
+
121
+
122
+	/**
123
+	 * @return void
124
+	 */
125
+	public static function translate_js_strings()
126
+	{
127
+		EE_Registry::$i18n_js_strings['ans_no_country']        = esc_html__(
128
+			'In order to proceed, you need to select the Country that your State/Province belongs to.',
129
+			'event_espresso'
130
+		);
131
+		EE_Registry::$i18n_js_strings['ans_no_name']           = esc_html__(
132
+			'In order to proceed, you need to enter the name of your State/Province.',
133
+			'event_espresso'
134
+		);
135
+		EE_Registry::$i18n_js_strings['ans_no_abbreviation']   = esc_html__(
136
+			'In order to proceed, you need to enter an abbreviation for the name of your State/Province.',
137
+			'event_espresso'
138
+		);
139
+		EE_Registry::$i18n_js_strings['ans_save_success']      = esc_html__(
140
+			'The new state was successfully saved to the database.',
141
+			'event_espresso'
142
+		);
143
+		EE_Registry::$i18n_js_strings['ans_server_save_error'] = esc_html__(
144
+			'An unknown error has occurred on the server while saving the new state to the database.',
145
+			'event_espresso'
146
+		);
147
+	}
148
+
149
+
150
+
151
+	/**
152
+	 * @return void
153
+	 */
154
+	public static function wp_enqueue_scripts()
155
+	{
156
+		if (apply_filters('EED_Single_Page_Checkout__SPCO_active', false)) {
157
+			wp_register_script('add_new_state', ANS_ASSETS_URL . 'add_new_state.js',
158
+				array('espresso_core', 'single_page_checkout'), EVENT_ESPRESSO_VERSION, true);
159
+			wp_enqueue_script('add_new_state');
160
+		}
161
+	}
162
+
163
+
164
+
165
+	/**
166
+	 * display_add_new_state_micro_form
167
+	 *
168
+	 * @param EE_Form_Section_Proper $question_group_reg_form
169
+	 * @return string
170
+	 * @throws EE_Error
171
+	 * @throws InvalidArgumentException
172
+	 * @throws InvalidDataTypeException
173
+	 * @throws InvalidInterfaceException
174
+	 */
175
+	//	public static function display_add_new_state_micro_form( $html, EE_Form_Input_With_Options_Base $input ){
176
+	public static function display_add_new_state_micro_form(EE_Form_Section_Proper $question_group_reg_form)
177
+	{
178
+		// only add the 'new_state_micro_form' when displaying reg forms,
179
+		// not during processing since we process the 'new_state_micro_form' in it's own AJAX request
180
+		$action = EE_Registry::instance()->REQ->get('action', '');
181
+		// is the "state" question in this form section?
182
+		$input = $question_group_reg_form->get_subsection('state');
183
+		if ($action === 'process_reg_step' || $action === 'update_reg_step') {
184
+			//ok then all we need to do is make sure the input's HTML name is consistent
185
+			//by forcing it to set it now, like it did while getting the form for display
186
+			if ($input instanceof EE_State_Select_Input) {
187
+				$input->html_name();
188
+			}
189
+			return $question_group_reg_form;
190
+		}
191
+		// we're only doing this for state select inputs
192
+		if ($input instanceof EE_State_Select_Input) {
193
+			// grab any set values from the request
194
+			$country_name        = str_replace('state', 'nsmf_new_state_country', $input->html_name());
195
+			$state_name          = str_replace('state', 'nsmf_new_state_name', $input->html_name());
196
+			$abbrv_name          = str_replace('state', 'nsmf_new_state_abbrv', $input->html_name());
197
+			$new_state_submit_id = str_replace('state', 'new_state', $input->html_id());
198
+			$country_options     = array();
199
+			$countries           = EEM_Country::instance()->get_all_countries();
200
+			if (! empty($countries)) {
201
+				foreach ($countries as $country) {
202
+					if ($country instanceof EE_Country) {
203
+						$country_options[$country->ID()] = $country->name();
204
+					}
205
+				}
206
+			}
207
+			$new_state_micro_form = new EE_Form_Section_Proper(
208
+				array(
209
+					'name'            => 'new_state_micro_form',
210
+					'html_id'         => 'new_state_micro_form',
211
+					'layout_strategy' => new EE_Div_Per_Section_Layout(),
212
+					'subsections'     => array(
213
+						// add hidden input to indicate that a new state is being added
214
+						'add_new_state'               => new EE_Hidden_Input(
215
+							array(
216
+								'html_name' => str_replace(
217
+									'state',
218
+									'nsmf_add_new_state',
219
+									$input->html_name()
220
+								),
221
+								'html_id'   => str_replace(
222
+									'state',
223
+									'nsmf_add_new_state',
224
+									$input->html_id()
225
+								),
226
+								'default'   => 0,
227
+							)
228
+						),
229
+						// add link for displaying hidden container
230
+						'click_here_link'             => new EE_Form_Section_HTML(
231
+							apply_filters(
232
+								'FHEE__EED_Add_New_State__display_add_new_state_micro_form__click_here_link',
233
+								EEH_HTML::link(
234
+									'',
235
+									esc_html__('click here to add a new state/province', 'event_espresso'),
236
+									'',
237
+									'display-' . $input->html_id(),
238
+									'ee-form-add-new-state-lnk display-the-hidden smaller-text hide-if-no-js',
239
+									'',
240
+									'data-target="' . $input->html_id() . '"'
241
+								)
242
+							)
243
+						),
244
+						// add initial html for hidden container
245
+						'add_new_state_micro_form'    => new EE_Form_Section_HTML(
246
+							apply_filters(
247
+								'FHEE__EED_Add_New_State__display_add_new_state_micro_form__add_new_state_micro_form',
248
+								EEH_HTML::div('', $input->html_id() . '-dv', 'ee-form-add-new-state-dv',
249
+									'display: none;') .
250
+								EEH_HTML::h6(
251
+									esc_html__(
252
+										'Is your state/province missing from the dropdown menu above? You can add it by completing the following steps:',
253
+										'event_espresso'
254
+									)
255
+								) .
256
+								EEH_HTML::ul() .
257
+								EEH_HTML::li(
258
+									esc_html__(
259
+										'first select the Country that your State/Province belongs to',
260
+										'event_espresso'
261
+									)
262
+								) .
263
+								EEH_HTML::li(
264
+									esc_html__('enter the name of your State/Province', 'event_espresso')
265
+								) .
266
+								EEH_HTML::li(
267
+									esc_html__(
268
+										'enter a two to six letter abbreviation for the name of your State/Province',
269
+										'event_espresso'
270
+									)
271
+								) .
272
+								EEH_HTML::li(esc_html__('click the ADD button', 'event_espresso')) .
273
+								EEH_HTML::ulx()
274
+							)
275
+						),
276
+						// NEW STATE COUNTRY
277
+						'new_state_country'           => new EE_Country_Select_Input(
278
+							$country_options,
279
+							array(
280
+								'html_name'       => $country_name,
281
+								'html_id'         => str_replace(
282
+									'state',
283
+									'nsmf_new_state_country', $input->html_id()
284
+								),
285
+								'html_class'      => $input->html_class() . ' new-state-country',
286
+								'html_label_text' => esc_html__('New State/Province Country', 'event_espresso'),
287
+								'default'         => EE_Registry::instance()->REQ->get($country_name, ''),
288
+								'required'        => false,
289
+							)
290
+						),
291
+						// NEW STATE NAME
292
+						'new_state_name'              => new EE_Text_Input(
293
+							array(
294
+								'html_name'       => $state_name,
295
+								'html_id'         => str_replace(
296
+									'state',
297
+									'nsmf_new_state_name', $input->html_id()
298
+								),
299
+								'html_class'      => $input->html_class() . ' new-state-state',
300
+								'html_label_text' => esc_html__('New State/Province Name',
301
+									'event_espresso'),
302
+								'default'         => EE_Registry::instance()->REQ->get($state_name, ''),
303
+								'required'        => false,
304
+							)
305
+						),
306
+						'spacer'                      => new EE_Form_Section_HTML(EEH_HTML::br()),
307
+						// NEW STATE NAME
308
+						'new_state_abbrv'             => new EE_Text_Input(
309
+							array(
310
+								'html_name'             => $abbrv_name,
311
+								'html_id'               => str_replace('state', 'nsmf_new_state_abbrv',
312
+									$input->html_id()),
313
+								'html_class'            => $input->html_class() . ' new-state-abbrv',
314
+								'html_label_text'       => esc_html__(
315
+															   'New State/Province Abbreviation',
316
+															   'event_espresso'
317
+														   ) . ' *',
318
+								'html_other_attributes' => 'size="24"',
319
+								'default'               => EE_Registry::instance()->REQ->get($abbrv_name, ''),
320
+								'required'              => false,
321
+							)
322
+						),
323
+						// "submit" button
324
+						'add_new_state_submit_button' => new EE_Form_Section_HTML(
325
+							apply_filters(
326
+								'FHEE__EED_Add_New_State__display_add_new_state_micro_form__add_new_state_submit_button',
327
+								EEH_HTML::nbsp(3) .
328
+								EEH_HTML::link(
329
+									'',
330
+									esc_html__('ADD', 'event_espresso'),
331
+									'',
332
+									'submit-' . $new_state_submit_id,
333
+									'ee-form-add-new-state-submit button button-secondary',
334
+									'',
335
+									'data-target="' . $new_state_submit_id . '"'
336
+								)
337
+							)
338
+						),
339
+						// extra info
340
+						'add_new_state_extra'         => new EE_Form_Section_HTML(
341
+							apply_filters(
342
+								'FHEE__EED_Add_New_State__display_add_new_state_micro_form__add_new_state_extra',
343
+								EEH_HTML::br(2)
344
+								.
345
+								EEH_HTML::div('', '', 'small-text')
346
+								.
347
+								EEH_HTML::strong(
348
+									'* ' .
349
+									esc_html__(
350
+										'Don\'t know your State/Province Abbreviation?',
351
+										'event_espresso'
352
+									)
353
+								)
354
+								.
355
+								EEH_HTML::br()
356
+								.
357
+								sprintf(
358
+									esc_html__(
359
+										'You can look here: %s, for a list of Countries and links to their State/Province Abbreviations ("Subdivisions assigned codes" column).',
360
+										'event_espresso'
361
+									),
362
+									EEH_HTML::link(
363
+										'http://en.wikipedia.org/wiki/ISO_3166-2',
364
+										'http://en.wikipedia.org/wiki/ISO_3166-2',
365
+										'',
366
+										'',
367
+										'ee-form-add-new-state-wiki-lnk',
368
+										'',
369
+										'target="_blank"'
370
+									)
371
+								)
372
+								.
373
+								EEH_HTML::divx()
374
+								.
375
+								EEH_HTML::br()
376
+								.
377
+								EEH_HTML::link(
378
+									'',
379
+									esc_html__('cancel new State/Province', 'event_espresso'),
380
+									'',
381
+									'hide-' . $input->html_id(),
382
+									'ee-form-cancel-new-state-lnk smaller-text',
383
+									'',
384
+									'data-target="' . $input->html_id() . '"'
385
+								)
386
+								.
387
+								EEH_HTML::divx()
388
+								.
389
+								EEH_HTML::br()
390
+							)
391
+						),
392
+					),
393
+				)
394
+			);
395
+			$question_group_reg_form->add_subsections(
396
+				array('new_state_micro_form' => $new_state_micro_form),
397
+				'state',
398
+				false
399
+			);
400
+		}
401
+		return $question_group_reg_form;
402
+	}
403
+
404
+
405
+
406
+	/**
407
+	 * set_new_state_input_width
408
+	 *
409
+	 * @return int|string
410
+	 * @throws EE_Error
411
+	 * @throws InvalidArgumentException
412
+	 * @throws InvalidDataTypeException
413
+	 * @throws InvalidInterfaceException
414
+	 * @throws ReflectionException
415
+	 */
416
+	public static function add_new_state()
417
+	{
418
+		$REQ = EE_Registry::instance()->load_core('Request_Handler');
419
+		if (absint($REQ->get('nsmf_add_new_state')) === 1) {
420
+			EE_Registry::instance()->load_model('State');
421
+			// grab country ISO code, new state name, and new state abbreviation
422
+			$state_country = $REQ->is_set('nsmf_new_state_country')
423
+				? sanitize_text_field($REQ->get('nsmf_new_state_country'))
424
+				: false;
425
+			$state_name    = $REQ->is_set('nsmf_new_state_name')
426
+				? sanitize_text_field($REQ->get('nsmf_new_state_name'))
427
+				: false;
428
+			$state_abbr    = $REQ->is_set('nsmf_new_state_abbrv')
429
+				? sanitize_text_field($REQ->get('nsmf_new_state_abbrv'))
430
+				: false;
431
+			if ($state_country && $state_name && $state_abbr) {
432
+				$new_state = EED_Add_New_State::save_new_state_to_db(array(
433
+					'CNT_ISO'    => strtoupper($state_country),
434
+					'STA_abbrev' => strtoupper($state_abbr),
435
+					'STA_name'   => ucwords($state_name),
436
+					'STA_active' => false,
437
+				));
438
+				if ($new_state instanceof EE_State) {
439
+					// clean house
440
+					EE_Registry::instance()->REQ->un_set('nsmf_add_new_state');
441
+					EE_Registry::instance()->REQ->un_set('nsmf_new_state_country');
442
+					EE_Registry::instance()->REQ->un_set('nsmf_new_state_name');
443
+					EE_Registry::instance()->REQ->un_set('nsmf_new_state_abbrv');
444
+					// get any existing new states
445
+					$new_states                   = EE_Registry::instance()->SSN->get_session_data(
446
+						'nsmf_new_states'
447
+					);
448
+					$new_states[$new_state->ID()] = $new_state;
449
+					EE_Registry::instance()->SSN->set_session_data(
450
+						array('nsmf_new_states' => $new_states)
451
+					);
452
+					if (EE_Registry::instance()->REQ->ajax) {
453
+						echo wp_json_encode(array(
454
+							'success'      => true,
455
+							'id'           => $new_state->ID(),
456
+							'name'         => $new_state->name(),
457
+							'abbrev'       => $new_state->abbrev(),
458
+							'country_iso'  => $new_state->country_iso(),
459
+							'country_name' => $new_state->country()->name(),
460
+						));
461
+						exit();
462
+					}
463
+					return $new_state->ID();
464
+				}
465
+			} else {
466
+				$error = esc_html__(
467
+					'A new State/Province could not be added because invalid or missing data was received.',
468
+					'event_espresso'
469
+				);
470
+				if (EE_Registry::instance()->REQ->ajax) {
471
+					echo wp_json_encode(array('error' => $error));
472
+					exit();
473
+				}
474
+				EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
475
+			}
476
+		}
477
+		return false;
478
+	}
479
+
480
+
481
+
482
+	/**
483
+	 * recursively drills down through request params to remove any that were added by this module
484
+	 *
485
+	 * @param array $request_params
486
+	 * @return array
487
+	 */
488
+	public static function filter_checkout_request_params($request_params)
489
+	{
490
+		foreach ($request_params as $form_section) {
491
+			if (is_array($form_section)) {
492
+				EED_Add_New_State::unset_new_state_request_params($form_section);
493
+				EED_Add_New_State::filter_checkout_request_params($form_section);
494
+			}
495
+		}
496
+		return $request_params;
497
+	}
498
+
499
+
500
+
501
+	/**
502
+	 * @param array $request_params
503
+	 * @return array
504
+	 */
505
+	public static function unset_new_state_request_params($request_params)
506
+	{
507
+		unset(
508
+			$request_params['new_state_micro_form'],
509
+			$request_params['new_state_micro_add_new_state'],
510
+			$request_params['new_state_micro_new_state_country'],
511
+			$request_params['new_state_micro_new_state_name'],
512
+			$request_params['new_state_micro_new_state_abbrv']
513
+		);
514
+		return $request_params;
515
+	}
516
+
517
+
518
+
519
+	/**
520
+	 * @param array $props_n_values
521
+	 * @return bool
522
+	 * @throws EE_Error
523
+	 * @throws InvalidArgumentException
524
+	 * @throws InvalidDataTypeException
525
+	 * @throws InvalidInterfaceException
526
+	 */
527
+	public static function save_new_state_to_db($props_n_values = array())
528
+	{
529
+		$existing_state = EEM_State::instance()->get_all(array($props_n_values, 'limit' => 1));
530
+		if (! empty($existing_state)) {
531
+			return array_pop($existing_state);
532
+		}
533
+		$new_state = EE_State::new_instance($props_n_values);
534
+		if ($new_state instanceof EE_State) {
535
+			$country_settings_url = add_query_arg(
536
+				array(
537
+					'page'    => 'espresso_general_settings',
538
+					'action'  => 'country_settings',
539
+					'country' => $new_state->country_iso(),
540
+				),
541
+				admin_url('admin.php')
542
+			);
543
+			// if not non-ajax admin
544
+			new PersistentAdminNotice(
545
+				'new-state-added-' . $new_state->country_iso() . '-' . $new_state->abbrev(),
546
+				sprintf(
547
+					esc_html__(
548
+						'A new State named "%1$s (%2$s)" was dynamically added from an Event Espresso form for the Country of "%3$s".%5$sTo verify, edit, and/or delete this new State, please go to the %4$s and update the States / Provinces section.%5$sCheck "Yes" to have this new State added to dropdown select lists in forms.',
549
+						'event_espresso'
550
+					),
551
+					'<b>' . $new_state->name() . '</b>',
552
+					'<b>' . $new_state->abbrev() . '</b>',
553
+					'<b>' . $new_state->country()->name() . '</b>',
554
+					'<a href="'
555
+					. $country_settings_url
556
+					. '">'
557
+					. esc_html__('Event Espresso - General Settings > Countries Tab',
558
+						'event_espresso')
559
+					. '</a>',
560
+					'<br />'
561
+				)
562
+			);
563
+			$new_state->save();
564
+			EEM_State::instance()->reset_cached_states();
565
+			return $new_state;
566
+		}
567
+		return false;
568
+	}
569
+
570
+
571
+
572
+	/**
573
+	 * @param string $CNT_ISO
574
+	 * @param string $STA_ID
575
+	 * @param array  $cols_n_values
576
+	 * @return void
577
+	 * @throws DomainException
578
+	 * @throws EE_Error
579
+	 * @throws InvalidArgumentException
580
+	 * @throws InvalidDataTypeException
581
+	 * @throws InvalidInterfaceException
582
+	 */
583
+	public static function update_country_settings($CNT_ISO = '', $STA_ID = '', $cols_n_values = array())
584
+	{
585
+		if (! $CNT_ISO) {
586
+			EE_Error::add_error(
587
+				esc_html__('An invalid or missing Country ISO Code was received.', 'event_espresso'),
588
+				__FILE__,
589
+				__FUNCTION__,
590
+				__LINE__
591
+			);
592
+		}
593
+		$STA_abbrev = is_array($cols_n_values) && isset($cols_n_values['STA_abbrev']) ? $cols_n_values['STA_abbrev']
594
+			: false;
595
+		if (! $STA_abbrev && ! empty($STA_ID)) {
596
+			$state = EEM_State::instance()->get_one_by_ID($STA_ID);
597
+			if ($state instanceof EE_State) {
598
+				$STA_abbrev = $state->abbrev();
599
+			}
600
+		}
601
+		if (! $STA_abbrev) {
602
+			EE_Error::add_error(
603
+				esc_html__('An invalid or missing State Abbreviation was received.', 'event_espresso'),
604
+				__FILE__,
605
+				__FUNCTION__,
606
+				__LINE__
607
+			);
608
+		}
609
+		/** @var PersistentAdminNoticeManager $persistent_admin_notice_manager */
610
+		$persistent_admin_notice_manager = LoaderFactory::getLoader()->getShared(
611
+			'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
612
+		);
613
+		$persistent_admin_notice_manager->dismissNotice($CNT_ISO . '-' . $STA_abbrev, true, true);
614
+	}
615
+
616
+
617
+
618
+	/**
619
+	 * @param EE_State[]                            $state_options
620
+	 * @param EE_SPCO_Reg_Step_Attendee_Information $reg_step
621
+	 * @param EE_Registration                       $registration
622
+	 * @param EE_Question                           $question
623
+	 * @param                                       $answer
624
+	 * @return array
625
+	 * @throws EE_Error
626
+	 * @throws InvalidArgumentException
627
+	 * @throws InvalidDataTypeException
628
+	 * @throws InvalidInterfaceException
629
+	 */
630
+	public static function inject_new_reg_state_into_options(
631
+		$state_options = array(),
632
+		EE_SPCO_Reg_Step_Attendee_Information $reg_step,
633
+		EE_Registration $registration,
634
+		EE_Question $question,
635
+		$answer
636
+	) {
637
+		if ($answer instanceof EE_Answer && $question instanceof EE_Question
638
+			&& $question->type() === EEM_Question::QST_type_state
639
+		) {
640
+			$STA_ID = $answer->value();
641
+			if (! empty($STA_ID)) {
642
+				$state = EEM_State::instance()->get_one_by_ID($STA_ID);
643
+				if ($state instanceof EE_State) {
644
+					$country = $state->country();
645
+					if ($country instanceof EE_Country) {
646
+						if (! isset($state_options[$country->name()])) {
647
+							$state_options[$country->name()] = array();
648
+						}
649
+						if (! isset($state_options[$country->name()][$STA_ID])) {
650
+							$state_options[$country->name()][$STA_ID] = $state->name();
651
+						}
652
+					}
653
+				}
654
+			}
655
+		}
656
+		return $state_options;
657
+	}
658
+
659
+
660
+
661
+	/**
662
+	 * @param EE_Country[]                          $country_options
663
+	 * @param EE_SPCO_Reg_Step_Attendee_Information $reg_step
664
+	 * @param EE_Registration                       $registration
665
+	 * @param EE_Question                           $question
666
+	 * @param                                       $answer
667
+	 * @return array
668
+	 * @throws EE_Error
669
+	 * @throws InvalidArgumentException
670
+	 * @throws InvalidDataTypeException
671
+	 * @throws InvalidInterfaceException
672
+	 */
673
+	public static function inject_new_reg_country_into_options(
674
+		$country_options = array(),
675
+		EE_SPCO_Reg_Step_Attendee_Information $reg_step,
676
+		EE_Registration $registration,
677
+		EE_Question $question,
678
+		$answer
679
+	) {
680
+		if ($answer instanceof EE_Answer && $question instanceof EE_Question
681
+			&& $question->type()
682
+			   === EEM_Question::QST_type_country
683
+		) {
684
+			$CNT_ISO = $answer->value();
685
+			if (! empty($CNT_ISO)) {
686
+				$country = EEM_Country::instance()->get_one_by_ID($CNT_ISO);
687
+				if ($country instanceof EE_Country) {
688
+					if (! isset($country_options[$CNT_ISO])) {
689
+						$country_options[$CNT_ISO] = $country->name();
690
+					}
691
+				}
692
+			}
693
+		}
694
+		return $country_options;
695
+	}
696
+
697
+
698
+
699
+	/**
700
+	 * @param EE_State[] $state_options
701
+	 * @return array
702
+	 * @throws EE_Error
703
+	 * @throws InvalidArgumentException
704
+	 * @throws InvalidDataTypeException
705
+	 * @throws InvalidInterfaceException
706
+	 */
707
+	public static function state_options($state_options = array())
708
+	{
709
+		$new_states = EED_Add_New_State::_get_new_states();
710
+		foreach ($new_states as $new_state) {
711
+			if (
712
+				$new_state instanceof EE_State
713
+				&& $new_state->country() instanceof EE_Country
714
+			) {
715
+				$state_options[$new_state->country()->name()][$new_state->ID()] = $new_state->name();
716
+			}
717
+		}
718
+		return $state_options;
719
+	}
720
+
721
+
722
+
723
+	/**
724
+	 * @return array
725
+	 * @throws InvalidArgumentException
726
+	 * @throws InvalidDataTypeException
727
+	 * @throws InvalidInterfaceException
728
+	 */
729
+	protected static function _get_new_states()
730
+	{
731
+		$new_states = array();
732
+		if (EE_Registry::instance()->SSN instanceof EE_Session) {
733
+			$new_states = EE_Registry::instance()->SSN->get_session_data(
734
+				'nsmf_new_states'
735
+			);
736
+		}
737
+		return is_array($new_states) ? $new_states : array();
738
+	}
739
+
740
+
741
+
742
+	/**
743
+	 * @param EE_Country[] $country_options
744
+	 * @return array
745
+	 * @throws EE_Error
746
+	 * @throws InvalidArgumentException
747
+	 * @throws InvalidDataTypeException
748
+	 * @throws InvalidInterfaceException
749
+	 */
750
+	public static function country_options($country_options = array())
751
+	{
752
+		$new_states = EED_Add_New_State::_get_new_states();
753
+		foreach ($new_states as $new_state) {
754
+			if (
755
+				$new_state instanceof EE_State
756
+				&& $new_state->country() instanceof EE_Country
757
+			) {
758
+				$country_options[$new_state->country()->ID()] = $new_state->country()->name();
759
+			}
760
+		}
761
+		return $country_options;
762
+	}
763 763
 
764 764
 
765 765
 
Please login to merge, or discard this patch.
Spacing   +42 added lines, -42 removed lines patch added patch discarded remove patch
@@ -99,11 +99,11 @@  discard block
 block discarded – undo
99 99
      */
100 100
     public static function set_definitions()
101 101
     {
102
-        define('ANS_ASSETS_URL', plugin_dir_url(__FILE__) . 'assets' . DS);
102
+        define('ANS_ASSETS_URL', plugin_dir_url(__FILE__).'assets'.DS);
103 103
         define('ANS_TEMPLATES_PATH', str_replace(
104 104
                                          '\\',
105 105
                                          DS,
106
-                                         plugin_dir_path(__FILE__)) . 'templates' . DS
106
+                                         plugin_dir_path(__FILE__)).'templates'.DS
107 107
         );
108 108
     }
109 109
 
@@ -124,19 +124,19 @@  discard block
 block discarded – undo
124 124
      */
125 125
     public static function translate_js_strings()
126 126
     {
127
-        EE_Registry::$i18n_js_strings['ans_no_country']        = esc_html__(
127
+        EE_Registry::$i18n_js_strings['ans_no_country'] = esc_html__(
128 128
             'In order to proceed, you need to select the Country that your State/Province belongs to.',
129 129
             'event_espresso'
130 130
         );
131
-        EE_Registry::$i18n_js_strings['ans_no_name']           = esc_html__(
131
+        EE_Registry::$i18n_js_strings['ans_no_name'] = esc_html__(
132 132
             'In order to proceed, you need to enter the name of your State/Province.',
133 133
             'event_espresso'
134 134
         );
135
-        EE_Registry::$i18n_js_strings['ans_no_abbreviation']   = esc_html__(
135
+        EE_Registry::$i18n_js_strings['ans_no_abbreviation'] = esc_html__(
136 136
             'In order to proceed, you need to enter an abbreviation for the name of your State/Province.',
137 137
             'event_espresso'
138 138
         );
139
-        EE_Registry::$i18n_js_strings['ans_save_success']      = esc_html__(
139
+        EE_Registry::$i18n_js_strings['ans_save_success'] = esc_html__(
140 140
             'The new state was successfully saved to the database.',
141 141
             'event_espresso'
142 142
         );
@@ -154,7 +154,7 @@  discard block
 block discarded – undo
154 154
     public static function wp_enqueue_scripts()
155 155
     {
156 156
         if (apply_filters('EED_Single_Page_Checkout__SPCO_active', false)) {
157
-            wp_register_script('add_new_state', ANS_ASSETS_URL . 'add_new_state.js',
157
+            wp_register_script('add_new_state', ANS_ASSETS_URL.'add_new_state.js',
158 158
                 array('espresso_core', 'single_page_checkout'), EVENT_ESPRESSO_VERSION, true);
159 159
             wp_enqueue_script('add_new_state');
160 160
         }
@@ -197,7 +197,7 @@  discard block
 block discarded – undo
197 197
             $new_state_submit_id = str_replace('state', 'new_state', $input->html_id());
198 198
             $country_options     = array();
199 199
             $countries           = EEM_Country::instance()->get_all_countries();
200
-            if (! empty($countries)) {
200
+            if ( ! empty($countries)) {
201 201
                 foreach ($countries as $country) {
202 202
                     if ($country instanceof EE_Country) {
203 203
                         $country_options[$country->ID()] = $country->name();
@@ -234,10 +234,10 @@  discard block
 block discarded – undo
234 234
                                     '',
235 235
                                     esc_html__('click here to add a new state/province', 'event_espresso'),
236 236
                                     '',
237
-                                    'display-' . $input->html_id(),
237
+                                    'display-'.$input->html_id(),
238 238
                                     'ee-form-add-new-state-lnk display-the-hidden smaller-text hide-if-no-js',
239 239
                                     '',
240
-                                    'data-target="' . $input->html_id() . '"'
240
+                                    'data-target="'.$input->html_id().'"'
241 241
                                 )
242 242
                             )
243 243
                         ),
@@ -245,31 +245,31 @@  discard block
 block discarded – undo
245 245
                         'add_new_state_micro_form'    => new EE_Form_Section_HTML(
246 246
                             apply_filters(
247 247
                                 'FHEE__EED_Add_New_State__display_add_new_state_micro_form__add_new_state_micro_form',
248
-                                EEH_HTML::div('', $input->html_id() . '-dv', 'ee-form-add-new-state-dv',
249
-                                    'display: none;') .
248
+                                EEH_HTML::div('', $input->html_id().'-dv', 'ee-form-add-new-state-dv',
249
+                                    'display: none;').
250 250
                                 EEH_HTML::h6(
251 251
                                     esc_html__(
252 252
                                         'Is your state/province missing from the dropdown menu above? You can add it by completing the following steps:',
253 253
                                         'event_espresso'
254 254
                                     )
255
-                                ) .
256
-                                EEH_HTML::ul() .
255
+                                ).
256
+                                EEH_HTML::ul().
257 257
                                 EEH_HTML::li(
258 258
                                     esc_html__(
259 259
                                         'first select the Country that your State/Province belongs to',
260 260
                                         'event_espresso'
261 261
                                     )
262
-                                ) .
262
+                                ).
263 263
                                 EEH_HTML::li(
264 264
                                     esc_html__('enter the name of your State/Province', 'event_espresso')
265
-                                ) .
265
+                                ).
266 266
                                 EEH_HTML::li(
267 267
                                     esc_html__(
268 268
                                         'enter a two to six letter abbreviation for the name of your State/Province',
269 269
                                         'event_espresso'
270 270
                                     )
271
-                                ) .
272
-                                EEH_HTML::li(esc_html__('click the ADD button', 'event_espresso')) .
271
+                                ).
272
+                                EEH_HTML::li(esc_html__('click the ADD button', 'event_espresso')).
273 273
                                 EEH_HTML::ulx()
274 274
                             )
275 275
                         ),
@@ -282,7 +282,7 @@  discard block
 block discarded – undo
282 282
                                     'state',
283 283
                                     'nsmf_new_state_country', $input->html_id()
284 284
                                 ),
285
-                                'html_class'      => $input->html_class() . ' new-state-country',
285
+                                'html_class'      => $input->html_class().' new-state-country',
286 286
                                 'html_label_text' => esc_html__('New State/Province Country', 'event_espresso'),
287 287
                                 'default'         => EE_Registry::instance()->REQ->get($country_name, ''),
288 288
                                 'required'        => false,
@@ -296,7 +296,7 @@  discard block
 block discarded – undo
296 296
                                     'state',
297 297
                                     'nsmf_new_state_name', $input->html_id()
298 298
                                 ),
299
-                                'html_class'      => $input->html_class() . ' new-state-state',
299
+                                'html_class'      => $input->html_class().' new-state-state',
300 300
                                 'html_label_text' => esc_html__('New State/Province Name',
301 301
                                     'event_espresso'),
302 302
                                 'default'         => EE_Registry::instance()->REQ->get($state_name, ''),
@@ -310,11 +310,11 @@  discard block
 block discarded – undo
310 310
                                 'html_name'             => $abbrv_name,
311 311
                                 'html_id'               => str_replace('state', 'nsmf_new_state_abbrv',
312 312
                                     $input->html_id()),
313
-                                'html_class'            => $input->html_class() . ' new-state-abbrv',
313
+                                'html_class'            => $input->html_class().' new-state-abbrv',
314 314
                                 'html_label_text'       => esc_html__(
315 315
                                                                'New State/Province Abbreviation',
316 316
                                                                'event_espresso'
317
-                                                           ) . ' *',
317
+                                                           ).' *',
318 318
                                 'html_other_attributes' => 'size="24"',
319 319
                                 'default'               => EE_Registry::instance()->REQ->get($abbrv_name, ''),
320 320
                                 'required'              => false,
@@ -324,15 +324,15 @@  discard block
 block discarded – undo
324 324
                         'add_new_state_submit_button' => new EE_Form_Section_HTML(
325 325
                             apply_filters(
326 326
                                 'FHEE__EED_Add_New_State__display_add_new_state_micro_form__add_new_state_submit_button',
327
-                                EEH_HTML::nbsp(3) .
327
+                                EEH_HTML::nbsp(3).
328 328
                                 EEH_HTML::link(
329 329
                                     '',
330 330
                                     esc_html__('ADD', 'event_espresso'),
331 331
                                     '',
332
-                                    'submit-' . $new_state_submit_id,
332
+                                    'submit-'.$new_state_submit_id,
333 333
                                     'ee-form-add-new-state-submit button button-secondary',
334 334
                                     '',
335
-                                    'data-target="' . $new_state_submit_id . '"'
335
+                                    'data-target="'.$new_state_submit_id.'"'
336 336
                                 )
337 337
                             )
338 338
                         ),
@@ -345,7 +345,7 @@  discard block
 block discarded – undo
345 345
                                 EEH_HTML::div('', '', 'small-text')
346 346
                                 .
347 347
                                 EEH_HTML::strong(
348
-                                    '* ' .
348
+                                    '* '.
349 349
                                     esc_html__(
350 350
                                         'Don\'t know your State/Province Abbreviation?',
351 351
                                         'event_espresso'
@@ -378,10 +378,10 @@  discard block
 block discarded – undo
378 378
                                     '',
379 379
                                     esc_html__('cancel new State/Province', 'event_espresso'),
380 380
                                     '',
381
-                                    'hide-' . $input->html_id(),
381
+                                    'hide-'.$input->html_id(),
382 382
                                     'ee-form-cancel-new-state-lnk smaller-text',
383 383
                                     '',
384
-                                    'data-target="' . $input->html_id() . '"'
384
+                                    'data-target="'.$input->html_id().'"'
385 385
                                 )
386 386
                                 .
387 387
                                 EEH_HTML::divx()
@@ -527,7 +527,7 @@  discard block
 block discarded – undo
527 527
     public static function save_new_state_to_db($props_n_values = array())
528 528
     {
529 529
         $existing_state = EEM_State::instance()->get_all(array($props_n_values, 'limit' => 1));
530
-        if (! empty($existing_state)) {
530
+        if ( ! empty($existing_state)) {
531 531
             return array_pop($existing_state);
532 532
         }
533 533
         $new_state = EE_State::new_instance($props_n_values);
@@ -542,15 +542,15 @@  discard block
 block discarded – undo
542 542
             );
543 543
             // if not non-ajax admin
544 544
             new PersistentAdminNotice(
545
-                'new-state-added-' . $new_state->country_iso() . '-' . $new_state->abbrev(),
545
+                'new-state-added-'.$new_state->country_iso().'-'.$new_state->abbrev(),
546 546
                 sprintf(
547 547
                     esc_html__(
548 548
                         'A new State named "%1$s (%2$s)" was dynamically added from an Event Espresso form for the Country of "%3$s".%5$sTo verify, edit, and/or delete this new State, please go to the %4$s and update the States / Provinces section.%5$sCheck "Yes" to have this new State added to dropdown select lists in forms.',
549 549
                         'event_espresso'
550 550
                     ),
551
-                    '<b>' . $new_state->name() . '</b>',
552
-                    '<b>' . $new_state->abbrev() . '</b>',
553
-                    '<b>' . $new_state->country()->name() . '</b>',
551
+                    '<b>'.$new_state->name().'</b>',
552
+                    '<b>'.$new_state->abbrev().'</b>',
553
+                    '<b>'.$new_state->country()->name().'</b>',
554 554
                     '<a href="'
555 555
                     . $country_settings_url
556 556
                     . '">'
@@ -582,7 +582,7 @@  discard block
 block discarded – undo
582 582
      */
583 583
     public static function update_country_settings($CNT_ISO = '', $STA_ID = '', $cols_n_values = array())
584 584
     {
585
-        if (! $CNT_ISO) {
585
+        if ( ! $CNT_ISO) {
586 586
             EE_Error::add_error(
587 587
                 esc_html__('An invalid or missing Country ISO Code was received.', 'event_espresso'),
588 588
                 __FILE__,
@@ -592,13 +592,13 @@  discard block
 block discarded – undo
592 592
         }
593 593
         $STA_abbrev = is_array($cols_n_values) && isset($cols_n_values['STA_abbrev']) ? $cols_n_values['STA_abbrev']
594 594
             : false;
595
-        if (! $STA_abbrev && ! empty($STA_ID)) {
595
+        if ( ! $STA_abbrev && ! empty($STA_ID)) {
596 596
             $state = EEM_State::instance()->get_one_by_ID($STA_ID);
597 597
             if ($state instanceof EE_State) {
598 598
                 $STA_abbrev = $state->abbrev();
599 599
             }
600 600
         }
601
-        if (! $STA_abbrev) {
601
+        if ( ! $STA_abbrev) {
602 602
             EE_Error::add_error(
603 603
                 esc_html__('An invalid or missing State Abbreviation was received.', 'event_espresso'),
604 604
                 __FILE__,
@@ -610,7 +610,7 @@  discard block
 block discarded – undo
610 610
         $persistent_admin_notice_manager = LoaderFactory::getLoader()->getShared(
611 611
             'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
612 612
         );
613
-        $persistent_admin_notice_manager->dismissNotice($CNT_ISO . '-' . $STA_abbrev, true, true);
613
+        $persistent_admin_notice_manager->dismissNotice($CNT_ISO.'-'.$STA_abbrev, true, true);
614 614
     }
615 615
 
616 616
 
@@ -638,15 +638,15 @@  discard block
 block discarded – undo
638 638
             && $question->type() === EEM_Question::QST_type_state
639 639
         ) {
640 640
             $STA_ID = $answer->value();
641
-            if (! empty($STA_ID)) {
641
+            if ( ! empty($STA_ID)) {
642 642
                 $state = EEM_State::instance()->get_one_by_ID($STA_ID);
643 643
                 if ($state instanceof EE_State) {
644 644
                     $country = $state->country();
645 645
                     if ($country instanceof EE_Country) {
646
-                        if (! isset($state_options[$country->name()])) {
646
+                        if ( ! isset($state_options[$country->name()])) {
647 647
                             $state_options[$country->name()] = array();
648 648
                         }
649
-                        if (! isset($state_options[$country->name()][$STA_ID])) {
649
+                        if ( ! isset($state_options[$country->name()][$STA_ID])) {
650 650
                             $state_options[$country->name()][$STA_ID] = $state->name();
651 651
                         }
652 652
                     }
@@ -682,10 +682,10 @@  discard block
 block discarded – undo
682 682
                === EEM_Question::QST_type_country
683 683
         ) {
684 684
             $CNT_ISO = $answer->value();
685
-            if (! empty($CNT_ISO)) {
685
+            if ( ! empty($CNT_ISO)) {
686 686
                 $country = EEM_Country::instance()->get_one_by_ID($CNT_ISO);
687 687
                 if ($country instanceof EE_Country) {
688
-                    if (! isset($country_options[$CNT_ISO])) {
688
+                    if ( ! isset($country_options[$CNT_ISO])) {
689 689
                         $country_options[$CNT_ISO] = $country->name();
690 690
                     }
691 691
                 }
Please login to merge, or discard this patch.
core/services/notifications/PersistentAdminNoticeManager.php 2 patches
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -86,7 +86,7 @@  discard block
 block discarded – undo
86 86
      */
87 87
     private function setReturnUrl($return_url)
88 88
     {
89
-        if (! is_string($return_url)) {
89
+        if ( ! is_string($return_url)) {
90 90
             throw new InvalidDataTypeException('$return_url', $return_url, 'string');
91 91
         }
92 92
         $this->return_url = $return_url;
@@ -103,7 +103,7 @@  discard block
 block discarded – undo
103 103
      */
104 104
     protected function getPersistentAdminNoticeCollection()
105 105
     {
106
-        if (! $this->notice_collection instanceof Collection) {
106
+        if ( ! $this->notice_collection instanceof Collection) {
107 107
             $this->notice_collection = new Collection(
108 108
                 'EventEspresso\core\domain\entities\notifications\PersistentAdminNotice'
109 109
             );
@@ -127,7 +127,7 @@  discard block
 block discarded – undo
127 127
     {
128 128
         $persistent_admin_notices = get_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array());
129 129
         // \EEH_Debug_Tools::printr($persistent_admin_notices, '$persistent_admin_notices', __FILE__, __LINE__);
130
-        if (! empty($persistent_admin_notices)) {
130
+        if ( ! empty($persistent_admin_notices)) {
131 131
             foreach ($persistent_admin_notices as $name => $details) {
132 132
                 if (is_array($details)) {
133 133
                     if (
@@ -166,7 +166,7 @@  discard block
 block discarded – undo
166 166
                         $this->notice_collection->add(
167 167
                             new PersistentAdminNotice(
168 168
                                 $name,
169
-                                (string)$details,
169
+                                (string) $details,
170 170
                                 false,
171 171
                                 '',
172 172
                                 '',
@@ -244,14 +244,14 @@  discard block
 block discarded – undo
244 244
     {
245 245
         wp_register_script(
246 246
             'espresso_core',
247
-            EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
247
+            EE_GLOBAL_ASSETS_URL.'scripts/espresso_core.js',
248 248
             array('jquery'),
249 249
             EVENT_ESPRESSO_VERSION,
250 250
             true
251 251
         );
252 252
         wp_register_script(
253 253
             'ee_error_js',
254
-            EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js',
254
+            EE_GLOBAL_ASSETS_URL.'scripts/EE_Error.js',
255 255
             array('espresso_core'),
256 256
             EVENT_ESPRESSO_VERSION,
257 257
             true
@@ -283,7 +283,7 @@  discard block
 block discarded – undo
283 283
         // used in template
284 284
         $persistent_admin_notice_name    = $persistent_admin_notice->getName();
285 285
         $persistent_admin_notice_message = $persistent_admin_notice->getMessage();
286
-        require EE_TEMPLATES . DS . 'notifications' . DS . 'persistent_admin_notice.template.php';
286
+        require EE_TEMPLATES.DS.'notifications'.DS.'persistent_admin_notice.template.php';
287 287
     }
288 288
 
289 289
 
@@ -304,7 +304,7 @@  discard block
 block discarded – undo
304 304
     {
305 305
         $pan_name                = $this->request->get('ee_nag_notice', $pan_name);
306 306
         $this->notice_collection = $this->getPersistentAdminNoticeCollection();
307
-        if (! empty($pan_name) && $this->notice_collection->has($pan_name)) {
307
+        if ( ! empty($pan_name) && $this->notice_collection->has($pan_name)) {
308 308
             /** @var PersistentAdminNotice $persistent_admin_notice */
309 309
             $persistent_admin_notice = $this->notice_collection->get($pan_name);
310 310
             $persistent_admin_notice->setDismissed(true);
Please login to merge, or discard this patch.
Indentation   +360 added lines, -360 removed lines patch added patch discarded remove patch
@@ -30,366 +30,366 @@
 block discarded – undo
30 30
 class PersistentAdminNoticeManager
31 31
 {
32 32
 
33
-    const WP_OPTION_KEY = 'ee_pers_admin_notices';
34
-
35
-    /**
36
-     * @var Collection|PersistentAdminNotice[] $notice_collection
37
-     */
38
-    private $notice_collection;
39
-
40
-    /**
41
-     * if AJAX is not enabled, then the return URL will be used for redirecting back to the admin page where the
42
-     * persistent admin notice was displayed, and ultimately dismissed from.
43
-     *
44
-     * @type string $return_url
45
-     */
46
-    private $return_url;
47
-
48
-    /**
49
-     * @type CapabilitiesChecker $capabilities_checker
50
-     */
51
-    private $capabilities_checker;
52
-
53
-    /**
54
-     * @type EE_Request $request
55
-     */
56
-    private $request;
57
-
58
-
59
-
60
-    /**
61
-     * CapChecker constructor
62
-     *
63
-     * @param string              $return_url  where to  redirect to after dismissing notices
64
-     * @param CapabilitiesChecker $capabilities_checker
65
-     * @param EE_Request          $request
66
-     * @throws InvalidDataTypeException
67
-     */
68
-    public function __construct($return_url = '', CapabilitiesChecker $capabilities_checker, EE_Request $request)
69
-    {
70
-        $this->setReturnUrl($return_url);
71
-        $this->capabilities_checker = $capabilities_checker;
72
-        $this->request              = $request;
73
-        // setup up notices at priority 9 because `EE_Admin::display_admin_notices()` runs at priority 10,
74
-        // and we want to retrieve and generate any nag notices at the last possible moment
75
-        add_action('admin_notices', array($this, 'displayNotices'), 9);
76
-        add_action('network_admin_notices', array($this, 'displayNotices'), 9);
77
-        add_action('wp_ajax_dismiss_ee_nag_notice', array($this, 'dismissNotice'));
78
-        add_action('shutdown', array($this, 'registerAndSaveNotices'), 998);
79
-    }
80
-
81
-
82
-
83
-    /**
84
-     * @param string $return_url
85
-     * @throws InvalidDataTypeException
86
-     */
87
-    private function setReturnUrl($return_url)
88
-    {
89
-        if (! is_string($return_url)) {
90
-            throw new InvalidDataTypeException('$return_url', $return_url, 'string');
91
-        }
92
-        $this->return_url = $return_url;
93
-    }
94
-
95
-
96
-
97
-    /**
98
-     * @return Collection
99
-     * @throws InvalidEntityException
100
-     * @throws InvalidInterfaceException
101
-     * @throws InvalidDataTypeException
102
-     * @throws DomainException
103
-     */
104
-    protected function getPersistentAdminNoticeCollection()
105
-    {
106
-        if (! $this->notice_collection instanceof Collection) {
107
-            $this->notice_collection = new Collection(
108
-                'EventEspresso\core\domain\entities\notifications\PersistentAdminNotice'
109
-            );
110
-            $this->retrieveStoredNotices();
111
-            $this->registerNotices();
112
-        }
113
-        return $this->notice_collection;
114
-    }
115
-
116
-
117
-
118
-    /**
119
-     * generates PersistentAdminNotice objects for all non-dismissed notices saved to the db
120
-     *
121
-     * @return void
122
-     * @throws InvalidEntityException
123
-     * @throws DomainException
124
-     * @throws InvalidDataTypeException
125
-     */
126
-    protected function retrieveStoredNotices()
127
-    {
128
-        $persistent_admin_notices = get_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array());
129
-        // \EEH_Debug_Tools::printr($persistent_admin_notices, '$persistent_admin_notices', __FILE__, __LINE__);
130
-        if (! empty($persistent_admin_notices)) {
131
-            foreach ($persistent_admin_notices as $name => $details) {
132
-                if (is_array($details)) {
133
-                    if (
134
-                        ! isset(
135
-                            $details['message'],
136
-                            $details['capability'],
137
-                            $details['cap_context'],
138
-                            $details['dismissed']
139
-                        )
140
-                    ) {
141
-                        throw new DomainException(
142
-                            sprintf(
143
-                                esc_html__(
144
-                                    'The "%1$s" PersistentAdminNotice could not be retrieved from the database.',
145
-                                    'event_espresso'
146
-                                ),
147
-                                $name
148
-                            )
149
-                        );
150
-                    }
151
-                    // new format for nag notices
152
-                    $this->notice_collection->add(
153
-                        new PersistentAdminNotice(
154
-                            $name,
155
-                            $details['message'],
156
-                            false,
157
-                            $details['capability'],
158
-                            $details['cap_context'],
159
-                            $details['dismissed']
160
-                        ),
161
-                        $name
162
-                    );
163
-                } else {
164
-                    try {
165
-                        // old nag notices, that we want to convert to the new format
166
-                        $this->notice_collection->add(
167
-                            new PersistentAdminNotice(
168
-                                $name,
169
-                                (string)$details,
170
-                                false,
171
-                                '',
172
-                                '',
173
-                                empty($details)
174
-                            ),
175
-                            $name
176
-                        );
177
-                    } catch (Exception $e) {
178
-                        EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
179
-                    }
180
-                }
181
-                // each notice will self register when the action hook in registerNotices is triggered
182
-            }
183
-        }
184
-    }
185
-
186
-
187
-
188
-    /**
189
-     * exposes the Persistent Admin Notice Collection via an action
190
-     * so that PersistentAdminNotice objects can be added and/or removed
191
-     * without compromising the actual collection like a filter would
192
-     */
193
-    protected function registerNotices()
194
-    {
195
-        do_action(
196
-            'AHEE__EventEspresso_core_services_notifications_PersistentAdminNoticeManager__registerNotices',
197
-            $this->notice_collection
198
-        );
199
-    }
200
-
201
-
202
-
203
-    /**
204
-     * @throws DomainException
205
-     * @throws InvalidClassException
206
-     * @throws InvalidDataTypeException
207
-     * @throws InvalidInterfaceException
208
-     * @throws InvalidEntityException
209
-     */
210
-    public function displayNotices()
211
-    {
212
-        $this->notice_collection = $this->getPersistentAdminNoticeCollection();
213
-        if ($this->notice_collection->hasObjects()) {
214
-            $enqueue_assets = false;
215
-            // and display notices
216
-            foreach ($this->notice_collection as $persistent_admin_notice) {
217
-                /** @var PersistentAdminNotice $persistent_admin_notice */
218
-                // don't display notices that have already been dismissed
219
-                if ($persistent_admin_notice->getDismissed()) {
220
-                    continue;
221
-                }
222
-                try {
223
-                    $this->capabilities_checker->processCapCheck(
224
-                        $persistent_admin_notice->getCapCheck()
225
-                    );
226
-                } catch (InsufficientPermissionsException $e) {
227
-                    // user does not have required cap, so skip to next notice
228
-                    // and just eat the exception - nom nom nom nom
229
-                    continue;
230
-                }
231
-                if ($persistent_admin_notice->getMessage() === '') {
232
-                    continue;
233
-                }
234
-                $this->displayPersistentAdminNotice($persistent_admin_notice);
235
-                $enqueue_assets = true;
236
-            }
237
-            if ($enqueue_assets) {
238
-                $this->enqueueAssets();
239
-            }
240
-        }
241
-    }
242
-
243
-
244
-
245
-    /**
246
-     * does what it's named
247
-     *
248
-     * @return void
249
-     */
250
-    public function enqueueAssets()
251
-    {
252
-        wp_register_script(
253
-            'espresso_core',
254
-            EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
255
-            array('jquery'),
256
-            EVENT_ESPRESSO_VERSION,
257
-            true
258
-        );
259
-        wp_register_script(
260
-            'ee_error_js',
261
-            EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js',
262
-            array('espresso_core'),
263
-            EVENT_ESPRESSO_VERSION,
264
-            true
265
-        );
266
-        wp_localize_script(
267
-            'ee_error_js',
268
-            'ee_dismiss',
269
-            array(
270
-                'return_url'    => urlencode($this->return_url),
271
-                'ajax_url'      => WP_AJAX_URL,
272
-                'unknown_error' => esc_html__(
273
-                    'An unknown error has occurred on the server while attempting to dismiss this notice.',
274
-                    'event_espresso'
275
-                ),
276
-            )
277
-        );
278
-        wp_enqueue_script('ee_error_js');
279
-    }
280
-
281
-
282
-
283
-    /**
284
-     * displayPersistentAdminNoticeHtml
285
-     *
286
-     * @param  PersistentAdminNotice $persistent_admin_notice
287
-     */
288
-    protected function displayPersistentAdminNotice(PersistentAdminNotice $persistent_admin_notice)
289
-    {
290
-        // used in template
291
-        $persistent_admin_notice_name    = $persistent_admin_notice->getName();
292
-        $persistent_admin_notice_message = $persistent_admin_notice->getMessage();
293
-        require EE_TEMPLATES . DS . 'notifications' . DS . 'persistent_admin_notice.template.php';
294
-    }
295
-
296
-
297
-
298
-    /**
299
-     * dismissNotice
300
-     *
301
-     * @param string $pan_name the name, or key of the Persistent Admin Notice to be dismissed
302
-     * @param bool   $purge    if true, then delete it from the db
303
-     * @param bool   $return   forget all of this AJAX or redirect nonsense, and just return
304
-     * @return void
305
-     * @throws InvalidEntityException
306
-     * @throws InvalidInterfaceException
307
-     * @throws InvalidDataTypeException
308
-     * @throws DomainException
309
-     */
310
-    public function dismissNotice($pan_name = '', $purge = false, $return = false)
311
-    {
312
-        $pan_name                = $this->request->get('ee_nag_notice', $pan_name);
313
-        $this->notice_collection = $this->getPersistentAdminNoticeCollection();
314
-        if (! empty($pan_name) && $this->notice_collection->has($pan_name)) {
315
-            /** @var PersistentAdminNotice $persistent_admin_notice */
316
-            $persistent_admin_notice = $this->notice_collection->get($pan_name);
317
-            $persistent_admin_notice->setDismissed(true);
318
-            $persistent_admin_notice->setPurge($purge);
319
-            $this->saveNotices();
320
-        }
321
-        if ($return) {
322
-            return;
323
-        }
324
-        if ($this->request->ajax) {
325
-            // grab any notices and concatenate into string
326
-            echo wp_json_encode(
327
-                array(
328
-                    'errors' => implode('<br />', EE_Error::get_notices(false)),
329
-                )
330
-            );
331
-            exit();
332
-        }
333
-        // save errors to a transient to be displayed on next request (after redirect)
334
-        EE_Error::get_notices(false, true);
335
-        wp_safe_redirect(
336
-            urldecode(
337
-                $this->request->get('return_url', '')
338
-            )
339
-        );
340
-    }
341
-
342
-
343
-
344
-    /**
345
-     * saveNotices
346
-     *
347
-     * @throws DomainException
348
-     * @throws InvalidDataTypeException
349
-     * @throws InvalidInterfaceException
350
-     * @throws InvalidEntityException
351
-     */
352
-    public function saveNotices()
353
-    {
354
-        $this->notice_collection = $this->getPersistentAdminNoticeCollection();
355
-        if ($this->notice_collection->hasObjects()) {
356
-            $persistent_admin_notices = get_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array());
357
-            //maybe initialize persistent_admin_notices
358
-            if (empty($persistent_admin_notices)) {
359
-                add_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array(), '', 'no');
360
-            }
361
-            foreach ($this->notice_collection as $persistent_admin_notice) {
362
-                // are we deleting this notice ?
363
-                if ($persistent_admin_notice->getPurge()) {
364
-                    unset($persistent_admin_notices[$persistent_admin_notice->getName()]);
365
-                } else {
366
-                    /** @var PersistentAdminNotice $persistent_admin_notice */
367
-                    $persistent_admin_notices[$persistent_admin_notice->getName()] = array(
368
-                        'message'     => $persistent_admin_notice->getMessage(),
369
-                        'capability'  => $persistent_admin_notice->getCapability(),
370
-                        'cap_context' => $persistent_admin_notice->getCapContext(),
371
-                        'dismissed'   => $persistent_admin_notice->getDismissed(),
372
-                    );
373
-                }
374
-            }
375
-            update_option(PersistentAdminNoticeManager::WP_OPTION_KEY, $persistent_admin_notices);
376
-        }
377
-    }
378
-
379
-
380
-
381
-    /**
382
-     * @throws DomainException
383
-     * @throws InvalidDataTypeException
384
-     * @throws InvalidEntityException
385
-     * @throws InvalidInterfaceException
386
-     */
387
-    public function registerAndSaveNotices()
388
-    {
389
-        $this->getPersistentAdminNoticeCollection();
390
-        $this->registerNotices();
391
-        $this->saveNotices();
392
-    }
33
+	const WP_OPTION_KEY = 'ee_pers_admin_notices';
34
+
35
+	/**
36
+	 * @var Collection|PersistentAdminNotice[] $notice_collection
37
+	 */
38
+	private $notice_collection;
39
+
40
+	/**
41
+	 * if AJAX is not enabled, then the return URL will be used for redirecting back to the admin page where the
42
+	 * persistent admin notice was displayed, and ultimately dismissed from.
43
+	 *
44
+	 * @type string $return_url
45
+	 */
46
+	private $return_url;
47
+
48
+	/**
49
+	 * @type CapabilitiesChecker $capabilities_checker
50
+	 */
51
+	private $capabilities_checker;
52
+
53
+	/**
54
+	 * @type EE_Request $request
55
+	 */
56
+	private $request;
57
+
58
+
59
+
60
+	/**
61
+	 * CapChecker constructor
62
+	 *
63
+	 * @param string              $return_url  where to  redirect to after dismissing notices
64
+	 * @param CapabilitiesChecker $capabilities_checker
65
+	 * @param EE_Request          $request
66
+	 * @throws InvalidDataTypeException
67
+	 */
68
+	public function __construct($return_url = '', CapabilitiesChecker $capabilities_checker, EE_Request $request)
69
+	{
70
+		$this->setReturnUrl($return_url);
71
+		$this->capabilities_checker = $capabilities_checker;
72
+		$this->request              = $request;
73
+		// setup up notices at priority 9 because `EE_Admin::display_admin_notices()` runs at priority 10,
74
+		// and we want to retrieve and generate any nag notices at the last possible moment
75
+		add_action('admin_notices', array($this, 'displayNotices'), 9);
76
+		add_action('network_admin_notices', array($this, 'displayNotices'), 9);
77
+		add_action('wp_ajax_dismiss_ee_nag_notice', array($this, 'dismissNotice'));
78
+		add_action('shutdown', array($this, 'registerAndSaveNotices'), 998);
79
+	}
80
+
81
+
82
+
83
+	/**
84
+	 * @param string $return_url
85
+	 * @throws InvalidDataTypeException
86
+	 */
87
+	private function setReturnUrl($return_url)
88
+	{
89
+		if (! is_string($return_url)) {
90
+			throw new InvalidDataTypeException('$return_url', $return_url, 'string');
91
+		}
92
+		$this->return_url = $return_url;
93
+	}
94
+
95
+
96
+
97
+	/**
98
+	 * @return Collection
99
+	 * @throws InvalidEntityException
100
+	 * @throws InvalidInterfaceException
101
+	 * @throws InvalidDataTypeException
102
+	 * @throws DomainException
103
+	 */
104
+	protected function getPersistentAdminNoticeCollection()
105
+	{
106
+		if (! $this->notice_collection instanceof Collection) {
107
+			$this->notice_collection = new Collection(
108
+				'EventEspresso\core\domain\entities\notifications\PersistentAdminNotice'
109
+			);
110
+			$this->retrieveStoredNotices();
111
+			$this->registerNotices();
112
+		}
113
+		return $this->notice_collection;
114
+	}
115
+
116
+
117
+
118
+	/**
119
+	 * generates PersistentAdminNotice objects for all non-dismissed notices saved to the db
120
+	 *
121
+	 * @return void
122
+	 * @throws InvalidEntityException
123
+	 * @throws DomainException
124
+	 * @throws InvalidDataTypeException
125
+	 */
126
+	protected function retrieveStoredNotices()
127
+	{
128
+		$persistent_admin_notices = get_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array());
129
+		// \EEH_Debug_Tools::printr($persistent_admin_notices, '$persistent_admin_notices', __FILE__, __LINE__);
130
+		if (! empty($persistent_admin_notices)) {
131
+			foreach ($persistent_admin_notices as $name => $details) {
132
+				if (is_array($details)) {
133
+					if (
134
+						! isset(
135
+							$details['message'],
136
+							$details['capability'],
137
+							$details['cap_context'],
138
+							$details['dismissed']
139
+						)
140
+					) {
141
+						throw new DomainException(
142
+							sprintf(
143
+								esc_html__(
144
+									'The "%1$s" PersistentAdminNotice could not be retrieved from the database.',
145
+									'event_espresso'
146
+								),
147
+								$name
148
+							)
149
+						);
150
+					}
151
+					// new format for nag notices
152
+					$this->notice_collection->add(
153
+						new PersistentAdminNotice(
154
+							$name,
155
+							$details['message'],
156
+							false,
157
+							$details['capability'],
158
+							$details['cap_context'],
159
+							$details['dismissed']
160
+						),
161
+						$name
162
+					);
163
+				} else {
164
+					try {
165
+						// old nag notices, that we want to convert to the new format
166
+						$this->notice_collection->add(
167
+							new PersistentAdminNotice(
168
+								$name,
169
+								(string)$details,
170
+								false,
171
+								'',
172
+								'',
173
+								empty($details)
174
+							),
175
+							$name
176
+						);
177
+					} catch (Exception $e) {
178
+						EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
179
+					}
180
+				}
181
+				// each notice will self register when the action hook in registerNotices is triggered
182
+			}
183
+		}
184
+	}
185
+
186
+
187
+
188
+	/**
189
+	 * exposes the Persistent Admin Notice Collection via an action
190
+	 * so that PersistentAdminNotice objects can be added and/or removed
191
+	 * without compromising the actual collection like a filter would
192
+	 */
193
+	protected function registerNotices()
194
+	{
195
+		do_action(
196
+			'AHEE__EventEspresso_core_services_notifications_PersistentAdminNoticeManager__registerNotices',
197
+			$this->notice_collection
198
+		);
199
+	}
200
+
201
+
202
+
203
+	/**
204
+	 * @throws DomainException
205
+	 * @throws InvalidClassException
206
+	 * @throws InvalidDataTypeException
207
+	 * @throws InvalidInterfaceException
208
+	 * @throws InvalidEntityException
209
+	 */
210
+	public function displayNotices()
211
+	{
212
+		$this->notice_collection = $this->getPersistentAdminNoticeCollection();
213
+		if ($this->notice_collection->hasObjects()) {
214
+			$enqueue_assets = false;
215
+			// and display notices
216
+			foreach ($this->notice_collection as $persistent_admin_notice) {
217
+				/** @var PersistentAdminNotice $persistent_admin_notice */
218
+				// don't display notices that have already been dismissed
219
+				if ($persistent_admin_notice->getDismissed()) {
220
+					continue;
221
+				}
222
+				try {
223
+					$this->capabilities_checker->processCapCheck(
224
+						$persistent_admin_notice->getCapCheck()
225
+					);
226
+				} catch (InsufficientPermissionsException $e) {
227
+					// user does not have required cap, so skip to next notice
228
+					// and just eat the exception - nom nom nom nom
229
+					continue;
230
+				}
231
+				if ($persistent_admin_notice->getMessage() === '') {
232
+					continue;
233
+				}
234
+				$this->displayPersistentAdminNotice($persistent_admin_notice);
235
+				$enqueue_assets = true;
236
+			}
237
+			if ($enqueue_assets) {
238
+				$this->enqueueAssets();
239
+			}
240
+		}
241
+	}
242
+
243
+
244
+
245
+	/**
246
+	 * does what it's named
247
+	 *
248
+	 * @return void
249
+	 */
250
+	public function enqueueAssets()
251
+	{
252
+		wp_register_script(
253
+			'espresso_core',
254
+			EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
255
+			array('jquery'),
256
+			EVENT_ESPRESSO_VERSION,
257
+			true
258
+		);
259
+		wp_register_script(
260
+			'ee_error_js',
261
+			EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js',
262
+			array('espresso_core'),
263
+			EVENT_ESPRESSO_VERSION,
264
+			true
265
+		);
266
+		wp_localize_script(
267
+			'ee_error_js',
268
+			'ee_dismiss',
269
+			array(
270
+				'return_url'    => urlencode($this->return_url),
271
+				'ajax_url'      => WP_AJAX_URL,
272
+				'unknown_error' => esc_html__(
273
+					'An unknown error has occurred on the server while attempting to dismiss this notice.',
274
+					'event_espresso'
275
+				),
276
+			)
277
+		);
278
+		wp_enqueue_script('ee_error_js');
279
+	}
280
+
281
+
282
+
283
+	/**
284
+	 * displayPersistentAdminNoticeHtml
285
+	 *
286
+	 * @param  PersistentAdminNotice $persistent_admin_notice
287
+	 */
288
+	protected function displayPersistentAdminNotice(PersistentAdminNotice $persistent_admin_notice)
289
+	{
290
+		// used in template
291
+		$persistent_admin_notice_name    = $persistent_admin_notice->getName();
292
+		$persistent_admin_notice_message = $persistent_admin_notice->getMessage();
293
+		require EE_TEMPLATES . DS . 'notifications' . DS . 'persistent_admin_notice.template.php';
294
+	}
295
+
296
+
297
+
298
+	/**
299
+	 * dismissNotice
300
+	 *
301
+	 * @param string $pan_name the name, or key of the Persistent Admin Notice to be dismissed
302
+	 * @param bool   $purge    if true, then delete it from the db
303
+	 * @param bool   $return   forget all of this AJAX or redirect nonsense, and just return
304
+	 * @return void
305
+	 * @throws InvalidEntityException
306
+	 * @throws InvalidInterfaceException
307
+	 * @throws InvalidDataTypeException
308
+	 * @throws DomainException
309
+	 */
310
+	public function dismissNotice($pan_name = '', $purge = false, $return = false)
311
+	{
312
+		$pan_name                = $this->request->get('ee_nag_notice', $pan_name);
313
+		$this->notice_collection = $this->getPersistentAdminNoticeCollection();
314
+		if (! empty($pan_name) && $this->notice_collection->has($pan_name)) {
315
+			/** @var PersistentAdminNotice $persistent_admin_notice */
316
+			$persistent_admin_notice = $this->notice_collection->get($pan_name);
317
+			$persistent_admin_notice->setDismissed(true);
318
+			$persistent_admin_notice->setPurge($purge);
319
+			$this->saveNotices();
320
+		}
321
+		if ($return) {
322
+			return;
323
+		}
324
+		if ($this->request->ajax) {
325
+			// grab any notices and concatenate into string
326
+			echo wp_json_encode(
327
+				array(
328
+					'errors' => implode('<br />', EE_Error::get_notices(false)),
329
+				)
330
+			);
331
+			exit();
332
+		}
333
+		// save errors to a transient to be displayed on next request (after redirect)
334
+		EE_Error::get_notices(false, true);
335
+		wp_safe_redirect(
336
+			urldecode(
337
+				$this->request->get('return_url', '')
338
+			)
339
+		);
340
+	}
341
+
342
+
343
+
344
+	/**
345
+	 * saveNotices
346
+	 *
347
+	 * @throws DomainException
348
+	 * @throws InvalidDataTypeException
349
+	 * @throws InvalidInterfaceException
350
+	 * @throws InvalidEntityException
351
+	 */
352
+	public function saveNotices()
353
+	{
354
+		$this->notice_collection = $this->getPersistentAdminNoticeCollection();
355
+		if ($this->notice_collection->hasObjects()) {
356
+			$persistent_admin_notices = get_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array());
357
+			//maybe initialize persistent_admin_notices
358
+			if (empty($persistent_admin_notices)) {
359
+				add_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array(), '', 'no');
360
+			}
361
+			foreach ($this->notice_collection as $persistent_admin_notice) {
362
+				// are we deleting this notice ?
363
+				if ($persistent_admin_notice->getPurge()) {
364
+					unset($persistent_admin_notices[$persistent_admin_notice->getName()]);
365
+				} else {
366
+					/** @var PersistentAdminNotice $persistent_admin_notice */
367
+					$persistent_admin_notices[$persistent_admin_notice->getName()] = array(
368
+						'message'     => $persistent_admin_notice->getMessage(),
369
+						'capability'  => $persistent_admin_notice->getCapability(),
370
+						'cap_context' => $persistent_admin_notice->getCapContext(),
371
+						'dismissed'   => $persistent_admin_notice->getDismissed(),
372
+					);
373
+				}
374
+			}
375
+			update_option(PersistentAdminNoticeManager::WP_OPTION_KEY, $persistent_admin_notices);
376
+		}
377
+	}
378
+
379
+
380
+
381
+	/**
382
+	 * @throws DomainException
383
+	 * @throws InvalidDataTypeException
384
+	 * @throws InvalidEntityException
385
+	 * @throws InvalidInterfaceException
386
+	 */
387
+	public function registerAndSaveNotices()
388
+	{
389
+		$this->getPersistentAdminNoticeCollection();
390
+		$this->registerNotices();
391
+		$this->saveNotices();
392
+	}
393 393
 
394 394
 
395 395
 }
Please login to merge, or discard this patch.
core/admin/EE_Admin_Page_Loader.core.php 4 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -1,6 +1,5 @@
 block discarded – undo
1 1
 <?php
2 2
 use EventEspresso\core\domain\entities\notifications\PersistentAdminNotice;
3
-use EventEspresso\core\exceptions\InvalidDataTypeException;
4 3
 
5 4
 if (!defined('EVENT_ESPRESSO_VERSION') )
6 5
 	exit('NO direct script access allowed');
Please login to merge, or discard this patch.
Indentation   +743 added lines, -743 removed lines patch added patch discarded remove patch
@@ -28,749 +28,749 @@
 block discarded – undo
28 28
 class EE_Admin_Page_Loader
29 29
 {
30 30
 
31
-    /**
32
-     * _installed_pages
33
-     * objects for page_init objects detected and loaded
34
-     *
35
-     * @access private
36
-     * @var \EE_Admin_Page_Init[]
37
-     */
38
-    private $_installed_pages = array();
39
-
40
-
41
-
42
-    /**
43
-     * this is used to hold the registry of menu slugs for all the installed admin pages
44
-     *
45
-     * @var array
46
-     */
47
-    private $_menu_slugs = array();
48
-
49
-
50
-    /**
51
-     * _caffeinated_extends
52
-     * This array is the generated configuration array for which core EE_Admin pages are extended (and the bits and
53
-     * pieces needed to do so).  This property is defined in the _set_caffeinated method.
54
-     *
55
-     * @var array
56
-     */
57
-    private $_caffeinated_extends = array();
58
-
59
-
60
-
61
-    /**
62
-     * _current_caf_extend_slug
63
-     * This property is used for holding the page slug that is required for referencing the correct
64
-     * _caffeinated_extends index when the corresponding core child EE_Admin_Page_init hooks are executed.
65
-     *
66
-     * @var array
67
-     */
68
-    private $_current_caf_extend_slug;
69
-
70
-
71
-
72
-    /**
73
-     * _caf_autoloader
74
-     * This property is used for holding an array of folder names of any NEW EE_Admin_Pages found in the
75
-     * caffeinated/new directory.  This array is then used to setup a corresponding dynamic autoloader for these pages
76
-     * classes.
77
-     *
78
-     * @var array
79
-     */
80
-    //	private $_caf_autoloader = array();
81
-    /**
82
-     * _prepped_menu_maps
83
-     * This is the prepared array of EE_Admin_Page_Menu_Maps for adding to the admin_menu.
84
-     *
85
-     * @since  4.4.0
86
-     * @var EE_Admin_Page_Menu_Map[]
87
-     */
88
-    private $_prepped_menu_maps = array();
89
-
90
-
91
-
92
-    /**
93
-     * _admin_menu_groups
94
-     * array that holds the group headings and details for
95
-     *
96
-     * @access private
97
-     * @var array
98
-     */
99
-    private $_admin_menu_groups = array();
100
-
101
-
102
-
103
-    /**
104
-     * This property will hold the hook file for setting up the filter that does all the connections between admin
105
-     * pages.
106
-     *
107
-     * @var string
108
-     */
109
-    public $hook_file;
110
-
111
-
112
-
113
-    /**
114
-     * constructor
115
-     *
116
-     * @access public
117
-     * @return \EE_Admin_Page_Loader
118
-     */
119
-    public function __construct()
120
-    {
121
-        //load menu_map classes
122
-        EE_Registry::instance()->load_file(EE_ADMIN, 'EE_Admin_Page_Menu_Map', 'core');
123
-        //define the default "groups" for the admin_pages
124
-        $this->_set_menu_groups();
125
-        //let's set default autoloaders.  Note that this just sets autoloaders for root admin files.
126
-        //		spl_autoload_register( array( $this, 'init_autoloaders') );
127
-        //let's do a scan and see what installed pages we have
128
-        $this->_get_installed_pages();
129
-        //set menus (has to be done on every load - we're not actually loading the page just setting the menus and where they point to).
130
-        add_action('admin_menu', array($this, 'set_menus'));
131
-        add_action('network_admin_menu', array($this, 'set_network_menus'));
132
-    }
133
-
134
-
135
-
136
-    /**
137
-     * When caffeinated system is detected, this method is called to setup the caffeinated directory constants used by
138
-     * files in the caffeinated folder.
139
-     *
140
-     * @access private
141
-     * @return void
142
-     */
143
-    private function _define_caffeinated_constants()
144
-    {
145
-        if (! defined('EE_CORE_CAF_ADMIN')) {
146
-            define('EE_CORE_CAF_ADMIN', EE_PLUGIN_DIR_PATH . 'caffeinated/admin/');
147
-            define('EE_CORE_CAF_ADMIN_URL', EE_PLUGIN_DIR_URL . 'caffeinated/admin/');
148
-            define('EE_CORE_CAF_ADMIN_NEW', EE_CORE_CAF_ADMIN . 'new/');
149
-            define('EE_CORE_CAF_ADMIN_EXTEND', EE_CORE_CAF_ADMIN . 'extend/');
150
-            define('EE_CORE_CAF_ADMIN_EXTEND_URL', EE_CORE_CAF_ADMIN_URL . 'extend/');
151
-            define('EE_CORE_CAF_ADMIN_HOOKS', EE_CORE_CAF_ADMIN . 'hooks/');
152
-        }
153
-    }
154
-
155
-
156
-
157
-    /**
158
-     * _set_menu_groups
159
-     * sets the filterable _admin_menu_groups property (list of various "groupings" within the EE admin menu array)
160
-     *
161
-     * @access private
162
-     * @return void
163
-     */
164
-    private function _set_menu_groups()
165
-    {
166
-
167
-        //set array of EE_Admin_Page_Menu_Group objects
168
-        $groups = array(
169
-            'main'       => new EE_Admin_Page_Menu_Group(
170
-                array(
171
-                    'menu_label'   => __('Main', 'event_espresso'),
172
-                    'show_on_menu' => EE_Admin_Page_Menu_Map::NONE,
173
-                    'menu_slug'    => 'main',
174
-                    'capability'   => 'ee_read_ee',
175
-                    'menu_order'   => 0,
176
-                    'parent_slug'  => 'espresso_events',
177
-                )
178
-            ),
179
-            'management' => new EE_Admin_Page_Menu_Group(
180
-                array(
181
-                    'menu_label'   => __('Management', 'event_espresso'),
182
-                    'show_on_menu' => EE_Admin_Page_Menu_Map::BLOG_ADMIN_ONLY,
183
-                    'menu_slug'    => 'management',
184
-                    'capability'   => 'ee_read_ee',
185
-                    'menu_order'   => 10,
186
-                    'parent_slug'  => 'espresso_events',
187
-                )
188
-            ),
189
-            'settings'   => new EE_Admin_Page_Menu_Group(
190
-                array(
191
-                    'menu_label'   => __('Settings', 'event_espresso'),
192
-                    'show_on_menu' => EE_Admin_Page_Menu_Map::BLOG_ADMIN_ONLY,
193
-                    'menu_slug'    => 'settings',
194
-                    'capability'   => 'ee_read_ee',
195
-                    'menu_order'   => 30,
196
-                    'parent_slug'  => 'espresso_events',
197
-                )
198
-            ),
199
-            'templates'  => new EE_Admin_Page_Menu_Group(
200
-                array(
201
-                    'menu_label'   => __('Templates', 'event_espresso'),
202
-                    'show_on_menu' => EE_Admin_Page_Menu_Map::BLOG_ADMIN_ONLY,
203
-                    'menu_slug'    => 'templates',
204
-                    'capability'   => 'ee_read_ee',
205
-                    'menu_order'   => 40,
206
-                    'parent_slug'  => 'espresso_events',
207
-                )
208
-            ),
209
-            'extras'     => new EE_Admin_Page_Menu_Group(
210
-                array(
211
-                    'menu_label'              => __('Extras', 'event_espresso'),
212
-                    'show_on_menu'            => EE_Admin_Page_Menu_Map::BLOG_AND_NETWORK_ADMIN,
213
-                    'menu_slug'               => 'extras',
214
-                    'capability'              => 'ee_read_ee',
215
-                    'menu_order'              => 50,
216
-                    'parent_slug'             => 'espresso_events',
217
-                    'maintenance_mode_parent' => 'espresso_maintenance_settings',
218
-                )
219
-            ),
220
-            'tools'      => new EE_Admin_Page_Menu_Group(
221
-                array(
222
-                    'menu_label'   => __("Tools", "event_espresso"),
223
-                    'show_on_menu' => EE_Admin_Page_Menu_Map::BLOG_ADMIN_ONLY,
224
-                    'menu_slug'    => 'tools',
225
-                    'capability'   => 'ee_read_ee',
226
-                    'menu_order'   => 60,
227
-                    'parent_slug'  => 'espresso_events',
228
-                )
229
-            ),
230
-            'addons'     => new EE_Admin_Page_Menu_Group(
231
-                array(
232
-                    'show_on_menu' => EE_Admin_Page_Menu_Map::BLOG_AND_NETWORK_ADMIN,
233
-                    'menu_label'   => __('Add-ons', 'event_espresso'),
234
-                    'menu_slug'    => 'addons',
235
-                    'capability'   => 'ee_read_ee',
236
-                    'menu_order'   => 20,
237
-                    'parent_slug'  => 'espresso_events',
238
-                )
239
-            ),
240
-        );
241
-        $this->_admin_menu_groups = apply_filters(
242
-            'FHEE__EE_Admin_Page_Loader___set_menu_groups__admin_menu_groups',
243
-            $groups
244
-        );
245
-    }
246
-
247
-
248
-
249
-    /**
250
-     * This takes all the groups in the _admin_menu_groups array and returns the array indexed by group
251
-     * slug.  The other utility with this function is it validates that all the groups are instances of
252
-     * EE_Admin_Page_Menu_Group (cause some invalid things might have slipped in via addons).
253
-     *
254
-     * @since  4.4.0
255
-     * @throws \EE_Error
256
-     * @return EE_Admin_Page_Menu_Group[]
257
-     */
258
-    private function _rearrange_menu_groups()
259
-    {
260
-        $groups = array();
261
-        //first let's order the menu groups by their internal menu order (note usort type hinting to ensure the incoming array is EE_Admin_Page_Menu_Map objects )
262
-        usort($this->_admin_menu_groups, array($this, '_sort_menu_maps'));
263
-        foreach ($this->_admin_menu_groups as $group) {
264
-            if (! $group instanceof EE_Admin_Page_Menu_Group) {
265
-                throw new EE_Error(
266
-                    sprintf(
267
-                        __(
268
-                            'Unable to continue sorting the menu groups array because there is an invalid value for the menu groups.  All values in this array are required to be a EE_Admin_Page_Menu_Group object.  Instead there was: %s',
269
-                            'event_espresso'
270
-                        ),
271
-                        print_r($group, true)
272
-                    )
273
-                );
274
-            }
275
-            $groups[$group->menu_slug] = $group;
276
-        }
277
-        return $groups;
278
-    }
279
-
280
-
281
-
282
-    /**
283
-     * _get_installed_pages
284
-     * This just gets the list of installed EE_Admin_pages.
285
-     *
286
-     * @access private
287
-     * @throws EE_Error
288
-     * @return void
289
-     */
290
-    private function _get_installed_pages()
291
-    {
292
-        $installed_refs = array();
293
-        $exclude        = array('assets', 'templates');
294
-        // grab everything in the  admin core directory
295
-        $admin_screens = glob(EE_ADMIN_PAGES . '*', GLOB_ONLYDIR);
296
-        if ($admin_screens) {
297
-            foreach ($admin_screens as $admin_screen) {
298
-                // files and anything in the exclude array need not apply
299
-                if (is_dir($admin_screen) && ! in_array(basename($admin_screen), $exclude)) {
300
-                    // these folders represent the different EE admin pages
301
-                    $installed_refs[basename($admin_screen)] = $admin_screen;
302
-                }
303
-            }
304
-        }
305
-        if (empty($installed_refs)) {
306
-            $error_msg[] = __(
307
-                'There are no EE_Admin pages detected, it looks like EE did not install properly',
308
-                'event_espresso'
309
-            );
310
-            $error_msg[] = $error_msg[0] . "\r\n" . sprintf(
311
-                    __(
312
-                        'Check that the %s folder exists and is writable. Maybe try deactivating, then reactivating Event Espresso again.',
313
-                        'event_espresso'
314
-                    ),
315
-                    EE_ADMIN_PAGES
316
-                );
317
-            throw new EE_Error(implode('||', $error_msg));
318
-        }
319
-        //this just checks the caffeinated folder and takes care of setting up any caffeinated stuff.
320
-        $installed_refs = $this->_set_caffeinated($installed_refs);
321
-        //allow plugins to add in their own pages (note at this point they will need to have an autoloader defined for their class) OR hook into EEH_Autoloader::load_admin_page() to add their path.;
322
-        $installed_refs             = apply_filters(
323
-            'FHEE__EE_Admin_Page_Loader___get_installed_pages__installed_refs',
324
-            $installed_refs
325
-        );
326
-        $this->_caffeinated_extends = apply_filters(
327
-            'FHEE__EE_Admin_Page_Loader___get_installed_pages__caffeinated_extends',
328
-            $this->_caffeinated_extends
329
-        );
330
-        //loop through admin pages and setup the $_installed_pages array.
331
-        $hooks_ref = array();
332
-        foreach ($installed_refs as $page => $path) {
333
-            // set autoloaders for our admin page classes based on included path information
334
-            EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder($path);
335
-            // build list of installed pages
336
-            $this->_installed_pages[$page] = $this->_load_admin_page($page, $path);
337
-            // verify returned object
338
-            if ($this->_installed_pages[$page] instanceof EE_Admin_Page_Init) {
339
-                if (! $this->_installed_pages[$page]->get_menu_map() instanceof EE_Admin_Page_Menu_Map) {
340
-                    continue;
341
-                }
342
-                //skip if in full maintenance mode and maintenance_mode_parent is set
343
-                $maintenance_mode_parent = $this->_installed_pages[$page]->get_menu_map()->maintenance_mode_parent;
344
-                if (empty($maintenance_mode_parent)
345
-                    && EE_Maintenance_Mode::instance()->level()
346
-                       == EE_Maintenance_Mode::level_2_complete_maintenance) {
347
-                    unset($installed_refs[$page]);
348
-                    continue;
349
-                }
350
-                $this->_menu_slugs[$this->_installed_pages[$page]->get_menu_map()->menu_slug] = $page;
351
-                //flag for register hooks on extended pages b/c extended pages use the default INIT.
352
-                $extend = false;
353
-                //now that we've got the admin_init objects... lets see if there are any caffeinated pages extending the originals.  If there are then let's hook into the init admin filter and load our extend instead.
354
-                if (isset($this->_caffeinated_extends[$page])) {
355
-                    $this->_current_caf_extend_slug = $page;
356
-                    $path_hook                      = 'FHEE__EE_Admin_Page_Init___initialize_admin_page__path_to_file__'
357
-                                                      . $this->_installed_pages[$page]->get_menu_map()->menu_slug
358
-                                                      . '_'
359
-                                                      . $this->_installed_pages[$page]->get_admin_page_name();
360
-                    $path_runtime                   = 'return "'
361
-                                                      . $this->_caffeinated_extends[$this->_current_caf_extend_slug]["path"]
362
-                                                      . '";';
363
-                    $page_hook                      = 'FHEE__EE_Admin_Page_Init___initialize_admin_page__admin_page__'
364
-                                                      . $this->_installed_pages[$page]->get_menu_map()->menu_slug
365
-                                                      . '_'
366
-                                                      . $this->_installed_pages[$page]->get_admin_page_name();
367
-                    $page_runtime                   = 'return "'
368
-                                                      . $this->_caffeinated_extends[$this->_current_caf_extend_slug]["admin_page"]
369
-                                                      . '";';
370
-                    $hook_function_path = create_function('$path_to_file', $path_runtime);
371
-                    $hook_function_page = create_function('$admin_page', $page_runtime);
372
-                    add_filter($path_hook, $hook_function_path);
373
-                    add_filter($page_hook, $hook_function_page);
374
-                    $extend = true;
375
-                }
376
-                //let's do the registered hooks
377
-                $extended_hooks = $this->_installed_pages[$page]->register_hooks($extend);
378
-                $hooks_ref      = array_merge($hooks_ref, $extended_hooks);
379
-            }
380
-        }
381
-        //the hooks_ref is all the pages where we have $extended _Hooks files that will extend a class in a different folder.  So we want to make sure we load the file for the parent.
382
-        //first make sure we've got unique values
383
-        $hooks_ref = array_unique($hooks_ref);
384
-        //now let's loop and require!
385
-        foreach ($hooks_ref as $path) {
386
-            require_once($path);
387
-        }
388
-        //make sure we have menu slugs global setup. Used in EE_Admin_Page->page_setup() to ensure we don't do a full class load for an admin page that isn't requested.
389
-        global $ee_menu_slugs;
390
-        $ee_menu_slugs = $this->_menu_slugs;
391
-        //we need to loop again to run any early code
392
-        foreach ($installed_refs as $page => $path) {
393
-            if ($this->_installed_pages[$page] instanceof EE_Admin_Page_Init) {
394
-                $this->_installed_pages[$page]->do_initial_loads();
395
-            }
396
-        }
397
-        do_action('AHEE__EE_Admin_Page_Loader___get_installed_pages_loaded', $this->_installed_pages);
398
-    }
399
-
400
-
401
-
402
-    /**
403
-     * get_admin_page_object
404
-     *
405
-     * @param string $page_slug
406
-     * @return EE_Admin_Page
407
-     */
408
-    public function get_admin_page_object($page_slug = '')
409
-    {
410
-        if (isset($this->_installed_pages[$page_slug])) {
411
-            return $this->_installed_pages[$page_slug]->loaded_page_object();
412
-        }
413
-        return null;
414
-    }
415
-
416
-
417
-
418
-    /**
419
-     * _get_classname_for_admin_page
420
-     * generates an "Admin Page" class based on the directory  name
421
-     *
422
-     * @param $dir_name
423
-     * @return string
424
-     */
425
-    private function _get_classname_for_admin_page($dir_name = '')
426
-    {
427
-        $class_name = str_replace('_', ' ', strtolower($dir_name));
428
-        return str_replace(' ', '_', ucwords($class_name)) . '_Admin_Page';
429
-    }
430
-
431
-
432
-
433
-    /**
434
-     * _get_classname_for_admin_init_page
435
-     * generates an "Admin Page Init" class based on the directory  name
436
-     *
437
-     * @param $dir_name
438
-     * @return string
439
-     */
440
-    private function _get_classname_for_admin_init_page($dir_name = '')
441
-    {
442
-        $class_name = str_replace('_', ' ', strtolower($dir_name));
443
-        return str_replace(' ', '_', ucwords($class_name)) . '_Admin_Page_Init';
444
-    }
445
-
446
-
447
-
448
-    /**
449
-     * _load_admin_page
450
-     * Loads and instantiates page_init object for a single EE_admin page.
451
-     *
452
-     * @param  string $page page_reference
453
-     * @param string  $path
454
-     * @throws EE_Error
455
-     * @return object|bool  return page object if valid, bool false if not.
456
-     */
457
-    private function _load_admin_page($page = '', $path = '')
458
-    {
459
-        $class_name = $this->_get_classname_for_admin_init_page($page);
460
-        EE_Registry::instance()->load_file($path, $class_name, 'core');
461
-        if (! class_exists($class_name)) {
462
-            $inner_error_msg = '<br />' . sprintf(
463
-                    esc_html__(
464
-                        'Make sure you have %1$s defined. If this is a non-EE-core admin page then you also must have an autoloader in place for your class',
465
-                        'event_espresso'
466
-                    ),
467
-                    '<strong>' . $class_name . '</strong>'
468
-                );
469
-            $error_msg[]     = sprintf(
470
-                __('Something went wrong with loading the %s admin page.', 'event_espresso'),
471
-                $page
472
-            );
473
-            $error_msg[]     = $error_msg[0]
474
-                               . "\r\n"
475
-                               . sprintf(
476
-                                   esc_html__(
477
-                                       'There is no Init class in place for the %s admin page.',
478
-                                       'event_espresso'
479
-                                   ),
480
-                                   $page
481
-                               )
482
-                               . $inner_error_msg;
483
-            throw new EE_Error(implode('||', $error_msg));
484
-        }
485
-        $a = new ReflectionClass($class_name);
486
-        return $a->newInstance();
487
-    }
488
-
489
-
490
-
491
-    /**
492
-     * set_menus
493
-     * This method sets up the menus for EE Admin Pages
494
-     *
495
-     * @access private
496
-     * @return void
497
-     */
498
-    public function set_menus()
499
-    {
500
-        //prep the menu pages (sort, group.)
501
-        $this->_prep_pages();
502
-        foreach ($this->_prepped_menu_maps as $menu_map) {
503
-            if (EE_Registry::instance()->CAP->current_user_can($menu_map->capability, $menu_map->menu_slug)) {
504
-                $menu_map->add_menu_page(false);
505
-            }
506
-        }
507
-    }
508
-
509
-
510
-    /**
511
-     * set_network_menus
512
-     * This method sets up the menus for network EE Admin Pages.
513
-     * Almost identical to EE_Admin_Page_Loader::set_menus() except pages
514
-     * are only added to the menu map if they are intended for the admin menu
515
-     *
516
-     * @return void
517
-     */
518
-    public function set_network_menus()
519
-    {
520
-        $this->_prep_pages();
521
-        foreach ($this->_prepped_menu_maps as $menu_map) {
522
-            if (EE_Registry::instance()->CAP->current_user_can($menu_map->capability, $menu_map->menu_slug)) {
523
-                $menu_map->add_menu_page(true);
524
-            }
525
-        }
526
-    }
527
-
528
-
529
-
530
-    /**
531
-     * _prep_pages
532
-     * sets the _prepped_menu_maps property
533
-     *
534
-     * @access private
535
-     * @throws EE_Error
536
-     * @return void
537
-     */
538
-    private function _prep_pages()
539
-    {
540
-        $pages_array = array();
541
-        //rearrange _admin_menu_groups to be indexed by group slug.
542
-        $menu_groups = $this->_rearrange_menu_groups();
543
-        foreach ($this->_installed_pages as $page) {
544
-            if ($page instanceof EE_Admin_page_Init) {
545
-                $page_map = $page->get_menu_map();
546
-                //if we've got an array then the menu map is in the old format so let's throw a persistent notice that the admin system isn't setup correctly for this item.
547
-                if (is_array($page_map) || empty($page_map)) {
548
-                      new PersistentAdminNotice(
549
-                        'menu_map_warning_' . str_replace(' ', '_', $page->label) . '_' . EVENT_ESPRESSO_VERSION,
550
-                        sprintf(
551
-                            __(
552
-                                'The admin page for %s was not correctly setup because it is using an older method for integrating with Event Espresso Core.  This means that full functionality for this component is not available.  This error message usually appears with an Add-on that is out of date.  Make sure you update all your Event Espresso 4 add-ons to the latest version to ensure they have necessary compatibility updates in place.',
553
-                                'event_espresso'
554
-                            ),
555
-                            $page->label
556
-                        )
557
-                    );
558
-                    continue;
559
-                }
560
-                //if page map is NOT a EE_Admin_Page_Menu_Map object then throw error.
561
-                if (! $page_map instanceof EE_Admin_Page_Menu_Map) {
562
-                    throw new EE_Error(
563
-                        sprintf(
564
-                            __(
565
-                                'The menu map for %s must be an EE_Admin_Page_Menu_Map object.  Instead it is %s.  Please double check that the menu map has been configured correctly.',
566
-                                'event_espresso'
567
-                            ),
568
-                            $page->label,
569
-                            $page_map
570
-                        )
571
-                    );
572
-                }
573
-                //use the maintenance_mode_parent property and maintenance mode status to determine if this page even gets added to array.
574
-                if (empty($page_map->maintenance_mode_parent)
575
-                    && EE_Maintenance_Mode::instance()->level()
576
-                       == EE_Maintenance_Mode::level_2_complete_maintenance) {
577
-                    continue;
578
-                }
579
-                //assign to group (remember $page_map has the admin page stored in it).
580
-                $pages_array[$page_map->menu_group][] = $page_map;
581
-            }
582
-        }
583
-        if (empty($pages_array)) {
584
-            throw new EE_Error(__('Something went wrong when prepping the admin pages', 'event_espresso'));
585
-        }
586
-        //let's sort the groups, make sure it's a valid group, add header (if to show).
587
-        foreach ($pages_array as $group => $menu_maps) {
588
-            //valid_group?
589
-            if (! array_key_exists($group, $menu_groups)) {
590
-                continue;
591
-            }
592
-            //sort pages.
593
-            usort($menu_maps, array($this, '_sort_menu_maps'));
594
-            //prepend header
595
-            array_unshift($menu_maps, $menu_groups[$group]);
596
-            //reset $pages_array with prepped data
597
-            $pages_array[$group] = $menu_maps;
598
-        }
599
-        //now let's setup the _prepped_menu_maps property
600
-        foreach ($menu_groups as $group => $group_objs) {
601
-            if (isset($pages_array[$group])) {
602
-                $this->_prepped_menu_maps = array_merge($this->_prepped_menu_maps, $pages_array[$group]);
603
-            }
604
-        }/**/
605
-    }
606
-
607
-
608
-    /**
609
-     * This method is the "workhorse" for detecting and setting up caffeinated functionality.
610
-     * In this method there are three checks being done:
611
-     * 1. Do we have any NEW admin page sets.  If we do, lets add them into the menu setup (via the $installed_refs
612
-     * array) etc.  (new page sets are found in caffeinated/new/{page})
613
-     * 2. Do we have any EXTENDED page sets.  Basically an extended EE_Admin Page extends the core {child}_Admin_Page
614
-     * class.  eg. would be caffeinated/extend/events/Extend_Events_Admin_Page.core.php and in there would be a class:
615
-     * Extend_Events_Admin_Page extends Events_Admin_Page.
616
-     * 3. Do we have any files just for setting up hooks into other core pages.  The files can be any name in
617
-     * "caffeinated/hooks" EXCEPT they need a ".class.php" extension and the file name must correspond with the
618
-     * classname inside.  These classes are instantiated really early so that any hooks in them are run before the
619
-     * corresponding apply_filters/do_actions that are found in any future loaded EE_Admin pages (INCLUDING caffeinated
620
-     * admin_pages)
621
-     *
622
-     * @param array $installed_refs the original installed_refs array that may contain our NEW EE_Admin_Pages to be
623
-     *                              loaded.
624
-     * @return array
625
-     */
626
-    private function _set_caffeinated($installed_refs)
627
-    {
628
-
629
-        //first let's check if there IS a caffeinated folder. If there is not then lets get out.
630
-        if (! is_dir(EE_PLUGIN_DIR_PATH . 'caffeinated' . DS . 'admin') || (defined('EE_DECAF') && EE_DECAF)) {
631
-            return $installed_refs;
632
-        }
633
-        $this->_define_caffeinated_constants();
634
-        $exclude = array('tickets');
635
-        //okay let's setup an "New" pages first (we'll return installed refs later)
636
-        $new_admin_screens = glob(EE_CORE_CAF_ADMIN . 'new/*', GLOB_ONLYDIR);
637
-        if ($new_admin_screens) {
638
-            foreach ($new_admin_screens as $admin_screen) {
639
-                // files and anything in the exclude array need not apply
640
-                if (is_dir($admin_screen) && ! in_array(basename($admin_screen), $exclude)) {
641
-                    // these folders represent the different NEW EE admin pages
642
-                    $installed_refs[basename($admin_screen)] = $admin_screen;
643
-                    // set autoloaders for our admin page classes based on included path information
644
-                    EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder($admin_screen);
645
-                    //					$this->_caf_autoloader[] = array(
646
-                    //						'dir' => 'new',
647
-                    //						'folder' => basename( $admin_screen )
648
-                    //					);
649
-                }
650
-            }
651
-        }
652
-        //let's see if there are any EXTENDS to setup in the $_caffeinated_extends array (that will be used later for hooking into the _initialize_admin_age in the related core_init admin page)
653
-        $extends = glob(EE_CORE_CAF_ADMIN . 'extend/*', GLOB_ONLYDIR);
654
-        if ($extends) {
655
-            foreach ($extends as $extend) {
656
-                if (is_dir($extend)) {
657
-                    $extend_ref = basename($extend);
658
-                    //now let's make sure there is a file that matches the expected format
659
-                    $filename                                              = str_replace(
660
-                        ' ',
661
-                        '_',
662
-                        ucwords(
663
-                            str_replace(
664
-                                '_',
665
-                                ' ',
666
-                                $extend_ref
667
-                            )
668
-                        )
669
-                    );
670
-                    $filename                                              = 'Extend_' . $filename . '_Admin_Page';
671
-                    $this->_caffeinated_extends[$extend_ref]['path']       = str_replace(
672
-                        array('\\', '/'),
673
-                        DS,
674
-                        EE_CORE_CAF_ADMIN
675
-                        . 'extend'
676
-                        . DS
677
-                        . $extend_ref
678
-                        . DS
679
-                        . $filename
680
-                        . '.core.php'
681
-                    );
682
-                    $this->_caffeinated_extends[$extend_ref]['admin_page'] = $filename;
683
-                    // set autoloaders for our admin page classes based on included path information
684
-                    EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder($extend);
685
-                    //					$this->_caf_autoloader[] = array(
686
-                    //						'dir' => 'extend',
687
-                    //						'folder' => $extend_ref
688
-                    //					);
689
-                }
690
-            }
691
-        }
692
-        //let's see if there are any HOOK files and instantiate them if there are (so that hooks are loaded early!).
693
-        $ee_admin_hooks = array();
694
-        $hooks          = glob(EE_CORE_CAF_ADMIN . 'hooks/*.class.php');
695
-        if ($hooks) {
696
-            foreach ($hooks as $hook) {
697
-                if (is_readable($hook)) {
698
-                    require_once $hook;
699
-                    $classname = str_replace(EE_CORE_CAF_ADMIN . 'hooks/', '', $hook);
700
-                    $classname = str_replace('.class.php', '', $classname);
701
-                    if (class_exists($classname)) {
702
-                        $a                = new ReflectionClass($classname);
703
-                        $ee_admin_hooks[] = $a->newInstance();
704
-                    }
705
-                }
706
-            }
707
-        }/**/
708
-        $ee_admin_hooks = apply_filters('FHEE__EE_Admin_Page_Loader__set_caffeinated__ee_admin_hooks', $ee_admin_hooks);
709
-        return $installed_refs;
710
-    }
711
-
712
-
713
-
714
-
715
-
716
-    /**
717
-     * Initial autoloader registration
718
-     * This just sets up the autoloader for the root admin files
719
-     *
720
-     * @param  string $className incoming classname to check for autoload
721
-     * @return void
722
-     */
723
-    //	public function init_autoloaders( $className ) {
724
-    //		$dir_ref = array(
725
-    //			EE_ADMIN => array('core', 'class')
726
-    //		);
727
-    //		EEH_Autoloader::try_autoload($dir_ref, $className );
728
-    //	}
729
-    /**
730
-     * This method takes care of setting up the autoloader dynamically for any NEW EE_Admin pages found in the
731
-     * caffeinated folders.
732
-     *
733
-     * @access public
734
-     * @param  string $className in coming classname being called
735
-     * @return void
736
-     */
737
-    //	public function caffeinated_autoloaders( $className ) {
738
-    //		//let's setup an array of paths to check (for each subsystem)
739
-    //		$dir_ref = array();
740
-    //		foreach ( $this->_caf_autoloader as $pathinfo) {
741
-    //			$dir_ref[ EE_CORE_CAF_ADMIN . $pathinfo['dir'] . DS . $pathinfo['folder'] . DS] = array('core', 'class');
742
-    //		}
743
-    //
744
-    //		EEH_Autoloader::try_autoload($dir_ref, $className );
745
-    //	}
746
-    /**
747
-     * Utility method for sorting the _menu_maps (callback for usort php function)
748
-     *
749
-     * @since  4.4.0
750
-     * @param  EE_Admin_Page_Menu_Map $a menu_map object
751
-     * @param  EE_Admin_Page_Menu_Map $b being compared to
752
-     * @return int    sort order
753
-     */
754
-    private function _sort_menu_maps(EE_Admin_Page_Menu_Map $a, EE_Admin_Page_Menu_Map $b)
755
-    {
756
-        if ($a->menu_order == $b->menu_order) {
757
-            return 0;
758
-        }
759
-        return ($a->menu_order < $b->menu_order) ? -1 : 1;
760
-    }
761
-
762
-
763
-
764
-    /**
765
-     * _default_header_link
766
-     * This is just a dummy method to use with header submenu items
767
-     *
768
-     * @return bool false
769
-     */
770
-    public function _default_header_link()
771
-    {
772
-        return false;
773
-    }
31
+	/**
32
+	 * _installed_pages
33
+	 * objects for page_init objects detected and loaded
34
+	 *
35
+	 * @access private
36
+	 * @var \EE_Admin_Page_Init[]
37
+	 */
38
+	private $_installed_pages = array();
39
+
40
+
41
+
42
+	/**
43
+	 * this is used to hold the registry of menu slugs for all the installed admin pages
44
+	 *
45
+	 * @var array
46
+	 */
47
+	private $_menu_slugs = array();
48
+
49
+
50
+	/**
51
+	 * _caffeinated_extends
52
+	 * This array is the generated configuration array for which core EE_Admin pages are extended (and the bits and
53
+	 * pieces needed to do so).  This property is defined in the _set_caffeinated method.
54
+	 *
55
+	 * @var array
56
+	 */
57
+	private $_caffeinated_extends = array();
58
+
59
+
60
+
61
+	/**
62
+	 * _current_caf_extend_slug
63
+	 * This property is used for holding the page slug that is required for referencing the correct
64
+	 * _caffeinated_extends index when the corresponding core child EE_Admin_Page_init hooks are executed.
65
+	 *
66
+	 * @var array
67
+	 */
68
+	private $_current_caf_extend_slug;
69
+
70
+
71
+
72
+	/**
73
+	 * _caf_autoloader
74
+	 * This property is used for holding an array of folder names of any NEW EE_Admin_Pages found in the
75
+	 * caffeinated/new directory.  This array is then used to setup a corresponding dynamic autoloader for these pages
76
+	 * classes.
77
+	 *
78
+	 * @var array
79
+	 */
80
+	//	private $_caf_autoloader = array();
81
+	/**
82
+	 * _prepped_menu_maps
83
+	 * This is the prepared array of EE_Admin_Page_Menu_Maps for adding to the admin_menu.
84
+	 *
85
+	 * @since  4.4.0
86
+	 * @var EE_Admin_Page_Menu_Map[]
87
+	 */
88
+	private $_prepped_menu_maps = array();
89
+
90
+
91
+
92
+	/**
93
+	 * _admin_menu_groups
94
+	 * array that holds the group headings and details for
95
+	 *
96
+	 * @access private
97
+	 * @var array
98
+	 */
99
+	private $_admin_menu_groups = array();
100
+
101
+
102
+
103
+	/**
104
+	 * This property will hold the hook file for setting up the filter that does all the connections between admin
105
+	 * pages.
106
+	 *
107
+	 * @var string
108
+	 */
109
+	public $hook_file;
110
+
111
+
112
+
113
+	/**
114
+	 * constructor
115
+	 *
116
+	 * @access public
117
+	 * @return \EE_Admin_Page_Loader
118
+	 */
119
+	public function __construct()
120
+	{
121
+		//load menu_map classes
122
+		EE_Registry::instance()->load_file(EE_ADMIN, 'EE_Admin_Page_Menu_Map', 'core');
123
+		//define the default "groups" for the admin_pages
124
+		$this->_set_menu_groups();
125
+		//let's set default autoloaders.  Note that this just sets autoloaders for root admin files.
126
+		//		spl_autoload_register( array( $this, 'init_autoloaders') );
127
+		//let's do a scan and see what installed pages we have
128
+		$this->_get_installed_pages();
129
+		//set menus (has to be done on every load - we're not actually loading the page just setting the menus and where they point to).
130
+		add_action('admin_menu', array($this, 'set_menus'));
131
+		add_action('network_admin_menu', array($this, 'set_network_menus'));
132
+	}
133
+
134
+
135
+
136
+	/**
137
+	 * When caffeinated system is detected, this method is called to setup the caffeinated directory constants used by
138
+	 * files in the caffeinated folder.
139
+	 *
140
+	 * @access private
141
+	 * @return void
142
+	 */
143
+	private function _define_caffeinated_constants()
144
+	{
145
+		if (! defined('EE_CORE_CAF_ADMIN')) {
146
+			define('EE_CORE_CAF_ADMIN', EE_PLUGIN_DIR_PATH . 'caffeinated/admin/');
147
+			define('EE_CORE_CAF_ADMIN_URL', EE_PLUGIN_DIR_URL . 'caffeinated/admin/');
148
+			define('EE_CORE_CAF_ADMIN_NEW', EE_CORE_CAF_ADMIN . 'new/');
149
+			define('EE_CORE_CAF_ADMIN_EXTEND', EE_CORE_CAF_ADMIN . 'extend/');
150
+			define('EE_CORE_CAF_ADMIN_EXTEND_URL', EE_CORE_CAF_ADMIN_URL . 'extend/');
151
+			define('EE_CORE_CAF_ADMIN_HOOKS', EE_CORE_CAF_ADMIN . 'hooks/');
152
+		}
153
+	}
154
+
155
+
156
+
157
+	/**
158
+	 * _set_menu_groups
159
+	 * sets the filterable _admin_menu_groups property (list of various "groupings" within the EE admin menu array)
160
+	 *
161
+	 * @access private
162
+	 * @return void
163
+	 */
164
+	private function _set_menu_groups()
165
+	{
166
+
167
+		//set array of EE_Admin_Page_Menu_Group objects
168
+		$groups = array(
169
+			'main'       => new EE_Admin_Page_Menu_Group(
170
+				array(
171
+					'menu_label'   => __('Main', 'event_espresso'),
172
+					'show_on_menu' => EE_Admin_Page_Menu_Map::NONE,
173
+					'menu_slug'    => 'main',
174
+					'capability'   => 'ee_read_ee',
175
+					'menu_order'   => 0,
176
+					'parent_slug'  => 'espresso_events',
177
+				)
178
+			),
179
+			'management' => new EE_Admin_Page_Menu_Group(
180
+				array(
181
+					'menu_label'   => __('Management', 'event_espresso'),
182
+					'show_on_menu' => EE_Admin_Page_Menu_Map::BLOG_ADMIN_ONLY,
183
+					'menu_slug'    => 'management',
184
+					'capability'   => 'ee_read_ee',
185
+					'menu_order'   => 10,
186
+					'parent_slug'  => 'espresso_events',
187
+				)
188
+			),
189
+			'settings'   => new EE_Admin_Page_Menu_Group(
190
+				array(
191
+					'menu_label'   => __('Settings', 'event_espresso'),
192
+					'show_on_menu' => EE_Admin_Page_Menu_Map::BLOG_ADMIN_ONLY,
193
+					'menu_slug'    => 'settings',
194
+					'capability'   => 'ee_read_ee',
195
+					'menu_order'   => 30,
196
+					'parent_slug'  => 'espresso_events',
197
+				)
198
+			),
199
+			'templates'  => new EE_Admin_Page_Menu_Group(
200
+				array(
201
+					'menu_label'   => __('Templates', 'event_espresso'),
202
+					'show_on_menu' => EE_Admin_Page_Menu_Map::BLOG_ADMIN_ONLY,
203
+					'menu_slug'    => 'templates',
204
+					'capability'   => 'ee_read_ee',
205
+					'menu_order'   => 40,
206
+					'parent_slug'  => 'espresso_events',
207
+				)
208
+			),
209
+			'extras'     => new EE_Admin_Page_Menu_Group(
210
+				array(
211
+					'menu_label'              => __('Extras', 'event_espresso'),
212
+					'show_on_menu'            => EE_Admin_Page_Menu_Map::BLOG_AND_NETWORK_ADMIN,
213
+					'menu_slug'               => 'extras',
214
+					'capability'              => 'ee_read_ee',
215
+					'menu_order'              => 50,
216
+					'parent_slug'             => 'espresso_events',
217
+					'maintenance_mode_parent' => 'espresso_maintenance_settings',
218
+				)
219
+			),
220
+			'tools'      => new EE_Admin_Page_Menu_Group(
221
+				array(
222
+					'menu_label'   => __("Tools", "event_espresso"),
223
+					'show_on_menu' => EE_Admin_Page_Menu_Map::BLOG_ADMIN_ONLY,
224
+					'menu_slug'    => 'tools',
225
+					'capability'   => 'ee_read_ee',
226
+					'menu_order'   => 60,
227
+					'parent_slug'  => 'espresso_events',
228
+				)
229
+			),
230
+			'addons'     => new EE_Admin_Page_Menu_Group(
231
+				array(
232
+					'show_on_menu' => EE_Admin_Page_Menu_Map::BLOG_AND_NETWORK_ADMIN,
233
+					'menu_label'   => __('Add-ons', 'event_espresso'),
234
+					'menu_slug'    => 'addons',
235
+					'capability'   => 'ee_read_ee',
236
+					'menu_order'   => 20,
237
+					'parent_slug'  => 'espresso_events',
238
+				)
239
+			),
240
+		);
241
+		$this->_admin_menu_groups = apply_filters(
242
+			'FHEE__EE_Admin_Page_Loader___set_menu_groups__admin_menu_groups',
243
+			$groups
244
+		);
245
+	}
246
+
247
+
248
+
249
+	/**
250
+	 * This takes all the groups in the _admin_menu_groups array and returns the array indexed by group
251
+	 * slug.  The other utility with this function is it validates that all the groups are instances of
252
+	 * EE_Admin_Page_Menu_Group (cause some invalid things might have slipped in via addons).
253
+	 *
254
+	 * @since  4.4.0
255
+	 * @throws \EE_Error
256
+	 * @return EE_Admin_Page_Menu_Group[]
257
+	 */
258
+	private function _rearrange_menu_groups()
259
+	{
260
+		$groups = array();
261
+		//first let's order the menu groups by their internal menu order (note usort type hinting to ensure the incoming array is EE_Admin_Page_Menu_Map objects )
262
+		usort($this->_admin_menu_groups, array($this, '_sort_menu_maps'));
263
+		foreach ($this->_admin_menu_groups as $group) {
264
+			if (! $group instanceof EE_Admin_Page_Menu_Group) {
265
+				throw new EE_Error(
266
+					sprintf(
267
+						__(
268
+							'Unable to continue sorting the menu groups array because there is an invalid value for the menu groups.  All values in this array are required to be a EE_Admin_Page_Menu_Group object.  Instead there was: %s',
269
+							'event_espresso'
270
+						),
271
+						print_r($group, true)
272
+					)
273
+				);
274
+			}
275
+			$groups[$group->menu_slug] = $group;
276
+		}
277
+		return $groups;
278
+	}
279
+
280
+
281
+
282
+	/**
283
+	 * _get_installed_pages
284
+	 * This just gets the list of installed EE_Admin_pages.
285
+	 *
286
+	 * @access private
287
+	 * @throws EE_Error
288
+	 * @return void
289
+	 */
290
+	private function _get_installed_pages()
291
+	{
292
+		$installed_refs = array();
293
+		$exclude        = array('assets', 'templates');
294
+		// grab everything in the  admin core directory
295
+		$admin_screens = glob(EE_ADMIN_PAGES . '*', GLOB_ONLYDIR);
296
+		if ($admin_screens) {
297
+			foreach ($admin_screens as $admin_screen) {
298
+				// files and anything in the exclude array need not apply
299
+				if (is_dir($admin_screen) && ! in_array(basename($admin_screen), $exclude)) {
300
+					// these folders represent the different EE admin pages
301
+					$installed_refs[basename($admin_screen)] = $admin_screen;
302
+				}
303
+			}
304
+		}
305
+		if (empty($installed_refs)) {
306
+			$error_msg[] = __(
307
+				'There are no EE_Admin pages detected, it looks like EE did not install properly',
308
+				'event_espresso'
309
+			);
310
+			$error_msg[] = $error_msg[0] . "\r\n" . sprintf(
311
+					__(
312
+						'Check that the %s folder exists and is writable. Maybe try deactivating, then reactivating Event Espresso again.',
313
+						'event_espresso'
314
+					),
315
+					EE_ADMIN_PAGES
316
+				);
317
+			throw new EE_Error(implode('||', $error_msg));
318
+		}
319
+		//this just checks the caffeinated folder and takes care of setting up any caffeinated stuff.
320
+		$installed_refs = $this->_set_caffeinated($installed_refs);
321
+		//allow plugins to add in their own pages (note at this point they will need to have an autoloader defined for their class) OR hook into EEH_Autoloader::load_admin_page() to add their path.;
322
+		$installed_refs             = apply_filters(
323
+			'FHEE__EE_Admin_Page_Loader___get_installed_pages__installed_refs',
324
+			$installed_refs
325
+		);
326
+		$this->_caffeinated_extends = apply_filters(
327
+			'FHEE__EE_Admin_Page_Loader___get_installed_pages__caffeinated_extends',
328
+			$this->_caffeinated_extends
329
+		);
330
+		//loop through admin pages and setup the $_installed_pages array.
331
+		$hooks_ref = array();
332
+		foreach ($installed_refs as $page => $path) {
333
+			// set autoloaders for our admin page classes based on included path information
334
+			EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder($path);
335
+			// build list of installed pages
336
+			$this->_installed_pages[$page] = $this->_load_admin_page($page, $path);
337
+			// verify returned object
338
+			if ($this->_installed_pages[$page] instanceof EE_Admin_Page_Init) {
339
+				if (! $this->_installed_pages[$page]->get_menu_map() instanceof EE_Admin_Page_Menu_Map) {
340
+					continue;
341
+				}
342
+				//skip if in full maintenance mode and maintenance_mode_parent is set
343
+				$maintenance_mode_parent = $this->_installed_pages[$page]->get_menu_map()->maintenance_mode_parent;
344
+				if (empty($maintenance_mode_parent)
345
+					&& EE_Maintenance_Mode::instance()->level()
346
+					   == EE_Maintenance_Mode::level_2_complete_maintenance) {
347
+					unset($installed_refs[$page]);
348
+					continue;
349
+				}
350
+				$this->_menu_slugs[$this->_installed_pages[$page]->get_menu_map()->menu_slug] = $page;
351
+				//flag for register hooks on extended pages b/c extended pages use the default INIT.
352
+				$extend = false;
353
+				//now that we've got the admin_init objects... lets see if there are any caffeinated pages extending the originals.  If there are then let's hook into the init admin filter and load our extend instead.
354
+				if (isset($this->_caffeinated_extends[$page])) {
355
+					$this->_current_caf_extend_slug = $page;
356
+					$path_hook                      = 'FHEE__EE_Admin_Page_Init___initialize_admin_page__path_to_file__'
357
+													  . $this->_installed_pages[$page]->get_menu_map()->menu_slug
358
+													  . '_'
359
+													  . $this->_installed_pages[$page]->get_admin_page_name();
360
+					$path_runtime                   = 'return "'
361
+													  . $this->_caffeinated_extends[$this->_current_caf_extend_slug]["path"]
362
+													  . '";';
363
+					$page_hook                      = 'FHEE__EE_Admin_Page_Init___initialize_admin_page__admin_page__'
364
+													  . $this->_installed_pages[$page]->get_menu_map()->menu_slug
365
+													  . '_'
366
+													  . $this->_installed_pages[$page]->get_admin_page_name();
367
+					$page_runtime                   = 'return "'
368
+													  . $this->_caffeinated_extends[$this->_current_caf_extend_slug]["admin_page"]
369
+													  . '";';
370
+					$hook_function_path = create_function('$path_to_file', $path_runtime);
371
+					$hook_function_page = create_function('$admin_page', $page_runtime);
372
+					add_filter($path_hook, $hook_function_path);
373
+					add_filter($page_hook, $hook_function_page);
374
+					$extend = true;
375
+				}
376
+				//let's do the registered hooks
377
+				$extended_hooks = $this->_installed_pages[$page]->register_hooks($extend);
378
+				$hooks_ref      = array_merge($hooks_ref, $extended_hooks);
379
+			}
380
+		}
381
+		//the hooks_ref is all the pages where we have $extended _Hooks files that will extend a class in a different folder.  So we want to make sure we load the file for the parent.
382
+		//first make sure we've got unique values
383
+		$hooks_ref = array_unique($hooks_ref);
384
+		//now let's loop and require!
385
+		foreach ($hooks_ref as $path) {
386
+			require_once($path);
387
+		}
388
+		//make sure we have menu slugs global setup. Used in EE_Admin_Page->page_setup() to ensure we don't do a full class load for an admin page that isn't requested.
389
+		global $ee_menu_slugs;
390
+		$ee_menu_slugs = $this->_menu_slugs;
391
+		//we need to loop again to run any early code
392
+		foreach ($installed_refs as $page => $path) {
393
+			if ($this->_installed_pages[$page] instanceof EE_Admin_Page_Init) {
394
+				$this->_installed_pages[$page]->do_initial_loads();
395
+			}
396
+		}
397
+		do_action('AHEE__EE_Admin_Page_Loader___get_installed_pages_loaded', $this->_installed_pages);
398
+	}
399
+
400
+
401
+
402
+	/**
403
+	 * get_admin_page_object
404
+	 *
405
+	 * @param string $page_slug
406
+	 * @return EE_Admin_Page
407
+	 */
408
+	public function get_admin_page_object($page_slug = '')
409
+	{
410
+		if (isset($this->_installed_pages[$page_slug])) {
411
+			return $this->_installed_pages[$page_slug]->loaded_page_object();
412
+		}
413
+		return null;
414
+	}
415
+
416
+
417
+
418
+	/**
419
+	 * _get_classname_for_admin_page
420
+	 * generates an "Admin Page" class based on the directory  name
421
+	 *
422
+	 * @param $dir_name
423
+	 * @return string
424
+	 */
425
+	private function _get_classname_for_admin_page($dir_name = '')
426
+	{
427
+		$class_name = str_replace('_', ' ', strtolower($dir_name));
428
+		return str_replace(' ', '_', ucwords($class_name)) . '_Admin_Page';
429
+	}
430
+
431
+
432
+
433
+	/**
434
+	 * _get_classname_for_admin_init_page
435
+	 * generates an "Admin Page Init" class based on the directory  name
436
+	 *
437
+	 * @param $dir_name
438
+	 * @return string
439
+	 */
440
+	private function _get_classname_for_admin_init_page($dir_name = '')
441
+	{
442
+		$class_name = str_replace('_', ' ', strtolower($dir_name));
443
+		return str_replace(' ', '_', ucwords($class_name)) . '_Admin_Page_Init';
444
+	}
445
+
446
+
447
+
448
+	/**
449
+	 * _load_admin_page
450
+	 * Loads and instantiates page_init object for a single EE_admin page.
451
+	 *
452
+	 * @param  string $page page_reference
453
+	 * @param string  $path
454
+	 * @throws EE_Error
455
+	 * @return object|bool  return page object if valid, bool false if not.
456
+	 */
457
+	private function _load_admin_page($page = '', $path = '')
458
+	{
459
+		$class_name = $this->_get_classname_for_admin_init_page($page);
460
+		EE_Registry::instance()->load_file($path, $class_name, 'core');
461
+		if (! class_exists($class_name)) {
462
+			$inner_error_msg = '<br />' . sprintf(
463
+					esc_html__(
464
+						'Make sure you have %1$s defined. If this is a non-EE-core admin page then you also must have an autoloader in place for your class',
465
+						'event_espresso'
466
+					),
467
+					'<strong>' . $class_name . '</strong>'
468
+				);
469
+			$error_msg[]     = sprintf(
470
+				__('Something went wrong with loading the %s admin page.', 'event_espresso'),
471
+				$page
472
+			);
473
+			$error_msg[]     = $error_msg[0]
474
+							   . "\r\n"
475
+							   . sprintf(
476
+								   esc_html__(
477
+									   'There is no Init class in place for the %s admin page.',
478
+									   'event_espresso'
479
+								   ),
480
+								   $page
481
+							   )
482
+							   . $inner_error_msg;
483
+			throw new EE_Error(implode('||', $error_msg));
484
+		}
485
+		$a = new ReflectionClass($class_name);
486
+		return $a->newInstance();
487
+	}
488
+
489
+
490
+
491
+	/**
492
+	 * set_menus
493
+	 * This method sets up the menus for EE Admin Pages
494
+	 *
495
+	 * @access private
496
+	 * @return void
497
+	 */
498
+	public function set_menus()
499
+	{
500
+		//prep the menu pages (sort, group.)
501
+		$this->_prep_pages();
502
+		foreach ($this->_prepped_menu_maps as $menu_map) {
503
+			if (EE_Registry::instance()->CAP->current_user_can($menu_map->capability, $menu_map->menu_slug)) {
504
+				$menu_map->add_menu_page(false);
505
+			}
506
+		}
507
+	}
508
+
509
+
510
+	/**
511
+	 * set_network_menus
512
+	 * This method sets up the menus for network EE Admin Pages.
513
+	 * Almost identical to EE_Admin_Page_Loader::set_menus() except pages
514
+	 * are only added to the menu map if they are intended for the admin menu
515
+	 *
516
+	 * @return void
517
+	 */
518
+	public function set_network_menus()
519
+	{
520
+		$this->_prep_pages();
521
+		foreach ($this->_prepped_menu_maps as $menu_map) {
522
+			if (EE_Registry::instance()->CAP->current_user_can($menu_map->capability, $menu_map->menu_slug)) {
523
+				$menu_map->add_menu_page(true);
524
+			}
525
+		}
526
+	}
527
+
528
+
529
+
530
+	/**
531
+	 * _prep_pages
532
+	 * sets the _prepped_menu_maps property
533
+	 *
534
+	 * @access private
535
+	 * @throws EE_Error
536
+	 * @return void
537
+	 */
538
+	private function _prep_pages()
539
+	{
540
+		$pages_array = array();
541
+		//rearrange _admin_menu_groups to be indexed by group slug.
542
+		$menu_groups = $this->_rearrange_menu_groups();
543
+		foreach ($this->_installed_pages as $page) {
544
+			if ($page instanceof EE_Admin_page_Init) {
545
+				$page_map = $page->get_menu_map();
546
+				//if we've got an array then the menu map is in the old format so let's throw a persistent notice that the admin system isn't setup correctly for this item.
547
+				if (is_array($page_map) || empty($page_map)) {
548
+					  new PersistentAdminNotice(
549
+						'menu_map_warning_' . str_replace(' ', '_', $page->label) . '_' . EVENT_ESPRESSO_VERSION,
550
+						sprintf(
551
+							__(
552
+								'The admin page for %s was not correctly setup because it is using an older method for integrating with Event Espresso Core.  This means that full functionality for this component is not available.  This error message usually appears with an Add-on that is out of date.  Make sure you update all your Event Espresso 4 add-ons to the latest version to ensure they have necessary compatibility updates in place.',
553
+								'event_espresso'
554
+							),
555
+							$page->label
556
+						)
557
+					);
558
+					continue;
559
+				}
560
+				//if page map is NOT a EE_Admin_Page_Menu_Map object then throw error.
561
+				if (! $page_map instanceof EE_Admin_Page_Menu_Map) {
562
+					throw new EE_Error(
563
+						sprintf(
564
+							__(
565
+								'The menu map for %s must be an EE_Admin_Page_Menu_Map object.  Instead it is %s.  Please double check that the menu map has been configured correctly.',
566
+								'event_espresso'
567
+							),
568
+							$page->label,
569
+							$page_map
570
+						)
571
+					);
572
+				}
573
+				//use the maintenance_mode_parent property and maintenance mode status to determine if this page even gets added to array.
574
+				if (empty($page_map->maintenance_mode_parent)
575
+					&& EE_Maintenance_Mode::instance()->level()
576
+					   == EE_Maintenance_Mode::level_2_complete_maintenance) {
577
+					continue;
578
+				}
579
+				//assign to group (remember $page_map has the admin page stored in it).
580
+				$pages_array[$page_map->menu_group][] = $page_map;
581
+			}
582
+		}
583
+		if (empty($pages_array)) {
584
+			throw new EE_Error(__('Something went wrong when prepping the admin pages', 'event_espresso'));
585
+		}
586
+		//let's sort the groups, make sure it's a valid group, add header (if to show).
587
+		foreach ($pages_array as $group => $menu_maps) {
588
+			//valid_group?
589
+			if (! array_key_exists($group, $menu_groups)) {
590
+				continue;
591
+			}
592
+			//sort pages.
593
+			usort($menu_maps, array($this, '_sort_menu_maps'));
594
+			//prepend header
595
+			array_unshift($menu_maps, $menu_groups[$group]);
596
+			//reset $pages_array with prepped data
597
+			$pages_array[$group] = $menu_maps;
598
+		}
599
+		//now let's setup the _prepped_menu_maps property
600
+		foreach ($menu_groups as $group => $group_objs) {
601
+			if (isset($pages_array[$group])) {
602
+				$this->_prepped_menu_maps = array_merge($this->_prepped_menu_maps, $pages_array[$group]);
603
+			}
604
+		}/**/
605
+	}
606
+
607
+
608
+	/**
609
+	 * This method is the "workhorse" for detecting and setting up caffeinated functionality.
610
+	 * In this method there are three checks being done:
611
+	 * 1. Do we have any NEW admin page sets.  If we do, lets add them into the menu setup (via the $installed_refs
612
+	 * array) etc.  (new page sets are found in caffeinated/new/{page})
613
+	 * 2. Do we have any EXTENDED page sets.  Basically an extended EE_Admin Page extends the core {child}_Admin_Page
614
+	 * class.  eg. would be caffeinated/extend/events/Extend_Events_Admin_Page.core.php and in there would be a class:
615
+	 * Extend_Events_Admin_Page extends Events_Admin_Page.
616
+	 * 3. Do we have any files just for setting up hooks into other core pages.  The files can be any name in
617
+	 * "caffeinated/hooks" EXCEPT they need a ".class.php" extension and the file name must correspond with the
618
+	 * classname inside.  These classes are instantiated really early so that any hooks in them are run before the
619
+	 * corresponding apply_filters/do_actions that are found in any future loaded EE_Admin pages (INCLUDING caffeinated
620
+	 * admin_pages)
621
+	 *
622
+	 * @param array $installed_refs the original installed_refs array that may contain our NEW EE_Admin_Pages to be
623
+	 *                              loaded.
624
+	 * @return array
625
+	 */
626
+	private function _set_caffeinated($installed_refs)
627
+	{
628
+
629
+		//first let's check if there IS a caffeinated folder. If there is not then lets get out.
630
+		if (! is_dir(EE_PLUGIN_DIR_PATH . 'caffeinated' . DS . 'admin') || (defined('EE_DECAF') && EE_DECAF)) {
631
+			return $installed_refs;
632
+		}
633
+		$this->_define_caffeinated_constants();
634
+		$exclude = array('tickets');
635
+		//okay let's setup an "New" pages first (we'll return installed refs later)
636
+		$new_admin_screens = glob(EE_CORE_CAF_ADMIN . 'new/*', GLOB_ONLYDIR);
637
+		if ($new_admin_screens) {
638
+			foreach ($new_admin_screens as $admin_screen) {
639
+				// files and anything in the exclude array need not apply
640
+				if (is_dir($admin_screen) && ! in_array(basename($admin_screen), $exclude)) {
641
+					// these folders represent the different NEW EE admin pages
642
+					$installed_refs[basename($admin_screen)] = $admin_screen;
643
+					// set autoloaders for our admin page classes based on included path information
644
+					EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder($admin_screen);
645
+					//					$this->_caf_autoloader[] = array(
646
+					//						'dir' => 'new',
647
+					//						'folder' => basename( $admin_screen )
648
+					//					);
649
+				}
650
+			}
651
+		}
652
+		//let's see if there are any EXTENDS to setup in the $_caffeinated_extends array (that will be used later for hooking into the _initialize_admin_age in the related core_init admin page)
653
+		$extends = glob(EE_CORE_CAF_ADMIN . 'extend/*', GLOB_ONLYDIR);
654
+		if ($extends) {
655
+			foreach ($extends as $extend) {
656
+				if (is_dir($extend)) {
657
+					$extend_ref = basename($extend);
658
+					//now let's make sure there is a file that matches the expected format
659
+					$filename                                              = str_replace(
660
+						' ',
661
+						'_',
662
+						ucwords(
663
+							str_replace(
664
+								'_',
665
+								' ',
666
+								$extend_ref
667
+							)
668
+						)
669
+					);
670
+					$filename                                              = 'Extend_' . $filename . '_Admin_Page';
671
+					$this->_caffeinated_extends[$extend_ref]['path']       = str_replace(
672
+						array('\\', '/'),
673
+						DS,
674
+						EE_CORE_CAF_ADMIN
675
+						. 'extend'
676
+						. DS
677
+						. $extend_ref
678
+						. DS
679
+						. $filename
680
+						. '.core.php'
681
+					);
682
+					$this->_caffeinated_extends[$extend_ref]['admin_page'] = $filename;
683
+					// set autoloaders for our admin page classes based on included path information
684
+					EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder($extend);
685
+					//					$this->_caf_autoloader[] = array(
686
+					//						'dir' => 'extend',
687
+					//						'folder' => $extend_ref
688
+					//					);
689
+				}
690
+			}
691
+		}
692
+		//let's see if there are any HOOK files and instantiate them if there are (so that hooks are loaded early!).
693
+		$ee_admin_hooks = array();
694
+		$hooks          = glob(EE_CORE_CAF_ADMIN . 'hooks/*.class.php');
695
+		if ($hooks) {
696
+			foreach ($hooks as $hook) {
697
+				if (is_readable($hook)) {
698
+					require_once $hook;
699
+					$classname = str_replace(EE_CORE_CAF_ADMIN . 'hooks/', '', $hook);
700
+					$classname = str_replace('.class.php', '', $classname);
701
+					if (class_exists($classname)) {
702
+						$a                = new ReflectionClass($classname);
703
+						$ee_admin_hooks[] = $a->newInstance();
704
+					}
705
+				}
706
+			}
707
+		}/**/
708
+		$ee_admin_hooks = apply_filters('FHEE__EE_Admin_Page_Loader__set_caffeinated__ee_admin_hooks', $ee_admin_hooks);
709
+		return $installed_refs;
710
+	}
711
+
712
+
713
+
714
+
715
+
716
+	/**
717
+	 * Initial autoloader registration
718
+	 * This just sets up the autoloader for the root admin files
719
+	 *
720
+	 * @param  string $className incoming classname to check for autoload
721
+	 * @return void
722
+	 */
723
+	//	public function init_autoloaders( $className ) {
724
+	//		$dir_ref = array(
725
+	//			EE_ADMIN => array('core', 'class')
726
+	//		);
727
+	//		EEH_Autoloader::try_autoload($dir_ref, $className );
728
+	//	}
729
+	/**
730
+	 * This method takes care of setting up the autoloader dynamically for any NEW EE_Admin pages found in the
731
+	 * caffeinated folders.
732
+	 *
733
+	 * @access public
734
+	 * @param  string $className in coming classname being called
735
+	 * @return void
736
+	 */
737
+	//	public function caffeinated_autoloaders( $className ) {
738
+	//		//let's setup an array of paths to check (for each subsystem)
739
+	//		$dir_ref = array();
740
+	//		foreach ( $this->_caf_autoloader as $pathinfo) {
741
+	//			$dir_ref[ EE_CORE_CAF_ADMIN . $pathinfo['dir'] . DS . $pathinfo['folder'] . DS] = array('core', 'class');
742
+	//		}
743
+	//
744
+	//		EEH_Autoloader::try_autoload($dir_ref, $className );
745
+	//	}
746
+	/**
747
+	 * Utility method for sorting the _menu_maps (callback for usort php function)
748
+	 *
749
+	 * @since  4.4.0
750
+	 * @param  EE_Admin_Page_Menu_Map $a menu_map object
751
+	 * @param  EE_Admin_Page_Menu_Map $b being compared to
752
+	 * @return int    sort order
753
+	 */
754
+	private function _sort_menu_maps(EE_Admin_Page_Menu_Map $a, EE_Admin_Page_Menu_Map $b)
755
+	{
756
+		if ($a->menu_order == $b->menu_order) {
757
+			return 0;
758
+		}
759
+		return ($a->menu_order < $b->menu_order) ? -1 : 1;
760
+	}
761
+
762
+
763
+
764
+	/**
765
+	 * _default_header_link
766
+	 * This is just a dummy method to use with header submenu items
767
+	 *
768
+	 * @return bool false
769
+	 */
770
+	public function _default_header_link()
771
+	{
772
+		return false;
773
+	}
774 774
 
775 775
 
776 776
 }
Please login to merge, or discard this patch.
Spacing   +31 added lines, -31 removed lines patch added patch discarded remove patch
@@ -2,7 +2,7 @@  discard block
 block discarded – undo
2 2
 use EventEspresso\core\domain\entities\notifications\PersistentAdminNotice;
3 3
 use EventEspresso\core\exceptions\InvalidDataTypeException;
4 4
 
5
-if (!defined('EVENT_ESPRESSO_VERSION') )
5
+if ( ! defined('EVENT_ESPRESSO_VERSION'))
6 6
 	exit('NO direct script access allowed');
7 7
 
8 8
 
@@ -142,13 +142,13 @@  discard block
 block discarded – undo
142 142
      */
143 143
     private function _define_caffeinated_constants()
144 144
     {
145
-        if (! defined('EE_CORE_CAF_ADMIN')) {
146
-            define('EE_CORE_CAF_ADMIN', EE_PLUGIN_DIR_PATH . 'caffeinated/admin/');
147
-            define('EE_CORE_CAF_ADMIN_URL', EE_PLUGIN_DIR_URL . 'caffeinated/admin/');
148
-            define('EE_CORE_CAF_ADMIN_NEW', EE_CORE_CAF_ADMIN . 'new/');
149
-            define('EE_CORE_CAF_ADMIN_EXTEND', EE_CORE_CAF_ADMIN . 'extend/');
150
-            define('EE_CORE_CAF_ADMIN_EXTEND_URL', EE_CORE_CAF_ADMIN_URL . 'extend/');
151
-            define('EE_CORE_CAF_ADMIN_HOOKS', EE_CORE_CAF_ADMIN . 'hooks/');
145
+        if ( ! defined('EE_CORE_CAF_ADMIN')) {
146
+            define('EE_CORE_CAF_ADMIN', EE_PLUGIN_DIR_PATH.'caffeinated/admin/');
147
+            define('EE_CORE_CAF_ADMIN_URL', EE_PLUGIN_DIR_URL.'caffeinated/admin/');
148
+            define('EE_CORE_CAF_ADMIN_NEW', EE_CORE_CAF_ADMIN.'new/');
149
+            define('EE_CORE_CAF_ADMIN_EXTEND', EE_CORE_CAF_ADMIN.'extend/');
150
+            define('EE_CORE_CAF_ADMIN_EXTEND_URL', EE_CORE_CAF_ADMIN_URL.'extend/');
151
+            define('EE_CORE_CAF_ADMIN_HOOKS', EE_CORE_CAF_ADMIN.'hooks/');
152 152
         }
153 153
     }
154 154
 
@@ -261,7 +261,7 @@  discard block
 block discarded – undo
261 261
         //first let's order the menu groups by their internal menu order (note usort type hinting to ensure the incoming array is EE_Admin_Page_Menu_Map objects )
262 262
         usort($this->_admin_menu_groups, array($this, '_sort_menu_maps'));
263 263
         foreach ($this->_admin_menu_groups as $group) {
264
-            if (! $group instanceof EE_Admin_Page_Menu_Group) {
264
+            if ( ! $group instanceof EE_Admin_Page_Menu_Group) {
265 265
                 throw new EE_Error(
266 266
                     sprintf(
267 267
                         __(
@@ -292,7 +292,7 @@  discard block
 block discarded – undo
292 292
         $installed_refs = array();
293 293
         $exclude        = array('assets', 'templates');
294 294
         // grab everything in the  admin core directory
295
-        $admin_screens = glob(EE_ADMIN_PAGES . '*', GLOB_ONLYDIR);
295
+        $admin_screens = glob(EE_ADMIN_PAGES.'*', GLOB_ONLYDIR);
296 296
         if ($admin_screens) {
297 297
             foreach ($admin_screens as $admin_screen) {
298 298
                 // files and anything in the exclude array need not apply
@@ -307,7 +307,7 @@  discard block
 block discarded – undo
307 307
                 'There are no EE_Admin pages detected, it looks like EE did not install properly',
308 308
                 'event_espresso'
309 309
             );
310
-            $error_msg[] = $error_msg[0] . "\r\n" . sprintf(
310
+            $error_msg[] = $error_msg[0]."\r\n".sprintf(
311 311
                     __(
312 312
                         'Check that the %s folder exists and is writable. Maybe try deactivating, then reactivating Event Espresso again.',
313 313
                         'event_espresso'
@@ -319,7 +319,7 @@  discard block
 block discarded – undo
319 319
         //this just checks the caffeinated folder and takes care of setting up any caffeinated stuff.
320 320
         $installed_refs = $this->_set_caffeinated($installed_refs);
321 321
         //allow plugins to add in their own pages (note at this point they will need to have an autoloader defined for their class) OR hook into EEH_Autoloader::load_admin_page() to add their path.;
322
-        $installed_refs             = apply_filters(
322
+        $installed_refs = apply_filters(
323 323
             'FHEE__EE_Admin_Page_Loader___get_installed_pages__installed_refs',
324 324
             $installed_refs
325 325
         );
@@ -336,7 +336,7 @@  discard block
 block discarded – undo
336 336
             $this->_installed_pages[$page] = $this->_load_admin_page($page, $path);
337 337
             // verify returned object
338 338
             if ($this->_installed_pages[$page] instanceof EE_Admin_Page_Init) {
339
-                if (! $this->_installed_pages[$page]->get_menu_map() instanceof EE_Admin_Page_Menu_Map) {
339
+                if ( ! $this->_installed_pages[$page]->get_menu_map() instanceof EE_Admin_Page_Menu_Map) {
340 340
                     continue;
341 341
                 }
342 342
                 //skip if in full maintenance mode and maintenance_mode_parent is set
@@ -364,7 +364,7 @@  discard block
 block discarded – undo
364 364
                                                       . $this->_installed_pages[$page]->get_menu_map()->menu_slug
365 365
                                                       . '_'
366 366
                                                       . $this->_installed_pages[$page]->get_admin_page_name();
367
-                    $page_runtime                   = 'return "'
367
+                    $page_runtime = 'return "'
368 368
                                                       . $this->_caffeinated_extends[$this->_current_caf_extend_slug]["admin_page"]
369 369
                                                       . '";';
370 370
                     $hook_function_path = create_function('$path_to_file', $path_runtime);
@@ -425,7 +425,7 @@  discard block
 block discarded – undo
425 425
     private function _get_classname_for_admin_page($dir_name = '')
426 426
     {
427 427
         $class_name = str_replace('_', ' ', strtolower($dir_name));
428
-        return str_replace(' ', '_', ucwords($class_name)) . '_Admin_Page';
428
+        return str_replace(' ', '_', ucwords($class_name)).'_Admin_Page';
429 429
     }
430 430
 
431 431
 
@@ -440,7 +440,7 @@  discard block
 block discarded – undo
440 440
     private function _get_classname_for_admin_init_page($dir_name = '')
441 441
     {
442 442
         $class_name = str_replace('_', ' ', strtolower($dir_name));
443
-        return str_replace(' ', '_', ucwords($class_name)) . '_Admin_Page_Init';
443
+        return str_replace(' ', '_', ucwords($class_name)).'_Admin_Page_Init';
444 444
     }
445 445
 
446 446
 
@@ -458,19 +458,19 @@  discard block
 block discarded – undo
458 458
     {
459 459
         $class_name = $this->_get_classname_for_admin_init_page($page);
460 460
         EE_Registry::instance()->load_file($path, $class_name, 'core');
461
-        if (! class_exists($class_name)) {
462
-            $inner_error_msg = '<br />' . sprintf(
461
+        if ( ! class_exists($class_name)) {
462
+            $inner_error_msg = '<br />'.sprintf(
463 463
                     esc_html__(
464 464
                         'Make sure you have %1$s defined. If this is a non-EE-core admin page then you also must have an autoloader in place for your class',
465 465
                         'event_espresso'
466 466
                     ),
467
-                    '<strong>' . $class_name . '</strong>'
467
+                    '<strong>'.$class_name.'</strong>'
468 468
                 );
469
-            $error_msg[]     = sprintf(
469
+            $error_msg[] = sprintf(
470 470
                 __('Something went wrong with loading the %s admin page.', 'event_espresso'),
471 471
                 $page
472 472
             );
473
-            $error_msg[]     = $error_msg[0]
473
+            $error_msg[] = $error_msg[0]
474 474
                                . "\r\n"
475 475
                                . sprintf(
476 476
                                    esc_html__(
@@ -546,7 +546,7 @@  discard block
 block discarded – undo
546 546
                 //if we've got an array then the menu map is in the old format so let's throw a persistent notice that the admin system isn't setup correctly for this item.
547 547
                 if (is_array($page_map) || empty($page_map)) {
548 548
                       new PersistentAdminNotice(
549
-                        'menu_map_warning_' . str_replace(' ', '_', $page->label) . '_' . EVENT_ESPRESSO_VERSION,
549
+                        'menu_map_warning_'.str_replace(' ', '_', $page->label).'_'.EVENT_ESPRESSO_VERSION,
550 550
                         sprintf(
551 551
                             __(
552 552
                                 'The admin page for %s was not correctly setup because it is using an older method for integrating with Event Espresso Core.  This means that full functionality for this component is not available.  This error message usually appears with an Add-on that is out of date.  Make sure you update all your Event Espresso 4 add-ons to the latest version to ensure they have necessary compatibility updates in place.',
@@ -558,7 +558,7 @@  discard block
 block discarded – undo
558 558
                     continue;
559 559
                 }
560 560
                 //if page map is NOT a EE_Admin_Page_Menu_Map object then throw error.
561
-                if (! $page_map instanceof EE_Admin_Page_Menu_Map) {
561
+                if ( ! $page_map instanceof EE_Admin_Page_Menu_Map) {
562 562
                     throw new EE_Error(
563 563
                         sprintf(
564 564
                             __(
@@ -586,7 +586,7 @@  discard block
 block discarded – undo
586 586
         //let's sort the groups, make sure it's a valid group, add header (if to show).
587 587
         foreach ($pages_array as $group => $menu_maps) {
588 588
             //valid_group?
589
-            if (! array_key_exists($group, $menu_groups)) {
589
+            if ( ! array_key_exists($group, $menu_groups)) {
590 590
                 continue;
591 591
             }
592 592
             //sort pages.
@@ -627,13 +627,13 @@  discard block
 block discarded – undo
627 627
     {
628 628
 
629 629
         //first let's check if there IS a caffeinated folder. If there is not then lets get out.
630
-        if (! is_dir(EE_PLUGIN_DIR_PATH . 'caffeinated' . DS . 'admin') || (defined('EE_DECAF') && EE_DECAF)) {
630
+        if ( ! is_dir(EE_PLUGIN_DIR_PATH.'caffeinated'.DS.'admin') || (defined('EE_DECAF') && EE_DECAF)) {
631 631
             return $installed_refs;
632 632
         }
633 633
         $this->_define_caffeinated_constants();
634 634
         $exclude = array('tickets');
635 635
         //okay let's setup an "New" pages first (we'll return installed refs later)
636
-        $new_admin_screens = glob(EE_CORE_CAF_ADMIN . 'new/*', GLOB_ONLYDIR);
636
+        $new_admin_screens = glob(EE_CORE_CAF_ADMIN.'new/*', GLOB_ONLYDIR);
637 637
         if ($new_admin_screens) {
638 638
             foreach ($new_admin_screens as $admin_screen) {
639 639
                 // files and anything in the exclude array need not apply
@@ -650,13 +650,13 @@  discard block
 block discarded – undo
650 650
             }
651 651
         }
652 652
         //let's see if there are any EXTENDS to setup in the $_caffeinated_extends array (that will be used later for hooking into the _initialize_admin_age in the related core_init admin page)
653
-        $extends = glob(EE_CORE_CAF_ADMIN . 'extend/*', GLOB_ONLYDIR);
653
+        $extends = glob(EE_CORE_CAF_ADMIN.'extend/*', GLOB_ONLYDIR);
654 654
         if ($extends) {
655 655
             foreach ($extends as $extend) {
656 656
                 if (is_dir($extend)) {
657 657
                     $extend_ref = basename($extend);
658 658
                     //now let's make sure there is a file that matches the expected format
659
-                    $filename                                              = str_replace(
659
+                    $filename = str_replace(
660 660
                         ' ',
661 661
                         '_',
662 662
                         ucwords(
@@ -667,7 +667,7 @@  discard block
 block discarded – undo
667 667
                             )
668 668
                         )
669 669
                     );
670
-                    $filename                                              = 'Extend_' . $filename . '_Admin_Page';
670
+                    $filename                                              = 'Extend_'.$filename.'_Admin_Page';
671 671
                     $this->_caffeinated_extends[$extend_ref]['path']       = str_replace(
672 672
                         array('\\', '/'),
673 673
                         DS,
@@ -691,12 +691,12 @@  discard block
 block discarded – undo
691 691
         }
692 692
         //let's see if there are any HOOK files and instantiate them if there are (so that hooks are loaded early!).
693 693
         $ee_admin_hooks = array();
694
-        $hooks          = glob(EE_CORE_CAF_ADMIN . 'hooks/*.class.php');
694
+        $hooks          = glob(EE_CORE_CAF_ADMIN.'hooks/*.class.php');
695 695
         if ($hooks) {
696 696
             foreach ($hooks as $hook) {
697 697
                 if (is_readable($hook)) {
698 698
                     require_once $hook;
699
-                    $classname = str_replace(EE_CORE_CAF_ADMIN . 'hooks/', '', $hook);
699
+                    $classname = str_replace(EE_CORE_CAF_ADMIN.'hooks/', '', $hook);
700 700
                     $classname = str_replace('.class.php', '', $classname);
701 701
                     if (class_exists($classname)) {
702 702
                         $a                = new ReflectionClass($classname);
Please login to merge, or discard this patch.
Braces   +2 added lines, -1 removed lines patch added patch discarded remove patch
@@ -2,8 +2,9 @@
 block discarded – undo
2 2
 use EventEspresso\core\domain\entities\notifications\PersistentAdminNotice;
3 3
 use EventEspresso\core\exceptions\InvalidDataTypeException;
4 4
 
5
-if (!defined('EVENT_ESPRESSO_VERSION') )
5
+if (!defined('EVENT_ESPRESSO_VERSION') ) {
6 6
 	exit('NO direct script access allowed');
7
+}
7 8
 
8 9
 
9 10
 
Please login to merge, or discard this patch.
core/EE_Dependency_Map.core.php 1 patch
Indentation   +800 added lines, -800 removed lines patch added patch discarded remove patch
@@ -5,7 +5,7 @@  discard block
 block discarded – undo
5 5
 use EventEspresso\core\services\loaders\LoaderInterface;
6 6
 
7 7
 if (! defined('EVENT_ESPRESSO_VERSION')) {
8
-    exit('No direct script access allowed');
8
+	exit('No direct script access allowed');
9 9
 }
10 10
 
11 11
 
@@ -22,805 +22,805 @@  discard block
 block discarded – undo
22 22
 class EE_Dependency_Map
23 23
 {
24 24
 
25
-    /**
26
-     * This means that the requested class dependency is not present in the dependency map
27
-     */
28
-    const not_registered = 0;
29
-
30
-    /**
31
-     * This instructs class loaders to ALWAYS return a newly instantiated object for the requested class.
32
-     */
33
-    const load_new_object = 1;
34
-
35
-    /**
36
-     * This instructs class loaders to return a previously instantiated and cached object for the requested class.
37
-     * IF a previously instantiated object does not exist, a new one will be created and added to the cache.
38
-     */
39
-    const load_from_cache = 2;
40
-
41
-    /**
42
-     * When registering a dependency,
43
-     * this indicates to keep any existing dependencies that already exist,
44
-     * and simply discard any new dependencies declared in the incoming data
45
-     */
46
-    const KEEP_EXISTING_DEPENDENCIES = 0;
47
-
48
-    /**
49
-     * When registering a dependency,
50
-     * this indicates to overwrite any existing dependencies that already exist using the incoming data
51
-     */
52
-    const OVERWRITE_DEPENDENCIES = 1;
53
-
54
-
55
-
56
-    /**
57
-     * @type EE_Dependency_Map $_instance
58
-     */
59
-    protected static $_instance;
60
-
61
-    /**
62
-     * @type EE_Request $request
63
-     */
64
-    protected $_request;
65
-
66
-    /**
67
-     * @type EE_Response $response
68
-     */
69
-    protected $_response;
70
-
71
-    /**
72
-     * @type LoaderInterface $loader
73
-     */
74
-    protected $loader;
75
-
76
-    /**
77
-     * @type array $_dependency_map
78
-     */
79
-    protected $_dependency_map = array();
80
-
81
-    /**
82
-     * @type array $_class_loaders
83
-     */
84
-    protected $_class_loaders = array();
85
-
86
-    /**
87
-     * @type array $_aliases
88
-     */
89
-    protected $_aliases = array();
90
-
91
-
92
-
93
-    /**
94
-     * EE_Dependency_Map constructor.
95
-     *
96
-     * @param EE_Request  $request
97
-     * @param EE_Response $response
98
-     */
99
-    protected function __construct(EE_Request $request, EE_Response $response)
100
-    {
101
-        $this->_request = $request;
102
-        $this->_response = $response;
103
-        add_action('EE_Load_Espresso_Core__handle_request__initialize_core_loading', array($this, 'initialize'));
104
-        do_action('EE_Dependency_Map____construct');
105
-    }
106
-
107
-
108
-
109
-    /**
110
-     * @throws InvalidDataTypeException
111
-     * @throws InvalidInterfaceException
112
-     * @throws InvalidArgumentException
113
-     */
114
-    public function initialize()
115
-    {
116
-        $this->_register_core_dependencies();
117
-        $this->_register_core_class_loaders();
118
-        $this->_register_core_aliases();
119
-    }
120
-
121
-
122
-
123
-    /**
124
-     * @singleton method used to instantiate class object
125
-     * @access    public
126
-     * @param EE_Request  $request
127
-     * @param EE_Response $response
128
-     * @return EE_Dependency_Map
129
-     */
130
-    public static function instance(EE_Request $request = null, EE_Response $response = null)
131
-    {
132
-        // check if class object is instantiated, and instantiated properly
133
-        if (! self::$_instance instanceof EE_Dependency_Map) {
134
-            self::$_instance = new EE_Dependency_Map($request, $response);
135
-        }
136
-        return self::$_instance;
137
-    }
138
-
139
-
140
-
141
-    /**
142
-     * @param LoaderInterface $loader
143
-     */
144
-    public function setLoader(LoaderInterface $loader)
145
-    {
146
-        $this->loader = $loader;
147
-    }
148
-
149
-
150
-
151
-    /**
152
-     * @param string $class
153
-     * @param array  $dependencies
154
-     * @param int    $overwrite
155
-     * @return bool
156
-     */
157
-    public static function register_dependencies(
158
-        $class,
159
-        array $dependencies,
160
-        $overwrite = EE_Dependency_Map::KEEP_EXISTING_DEPENDENCIES
161
-    ) {
162
-        return self::$_instance->registerDependencies($class, $dependencies, $overwrite);
163
-    }
164
-
165
-
166
-
167
-    /**
168
-     * Assigns an array of class names and corresponding load sources (new or cached)
169
-     * to the class specified by the first parameter.
170
-     * IMPORTANT !!!
171
-     * The order of elements in the incoming $dependencies array MUST match
172
-     * the order of the constructor parameters for the class in question.
173
-     * This is especially important when overriding any existing dependencies that are registered.
174
-     * the third parameter controls whether any duplicate dependencies are overwritten or not.
175
-     *
176
-     * @param string $class
177
-     * @param array  $dependencies
178
-     * @param int    $overwrite
179
-     * @return bool
180
-     */
181
-    public function registerDependencies(
182
-        $class,
183
-        array $dependencies,
184
-        $overwrite = EE_Dependency_Map::KEEP_EXISTING_DEPENDENCIES
185
-    ) {
186
-        $class = trim($class, '\\');
187
-        $registered = false;
188
-        if (empty(self::$_instance->_dependency_map[ $class ])) {
189
-            self::$_instance->_dependency_map[ $class ] = array();
190
-        }
191
-        // we need to make sure that any aliases used when registering a dependency
192
-        // get resolved to the correct class name
193
-        foreach ((array)$dependencies as $dependency => $load_source) {
194
-            $alias = self::$_instance->get_alias($dependency);
195
-            if (
196
-                $overwrite === EE_Dependency_Map::OVERWRITE_DEPENDENCIES
197
-                || ! isset(self::$_instance->_dependency_map[ $class ][ $alias ])
198
-            ) {
199
-                unset($dependencies[$dependency]);
200
-                $dependencies[$alias] = $load_source;
201
-                $registered = true;
202
-            }
203
-        }
204
-        // now add our two lists of dependencies together.
205
-        // using Union (+=) favours the arrays in precedence from left to right,
206
-        // so $dependencies is NOT overwritten because it is listed first
207
-        // ie: with A = B + C, entries in B take precedence over duplicate entries in C
208
-        // Union is way faster than array_merge() but should be used with caution...
209
-        // especially with numerically indexed arrays
210
-        $dependencies += self::$_instance->_dependency_map[ $class ];
211
-        // now we need to ensure that the resulting dependencies
212
-        // array only has the entries that are required for the class
213
-        // so first count how many dependencies were originally registered for the class
214
-        $dependency_count = count(self::$_instance->_dependency_map[ $class ]);
215
-        // if that count is non-zero (meaning dependencies were already registered)
216
-        self::$_instance->_dependency_map[ $class ] = $dependency_count
217
-            // then truncate the  final array to match that count
218
-            ? array_slice($dependencies, 0, $dependency_count)
219
-            // otherwise just take the incoming array because nothing previously existed
220
-            : $dependencies;
221
-        return $registered;
222
-    }
223
-
224
-
225
-
226
-    /**
227
-     * @param string $class_name
228
-     * @param string $loader
229
-     * @return bool
230
-     * @throws DomainException
231
-     */
232
-    public static function register_class_loader($class_name, $loader = 'load_core')
233
-    {
234
-        if (! $loader instanceof Closure && strpos($class_name, '\\') !== false) {
235
-            throw new DomainException(
236
-                esc_html__('Don\'t use class loaders for FQCNs.', 'event_espresso')
237
-            );
238
-        }
239
-        // check that loader is callable or method starts with "load_" and exists in EE_Registry
240
-        if (
241
-            ! is_callable($loader)
242
-            && (
243
-                strpos($loader, 'load_') !== 0
244
-                || ! method_exists('EE_Registry', $loader)
245
-            )
246
-        ) {
247
-            throw new DomainException(
248
-                sprintf(
249
-                    esc_html__(
250
-                        '"%1$s" is not a valid loader method on EE_Registry.',
251
-                        'event_espresso'
252
-                    ),
253
-                    $loader
254
-                )
255
-            );
256
-        }
257
-        $class_name = self::$_instance->get_alias($class_name);
258
-        if (! isset(self::$_instance->_class_loaders[$class_name])) {
259
-            self::$_instance->_class_loaders[$class_name] = $loader;
260
-            return true;
261
-        }
262
-        return false;
263
-    }
264
-
265
-
266
-
267
-    /**
268
-     * @return array
269
-     */
270
-    public function dependency_map()
271
-    {
272
-        return $this->_dependency_map;
273
-    }
274
-
275
-
276
-
277
-    /**
278
-     * returns TRUE if dependency map contains a listing for the provided class name
279
-     *
280
-     * @param string $class_name
281
-     * @return boolean
282
-     */
283
-    public function has($class_name = '')
284
-    {
285
-        // all legacy models have the same dependencies
286
-        if (strpos($class_name, 'EEM_') === 0) {
287
-            $class_name = 'LEGACY_MODELS';
288
-        }
289
-        return isset($this->_dependency_map[$class_name]) ? true : false;
290
-    }
291
-
292
-
293
-
294
-    /**
295
-     * returns TRUE if dependency map contains a listing for the provided class name AND dependency
296
-     *
297
-     * @param string $class_name
298
-     * @param string $dependency
299
-     * @return bool
300
-     */
301
-    public function has_dependency_for_class($class_name = '', $dependency = '')
302
-    {
303
-        // all legacy models have the same dependencies
304
-        if (strpos($class_name, 'EEM_') === 0) {
305
-            $class_name = 'LEGACY_MODELS';
306
-        }
307
-        $dependency = $this->get_alias($dependency);
308
-        return isset($this->_dependency_map[$class_name], $this->_dependency_map[$class_name][$dependency])
309
-            ? true
310
-            : false;
311
-    }
312
-
313
-
314
-
315
-    /**
316
-     * returns loading strategy for whether a previously cached dependency should be loaded or a new instance returned
317
-     *
318
-     * @param string $class_name
319
-     * @param string $dependency
320
-     * @return int
321
-     */
322
-    public function loading_strategy_for_class_dependency($class_name = '', $dependency = '')
323
-    {
324
-        // all legacy models have the same dependencies
325
-        if (strpos($class_name, 'EEM_') === 0) {
326
-            $class_name = 'LEGACY_MODELS';
327
-        }
328
-        $dependency = $this->get_alias($dependency);
329
-        return $this->has_dependency_for_class($class_name, $dependency)
330
-            ? $this->_dependency_map[$class_name][$dependency]
331
-            : EE_Dependency_Map::not_registered;
332
-    }
333
-
334
-
335
-
336
-    /**
337
-     * @param string $class_name
338
-     * @return string | Closure
339
-     */
340
-    public function class_loader($class_name)
341
-    {
342
-        // all legacy models use load_model()
343
-        if(strpos($class_name, 'EEM_') === 0){
344
-            return 'load_model';
345
-        }
346
-        $class_name = $this->get_alias($class_name);
347
-        return isset($this->_class_loaders[$class_name]) ? $this->_class_loaders[$class_name] : '';
348
-    }
349
-
350
-
351
-
352
-    /**
353
-     * @return array
354
-     */
355
-    public function class_loaders()
356
-    {
357
-        return $this->_class_loaders;
358
-    }
359
-
360
-
361
-
362
-    /**
363
-     * adds an alias for a classname
364
-     *
365
-     * @param string $class_name the class name that should be used (concrete class to replace interface)
366
-     * @param string $alias      the class name that would be type hinted for (abstract parent or interface)
367
-     * @param string $for_class  the class that has the dependency (is type hinting for the interface)
368
-     */
369
-    public function add_alias($class_name, $alias, $for_class = '')
370
-    {
371
-        if ($for_class !== '') {
372
-            if (! isset($this->_aliases[$for_class])) {
373
-                $this->_aliases[$for_class] = array();
374
-            }
375
-            $this->_aliases[$for_class][$class_name] = $alias;
376
-        }
377
-        $this->_aliases[$class_name] = $alias;
378
-    }
379
-
380
-
381
-
382
-    /**
383
-     * returns TRUE if the provided class name has an alias
384
-     *
385
-     * @param string $class_name
386
-     * @param string $for_class
387
-     * @return bool
388
-     */
389
-    public function has_alias($class_name = '', $for_class = '')
390
-    {
391
-        return isset($this->_aliases[$for_class], $this->_aliases[$for_class][$class_name])
392
-               || (
393
-                   isset($this->_aliases[$class_name])
394
-                   && ! is_array($this->_aliases[$class_name])
395
-               );
396
-    }
397
-
398
-
399
-
400
-    /**
401
-     * returns alias for class name if one exists, otherwise returns the original classname
402
-     * functions recursively, so that multiple aliases can be used to drill down to a classname
403
-     *  for example:
404
-     *      if the following two entries were added to the _aliases array:
405
-     *          array(
406
-     *              'interface_alias'           => 'some\namespace\interface'
407
-     *              'some\namespace\interface'  => 'some\namespace\classname'
408
-     *          )
409
-     *      then one could use EE_Registry::instance()->create( 'interface_alias' )
410
-     *      to load an instance of 'some\namespace\classname'
411
-     *
412
-     * @param string $class_name
413
-     * @param string $for_class
414
-     * @return string
415
-     */
416
-    public function get_alias($class_name = '', $for_class = '')
417
-    {
418
-        if (! $this->has_alias($class_name, $for_class)) {
419
-            return $class_name;
420
-        }
421
-        if ($for_class !== '' && isset($this->_aliases[ $for_class ][ $class_name ])) {
422
-            return $this->get_alias($this->_aliases[$for_class][$class_name], $for_class);
423
-        }
424
-        return $this->get_alias($this->_aliases[$class_name]);
425
-    }
426
-
427
-
428
-
429
-    /**
430
-     * Registers the core dependencies and whether a previously instantiated object should be loaded from the cache,
431
-     * if one exists, or whether a new object should be generated every time the requested class is loaded.
432
-     * This is done by using the following class constants:
433
-     *        EE_Dependency_Map::load_from_cache - loads previously instantiated object
434
-     *        EE_Dependency_Map::load_new_object - generates a new object every time
435
-     */
436
-    protected function _register_core_dependencies()
437
-    {
438
-        $this->_dependency_map = array(
439
-            'EE_Request_Handler'                                                                                          => array(
440
-                'EE_Request' => EE_Dependency_Map::load_from_cache,
441
-            ),
442
-            'EE_System'                                                                                                   => array(
443
-                'EE_Registry'                                => EE_Dependency_Map::load_from_cache,
444
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
445
-                'EE_Capabilities'                            => EE_Dependency_Map::load_from_cache,
446
-                'EE_Request'                                 => EE_Dependency_Map::load_from_cache,
447
-                'EE_Maintenance_Mode'                        => EE_Dependency_Map::load_from_cache,
448
-            ),
449
-            'EE_Session'                                                                                                  => array(
450
-                'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
451
-                'EE_Encryption'                                           => EE_Dependency_Map::load_from_cache,
452
-            ),
453
-            'EE_Cart'                                                                                                     => array(
454
-                'EE_Session' => EE_Dependency_Map::load_from_cache,
455
-            ),
456
-            'EE_Front_Controller'                                                                                         => array(
457
-                'EE_Registry'              => EE_Dependency_Map::load_from_cache,
458
-                'EE_Request_Handler'       => EE_Dependency_Map::load_from_cache,
459
-                'EE_Module_Request_Router' => EE_Dependency_Map::load_from_cache,
460
-            ),
461
-            'EE_Messenger_Collection_Loader'                                                                              => array(
462
-                'EE_Messenger_Collection' => EE_Dependency_Map::load_new_object,
463
-            ),
464
-            'EE_Message_Type_Collection_Loader'                                                                           => array(
465
-                'EE_Message_Type_Collection' => EE_Dependency_Map::load_new_object,
466
-            ),
467
-            'EE_Message_Resource_Manager'                                                                                 => array(
468
-                'EE_Messenger_Collection_Loader'    => EE_Dependency_Map::load_new_object,
469
-                'EE_Message_Type_Collection_Loader' => EE_Dependency_Map::load_new_object,
470
-                'EEM_Message_Template_Group'        => EE_Dependency_Map::load_from_cache,
471
-            ),
472
-            'EE_Message_Factory'                                                                                          => array(
473
-                'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
474
-            ),
475
-            'EE_messages'                                                                                                 => array(
476
-                'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
477
-            ),
478
-            'EE_Messages_Generator'                                                                                       => array(
479
-                'EE_Messages_Queue'                    => EE_Dependency_Map::load_new_object,
480
-                'EE_Messages_Data_Handler_Collection'  => EE_Dependency_Map::load_new_object,
481
-                'EE_Message_Template_Group_Collection' => EE_Dependency_Map::load_new_object,
482
-                'EEH_Parse_Shortcodes'                 => EE_Dependency_Map::load_from_cache,
483
-            ),
484
-            'EE_Messages_Processor'                                                                                       => array(
485
-                'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
486
-            ),
487
-            'EE_Messages_Queue'                                                                                           => array(
488
-                'EE_Message_Repository' => EE_Dependency_Map::load_new_object,
489
-            ),
490
-            'EE_Messages_Template_Defaults'                                                                               => array(
491
-                'EEM_Message_Template_Group' => EE_Dependency_Map::load_from_cache,
492
-                'EEM_Message_Template'       => EE_Dependency_Map::load_from_cache,
493
-            ),
494
-            'EE_Message_To_Generate_From_Request'                                                                         => array(
495
-                'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
496
-                'EE_Request_Handler'          => EE_Dependency_Map::load_from_cache,
497
-            ),
498
-            'EventEspresso\core\services\commands\CommandBus'                                                             => array(
499
-                'EventEspresso\core\services\commands\CommandHandlerManager' => EE_Dependency_Map::load_from_cache,
500
-            ),
501
-            'EventEspresso\services\commands\CommandHandler'                                                              => array(
502
-                'EE_Registry'         => EE_Dependency_Map::load_from_cache,
503
-                'CommandBusInterface' => EE_Dependency_Map::load_from_cache,
504
-            ),
505
-            'EventEspresso\core\services\commands\CommandHandlerManager'                                                  => array(
506
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
507
-            ),
508
-            'EventEspresso\core\services\commands\CompositeCommandHandler'                                                => array(
509
-                'EventEspresso\core\services\commands\CommandBus'     => EE_Dependency_Map::load_from_cache,
510
-                'EventEspresso\core\services\commands\CommandFactory' => EE_Dependency_Map::load_from_cache,
511
-            ),
512
-            'EventEspresso\core\services\commands\CommandFactory'                                                         => array(
513
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
514
-            ),
515
-            'EventEspresso\core\services\commands\middleware\CapChecker'                                                  => array(
516
-                'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
517
-            ),
518
-            'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker'                                         => array(
519
-                'EE_Capabilities' => EE_Dependency_Map::load_from_cache,
520
-            ),
521
-            'EventEspresso\core\domain\services\capabilities\RegistrationsCapChecker'                                     => array(
522
-                'EE_Capabilities' => EE_Dependency_Map::load_from_cache,
523
-            ),
524
-            'EventEspresso\core\services\commands\registration\CreateRegistrationCommandHandler'                          => array(
525
-                'EventEspresso\core\domain\services\registration\CreateRegistrationService' => EE_Dependency_Map::load_from_cache,
526
-            ),
527
-            'EventEspresso\core\services\commands\registration\CopyRegistrationDetailsCommandHandler'                     => array(
528
-                'EventEspresso\core\domain\services\registration\CopyRegistrationService' => EE_Dependency_Map::load_from_cache,
529
-            ),
530
-            'EventEspresso\core\services\commands\registration\CopyRegistrationPaymentsCommandHandler'                    => array(
531
-                'EventEspresso\core\domain\services\registration\CopyRegistrationService' => EE_Dependency_Map::load_from_cache,
532
-            ),
533
-            'EventEspresso\core\services\commands\registration\CancelRegistrationAndTicketLineItemCommandHandler'         => array(
534
-                'EventEspresso\core\domain\services\registration\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
535
-            ),
536
-            'EventEspresso\core\services\commands\registration\UpdateRegistrationAndTransactionAfterChangeCommandHandler' => array(
537
-                'EventEspresso\core\domain\services\registration\UpdateRegistrationService' => EE_Dependency_Map::load_from_cache,
538
-            ),
539
-            'EventEspresso\core\services\commands\ticket\CreateTicketLineItemCommandHandler'                              => array(
540
-                'EventEspresso\core\domain\services\ticket\CreateTicketLineItemService' => EE_Dependency_Map::load_from_cache,
541
-            ),
542
-            'EventEspresso\core\services\commands\ticket\CancelTicketLineItemCommandHandler'                              => array(
543
-                'EventEspresso\core\domain\services\ticket\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
544
-            ),
545
-            'EventEspresso\core\domain\services\registration\CancelRegistrationService'                                   => array(
546
-                'EventEspresso\core\domain\services\ticket\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
547
-            ),
548
-            'EventEspresso\core\services\commands\attendee\CreateAttendeeCommandHandler'                                  => array(
549
-                'EEM_Attendee' => EE_Dependency_Map::load_from_cache,
550
-            ),
551
-            'EventEspresso\core\services\database\TableManager'                                                           => array(
552
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
553
-            ),
554
-            'EE_Data_Migration_Class_Base'                                                                                => array(
555
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
556
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
557
-            ),
558
-            'EE_DMS_Core_4_1_0'                                                                                           => array(
559
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
560
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
561
-            ),
562
-            'EE_DMS_Core_4_2_0'                                                                                           => array(
563
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
564
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
565
-            ),
566
-            'EE_DMS_Core_4_3_0'                                                                                           => array(
567
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
568
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
569
-            ),
570
-            'EE_DMS_Core_4_4_0'                                                                                           => array(
571
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
572
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
573
-            ),
574
-            'EE_DMS_Core_4_5_0'                                                                                           => array(
575
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
576
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
577
-            ),
578
-            'EE_DMS_Core_4_6_0'                                                                                           => array(
579
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
580
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
581
-            ),
582
-            'EE_DMS_Core_4_7_0'                                                                                           => array(
583
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
584
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
585
-            ),
586
-            'EE_DMS_Core_4_8_0'                                                                                           => array(
587
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
588
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
589
-            ),
590
-            'EE_DMS_Core_4_9_0'                                                                                           => array(
591
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
592
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
593
-            ),
594
-            'EventEspresso\core\services\assets\Registry'                                                                 => array(
595
-                'EE_Template_Config' => EE_Dependency_Map::load_from_cache,
596
-                'EE_Currency_Config' => EE_Dependency_Map::load_from_cache,
597
-            ),
598
-            'EventEspresso\core\domain\entities\shortcodes\EspressoCancelled'                                             => array(
599
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
600
-            ),
601
-            'EventEspresso\core\domain\entities\shortcodes\EspressoCheckout'                                              => array(
602
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
603
-            ),
604
-            'EventEspresso\core\domain\entities\shortcodes\EspressoEventAttendees'                                        => array(
605
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
606
-            ),
607
-            'EventEspresso\core\domain\entities\shortcodes\EspressoEvents'                                                => array(
608
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
609
-            ),
610
-            'EventEspresso\core\domain\entities\shortcodes\EspressoThankYou'                                              => array(
611
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
612
-            ),
613
-            'EventEspresso\core\domain\entities\shortcodes\EspressoTicketSelector'                                        => array(
614
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
615
-            ),
616
-            'EventEspresso\core\domain\entities\shortcodes\EspressoTxnPage'                                               => array(
617
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
618
-            ),
619
-            'EventEspresso\core\services\cache\BasicCacheManager'                        => array(
620
-                'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
621
-            ),
622
-            'EventEspresso\core\services\cache\PostRelatedCacheManager'                  => array(
623
-                'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
624
-            ),
625
-            'EventEspresso\core\domain\services\validation\email\EmailValidationService' => array(
626
-                'EE_Registration_Config'                                  => EE_Dependency_Map::load_from_cache,
627
-                'EventEspresso\core\services\loaders\Loader'              => EE_Dependency_Map::load_from_cache,
628
-            ),
629
-            'EventEspresso\core\domain\values\EmailAddress'                              => array(
630
-                null,
631
-                'EventEspresso\core\domain\services\validation\email\EmailValidationService' => EE_Dependency_Map::load_from_cache,
632
-            ),
633
-            'EventEspresso\core\services\orm\ModelFieldFactory' => array(
634
-                'EventEspresso\core\services\loaders\Loader'              => EE_Dependency_Map::load_from_cache,
635
-            ),
636
-            'LEGACY_MODELS'                                                   => array(
637
-                null,
638
-                'EventEspresso\core\services\database\ModelFieldFactory' => EE_Dependency_Map::load_from_cache,
639
-            ),
640
-            'EE_Module_Request_Router' => array(
641
-                'EE_Request' => EE_Dependency_Map::load_from_cache,
642
-            ),
643
-            'EE_Registration_Processor' => array(
644
-                'EE_Request' => EE_Dependency_Map::load_from_cache,
645
-            ),
646
-            'EventEspresso\core\services\notifications\PersistentAdminNoticeManager' => array(
647
-                null,
648
-                'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
649
-                'EE_Request' => EE_Dependency_Map::load_from_cache,
650
-            ),
651
-        );
652
-    }
653
-
654
-
655
-
656
-    /**
657
-     * Registers how core classes are loaded.
658
-     * This can either be done by simply providing the name of one of the EE_Registry loader methods such as:
659
-     *        'EE_Request_Handler' => 'load_core'
660
-     *        'EE_Messages_Queue'  => 'load_lib'
661
-     *        'EEH_Debug_Tools'    => 'load_helper'
662
-     * or, if greater control is required, by providing a custom closure. For example:
663
-     *        'Some_Class' => function () {
664
-     *            return new Some_Class();
665
-     *        },
666
-     * This is required for instantiating dependencies
667
-     * where an interface has been type hinted in a class constructor. For example:
668
-     *        'Required_Interface' => function () {
669
-     *            return new A_Class_That_Implements_Required_Interface();
670
-     *        },
671
-     *
672
-     * @throws InvalidInterfaceException
673
-     * @throws InvalidDataTypeException
674
-     * @throws InvalidArgumentException
675
-     */
676
-    protected function _register_core_class_loaders()
677
-    {
678
-        //for PHP5.3 compat, we need to register any properties called here in a variable because `$this` cannot
679
-        //be used in a closure.
680
-        $request = &$this->_request;
681
-        $response = &$this->_response;
682
-        // $loader = &$this->loader;
683
-        $this->_class_loaders = array(
684
-            //load_core
685
-            'EE_Capabilities'                      => 'load_core',
686
-            'EE_Encryption'                        => 'load_core',
687
-            'EE_Front_Controller'                  => 'load_core',
688
-            'EE_Module_Request_Router'             => 'load_core',
689
-            'EE_Registry'                          => 'load_core',
690
-            'EE_Request'                           => function () use (&$request) {
691
-                return $request;
692
-            },
693
-            'EE_Response'                          => function () use (&$response) {
694
-                return $response;
695
-            },
696
-            'EE_Request_Handler'                   => 'load_core',
697
-            'EE_Session'                           => 'load_core',
698
-            'EE_Cron_Tasks'                        => 'load_core',
699
-            'EE_System'                            => 'load_core',
700
-            'EE_Maintenance_Mode'                  => 'load_core',
701
-            'EE_Register_CPTs'                     => 'load_core',
702
-            'EE_Admin'                             => 'load_core',
703
-            //load_lib
704
-            'EE_Message_Resource_Manager'          => 'load_lib',
705
-            'EE_Message_Type_Collection'           => 'load_lib',
706
-            'EE_Message_Type_Collection_Loader'    => 'load_lib',
707
-            'EE_Messenger_Collection'              => 'load_lib',
708
-            'EE_Messenger_Collection_Loader'       => 'load_lib',
709
-            'EE_Messages_Processor'                => 'load_lib',
710
-            'EE_Message_Repository'                => 'load_lib',
711
-            'EE_Messages_Queue'                    => 'load_lib',
712
-            'EE_Messages_Data_Handler_Collection'  => 'load_lib',
713
-            'EE_Message_Template_Group_Collection' => 'load_lib',
714
-            'EE_Payment_Method_Manager'            => 'load_lib',
715
-            'EE_Messages_Generator'                => function () {
716
-                return EE_Registry::instance()->load_lib(
717
-                    'Messages_Generator',
718
-                    array(),
719
-                    false,
720
-                    false
721
-                );
722
-            },
723
-            'EE_Messages_Template_Defaults'        => function ($arguments = array()) {
724
-                return EE_Registry::instance()->load_lib(
725
-                    'Messages_Template_Defaults',
726
-                    $arguments,
727
-                    false,
728
-                    false
729
-                );
730
-            },
731
-            //load_model
732
-            // 'EEM_Attendee'                         => 'load_model',
733
-            // 'EEM_Message_Template_Group'           => 'load_model',
734
-            // 'EEM_Message_Template'                 => 'load_model',
735
-            //load_helper
736
-            'EEH_Parse_Shortcodes'                 => function () {
737
-                if (EE_Registry::instance()->load_helper('Parse_Shortcodes')) {
738
-                    return new EEH_Parse_Shortcodes();
739
-                }
740
-                return null;
741
-            },
742
-            'EE_Template_Config'                   => function () {
743
-                return EE_Config::instance()->template_settings;
744
-            },
745
-            'EE_Currency_Config'                   => function () {
746
-                return EE_Config::instance()->currency;
747
-            },
748
-            'EE_Registration_Config'                   => function () {
749
-                return EE_Config::instance()->registration;
750
-            },
751
-            'EventEspresso\core\services\loaders\Loader' => function () {
752
-                return LoaderFactory::getLoader();
753
-            },
754
-        );
755
-    }
756
-
757
-
758
-
759
-    /**
760
-     * can be used for supplying alternate names for classes,
761
-     * or for connecting interface names to instantiable classes
762
-     */
763
-    protected function _register_core_aliases()
764
-    {
765
-        $this->_aliases = array(
766
-            'CommandBusInterface'                                                          => 'EventEspresso\core\services\commands\CommandBusInterface',
767
-            'EventEspresso\core\services\commands\CommandBusInterface'                     => 'EventEspresso\core\services\commands\CommandBus',
768
-            'CommandHandlerManagerInterface'                                               => 'EventEspresso\core\services\commands\CommandHandlerManagerInterface',
769
-            'EventEspresso\core\services\commands\CommandHandlerManagerInterface'          => 'EventEspresso\core\services\commands\CommandHandlerManager',
770
-            'CapChecker'                                                                   => 'EventEspresso\core\services\commands\middleware\CapChecker',
771
-            'AddActionHook'                                                                => 'EventEspresso\core\services\commands\middleware\AddActionHook',
772
-            'CapabilitiesChecker'                                                          => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
773
-            'CapabilitiesCheckerInterface'                                                 => 'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface',
774
-            'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface' => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
775
-            'CreateRegistrationService'                                                    => 'EventEspresso\core\domain\services\registration\CreateRegistrationService',
776
-            'CreateRegCodeCommandHandler'                                                  => 'EventEspresso\core\services\commands\registration\CreateRegCodeCommand',
777
-            'CreateRegUrlLinkCommandHandler'                                               => 'EventEspresso\core\services\commands\registration\CreateRegUrlLinkCommand',
778
-            'CreateRegistrationCommandHandler'                                             => 'EventEspresso\core\services\commands\registration\CreateRegistrationCommand',
779
-            'CopyRegistrationDetailsCommandHandler'                                        => 'EventEspresso\core\services\commands\registration\CopyRegistrationDetailsCommand',
780
-            'CopyRegistrationPaymentsCommandHandler'                                       => 'EventEspresso\core\services\commands\registration\CopyRegistrationPaymentsCommand',
781
-            'CancelRegistrationAndTicketLineItemCommandHandler'                            => 'EventEspresso\core\services\commands\registration\CancelRegistrationAndTicketLineItemCommandHandler',
782
-            'UpdateRegistrationAndTransactionAfterChangeCommandHandler'                    => 'EventEspresso\core\services\commands\registration\UpdateRegistrationAndTransactionAfterChangeCommandHandler',
783
-            'CreateTicketLineItemCommandHandler'                                           => 'EventEspresso\core\services\commands\ticket\CreateTicketLineItemCommand',
784
-            'CreateTransactionCommandHandler'                                     => 'EventEspresso\core\services\commands\transaction\CreateTransactionCommandHandler',
785
-            'CreateAttendeeCommandHandler'                                        => 'EventEspresso\core\services\commands\attendee\CreateAttendeeCommandHandler',
786
-            'TableManager'                                                                 => 'EventEspresso\core\services\database\TableManager',
787
-            'TableAnalysis'                                                                => 'EventEspresso\core\services\database\TableAnalysis',
788
-            'EspressoShortcode'                                                            => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
789
-            'ShortcodeInterface'                                                           => 'EventEspresso\core\services\shortcodes\ShortcodeInterface',
790
-            'EventEspresso\core\services\shortcodes\ShortcodeInterface'                    => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
791
-            'EventEspresso\core\services\cache\CacheStorageInterface'                      => 'EventEspresso\core\services\cache\TransientCacheStorage',
792
-            'LoaderInterface'                                                              => 'EventEspresso\core\services\loaders\LoaderInterface',
793
-            'EventEspresso\core\services\loaders\LoaderInterface'                          => 'EventEspresso\core\services\loaders\Loader',
794
-            'CommandFactoryInterface'                                                     => 'EventEspresso\core\services\commands\CommandFactoryInterface',
795
-            'EventEspresso\core\services\commands\CommandFactoryInterface'                => 'EventEspresso\core\services\commands\CommandFactory',
796
-            'EventEspresso\core\domain\services\session\SessionIdentifierInterface'       => 'EE_Session',
797
-            'EmailValidatorInterface'                                                     => 'EventEspresso\core\domain\services\validation\email\EmailValidatorInterface',
798
-            'EventEspresso\core\domain\services\validation\email\EmailValidatorInterface' => 'EventEspresso\core\domain\services\validation\email\EmailValidationService',
799
-            'NoticeConverterInterface'                                            => 'EventEspresso\core\services\notices\NoticeConverterInterface',
800
-            'EventEspresso\core\services\notices\NoticeConverterInterface'        => 'EventEspresso\core\services\notices\ConvertNoticesToEeErrors',
801
-            'NoticesContainerInterface'                                            => 'EventEspresso\core\services\notices\NoticesContainerInterface',
802
-            'EventEspresso\core\services\notices\NoticesContainerInterface'        => 'EventEspresso\core\services\notices\NoticesContainer',
803
-        );
804
-        if (! (defined('DOING_AJAX') && DOING_AJAX) && is_admin()) {
805
-            $this->_aliases['EventEspresso\core\services\notices\NoticeConverterInterface'] = 'EventEspresso\core\services\notices\ConvertNoticesToAdminNotices';
806
-        }
807
-    }
808
-
809
-
810
-
811
-    /**
812
-     * This is used to reset the internal map and class_loaders to their original default state at the beginning of the
813
-     * request Primarily used by unit tests.
814
-     *
815
-     * @throws InvalidDataTypeException
816
-     * @throws InvalidInterfaceException
817
-     * @throws InvalidArgumentException
818
-     */
819
-    public function reset()
820
-    {
821
-        $this->_register_core_class_loaders();
822
-        $this->_register_core_dependencies();
823
-    }
25
+	/**
26
+	 * This means that the requested class dependency is not present in the dependency map
27
+	 */
28
+	const not_registered = 0;
29
+
30
+	/**
31
+	 * This instructs class loaders to ALWAYS return a newly instantiated object for the requested class.
32
+	 */
33
+	const load_new_object = 1;
34
+
35
+	/**
36
+	 * This instructs class loaders to return a previously instantiated and cached object for the requested class.
37
+	 * IF a previously instantiated object does not exist, a new one will be created and added to the cache.
38
+	 */
39
+	const load_from_cache = 2;
40
+
41
+	/**
42
+	 * When registering a dependency,
43
+	 * this indicates to keep any existing dependencies that already exist,
44
+	 * and simply discard any new dependencies declared in the incoming data
45
+	 */
46
+	const KEEP_EXISTING_DEPENDENCIES = 0;
47
+
48
+	/**
49
+	 * When registering a dependency,
50
+	 * this indicates to overwrite any existing dependencies that already exist using the incoming data
51
+	 */
52
+	const OVERWRITE_DEPENDENCIES = 1;
53
+
54
+
55
+
56
+	/**
57
+	 * @type EE_Dependency_Map $_instance
58
+	 */
59
+	protected static $_instance;
60
+
61
+	/**
62
+	 * @type EE_Request $request
63
+	 */
64
+	protected $_request;
65
+
66
+	/**
67
+	 * @type EE_Response $response
68
+	 */
69
+	protected $_response;
70
+
71
+	/**
72
+	 * @type LoaderInterface $loader
73
+	 */
74
+	protected $loader;
75
+
76
+	/**
77
+	 * @type array $_dependency_map
78
+	 */
79
+	protected $_dependency_map = array();
80
+
81
+	/**
82
+	 * @type array $_class_loaders
83
+	 */
84
+	protected $_class_loaders = array();
85
+
86
+	/**
87
+	 * @type array $_aliases
88
+	 */
89
+	protected $_aliases = array();
90
+
91
+
92
+
93
+	/**
94
+	 * EE_Dependency_Map constructor.
95
+	 *
96
+	 * @param EE_Request  $request
97
+	 * @param EE_Response $response
98
+	 */
99
+	protected function __construct(EE_Request $request, EE_Response $response)
100
+	{
101
+		$this->_request = $request;
102
+		$this->_response = $response;
103
+		add_action('EE_Load_Espresso_Core__handle_request__initialize_core_loading', array($this, 'initialize'));
104
+		do_action('EE_Dependency_Map____construct');
105
+	}
106
+
107
+
108
+
109
+	/**
110
+	 * @throws InvalidDataTypeException
111
+	 * @throws InvalidInterfaceException
112
+	 * @throws InvalidArgumentException
113
+	 */
114
+	public function initialize()
115
+	{
116
+		$this->_register_core_dependencies();
117
+		$this->_register_core_class_loaders();
118
+		$this->_register_core_aliases();
119
+	}
120
+
121
+
122
+
123
+	/**
124
+	 * @singleton method used to instantiate class object
125
+	 * @access    public
126
+	 * @param EE_Request  $request
127
+	 * @param EE_Response $response
128
+	 * @return EE_Dependency_Map
129
+	 */
130
+	public static function instance(EE_Request $request = null, EE_Response $response = null)
131
+	{
132
+		// check if class object is instantiated, and instantiated properly
133
+		if (! self::$_instance instanceof EE_Dependency_Map) {
134
+			self::$_instance = new EE_Dependency_Map($request, $response);
135
+		}
136
+		return self::$_instance;
137
+	}
138
+
139
+
140
+
141
+	/**
142
+	 * @param LoaderInterface $loader
143
+	 */
144
+	public function setLoader(LoaderInterface $loader)
145
+	{
146
+		$this->loader = $loader;
147
+	}
148
+
149
+
150
+
151
+	/**
152
+	 * @param string $class
153
+	 * @param array  $dependencies
154
+	 * @param int    $overwrite
155
+	 * @return bool
156
+	 */
157
+	public static function register_dependencies(
158
+		$class,
159
+		array $dependencies,
160
+		$overwrite = EE_Dependency_Map::KEEP_EXISTING_DEPENDENCIES
161
+	) {
162
+		return self::$_instance->registerDependencies($class, $dependencies, $overwrite);
163
+	}
164
+
165
+
166
+
167
+	/**
168
+	 * Assigns an array of class names and corresponding load sources (new or cached)
169
+	 * to the class specified by the first parameter.
170
+	 * IMPORTANT !!!
171
+	 * The order of elements in the incoming $dependencies array MUST match
172
+	 * the order of the constructor parameters for the class in question.
173
+	 * This is especially important when overriding any existing dependencies that are registered.
174
+	 * the third parameter controls whether any duplicate dependencies are overwritten or not.
175
+	 *
176
+	 * @param string $class
177
+	 * @param array  $dependencies
178
+	 * @param int    $overwrite
179
+	 * @return bool
180
+	 */
181
+	public function registerDependencies(
182
+		$class,
183
+		array $dependencies,
184
+		$overwrite = EE_Dependency_Map::KEEP_EXISTING_DEPENDENCIES
185
+	) {
186
+		$class = trim($class, '\\');
187
+		$registered = false;
188
+		if (empty(self::$_instance->_dependency_map[ $class ])) {
189
+			self::$_instance->_dependency_map[ $class ] = array();
190
+		}
191
+		// we need to make sure that any aliases used when registering a dependency
192
+		// get resolved to the correct class name
193
+		foreach ((array)$dependencies as $dependency => $load_source) {
194
+			$alias = self::$_instance->get_alias($dependency);
195
+			if (
196
+				$overwrite === EE_Dependency_Map::OVERWRITE_DEPENDENCIES
197
+				|| ! isset(self::$_instance->_dependency_map[ $class ][ $alias ])
198
+			) {
199
+				unset($dependencies[$dependency]);
200
+				$dependencies[$alias] = $load_source;
201
+				$registered = true;
202
+			}
203
+		}
204
+		// now add our two lists of dependencies together.
205
+		// using Union (+=) favours the arrays in precedence from left to right,
206
+		// so $dependencies is NOT overwritten because it is listed first
207
+		// ie: with A = B + C, entries in B take precedence over duplicate entries in C
208
+		// Union is way faster than array_merge() but should be used with caution...
209
+		// especially with numerically indexed arrays
210
+		$dependencies += self::$_instance->_dependency_map[ $class ];
211
+		// now we need to ensure that the resulting dependencies
212
+		// array only has the entries that are required for the class
213
+		// so first count how many dependencies were originally registered for the class
214
+		$dependency_count = count(self::$_instance->_dependency_map[ $class ]);
215
+		// if that count is non-zero (meaning dependencies were already registered)
216
+		self::$_instance->_dependency_map[ $class ] = $dependency_count
217
+			// then truncate the  final array to match that count
218
+			? array_slice($dependencies, 0, $dependency_count)
219
+			// otherwise just take the incoming array because nothing previously existed
220
+			: $dependencies;
221
+		return $registered;
222
+	}
223
+
224
+
225
+
226
+	/**
227
+	 * @param string $class_name
228
+	 * @param string $loader
229
+	 * @return bool
230
+	 * @throws DomainException
231
+	 */
232
+	public static function register_class_loader($class_name, $loader = 'load_core')
233
+	{
234
+		if (! $loader instanceof Closure && strpos($class_name, '\\') !== false) {
235
+			throw new DomainException(
236
+				esc_html__('Don\'t use class loaders for FQCNs.', 'event_espresso')
237
+			);
238
+		}
239
+		// check that loader is callable or method starts with "load_" and exists in EE_Registry
240
+		if (
241
+			! is_callable($loader)
242
+			&& (
243
+				strpos($loader, 'load_') !== 0
244
+				|| ! method_exists('EE_Registry', $loader)
245
+			)
246
+		) {
247
+			throw new DomainException(
248
+				sprintf(
249
+					esc_html__(
250
+						'"%1$s" is not a valid loader method on EE_Registry.',
251
+						'event_espresso'
252
+					),
253
+					$loader
254
+				)
255
+			);
256
+		}
257
+		$class_name = self::$_instance->get_alias($class_name);
258
+		if (! isset(self::$_instance->_class_loaders[$class_name])) {
259
+			self::$_instance->_class_loaders[$class_name] = $loader;
260
+			return true;
261
+		}
262
+		return false;
263
+	}
264
+
265
+
266
+
267
+	/**
268
+	 * @return array
269
+	 */
270
+	public function dependency_map()
271
+	{
272
+		return $this->_dependency_map;
273
+	}
274
+
275
+
276
+
277
+	/**
278
+	 * returns TRUE if dependency map contains a listing for the provided class name
279
+	 *
280
+	 * @param string $class_name
281
+	 * @return boolean
282
+	 */
283
+	public function has($class_name = '')
284
+	{
285
+		// all legacy models have the same dependencies
286
+		if (strpos($class_name, 'EEM_') === 0) {
287
+			$class_name = 'LEGACY_MODELS';
288
+		}
289
+		return isset($this->_dependency_map[$class_name]) ? true : false;
290
+	}
291
+
292
+
293
+
294
+	/**
295
+	 * returns TRUE if dependency map contains a listing for the provided class name AND dependency
296
+	 *
297
+	 * @param string $class_name
298
+	 * @param string $dependency
299
+	 * @return bool
300
+	 */
301
+	public function has_dependency_for_class($class_name = '', $dependency = '')
302
+	{
303
+		// all legacy models have the same dependencies
304
+		if (strpos($class_name, 'EEM_') === 0) {
305
+			$class_name = 'LEGACY_MODELS';
306
+		}
307
+		$dependency = $this->get_alias($dependency);
308
+		return isset($this->_dependency_map[$class_name], $this->_dependency_map[$class_name][$dependency])
309
+			? true
310
+			: false;
311
+	}
312
+
313
+
314
+
315
+	/**
316
+	 * returns loading strategy for whether a previously cached dependency should be loaded or a new instance returned
317
+	 *
318
+	 * @param string $class_name
319
+	 * @param string $dependency
320
+	 * @return int
321
+	 */
322
+	public function loading_strategy_for_class_dependency($class_name = '', $dependency = '')
323
+	{
324
+		// all legacy models have the same dependencies
325
+		if (strpos($class_name, 'EEM_') === 0) {
326
+			$class_name = 'LEGACY_MODELS';
327
+		}
328
+		$dependency = $this->get_alias($dependency);
329
+		return $this->has_dependency_for_class($class_name, $dependency)
330
+			? $this->_dependency_map[$class_name][$dependency]
331
+			: EE_Dependency_Map::not_registered;
332
+	}
333
+
334
+
335
+
336
+	/**
337
+	 * @param string $class_name
338
+	 * @return string | Closure
339
+	 */
340
+	public function class_loader($class_name)
341
+	{
342
+		// all legacy models use load_model()
343
+		if(strpos($class_name, 'EEM_') === 0){
344
+			return 'load_model';
345
+		}
346
+		$class_name = $this->get_alias($class_name);
347
+		return isset($this->_class_loaders[$class_name]) ? $this->_class_loaders[$class_name] : '';
348
+	}
349
+
350
+
351
+
352
+	/**
353
+	 * @return array
354
+	 */
355
+	public function class_loaders()
356
+	{
357
+		return $this->_class_loaders;
358
+	}
359
+
360
+
361
+
362
+	/**
363
+	 * adds an alias for a classname
364
+	 *
365
+	 * @param string $class_name the class name that should be used (concrete class to replace interface)
366
+	 * @param string $alias      the class name that would be type hinted for (abstract parent or interface)
367
+	 * @param string $for_class  the class that has the dependency (is type hinting for the interface)
368
+	 */
369
+	public function add_alias($class_name, $alias, $for_class = '')
370
+	{
371
+		if ($for_class !== '') {
372
+			if (! isset($this->_aliases[$for_class])) {
373
+				$this->_aliases[$for_class] = array();
374
+			}
375
+			$this->_aliases[$for_class][$class_name] = $alias;
376
+		}
377
+		$this->_aliases[$class_name] = $alias;
378
+	}
379
+
380
+
381
+
382
+	/**
383
+	 * returns TRUE if the provided class name has an alias
384
+	 *
385
+	 * @param string $class_name
386
+	 * @param string $for_class
387
+	 * @return bool
388
+	 */
389
+	public function has_alias($class_name = '', $for_class = '')
390
+	{
391
+		return isset($this->_aliases[$for_class], $this->_aliases[$for_class][$class_name])
392
+			   || (
393
+				   isset($this->_aliases[$class_name])
394
+				   && ! is_array($this->_aliases[$class_name])
395
+			   );
396
+	}
397
+
398
+
399
+
400
+	/**
401
+	 * returns alias for class name if one exists, otherwise returns the original classname
402
+	 * functions recursively, so that multiple aliases can be used to drill down to a classname
403
+	 *  for example:
404
+	 *      if the following two entries were added to the _aliases array:
405
+	 *          array(
406
+	 *              'interface_alias'           => 'some\namespace\interface'
407
+	 *              'some\namespace\interface'  => 'some\namespace\classname'
408
+	 *          )
409
+	 *      then one could use EE_Registry::instance()->create( 'interface_alias' )
410
+	 *      to load an instance of 'some\namespace\classname'
411
+	 *
412
+	 * @param string $class_name
413
+	 * @param string $for_class
414
+	 * @return string
415
+	 */
416
+	public function get_alias($class_name = '', $for_class = '')
417
+	{
418
+		if (! $this->has_alias($class_name, $for_class)) {
419
+			return $class_name;
420
+		}
421
+		if ($for_class !== '' && isset($this->_aliases[ $for_class ][ $class_name ])) {
422
+			return $this->get_alias($this->_aliases[$for_class][$class_name], $for_class);
423
+		}
424
+		return $this->get_alias($this->_aliases[$class_name]);
425
+	}
426
+
427
+
428
+
429
+	/**
430
+	 * Registers the core dependencies and whether a previously instantiated object should be loaded from the cache,
431
+	 * if one exists, or whether a new object should be generated every time the requested class is loaded.
432
+	 * This is done by using the following class constants:
433
+	 *        EE_Dependency_Map::load_from_cache - loads previously instantiated object
434
+	 *        EE_Dependency_Map::load_new_object - generates a new object every time
435
+	 */
436
+	protected function _register_core_dependencies()
437
+	{
438
+		$this->_dependency_map = array(
439
+			'EE_Request_Handler'                                                                                          => array(
440
+				'EE_Request' => EE_Dependency_Map::load_from_cache,
441
+			),
442
+			'EE_System'                                                                                                   => array(
443
+				'EE_Registry'                                => EE_Dependency_Map::load_from_cache,
444
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
445
+				'EE_Capabilities'                            => EE_Dependency_Map::load_from_cache,
446
+				'EE_Request'                                 => EE_Dependency_Map::load_from_cache,
447
+				'EE_Maintenance_Mode'                        => EE_Dependency_Map::load_from_cache,
448
+			),
449
+			'EE_Session'                                                                                                  => array(
450
+				'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
451
+				'EE_Encryption'                                           => EE_Dependency_Map::load_from_cache,
452
+			),
453
+			'EE_Cart'                                                                                                     => array(
454
+				'EE_Session' => EE_Dependency_Map::load_from_cache,
455
+			),
456
+			'EE_Front_Controller'                                                                                         => array(
457
+				'EE_Registry'              => EE_Dependency_Map::load_from_cache,
458
+				'EE_Request_Handler'       => EE_Dependency_Map::load_from_cache,
459
+				'EE_Module_Request_Router' => EE_Dependency_Map::load_from_cache,
460
+			),
461
+			'EE_Messenger_Collection_Loader'                                                                              => array(
462
+				'EE_Messenger_Collection' => EE_Dependency_Map::load_new_object,
463
+			),
464
+			'EE_Message_Type_Collection_Loader'                                                                           => array(
465
+				'EE_Message_Type_Collection' => EE_Dependency_Map::load_new_object,
466
+			),
467
+			'EE_Message_Resource_Manager'                                                                                 => array(
468
+				'EE_Messenger_Collection_Loader'    => EE_Dependency_Map::load_new_object,
469
+				'EE_Message_Type_Collection_Loader' => EE_Dependency_Map::load_new_object,
470
+				'EEM_Message_Template_Group'        => EE_Dependency_Map::load_from_cache,
471
+			),
472
+			'EE_Message_Factory'                                                                                          => array(
473
+				'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
474
+			),
475
+			'EE_messages'                                                                                                 => array(
476
+				'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
477
+			),
478
+			'EE_Messages_Generator'                                                                                       => array(
479
+				'EE_Messages_Queue'                    => EE_Dependency_Map::load_new_object,
480
+				'EE_Messages_Data_Handler_Collection'  => EE_Dependency_Map::load_new_object,
481
+				'EE_Message_Template_Group_Collection' => EE_Dependency_Map::load_new_object,
482
+				'EEH_Parse_Shortcodes'                 => EE_Dependency_Map::load_from_cache,
483
+			),
484
+			'EE_Messages_Processor'                                                                                       => array(
485
+				'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
486
+			),
487
+			'EE_Messages_Queue'                                                                                           => array(
488
+				'EE_Message_Repository' => EE_Dependency_Map::load_new_object,
489
+			),
490
+			'EE_Messages_Template_Defaults'                                                                               => array(
491
+				'EEM_Message_Template_Group' => EE_Dependency_Map::load_from_cache,
492
+				'EEM_Message_Template'       => EE_Dependency_Map::load_from_cache,
493
+			),
494
+			'EE_Message_To_Generate_From_Request'                                                                         => array(
495
+				'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
496
+				'EE_Request_Handler'          => EE_Dependency_Map::load_from_cache,
497
+			),
498
+			'EventEspresso\core\services\commands\CommandBus'                                                             => array(
499
+				'EventEspresso\core\services\commands\CommandHandlerManager' => EE_Dependency_Map::load_from_cache,
500
+			),
501
+			'EventEspresso\services\commands\CommandHandler'                                                              => array(
502
+				'EE_Registry'         => EE_Dependency_Map::load_from_cache,
503
+				'CommandBusInterface' => EE_Dependency_Map::load_from_cache,
504
+			),
505
+			'EventEspresso\core\services\commands\CommandHandlerManager'                                                  => array(
506
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
507
+			),
508
+			'EventEspresso\core\services\commands\CompositeCommandHandler'                                                => array(
509
+				'EventEspresso\core\services\commands\CommandBus'     => EE_Dependency_Map::load_from_cache,
510
+				'EventEspresso\core\services\commands\CommandFactory' => EE_Dependency_Map::load_from_cache,
511
+			),
512
+			'EventEspresso\core\services\commands\CommandFactory'                                                         => array(
513
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
514
+			),
515
+			'EventEspresso\core\services\commands\middleware\CapChecker'                                                  => array(
516
+				'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
517
+			),
518
+			'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker'                                         => array(
519
+				'EE_Capabilities' => EE_Dependency_Map::load_from_cache,
520
+			),
521
+			'EventEspresso\core\domain\services\capabilities\RegistrationsCapChecker'                                     => array(
522
+				'EE_Capabilities' => EE_Dependency_Map::load_from_cache,
523
+			),
524
+			'EventEspresso\core\services\commands\registration\CreateRegistrationCommandHandler'                          => array(
525
+				'EventEspresso\core\domain\services\registration\CreateRegistrationService' => EE_Dependency_Map::load_from_cache,
526
+			),
527
+			'EventEspresso\core\services\commands\registration\CopyRegistrationDetailsCommandHandler'                     => array(
528
+				'EventEspresso\core\domain\services\registration\CopyRegistrationService' => EE_Dependency_Map::load_from_cache,
529
+			),
530
+			'EventEspresso\core\services\commands\registration\CopyRegistrationPaymentsCommandHandler'                    => array(
531
+				'EventEspresso\core\domain\services\registration\CopyRegistrationService' => EE_Dependency_Map::load_from_cache,
532
+			),
533
+			'EventEspresso\core\services\commands\registration\CancelRegistrationAndTicketLineItemCommandHandler'         => array(
534
+				'EventEspresso\core\domain\services\registration\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
535
+			),
536
+			'EventEspresso\core\services\commands\registration\UpdateRegistrationAndTransactionAfterChangeCommandHandler' => array(
537
+				'EventEspresso\core\domain\services\registration\UpdateRegistrationService' => EE_Dependency_Map::load_from_cache,
538
+			),
539
+			'EventEspresso\core\services\commands\ticket\CreateTicketLineItemCommandHandler'                              => array(
540
+				'EventEspresso\core\domain\services\ticket\CreateTicketLineItemService' => EE_Dependency_Map::load_from_cache,
541
+			),
542
+			'EventEspresso\core\services\commands\ticket\CancelTicketLineItemCommandHandler'                              => array(
543
+				'EventEspresso\core\domain\services\ticket\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
544
+			),
545
+			'EventEspresso\core\domain\services\registration\CancelRegistrationService'                                   => array(
546
+				'EventEspresso\core\domain\services\ticket\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
547
+			),
548
+			'EventEspresso\core\services\commands\attendee\CreateAttendeeCommandHandler'                                  => array(
549
+				'EEM_Attendee' => EE_Dependency_Map::load_from_cache,
550
+			),
551
+			'EventEspresso\core\services\database\TableManager'                                                           => array(
552
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
553
+			),
554
+			'EE_Data_Migration_Class_Base'                                                                                => array(
555
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
556
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
557
+			),
558
+			'EE_DMS_Core_4_1_0'                                                                                           => array(
559
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
560
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
561
+			),
562
+			'EE_DMS_Core_4_2_0'                                                                                           => array(
563
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
564
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
565
+			),
566
+			'EE_DMS_Core_4_3_0'                                                                                           => array(
567
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
568
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
569
+			),
570
+			'EE_DMS_Core_4_4_0'                                                                                           => array(
571
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
572
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
573
+			),
574
+			'EE_DMS_Core_4_5_0'                                                                                           => array(
575
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
576
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
577
+			),
578
+			'EE_DMS_Core_4_6_0'                                                                                           => array(
579
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
580
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
581
+			),
582
+			'EE_DMS_Core_4_7_0'                                                                                           => array(
583
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
584
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
585
+			),
586
+			'EE_DMS_Core_4_8_0'                                                                                           => array(
587
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
588
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
589
+			),
590
+			'EE_DMS_Core_4_9_0'                                                                                           => array(
591
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
592
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
593
+			),
594
+			'EventEspresso\core\services\assets\Registry'                                                                 => array(
595
+				'EE_Template_Config' => EE_Dependency_Map::load_from_cache,
596
+				'EE_Currency_Config' => EE_Dependency_Map::load_from_cache,
597
+			),
598
+			'EventEspresso\core\domain\entities\shortcodes\EspressoCancelled'                                             => array(
599
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
600
+			),
601
+			'EventEspresso\core\domain\entities\shortcodes\EspressoCheckout'                                              => array(
602
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
603
+			),
604
+			'EventEspresso\core\domain\entities\shortcodes\EspressoEventAttendees'                                        => array(
605
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
606
+			),
607
+			'EventEspresso\core\domain\entities\shortcodes\EspressoEvents'                                                => array(
608
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
609
+			),
610
+			'EventEspresso\core\domain\entities\shortcodes\EspressoThankYou'                                              => array(
611
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
612
+			),
613
+			'EventEspresso\core\domain\entities\shortcodes\EspressoTicketSelector'                                        => array(
614
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
615
+			),
616
+			'EventEspresso\core\domain\entities\shortcodes\EspressoTxnPage'                                               => array(
617
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
618
+			),
619
+			'EventEspresso\core\services\cache\BasicCacheManager'                        => array(
620
+				'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
621
+			),
622
+			'EventEspresso\core\services\cache\PostRelatedCacheManager'                  => array(
623
+				'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
624
+			),
625
+			'EventEspresso\core\domain\services\validation\email\EmailValidationService' => array(
626
+				'EE_Registration_Config'                                  => EE_Dependency_Map::load_from_cache,
627
+				'EventEspresso\core\services\loaders\Loader'              => EE_Dependency_Map::load_from_cache,
628
+			),
629
+			'EventEspresso\core\domain\values\EmailAddress'                              => array(
630
+				null,
631
+				'EventEspresso\core\domain\services\validation\email\EmailValidationService' => EE_Dependency_Map::load_from_cache,
632
+			),
633
+			'EventEspresso\core\services\orm\ModelFieldFactory' => array(
634
+				'EventEspresso\core\services\loaders\Loader'              => EE_Dependency_Map::load_from_cache,
635
+			),
636
+			'LEGACY_MODELS'                                                   => array(
637
+				null,
638
+				'EventEspresso\core\services\database\ModelFieldFactory' => EE_Dependency_Map::load_from_cache,
639
+			),
640
+			'EE_Module_Request_Router' => array(
641
+				'EE_Request' => EE_Dependency_Map::load_from_cache,
642
+			),
643
+			'EE_Registration_Processor' => array(
644
+				'EE_Request' => EE_Dependency_Map::load_from_cache,
645
+			),
646
+			'EventEspresso\core\services\notifications\PersistentAdminNoticeManager' => array(
647
+				null,
648
+				'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
649
+				'EE_Request' => EE_Dependency_Map::load_from_cache,
650
+			),
651
+		);
652
+	}
653
+
654
+
655
+
656
+	/**
657
+	 * Registers how core classes are loaded.
658
+	 * This can either be done by simply providing the name of one of the EE_Registry loader methods such as:
659
+	 *        'EE_Request_Handler' => 'load_core'
660
+	 *        'EE_Messages_Queue'  => 'load_lib'
661
+	 *        'EEH_Debug_Tools'    => 'load_helper'
662
+	 * or, if greater control is required, by providing a custom closure. For example:
663
+	 *        'Some_Class' => function () {
664
+	 *            return new Some_Class();
665
+	 *        },
666
+	 * This is required for instantiating dependencies
667
+	 * where an interface has been type hinted in a class constructor. For example:
668
+	 *        'Required_Interface' => function () {
669
+	 *            return new A_Class_That_Implements_Required_Interface();
670
+	 *        },
671
+	 *
672
+	 * @throws InvalidInterfaceException
673
+	 * @throws InvalidDataTypeException
674
+	 * @throws InvalidArgumentException
675
+	 */
676
+	protected function _register_core_class_loaders()
677
+	{
678
+		//for PHP5.3 compat, we need to register any properties called here in a variable because `$this` cannot
679
+		//be used in a closure.
680
+		$request = &$this->_request;
681
+		$response = &$this->_response;
682
+		// $loader = &$this->loader;
683
+		$this->_class_loaders = array(
684
+			//load_core
685
+			'EE_Capabilities'                      => 'load_core',
686
+			'EE_Encryption'                        => 'load_core',
687
+			'EE_Front_Controller'                  => 'load_core',
688
+			'EE_Module_Request_Router'             => 'load_core',
689
+			'EE_Registry'                          => 'load_core',
690
+			'EE_Request'                           => function () use (&$request) {
691
+				return $request;
692
+			},
693
+			'EE_Response'                          => function () use (&$response) {
694
+				return $response;
695
+			},
696
+			'EE_Request_Handler'                   => 'load_core',
697
+			'EE_Session'                           => 'load_core',
698
+			'EE_Cron_Tasks'                        => 'load_core',
699
+			'EE_System'                            => 'load_core',
700
+			'EE_Maintenance_Mode'                  => 'load_core',
701
+			'EE_Register_CPTs'                     => 'load_core',
702
+			'EE_Admin'                             => 'load_core',
703
+			//load_lib
704
+			'EE_Message_Resource_Manager'          => 'load_lib',
705
+			'EE_Message_Type_Collection'           => 'load_lib',
706
+			'EE_Message_Type_Collection_Loader'    => 'load_lib',
707
+			'EE_Messenger_Collection'              => 'load_lib',
708
+			'EE_Messenger_Collection_Loader'       => 'load_lib',
709
+			'EE_Messages_Processor'                => 'load_lib',
710
+			'EE_Message_Repository'                => 'load_lib',
711
+			'EE_Messages_Queue'                    => 'load_lib',
712
+			'EE_Messages_Data_Handler_Collection'  => 'load_lib',
713
+			'EE_Message_Template_Group_Collection' => 'load_lib',
714
+			'EE_Payment_Method_Manager'            => 'load_lib',
715
+			'EE_Messages_Generator'                => function () {
716
+				return EE_Registry::instance()->load_lib(
717
+					'Messages_Generator',
718
+					array(),
719
+					false,
720
+					false
721
+				);
722
+			},
723
+			'EE_Messages_Template_Defaults'        => function ($arguments = array()) {
724
+				return EE_Registry::instance()->load_lib(
725
+					'Messages_Template_Defaults',
726
+					$arguments,
727
+					false,
728
+					false
729
+				);
730
+			},
731
+			//load_model
732
+			// 'EEM_Attendee'                         => 'load_model',
733
+			// 'EEM_Message_Template_Group'           => 'load_model',
734
+			// 'EEM_Message_Template'                 => 'load_model',
735
+			//load_helper
736
+			'EEH_Parse_Shortcodes'                 => function () {
737
+				if (EE_Registry::instance()->load_helper('Parse_Shortcodes')) {
738
+					return new EEH_Parse_Shortcodes();
739
+				}
740
+				return null;
741
+			},
742
+			'EE_Template_Config'                   => function () {
743
+				return EE_Config::instance()->template_settings;
744
+			},
745
+			'EE_Currency_Config'                   => function () {
746
+				return EE_Config::instance()->currency;
747
+			},
748
+			'EE_Registration_Config'                   => function () {
749
+				return EE_Config::instance()->registration;
750
+			},
751
+			'EventEspresso\core\services\loaders\Loader' => function () {
752
+				return LoaderFactory::getLoader();
753
+			},
754
+		);
755
+	}
756
+
757
+
758
+
759
+	/**
760
+	 * can be used for supplying alternate names for classes,
761
+	 * or for connecting interface names to instantiable classes
762
+	 */
763
+	protected function _register_core_aliases()
764
+	{
765
+		$this->_aliases = array(
766
+			'CommandBusInterface'                                                          => 'EventEspresso\core\services\commands\CommandBusInterface',
767
+			'EventEspresso\core\services\commands\CommandBusInterface'                     => 'EventEspresso\core\services\commands\CommandBus',
768
+			'CommandHandlerManagerInterface'                                               => 'EventEspresso\core\services\commands\CommandHandlerManagerInterface',
769
+			'EventEspresso\core\services\commands\CommandHandlerManagerInterface'          => 'EventEspresso\core\services\commands\CommandHandlerManager',
770
+			'CapChecker'                                                                   => 'EventEspresso\core\services\commands\middleware\CapChecker',
771
+			'AddActionHook'                                                                => 'EventEspresso\core\services\commands\middleware\AddActionHook',
772
+			'CapabilitiesChecker'                                                          => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
773
+			'CapabilitiesCheckerInterface'                                                 => 'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface',
774
+			'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface' => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
775
+			'CreateRegistrationService'                                                    => 'EventEspresso\core\domain\services\registration\CreateRegistrationService',
776
+			'CreateRegCodeCommandHandler'                                                  => 'EventEspresso\core\services\commands\registration\CreateRegCodeCommand',
777
+			'CreateRegUrlLinkCommandHandler'                                               => 'EventEspresso\core\services\commands\registration\CreateRegUrlLinkCommand',
778
+			'CreateRegistrationCommandHandler'                                             => 'EventEspresso\core\services\commands\registration\CreateRegistrationCommand',
779
+			'CopyRegistrationDetailsCommandHandler'                                        => 'EventEspresso\core\services\commands\registration\CopyRegistrationDetailsCommand',
780
+			'CopyRegistrationPaymentsCommandHandler'                                       => 'EventEspresso\core\services\commands\registration\CopyRegistrationPaymentsCommand',
781
+			'CancelRegistrationAndTicketLineItemCommandHandler'                            => 'EventEspresso\core\services\commands\registration\CancelRegistrationAndTicketLineItemCommandHandler',
782
+			'UpdateRegistrationAndTransactionAfterChangeCommandHandler'                    => 'EventEspresso\core\services\commands\registration\UpdateRegistrationAndTransactionAfterChangeCommandHandler',
783
+			'CreateTicketLineItemCommandHandler'                                           => 'EventEspresso\core\services\commands\ticket\CreateTicketLineItemCommand',
784
+			'CreateTransactionCommandHandler'                                     => 'EventEspresso\core\services\commands\transaction\CreateTransactionCommandHandler',
785
+			'CreateAttendeeCommandHandler'                                        => 'EventEspresso\core\services\commands\attendee\CreateAttendeeCommandHandler',
786
+			'TableManager'                                                                 => 'EventEspresso\core\services\database\TableManager',
787
+			'TableAnalysis'                                                                => 'EventEspresso\core\services\database\TableAnalysis',
788
+			'EspressoShortcode'                                                            => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
789
+			'ShortcodeInterface'                                                           => 'EventEspresso\core\services\shortcodes\ShortcodeInterface',
790
+			'EventEspresso\core\services\shortcodes\ShortcodeInterface'                    => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
791
+			'EventEspresso\core\services\cache\CacheStorageInterface'                      => 'EventEspresso\core\services\cache\TransientCacheStorage',
792
+			'LoaderInterface'                                                              => 'EventEspresso\core\services\loaders\LoaderInterface',
793
+			'EventEspresso\core\services\loaders\LoaderInterface'                          => 'EventEspresso\core\services\loaders\Loader',
794
+			'CommandFactoryInterface'                                                     => 'EventEspresso\core\services\commands\CommandFactoryInterface',
795
+			'EventEspresso\core\services\commands\CommandFactoryInterface'                => 'EventEspresso\core\services\commands\CommandFactory',
796
+			'EventEspresso\core\domain\services\session\SessionIdentifierInterface'       => 'EE_Session',
797
+			'EmailValidatorInterface'                                                     => 'EventEspresso\core\domain\services\validation\email\EmailValidatorInterface',
798
+			'EventEspresso\core\domain\services\validation\email\EmailValidatorInterface' => 'EventEspresso\core\domain\services\validation\email\EmailValidationService',
799
+			'NoticeConverterInterface'                                            => 'EventEspresso\core\services\notices\NoticeConverterInterface',
800
+			'EventEspresso\core\services\notices\NoticeConverterInterface'        => 'EventEspresso\core\services\notices\ConvertNoticesToEeErrors',
801
+			'NoticesContainerInterface'                                            => 'EventEspresso\core\services\notices\NoticesContainerInterface',
802
+			'EventEspresso\core\services\notices\NoticesContainerInterface'        => 'EventEspresso\core\services\notices\NoticesContainer',
803
+		);
804
+		if (! (defined('DOING_AJAX') && DOING_AJAX) && is_admin()) {
805
+			$this->_aliases['EventEspresso\core\services\notices\NoticeConverterInterface'] = 'EventEspresso\core\services\notices\ConvertNoticesToAdminNotices';
806
+		}
807
+	}
808
+
809
+
810
+
811
+	/**
812
+	 * This is used to reset the internal map and class_loaders to their original default state at the beginning of the
813
+	 * request Primarily used by unit tests.
814
+	 *
815
+	 * @throws InvalidDataTypeException
816
+	 * @throws InvalidInterfaceException
817
+	 * @throws InvalidArgumentException
818
+	 */
819
+	public function reset()
820
+	{
821
+		$this->_register_core_class_loaders();
822
+		$this->_register_core_dependencies();
823
+	}
824 824
 
825 825
 
826 826
 }
Please login to merge, or discard this patch.
modules/core_rest_api/EED_Core_Rest_Api.module.php 1 patch
Indentation   +1295 added lines, -1295 removed lines patch added patch discarded remove patch
@@ -24,1302 +24,1302 @@
 block discarded – undo
24 24
 class EED_Core_Rest_Api extends \EED_Module
25 25
 {
26 26
 
27
-    const ee_api_namespace           = 'ee/v';
27
+	const ee_api_namespace           = 'ee/v';
28 28
 
29
-    const ee_api_namespace_for_regex = 'ee\/v([^/]*)\/';
30
-
31
-    const saved_routes_option_names  = 'ee_core_routes';
32
-
33
-    /**
34
-     * string used in _links response bodies to make them globally unique.
35
-     *
36
-     * @see http://v2.wp-api.org/extending/linking/
37
-     */
38
-    const ee_api_link_namespace = 'https://api.eventespresso.com/';
39
-
40
-    /**
41
-     * @var CalculatedModelFields
42
-     */
43
-    protected static $_field_calculator;
44
-
45
-
46
-
47
-    /**
48
-     * @return EED_Core_Rest_Api|EED_Module
49
-     */
50
-    public static function instance()
51
-    {
52
-        self::$_field_calculator = new CalculatedModelFields();
53
-        return parent::get_instance(__CLASS__);
54
-    }
55
-
56
-
57
-
58
-    /**
59
-     *    set_hooks - for hooking into EE Core, other modules, etc
60
-     *
61
-     * @access    public
62
-     * @return    void
63
-     */
64
-    public static function set_hooks()
65
-    {
66
-        self::set_hooks_both();
67
-    }
68
-
69
-
70
-
71
-    /**
72
-     *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
73
-     *
74
-     * @access    public
75
-     * @return    void
76
-     */
77
-    public static function set_hooks_admin()
78
-    {
79
-        self::set_hooks_both();
80
-    }
81
-
82
-
83
-
84
-    public static function set_hooks_both()
85
-    {
86
-        add_action('rest_api_init', array('EED_Core_Rest_Api', 'register_routes'), 10);
87
-        add_action('rest_api_init', array('EED_Core_Rest_Api', 'set_hooks_rest_api'), 5);
88
-        add_filter('rest_route_data', array('EED_Core_Rest_Api', 'hide_old_endpoints'), 10, 2);
89
-        add_filter('rest_index',
90
-            array('EventEspresso\core\libraries\rest_api\controllers\model\Meta', 'filterEeMetadataIntoIndex'));
91
-        EED_Core_Rest_Api::invalidate_cached_route_data_on_version_change();
92
-    }
93
-
94
-
95
-
96
-    /**
97
-     * sets up hooks which only need to be included as part of REST API requests;
98
-     * other requests like to the frontend or admin etc don't need them
99
-     *
100
-     * @throws \EE_Error
101
-     */
102
-    public static function set_hooks_rest_api()
103
-    {
104
-        //set hooks which account for changes made to the API
105
-        EED_Core_Rest_Api::_set_hooks_for_changes();
106
-    }
107
-
108
-
109
-
110
-    /**
111
-     * public wrapper of _set_hooks_for_changes.
112
-     * Loads all the hooks which make requests to old versions of the API
113
-     * appear the same as they always did
114
-     *
115
-     * @throws EE_Error
116
-     */
117
-    public static function set_hooks_for_changes()
118
-    {
119
-        self::_set_hooks_for_changes();
120
-    }
121
-
122
-
123
-
124
-    /**
125
-     * If the user appears to be using WP API basic auth, tell them (via a persistent
126
-     * admin notice and an email) that we're going to remove it soon, so they should
127
-     * replace it with application passwords.
128
-     *
129
-     * @throws InvalidDataTypeException
130
-     */
131
-    public static function maybe_notify_of_basic_auth_removal()
132
-    {
133
-        if (
134
-        apply_filters(
135
-            'FHEE__EED_Core_Rest_Api__maybe_notify_of_basic_auth_removal__override',
136
-            ! isset($_SERVER['PHP_AUTH_USER'])
137
-            && ! isset($_SERVER['HTTP_AUTHORIZATION'])
138
-        )
139
-        ) {
140
-            //sure it's a WP API request, but they aren't using basic auth, so don't bother them
141
-            return;
142
-        }
143
-        //ok they're using the WP API with Basic Auth
144
-        new PersistentAdminNotice(
145
-            'using_basic_auth',
146
-            sprintf(
147
-                __(
148
-                    'We noticed you\'re using the WP API, which is used by the Event Espresso 4 mobile apps. Because of security and compatibility concerns, we will soon be removing our default authentication mechanism, WP API Basic Auth, from Event Espresso. It is recommended you instead install the %1$sWP Application Passwords plugin%2$s and use it with the EE4 Mobile apps. See %3$sour mobile app documentation%2$s for more information. %4$sIf you have installed the WP API Basic Auth plugin separately, or are not using the Event Espresso 4 mobile apps, you can disregard this message.%4$sThe Event Espresso Team',
149
-                    'event_espresso'
150
-                ),
151
-                '<a href="https://wordpress.org/plugins/application-passwords/">',
152
-                '</a>',
153
-                '<a href="https://eventespresso.com/wiki/ee4-event-apps/#authentication">',
154
-                '<br/>'
155
-            )
156
-        );
157
-        if ( ! get_option('ee_notified_admin_on_basic_auth_removal', false)) {
158
-            add_option('ee_notified_admin_on_basic_auth_removal', true);
159
-            //piggy back off EE_Error::set_content_type, which sets the content type to HTML
160
-            add_filter('wp_mail_content_type', array('EE_Error', 'set_content_type'));
161
-            //and send the message to the site admin too
162
-            wp_mail(get_option('admin_email'),
163
-                __('Notice of Removal of WP API Basic Auth From Event Espresso 4', 'event_espresso'), $message);
164
-            remove_filter('wp_mail_content_type', array('EE_Error', 'set_content_type'));
165
-        }
166
-    }
167
-
168
-
169
-
170
-    /**
171
-     * Loads all the hooks which make requests to old versions of the API
172
-     * appear the same as they always did
173
-     *
174
-     * @throws EE_Error
175
-     */
176
-    protected static function _set_hooks_for_changes()
177
-    {
178
-        $folder_contents = EEH_File::get_contents_of_folders(array(EE_LIBRARIES . 'rest_api' . DS . 'changes'), false);
179
-        foreach ($folder_contents as $classname_in_namespace => $filepath) {
180
-            //ignore the base parent class
181
-            //and legacy named classes
182
-            if ($classname_in_namespace === 'ChangesInBase'
183
-                || strpos($classname_in_namespace, 'Changes_In_') === 0
184
-            ) {
185
-                continue;
186
-            }
187
-            $full_classname = 'EventEspresso\core\libraries\rest_api\changes\\' . $classname_in_namespace;
188
-            if (class_exists($full_classname)) {
189
-                $instance_of_class = new $full_classname;
190
-                if ($instance_of_class instanceof ChangesInBase) {
191
-                    $instance_of_class->setHooks();
192
-                }
193
-            }
194
-        }
195
-    }
196
-
197
-
198
-
199
-    /**
200
-     * Filters the WP routes to add our EE-related ones. This takes a bit of time
201
-     * so we actually prefer to only do it when an EE plugin is activated or upgraded
202
-     *
203
-     * @throws \EE_Error
204
-     */
205
-    public static function register_routes()
206
-    {
207
-        foreach (EED_Core_Rest_Api::get_ee_route_data() as $namespace => $relative_routes) {
208
-            foreach ($relative_routes as $relative_route => $data_for_multiple_endpoints) {
209
-                /**
210
-                 * @var array $data_for_multiple_endpoints numerically indexed array
211
-                 *                                         but can also contain route options like {
212
-                 * @type array    $schema                      {
213
-                 * @type callable $schema_callback
214
-                 * @type array    $callback_args               arguments that will be passed to the callback, after the
215
-                 * WP_REST_Request of course
216
-                 * }
217
-                 * }
218
-                 */
219
-                //when registering routes, register all the endpoints' data at the same time
220
-                $multiple_endpoint_args = array();
221
-                foreach ($data_for_multiple_endpoints as $endpoint_key => $data_for_single_endpoint) {
222
-                    /**
223
-                     * @var array     $data_for_single_endpoint {
224
-                     * @type callable $callback
225
-                     * @type string methods
226
-                     * @type array args
227
-                     * @type array _links
228
-                     * @type array    $callback_args            arguments that will be passed to the callback, after the
229
-                     * WP_REST_Request of course
230
-                     * }
231
-                     */
232
-                    //skip route options
233
-                    if (! is_numeric($endpoint_key)) {
234
-                        continue;
235
-                    }
236
-                    if (! isset($data_for_single_endpoint['callback'], $data_for_single_endpoint['methods'])) {
237
-                        throw new EE_Error(
238
-                            esc_html__(
239
-                                // @codingStandardsIgnoreStart
240
-                                'Endpoint configuration data needs to have entries "callback" (callable) and "methods" (comma-separated list of accepts HTTP methods).',
241
-                                // @codingStandardsIgnoreEnd
242
-                                'event_espresso')
243
-                        );
244
-                    }
245
-                    $callback = $data_for_single_endpoint['callback'];
246
-                    $single_endpoint_args = array(
247
-                        'methods' => $data_for_single_endpoint['methods'],
248
-                        'args'    => isset($data_for_single_endpoint['args']) ? $data_for_single_endpoint['args']
249
-                            : array(),
250
-                    );
251
-                    if (isset($data_for_single_endpoint['_links'])) {
252
-                        $single_endpoint_args['_links'] = $data_for_single_endpoint['_links'];
253
-                    }
254
-                    if (isset($data_for_single_endpoint['callback_args'])) {
255
-                        $callback_args = $data_for_single_endpoint['callback_args'];
256
-                        $single_endpoint_args['callback'] = function (\WP_REST_Request $request) use (
257
-                            $callback,
258
-                            $callback_args
259
-                        ) {
260
-                            array_unshift($callback_args, $request);
261
-                            return call_user_func_array(
262
-                                $callback,
263
-                                $callback_args
264
-                            );
265
-                        };
266
-                    } else {
267
-                        $single_endpoint_args['callback'] = $data_for_single_endpoint['callback'];
268
-                    }
269
-                    $multiple_endpoint_args[] = $single_endpoint_args;
270
-                }
271
-                if (isset($data_for_multiple_endpoints['schema'])) {
272
-                    $schema_route_data = $data_for_multiple_endpoints['schema'];
273
-                    $schema_callback = $schema_route_data['schema_callback'];
274
-                    $callback_args = $schema_route_data['callback_args'];
275
-                    $multiple_endpoint_args['schema'] = function () use ($schema_callback, $callback_args) {
276
-                        return call_user_func_array(
277
-                            $schema_callback,
278
-                            $callback_args
279
-                        );
280
-                    };
281
-                }
282
-                register_rest_route(
283
-                    $namespace,
284
-                    $relative_route,
285
-                    $multiple_endpoint_args
286
-                );
287
-            }
288
-        }
289
-    }
290
-
291
-
292
-
293
-    /**
294
-     * Checks if there was a version change or something that merits invalidating the cached
295
-     * route data. If so, invalidates the cached route data so that it gets refreshed
296
-     * next time the WP API is used
297
-     */
298
-    public static function invalidate_cached_route_data_on_version_change()
299
-    {
300
-        if (EE_System::instance()->detect_req_type() !== EE_System::req_type_normal) {
301
-            EED_Core_Rest_Api::invalidate_cached_route_data();
302
-        }
303
-        foreach (EE_Registry::instance()->addons as $addon) {
304
-            if ($addon instanceof EE_Addon && $addon->detect_req_type() !== EE_System::req_type_normal) {
305
-                EED_Core_Rest_Api::invalidate_cached_route_data();
306
-            }
307
-        }
308
-    }
309
-
310
-
311
-
312
-    /**
313
-     * Removes the cached route data so it will get refreshed next time the WP API is used
314
-     */
315
-    public static function invalidate_cached_route_data()
316
-    {
317
-        //delete the saved EE REST API routes
318
-        foreach (EED_Core_Rest_Api::versions_served() as $version => $hidden) {
319
-            delete_option(EED_Core_Rest_Api::saved_routes_option_names . $version);
320
-        }
321
-    }
322
-
323
-
324
-
325
-    /**
326
-     * Gets the EE route data
327
-     *
328
-     * @return array top-level key is the namespace, next-level key is the route and its value is array{
329
-     * @throws \EE_Error
330
-     * @type string|array $callback
331
-     * @type string       $methods
332
-     * @type boolean      $hidden_endpoint
333
-     * }
334
-     */
335
-    public static function get_ee_route_data()
336
-    {
337
-        $ee_routes = array();
338
-        foreach (self::versions_served() as $version => $hidden_endpoints) {
339
-            $ee_routes[self::ee_api_namespace . $version] = self::_get_ee_route_data_for_version(
340
-                $version,
341
-                $hidden_endpoints
342
-            );
343
-        }
344
-        return $ee_routes;
345
-    }
346
-
347
-
348
-
349
-    /**
350
-     * Gets the EE route data from the wp options if it exists already,
351
-     * otherwise re-generates it and saves it to the option
352
-     *
353
-     * @param string  $version
354
-     * @param boolean $hidden_endpoints
355
-     * @return array
356
-     * @throws \EE_Error
357
-     */
358
-    protected static function _get_ee_route_data_for_version($version, $hidden_endpoints = false)
359
-    {
360
-        $ee_routes = get_option(self::saved_routes_option_names . $version, null);
361
-        if (! $ee_routes || (defined('EE_REST_API_DEBUG_MODE') && EE_REST_API_DEBUG_MODE)) {
362
-            $ee_routes = self::_save_ee_route_data_for_version($version, $hidden_endpoints);
363
-        }
364
-        return $ee_routes;
365
-    }
366
-
367
-
368
-
369
-    /**
370
-     * Saves the EE REST API route data to a wp option and returns it
371
-     *
372
-     * @param string  $version
373
-     * @param boolean $hidden_endpoints
374
-     * @return mixed|null
375
-     * @throws \EE_Error
376
-     */
377
-    protected static function _save_ee_route_data_for_version($version, $hidden_endpoints = false)
378
-    {
379
-        $instance = self::instance();
380
-        $routes = apply_filters(
381
-            'EED_Core_Rest_Api__save_ee_route_data_for_version__routes',
382
-            array_replace_recursive(
383
-                $instance->_get_config_route_data_for_version($version, $hidden_endpoints),
384
-                $instance->_get_meta_route_data_for_version($version, $hidden_endpoints),
385
-                $instance->_get_model_route_data_for_version($version, $hidden_endpoints),
386
-                $instance->_get_rpc_route_data_for_version($version, $hidden_endpoints)
387
-            )
388
-        );
389
-        $option_name = self::saved_routes_option_names . $version;
390
-        if (get_option($option_name)) {
391
-            update_option($option_name, $routes, true);
392
-        } else {
393
-            add_option($option_name, $routes, null, 'no');
394
-        }
395
-        return $routes;
396
-    }
397
-
398
-
399
-
400
-    /**
401
-     * Calculates all the EE routes and saves it to a WordPress option so we don't
402
-     * need to calculate it on every request
403
-     *
404
-     * @deprecated since version 4.9.1
405
-     * @return void
406
-     */
407
-    public static function save_ee_routes()
408
-    {
409
-        if (EE_Maintenance_Mode::instance()->models_can_query()) {
410
-            $instance = self::instance();
411
-            $routes = apply_filters(
412
-                'EED_Core_Rest_Api__save_ee_routes__routes',
413
-                array_replace_recursive(
414
-                    $instance->_register_config_routes(),
415
-                    $instance->_register_meta_routes(),
416
-                    $instance->_register_model_routes(),
417
-                    $instance->_register_rpc_routes()
418
-                )
419
-            );
420
-            update_option(self::saved_routes_option_names, $routes, true);
421
-        }
422
-    }
423
-
424
-
425
-
426
-    /**
427
-     * Gets all the route information relating to EE models
428
-     *
429
-     * @return array @see get_ee_route_data
430
-     * @deprecated since version 4.9.1
431
-     */
432
-    protected function _register_model_routes()
433
-    {
434
-        $model_routes = array();
435
-        foreach (self::versions_served() as $version => $hidden_endpoint) {
436
-            $model_routes[EED_Core_Rest_Api::ee_api_namespace
437
-                          . $version] = $this->_get_config_route_data_for_version($version, $hidden_endpoint);
438
-        }
439
-        return $model_routes;
440
-    }
441
-
442
-
443
-
444
-    /**
445
-     * Decides whether or not to add write endpoints for this model.
446
-     *
447
-     * Currently, this defaults to exclude all global tables and models
448
-     * which would allow inserting WP core data (we don't want to duplicate
449
-     * what WP API does, as it's unnecessary, extra work, and potentially extra bugs)
450
-     * @param EEM_Base $model
451
-     * @return bool
452
-     */
453
-    public static function should_have_write_endpoints(EEM_Base $model)
454
-    {
455
-        if ($model->is_wp_core_model()){
456
-            return false;
457
-        }
458
-        foreach($model->get_tables() as $table){
459
-            if( $table->is_global()){
460
-                return false;
461
-            }
462
-        }
463
-        return true;
464
-    }
465
-
466
-
467
-
468
-    /**
469
-     * Gets the names of all models which should have plural routes (eg `ee/v4.8.36/events`)
470
-     * in this versioned namespace of EE4
471
-     * @param $version
472
-     * @return array keys are model names (eg 'Event') and values ar either classnames (eg 'EEM_Event')
473
-     */
474
-    public static function model_names_with_plural_routes($version){
475
-        $model_version_info = new ModelVersionInfo($version);
476
-        $models_to_register = $model_version_info->modelsForRequestedVersion();
477
-        //let's not bother having endpoints for extra metas
478
-        unset(
479
-            $models_to_register['Extra_Meta'],
480
-            $models_to_register['Extra_Join'],
481
-            $models_to_register['Post_Meta']
482
-        );
483
-        return apply_filters(
484
-            'FHEE__EED_Core_REST_API___register_model_routes',
485
-            $models_to_register
486
-        );
487
-    }
488
-
489
-
490
-
491
-    /**
492
-     * Gets the route data for EE models in the specified version
493
-     *
494
-     * @param string  $version
495
-     * @param boolean $hidden_endpoint
496
-     * @return array
497
-     * @throws EE_Error
498
-     */
499
-    protected function _get_model_route_data_for_version($version, $hidden_endpoint = false)
500
-    {
501
-        $model_routes = array();
502
-        $model_version_info = new ModelVersionInfo($version);
503
-        foreach (EED_Core_Rest_Api::model_names_with_plural_routes($version) as $model_name => $model_classname) {
504
-            $model = \EE_Registry::instance()->load_model($model_name);
505
-            //if this isn't a valid model then let's skip iterate to the next item in the loop.
506
-            if (! $model instanceof EEM_Base) {
507
-                continue;
508
-            }
509
-            //yes we could just register one route for ALL models, but then they wouldn't show up in the index
510
-            $plural_model_route = EED_Core_Rest_Api::get_collection_route($model);
511
-            $singular_model_route = EED_Core_Rest_Api::get_entity_route($model, '(?P<id>[^\/]+)');
512
-            $model_routes[$plural_model_route] = array(
513
-                array(
514
-                    'callback'        => array(
515
-                        'EventEspresso\core\libraries\rest_api\controllers\model\Read',
516
-                        'handleRequestGetAll',
517
-                    ),
518
-                    'callback_args'   => array($version, $model_name),
519
-                    'methods'         => WP_REST_Server::READABLE,
520
-                    'hidden_endpoint' => $hidden_endpoint,
521
-                    'args'            => $this->_get_read_query_params($model, $version),
522
-                    '_links'          => array(
523
-                        'self' => rest_url(EED_Core_Rest_Api::ee_api_namespace . $version . $singular_model_route),
524
-                    ),
525
-                ),
526
-                'schema' => array(
527
-                    'schema_callback' => array(
528
-                        'EventEspresso\core\libraries\rest_api\controllers\model\Read',
529
-                        'handleSchemaRequest',
530
-                    ),
531
-                    'callback_args'   => array($version, $model_name),
532
-                ),
533
-            );
534
-            $model_routes[$singular_model_route] = array(
535
-                array(
536
-                    'callback'        => array(
537
-                        'EventEspresso\core\libraries\rest_api\controllers\model\Read',
538
-                        'handleRequestGetOne',
539
-                    ),
540
-                    'callback_args'   => array($version, $model_name),
541
-                    'methods'         => WP_REST_Server::READABLE,
542
-                    'hidden_endpoint' => $hidden_endpoint,
543
-                    'args'            => $this->_get_response_selection_query_params($model, $version),
544
-                ),
545
-            );
546
-            if( apply_filters(
547
-                'FHEE__EED_Core_Rest_Api___get_model_route_data_for_version__add_write_endpoints',
548
-                EED_Core_Rest_Api::should_have_write_endpoints($model),
549
-                $model
550
-            )){
551
-                $model_routes[$plural_model_route][] = array(
552
-                    'callback'        => array(
553
-                        'EventEspresso\core\libraries\rest_api\controllers\model\Write',
554
-                        'handleRequestInsert',
555
-                    ),
556
-                    'callback_args'   => array($version, $model_name),
557
-                    'methods'         => WP_REST_Server::CREATABLE,
558
-                    'hidden_endpoint' => $hidden_endpoint,
559
-                    'args'            => $this->_get_write_params($model_name, $model_version_info, true),
560
-                );
561
-                $model_routes[$singular_model_route] = array_merge(
562
-                    $model_routes[$singular_model_route],
563
-                    array(
564
-                        array(
565
-                            'callback'        => array(
566
-                                'EventEspresso\core\libraries\rest_api\controllers\model\Write',
567
-                                'handleRequestUpdate',
568
-                            ),
569
-                            'callback_args'   => array($version, $model_name),
570
-                            'methods'         => WP_REST_Server::EDITABLE,
571
-                            'hidden_endpoint' => $hidden_endpoint,
572
-                            'args'            => $this->_get_write_params($model_name, $model_version_info),
573
-                        ),
574
-                        array(
575
-                            'callback'        => array(
576
-                                'EventEspresso\core\libraries\rest_api\controllers\model\Write',
577
-                                'handleRequestDelete',
578
-                            ),
579
-                            'callback_args'   => array($version, $model_name),
580
-                            'methods'         => WP_REST_Server::DELETABLE,
581
-                            'hidden_endpoint' => $hidden_endpoint,
582
-                            'args'            => $this->_get_delete_query_params($model, $version),
583
-                        )
584
-                    )
585
-                );
586
-            }
587
-            foreach ($model->relation_settings() as $relation_name => $relation_obj) {
588
-
589
-                $related_route = EED_Core_Rest_Api::get_relation_route_via(
590
-                    $model,
591
-                    '(?P<id>[^\/]+)',
592
-                    $relation_obj
593
-                );
594
-                $endpoints = array(
595
-                    array(
596
-                        'callback'        => array(
597
-                            'EventEspresso\core\libraries\rest_api\controllers\model\Read',
598
-                            'handleRequestGetRelated',
599
-                        ),
600
-                        'callback_args'   => array($version, $model_name, $relation_name),
601
-                        'methods'         => WP_REST_Server::READABLE,
602
-                        'hidden_endpoint' => $hidden_endpoint,
603
-                        'args'            => $this->_get_read_query_params($relation_obj->get_other_model(), $version),
604
-                    ),
605
-                );
606
-                $model_routes[$related_route] = $endpoints;
607
-            }
608
-        }
609
-        return $model_routes;
610
-    }
611
-
612
-
613
-
614
-    /**
615
-     * Gets the relative URI to a model's REST API plural route, after the EE4 versioned namespace,
616
-     * excluding the preceding slash.
617
-     * Eg you pass get_plural_route_to('Event') = 'events'
618
-     *
619
-     * @param EEM_Base $model
620
-     * @return string
621
-     */
622
-    public static function get_collection_route(EEM_Base $model)
623
-    {
624
-        return EEH_Inflector::pluralize_and_lower($model->get_this_model_name());
625
-    }
626
-
627
-
628
-
629
-    /**
630
-     * Gets the relative URI to a model's REST API singular route, after the EE4 versioned namespace,
631
-     * excluding the preceding slash.
632
-     * Eg you pass get_plural_route_to('Event', 12) = 'events/12'
633
-     *
634
-     * @param EEM_Base $model eg Event or Venue
635
-     * @param string $id
636
-     * @return string
637
-     */
638
-    public static function get_entity_route($model, $id)
639
-    {
640
-        return EED_Core_Rest_Api::get_collection_route($model). '/' . $id;
641
-    }
642
-
643
-
644
-    /**
645
-     * Gets the relative URI to a model's REST API singular route, after the EE4 versioned namespace,
646
-     * excluding the preceding slash.
647
-     * Eg you pass get_plural_route_to('Event', 12) = 'events/12'
648
-     *
649
-     * @param EEM_Base                 $model eg Event or Venue
650
-     * @param string                 $id
651
-     * @param EE_Model_Relation_Base $relation_obj
652
-     * @return string
653
-     */
654
-    public static function get_relation_route_via(EEM_Base $model, $id, EE_Model_Relation_Base $relation_obj)
655
-    {
656
-        $related_model_name_endpoint_part = ModelRead::getRelatedEntityName(
657
-            $relation_obj->get_other_model()->get_this_model_name(),
658
-            $relation_obj
659
-        );
660
-        return EED_Core_Rest_Api::get_entity_route($model, $id) . '/' . $related_model_name_endpoint_part;
661
-    }
662
-
663
-
664
-
665
-    /**
666
-     * Adds onto the $relative_route the EE4 REST API versioned namespace.
667
-     * Eg if given '4.8.36' and 'events', will return 'ee/v4.8.36/events'
668
-     * @param string $relative_route
669
-     * @param string $version
670
-     * @return string
671
-     */
672
-    public static function get_versioned_route_to($relative_route, $version = '4.8.36'){
673
-        return '/' . EED_Core_Rest_Api::ee_api_namespace . $version . '/' . $relative_route;
674
-    }
675
-
676
-
677
-
678
-    /**
679
-     * Adds all the RPC-style routes (remote procedure call-like routes, ie
680
-     * routes that don't conform to the traditional REST CRUD-style).
681
-     *
682
-     * @deprecated since 4.9.1
683
-     */
684
-    protected function _register_rpc_routes()
685
-    {
686
-        $routes = array();
687
-        foreach (self::versions_served() as $version => $hidden_endpoint) {
688
-            $routes[self::ee_api_namespace . $version] = $this->_get_rpc_route_data_for_version(
689
-                $version,
690
-                $hidden_endpoint
691
-            );
692
-        }
693
-        return $routes;
694
-    }
695
-
696
-
697
-
698
-    /**
699
-     * @param string  $version
700
-     * @param boolean $hidden_endpoint
701
-     * @return array
702
-     */
703
-    protected function _get_rpc_route_data_for_version($version, $hidden_endpoint = false)
704
-    {
705
-        $this_versions_routes = array();
706
-        //checkin endpoint
707
-        $this_versions_routes['registrations/(?P<REG_ID>\d+)/toggle_checkin_for_datetime/(?P<DTT_ID>\d+)'] = array(
708
-            array(
709
-                'callback'        => array(
710
-                    'EventEspresso\core\libraries\rest_api\controllers\rpc\Checkin',
711
-                    'handleRequestToggleCheckin',
712
-                ),
713
-                'methods'         => WP_REST_Server::CREATABLE,
714
-                'hidden_endpoint' => $hidden_endpoint,
715
-                'args'            => array(
716
-                    'force' => array(
717
-                        'required'    => false,
718
-                        'default'     => false,
719
-                        'description' => __(
720
-                            // @codingStandardsIgnoreStart
721
-                            'Whether to force toggle checkin, or to verify the registration status and allowed ticket uses',
722
-                            // @codingStandardsIgnoreEnd
723
-                            'event_espresso'
724
-                        ),
725
-                    ),
726
-                ),
727
-                'callback_args'   => array($version),
728
-            ),
729
-        );
730
-        return apply_filters(
731
-            'FHEE__EED_Core_Rest_Api___register_rpc_routes__this_versions_routes',
732
-            $this_versions_routes,
733
-            $version,
734
-            $hidden_endpoint
735
-        );
736
-    }
737
-
738
-
739
-
740
-    /**
741
-     * Gets the query params that can be used when request one or many
742
-     *
743
-     * @param EEM_Base $model
744
-     * @param string   $version
745
-     * @return array
746
-     */
747
-    protected function _get_response_selection_query_params(\EEM_Base $model, $version)
748
-    {
749
-        return apply_filters(
750
-            'FHEE__EED_Core_Rest_Api___get_response_selection_query_params',
751
-            array(
752
-                'include'   => array(
753
-                    'required' => false,
754
-                    'default'  => '*',
755
-                    'type'     => 'string',
756
-                ),
757
-                'calculate' => array(
758
-                    'required'          => false,
759
-                    'default'           => '',
760
-                    'enum'              => self::$_field_calculator->retrieveCalculatedFieldsForModel($model),
761
-                    'type'              => 'string',
762
-                    //because we accept a CSV'd list of the enumerated strings, WP core validation and sanitization
763
-                    //freaks out. We'll just validate this argument while handling the request
764
-                    'validate_callback' => null,
765
-                    'sanitize_callback' => null,
766
-                ),
767
-            ),
768
-            $model,
769
-            $version
770
-        );
771
-    }
772
-
773
-
774
-
775
-    /**
776
-     * Gets the parameters acceptable for delete requests
777
-     *
778
-     * @param \EEM_Base $model
779
-     * @param string    $version
780
-     * @return array
781
-     */
782
-    protected function _get_delete_query_params(\EEM_Base $model, $version)
783
-    {
784
-        $params_for_delete = array(
785
-            'allow_blocking' => array(
786
-                'required' => false,
787
-                'default'  => true,
788
-                'type'     => 'boolean',
789
-            ),
790
-        );
791
-        $params_for_delete['force'] = array(
792
-            'required' => false,
793
-            'default'  => false,
794
-            'type'     => 'boolean',
795
-        );
796
-        return apply_filters(
797
-            'FHEE__EED_Core_Rest_Api___get_delete_query_params',
798
-            $params_for_delete,
799
-            $model,
800
-            $version
801
-        );
802
-    }
803
-
804
-
805
-
806
-    /**
807
-     * Gets info about reading query params that are acceptable
808
-     *
809
-     * @param \EEM_Base $model eg 'Event' or 'Venue'
810
-     * @param  string   $version
811
-     * @return array    describing the args acceptable when querying this model
812
-     * @throws EE_Error
813
-     */
814
-    protected function _get_read_query_params(\EEM_Base $model, $version)
815
-    {
816
-        $default_orderby = array();
817
-        foreach ($model->get_combined_primary_key_fields() as $key_field) {
818
-            $default_orderby[$key_field->get_name()] = 'ASC';
819
-        }
820
-        return array_merge(
821
-            $this->_get_response_selection_query_params($model, $version),
822
-            array(
823
-                'where'    => array(
824
-                    'required' => false,
825
-                    'default'  => array(),
826
-                    'type'     => 'object',
827
-                    //because we accept an almost infinite list of possible where conditions, WP
828
-                    // core validation and sanitization freaks out. We'll just validate this argument
829
-                    // while handling the request
830
-                    'validate_callback' => null,
831
-                    'sanitize_callback' => null,
832
-                ),
833
-                'limit'    => array(
834
-                    'required' => false,
835
-                    'default'  => EED_Core_Rest_Api::get_default_query_limit(),
836
-                    'type'     => array(
837
-                        'array',
838
-                        'string',
839
-                        'integer',
840
-                    ),
841
-                    //because we accept a variety of types, WP core validation and sanitization
842
-                    //freaks out. We'll just validate this argument while handling the request
843
-                    'validate_callback' => null,
844
-                    'sanitize_callback' => null,
845
-                ),
846
-                'order_by' => array(
847
-                    'required' => false,
848
-                    'default'  => $default_orderby,
849
-                    'type'     => array(
850
-                        'object',
851
-                        'string',
852
-                    ),//because we accept a variety of types, WP core validation and sanitization
853
-                    //freaks out. We'll just validate this argument while handling the request
854
-                    'validate_callback' => null,
855
-                    'sanitize_callback' => null,
856
-                ),
857
-                'group_by' => array(
858
-                    'required' => false,
859
-                    'default'  => null,
860
-                    'type'     => array(
861
-                        'object',
862
-                        'string',
863
-                    ),
864
-                    //because we accept  an almost infinite list of possible groupings,
865
-                    // WP core validation and sanitization
866
-                    //freaks out. We'll just validate this argument while handling the request
867
-                    'validate_callback' => null,
868
-                    'sanitize_callback' => null,
869
-                ),
870
-                'having'   => array(
871
-                    'required' => false,
872
-                    'default'  => null,
873
-                    'type'     => 'object',
874
-                    //because we accept an almost infinite list of possible where conditions, WP
875
-                    // core validation and sanitization freaks out. We'll just validate this argument
876
-                    // while handling the request
877
-                    'validate_callback' => null,
878
-                    'sanitize_callback' => null,
879
-                ),
880
-                'caps'     => array(
881
-                    'required' => false,
882
-                    'default'  => EEM_Base::caps_read,
883
-                    'type'     => 'string',
884
-                    'enum'     => array(
885
-                        EEM_Base::caps_read,
886
-                        EEM_Base::caps_read_admin,
887
-                        EEM_Base::caps_edit,
888
-                        EEM_Base::caps_delete
889
-                    )
890
-                ),
891
-            )
892
-        );
893
-    }
894
-
895
-
896
-
897
-    /**
898
-     * Gets parameter information for a model regarding writing data
899
-     *
900
-     * @param string           $model_name
901
-     * @param ModelVersionInfo $model_version_info
902
-     * @param boolean          $create                                       whether this is for request to create (in which case we need
903
-     *                                                                       all required params) or just to update (in which case we don't need those on every request)
904
-     * @return array
905
-     */
906
-    protected function _get_write_params(
907
-        $model_name,
908
-        ModelVersionInfo $model_version_info,
909
-        $create = false
910
-    ) {
911
-        $model = EE_Registry::instance()->load_model($model_name);
912
-        $fields = $model_version_info->fieldsOnModelInThisVersion($model);
913
-        $args_info = array();
914
-        foreach ($fields as $field_name => $field_obj) {
915
-            if ($field_obj->is_auto_increment()) {
916
-                //totally ignore auto increment IDs
917
-                continue;
918
-            }
919
-            $arg_info = $field_obj->getSchema();
920
-            $required = $create && ! $field_obj->is_nullable() && $field_obj->get_default_value() === null;
921
-            $arg_info['required'] = $required;
922
-            //remove the read-only flag. If it were read-only we wouldn't list it as an argument while writing, right?
923
-            unset($arg_info['readonly']);
924
-            $schema_properties = $field_obj->getSchemaProperties();
925
-            if (
926
-                isset($schema_properties['raw'])
927
-                && $field_obj->getSchemaType() === 'object'
928
-            ) {
929
-                //if there's a "raw" form of this argument, use those properties instead
930
-                $arg_info = array_replace(
931
-                    $arg_info,
932
-                    $schema_properties['raw']
933
-                );
934
-            }
935
-            $arg_info['default'] = ModelDataTranslator::prepareFieldValueForJson(
936
-                $field_obj,
937
-                $field_obj->get_default_value(),
938
-                $model_version_info->requestedVersion()
939
-            );
940
-            //we do our own validation and sanitization within the controller
941
-            $arg_info['sanitize_callback'] =
942
-                array(
943
-                    'EED_Core_Rest_Api',
944
-                    'default_sanitize_callback',
945
-                );
946
-            $args_info[$field_name] = $arg_info;
947
-            if ($field_obj instanceof EE_Datetime_Field) {
948
-                $gmt_arg_info = $arg_info;
949
-                $gmt_arg_info['description'] = sprintf(
950
-                    esc_html__(
951
-                        '%1$s - the value for this field in UTC. Ignored if %2$s is provided.',
952
-                        'event_espresso'
953
-                    ),
954
-                    $field_obj->get_nicename(),
955
-                    $field_name
956
-                );
957
-                $args_info[$field_name . '_gmt'] = $gmt_arg_info;
958
-            }
959
-        }
960
-        return $args_info;
961
-    }
962
-
963
-
964
-
965
-    /**
966
-     * Replacement for WP API's 'rest_parse_request_arg'.
967
-     * If the value is blank but not required, don't bother validating it.
968
-     * Also, it uses our email validation instead of WP API's default.
969
-     *
970
-     * @param                 $value
971
-     * @param WP_REST_Request $request
972
-     * @param                 $param
973
-     * @return bool|true|WP_Error
974
-     * @throws InvalidArgumentException
975
-     * @throws InvalidInterfaceException
976
-     * @throws InvalidDataTypeException
977
-     */
978
-    public static function default_sanitize_callback( $value, WP_REST_Request $request, $param)
979
-    {
980
-        $attributes = $request->get_attributes();
981
-        if (! isset($attributes['args'][$param])
982
-            || ! is_array($attributes['args'][$param])) {
983
-            $validation_result = true;
984
-        } else {
985
-            $args = $attributes['args'][$param];
986
-            if ((
987
-                    $value === ''
988
-                    || $value === null
989
-                )
990
-                && (! isset($args['required'])
991
-                    || $args['required'] === false
992
-                )
993
-            ) {
994
-                //not required and not provided? that's cool
995
-                $validation_result = true;
996
-            } elseif (isset($args['format'])
997
-                && $args['format'] === 'email'
998
-            ) {
999
-                $validation_result = true;
1000
-                if (! self::_validate_email($value)) {
1001
-                    $validation_result = new WP_Error(
1002
-                        'rest_invalid_param',
1003
-                        esc_html__(
1004
-                            'The email address is not valid or does not exist.',
1005
-                            'event_espresso'
1006
-                        )
1007
-                    );
1008
-                }
1009
-            } else {
1010
-                $validation_result = rest_validate_value_from_schema($value, $args, $param);
1011
-            }
1012
-        }
1013
-        if (is_wp_error($validation_result)) {
1014
-            return $validation_result;
1015
-        }
1016
-        return rest_sanitize_request_arg($value, $request, $param);
1017
-    }
1018
-
1019
-
1020
-
1021
-    /**
1022
-     * Returns whether or not this email address is valid. Copied from EE_Email_Validation_Strategy::_validate_email()
1023
-     *
1024
-     * @param $email
1025
-     * @return bool
1026
-     * @throws InvalidArgumentException
1027
-     * @throws InvalidInterfaceException
1028
-     * @throws InvalidDataTypeException
1029
-     */
1030
-    protected static function _validate_email($email){
1031
-        try {
1032
-            EmailAddressFactory::create($email);
1033
-            return true;
1034
-        } catch (EmailValidationException $e) {
1035
-            return false;
1036
-        }
1037
-    }
1038
-
1039
-
1040
-
1041
-    /**
1042
-     * Gets routes for the config
1043
-     *
1044
-     * @return array @see _register_model_routes
1045
-     * @deprecated since version 4.9.1
1046
-     */
1047
-    protected function _register_config_routes()
1048
-    {
1049
-        $config_routes = array();
1050
-        foreach (self::versions_served() as $version => $hidden_endpoint) {
1051
-            $config_routes[self::ee_api_namespace . $version] = $this->_get_config_route_data_for_version(
1052
-                $version,
1053
-                $hidden_endpoint
1054
-            );
1055
-        }
1056
-        return $config_routes;
1057
-    }
1058
-
1059
-
1060
-
1061
-    /**
1062
-     * Gets routes for the config for the specified version
1063
-     *
1064
-     * @param string  $version
1065
-     * @param boolean $hidden_endpoint
1066
-     * @return array
1067
-     */
1068
-    protected function _get_config_route_data_for_version($version, $hidden_endpoint)
1069
-    {
1070
-        return array(
1071
-            'config'    => array(
1072
-                array(
1073
-                    'callback'        => array(
1074
-                        'EventEspresso\core\libraries\rest_api\controllers\config\Read',
1075
-                        'handleRequest',
1076
-                    ),
1077
-                    'methods'         => WP_REST_Server::READABLE,
1078
-                    'hidden_endpoint' => $hidden_endpoint,
1079
-                    'callback_args'   => array($version),
1080
-                ),
1081
-            ),
1082
-            'site_info' => array(
1083
-                array(
1084
-                    'callback'        => array(
1085
-                        'EventEspresso\core\libraries\rest_api\controllers\config\Read',
1086
-                        'handleRequestSiteInfo',
1087
-                    ),
1088
-                    'methods'         => WP_REST_Server::READABLE,
1089
-                    'hidden_endpoint' => $hidden_endpoint,
1090
-                    'callback_args'   => array($version),
1091
-                ),
1092
-            ),
1093
-        );
1094
-    }
1095
-
1096
-
1097
-
1098
-    /**
1099
-     * Gets the meta info routes
1100
-     *
1101
-     * @return array @see _register_model_routes
1102
-     * @deprecated since version 4.9.1
1103
-     */
1104
-    protected function _register_meta_routes()
1105
-    {
1106
-        $meta_routes = array();
1107
-        foreach (self::versions_served() as $version => $hidden_endpoint) {
1108
-            $meta_routes[self::ee_api_namespace . $version] = $this->_get_meta_route_data_for_version(
1109
-                $version,
1110
-                $hidden_endpoint
1111
-            );
1112
-        }
1113
-        return $meta_routes;
1114
-    }
1115
-
1116
-
1117
-
1118
-    /**
1119
-     * @param string  $version
1120
-     * @param boolean $hidden_endpoint
1121
-     * @return array
1122
-     */
1123
-    protected function _get_meta_route_data_for_version($version, $hidden_endpoint = false)
1124
-    {
1125
-        return array(
1126
-            'resources' => array(
1127
-                array(
1128
-                    'callback'        => array(
1129
-                        'EventEspresso\core\libraries\rest_api\controllers\model\Meta',
1130
-                        'handleRequestModelsMeta',
1131
-                    ),
1132
-                    'methods'         => WP_REST_Server::READABLE,
1133
-                    'hidden_endpoint' => $hidden_endpoint,
1134
-                    'callback_args'   => array($version),
1135
-                ),
1136
-            ),
1137
-        );
1138
-    }
1139
-
1140
-
1141
-
1142
-    /**
1143
-     * Tries to hide old 4.6 endpoints from the
1144
-     *
1145
-     * @param array $route_data
1146
-     * @return array
1147
-     * @throws \EE_Error
1148
-     */
1149
-    public static function hide_old_endpoints($route_data)
1150
-    {
1151
-        //allow API clients to override which endpoints get hidden, in case
1152
-        //they want to discover particular endpoints
1153
-        //also, we don't have access to the request so we have to just grab it from the superglobal
1154
-        $force_show_ee_namespace = ltrim(
1155
-            EEH_Array::is_set($_REQUEST, 'force_show_ee_namespace', ''),
1156
-            '/'
1157
-        );
1158
-        foreach (EED_Core_Rest_Api::get_ee_route_data() as $namespace => $relative_urls) {
1159
-            foreach ($relative_urls as $resource_name => $endpoints) {
1160
-                foreach ($endpoints as $key => $endpoint) {
1161
-                    //skip schema and other route options
1162
-                    if (! is_numeric($key)) {
1163
-                        continue;
1164
-                    }
1165
-                    //by default, hide "hidden_endpoint"s, unless the request indicates
1166
-                    //to $force_show_ee_namespace, in which case only show that one
1167
-                    //namespace's endpoints (and hide all others)
1168
-                    if (
1169
-                        ($force_show_ee_namespace !== '' && $force_show_ee_namespace !== $namespace)
1170
-                        || ($endpoint['hidden_endpoint'] && $force_show_ee_namespace === '')
1171
-                    ) {
1172
-                        $full_route = '/' . ltrim($namespace, '/');
1173
-                        $full_route .= '/' . ltrim($resource_name, '/');
1174
-                        unset($route_data[$full_route]);
1175
-                    }
1176
-                }
1177
-            }
1178
-        }
1179
-        return $route_data;
1180
-    }
1181
-
1182
-
1183
-
1184
-    /**
1185
-     * Returns an array describing which versions of core support serving requests for.
1186
-     * Keys are core versions' major and minor version, and values are the
1187
-     * LOWEST requested version they can serve. Eg, 4.7 can serve requests for 4.6-like
1188
-     * data by just removing a few models and fields from the responses. However, 4.15 might remove
1189
-     * the answers table entirely, in which case it would be very difficult for
1190
-     * it to serve 4.6-style responses.
1191
-     * Versions of core that are missing from this array are unknowns.
1192
-     * previous ver
1193
-     *
1194
-     * @return array
1195
-     */
1196
-    public static function version_compatibilities()
1197
-    {
1198
-        return apply_filters(
1199
-            'FHEE__EED_Core_REST_API__version_compatibilities',
1200
-            array(
1201
-                '4.8.29' => '4.8.29',
1202
-                '4.8.33' => '4.8.29',
1203
-                '4.8.34' => '4.8.29',
1204
-                '4.8.36' => '4.8.29',
1205
-            )
1206
-        );
1207
-    }
1208
-
1209
-
1210
-
1211
-    /**
1212
-     * Gets the latest API version served. Eg if there
1213
-     * are two versions served of the API, 4.8.29 and 4.8.32, and
1214
-     * we are on core version 4.8.34, it will return the string "4.8.32"
1215
-     *
1216
-     * @return string
1217
-     */
1218
-    public static function latest_rest_api_version()
1219
-    {
1220
-        $versions_served = \EED_Core_Rest_Api::versions_served();
1221
-        $versions_served_keys = array_keys($versions_served);
1222
-        return end($versions_served_keys);
1223
-    }
1224
-
1225
-
1226
-
1227
-    /**
1228
-     * Using EED_Core_Rest_Api::version_compatibilities(), determines what version of
1229
-     * EE the API can serve requests for. Eg, if we are on 4.15 of core, and
1230
-     * we can serve requests from 4.12 or later, this will return array( '4.12', '4.13', '4.14', '4.15' ).
1231
-     * We also indicate whether or not this version should be put in the index or not
1232
-     *
1233
-     * @return array keys are API version numbers (just major and minor numbers), and values
1234
-     * are whether or not they should be hidden
1235
-     */
1236
-    public static function versions_served()
1237
-    {
1238
-        $versions_served = array();
1239
-        $possibly_served_versions = EED_Core_Rest_Api::version_compatibilities();
1240
-        $lowest_compatible_version = end($possibly_served_versions);
1241
-        reset($possibly_served_versions);
1242
-        $versions_served_historically = array_keys($possibly_served_versions);
1243
-        $latest_version = end($versions_served_historically);
1244
-        reset($versions_served_historically);
1245
-        //for each version of core we have ever served:
1246
-        foreach ($versions_served_historically as $key_versioned_endpoint) {
1247
-            //if it's not above the current core version, and it's compatible with the current version of core
1248
-            if ($key_versioned_endpoint === $latest_version) {
1249
-                //don't hide the latest version in the index
1250
-                $versions_served[$key_versioned_endpoint] = false;
1251
-            } elseif (
1252
-                $key_versioned_endpoint >= $lowest_compatible_version
1253
-                && $key_versioned_endpoint < EED_Core_Rest_Api::core_version()
1254
-            ) {
1255
-                //include, but hide, previous versions which are still supported
1256
-                $versions_served[$key_versioned_endpoint] = true;
1257
-            } elseif (apply_filters(
1258
-                'FHEE__EED_Core_Rest_Api__versions_served__include_incompatible_versions',
1259
-                false,
1260
-                $possibly_served_versions
1261
-            )) {
1262
-                //if a version is no longer supported, don't include it in index or list of versions served
1263
-                $versions_served[$key_versioned_endpoint] = true;
1264
-            }
1265
-        }
1266
-        return $versions_served;
1267
-    }
1268
-
1269
-
1270
-
1271
-    /**
1272
-     * Gets the major and minor version of EE core's version string
1273
-     *
1274
-     * @return string
1275
-     */
1276
-    public static function core_version()
1277
-    {
1278
-        return apply_filters(
1279
-            'FHEE__EED_Core_REST_API__core_version',
1280
-            implode(
1281
-                '.',
1282
-                array_slice(
1283
-                    explode(
1284
-                        '.',
1285
-                        espresso_version()
1286
-                    ),
1287
-                0,
1288
-                3
1289
-                )
1290
-            )
1291
-        );
1292
-    }
1293
-
1294
-
1295
-
1296
-    /**
1297
-     * Gets the default limit that should be used when querying for resources
1298
-     *
1299
-     * @return int
1300
-     */
1301
-    public static function get_default_query_limit()
1302
-    {
1303
-        //we actually don't use a const because we want folks to always use
1304
-        //this method, not the const directly
1305
-        return apply_filters(
1306
-            'FHEE__EED_Core_Rest_Api__get_default_query_limit',
1307
-            50
1308
-        );
1309
-    }
1310
-
1311
-
1312
-
1313
-    /**
1314
-     *    run - initial module setup
1315
-     *
1316
-     * @access    public
1317
-     * @param  WP $WP
1318
-     * @return    void
1319
-     */
1320
-    public function run($WP)
1321
-    {
1322
-    }
29
+	const ee_api_namespace_for_regex = 'ee\/v([^/]*)\/';
30
+
31
+	const saved_routes_option_names  = 'ee_core_routes';
32
+
33
+	/**
34
+	 * string used in _links response bodies to make them globally unique.
35
+	 *
36
+	 * @see http://v2.wp-api.org/extending/linking/
37
+	 */
38
+	const ee_api_link_namespace = 'https://api.eventespresso.com/';
39
+
40
+	/**
41
+	 * @var CalculatedModelFields
42
+	 */
43
+	protected static $_field_calculator;
44
+
45
+
46
+
47
+	/**
48
+	 * @return EED_Core_Rest_Api|EED_Module
49
+	 */
50
+	public static function instance()
51
+	{
52
+		self::$_field_calculator = new CalculatedModelFields();
53
+		return parent::get_instance(__CLASS__);
54
+	}
55
+
56
+
57
+
58
+	/**
59
+	 *    set_hooks - for hooking into EE Core, other modules, etc
60
+	 *
61
+	 * @access    public
62
+	 * @return    void
63
+	 */
64
+	public static function set_hooks()
65
+	{
66
+		self::set_hooks_both();
67
+	}
68
+
69
+
70
+
71
+	/**
72
+	 *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
73
+	 *
74
+	 * @access    public
75
+	 * @return    void
76
+	 */
77
+	public static function set_hooks_admin()
78
+	{
79
+		self::set_hooks_both();
80
+	}
81
+
82
+
83
+
84
+	public static function set_hooks_both()
85
+	{
86
+		add_action('rest_api_init', array('EED_Core_Rest_Api', 'register_routes'), 10);
87
+		add_action('rest_api_init', array('EED_Core_Rest_Api', 'set_hooks_rest_api'), 5);
88
+		add_filter('rest_route_data', array('EED_Core_Rest_Api', 'hide_old_endpoints'), 10, 2);
89
+		add_filter('rest_index',
90
+			array('EventEspresso\core\libraries\rest_api\controllers\model\Meta', 'filterEeMetadataIntoIndex'));
91
+		EED_Core_Rest_Api::invalidate_cached_route_data_on_version_change();
92
+	}
93
+
94
+
95
+
96
+	/**
97
+	 * sets up hooks which only need to be included as part of REST API requests;
98
+	 * other requests like to the frontend or admin etc don't need them
99
+	 *
100
+	 * @throws \EE_Error
101
+	 */
102
+	public static function set_hooks_rest_api()
103
+	{
104
+		//set hooks which account for changes made to the API
105
+		EED_Core_Rest_Api::_set_hooks_for_changes();
106
+	}
107
+
108
+
109
+
110
+	/**
111
+	 * public wrapper of _set_hooks_for_changes.
112
+	 * Loads all the hooks which make requests to old versions of the API
113
+	 * appear the same as they always did
114
+	 *
115
+	 * @throws EE_Error
116
+	 */
117
+	public static function set_hooks_for_changes()
118
+	{
119
+		self::_set_hooks_for_changes();
120
+	}
121
+
122
+
123
+
124
+	/**
125
+	 * If the user appears to be using WP API basic auth, tell them (via a persistent
126
+	 * admin notice and an email) that we're going to remove it soon, so they should
127
+	 * replace it with application passwords.
128
+	 *
129
+	 * @throws InvalidDataTypeException
130
+	 */
131
+	public static function maybe_notify_of_basic_auth_removal()
132
+	{
133
+		if (
134
+		apply_filters(
135
+			'FHEE__EED_Core_Rest_Api__maybe_notify_of_basic_auth_removal__override',
136
+			! isset($_SERVER['PHP_AUTH_USER'])
137
+			&& ! isset($_SERVER['HTTP_AUTHORIZATION'])
138
+		)
139
+		) {
140
+			//sure it's a WP API request, but they aren't using basic auth, so don't bother them
141
+			return;
142
+		}
143
+		//ok they're using the WP API with Basic Auth
144
+		new PersistentAdminNotice(
145
+			'using_basic_auth',
146
+			sprintf(
147
+				__(
148
+					'We noticed you\'re using the WP API, which is used by the Event Espresso 4 mobile apps. Because of security and compatibility concerns, we will soon be removing our default authentication mechanism, WP API Basic Auth, from Event Espresso. It is recommended you instead install the %1$sWP Application Passwords plugin%2$s and use it with the EE4 Mobile apps. See %3$sour mobile app documentation%2$s for more information. %4$sIf you have installed the WP API Basic Auth plugin separately, or are not using the Event Espresso 4 mobile apps, you can disregard this message.%4$sThe Event Espresso Team',
149
+					'event_espresso'
150
+				),
151
+				'<a href="https://wordpress.org/plugins/application-passwords/">',
152
+				'</a>',
153
+				'<a href="https://eventespresso.com/wiki/ee4-event-apps/#authentication">',
154
+				'<br/>'
155
+			)
156
+		);
157
+		if ( ! get_option('ee_notified_admin_on_basic_auth_removal', false)) {
158
+			add_option('ee_notified_admin_on_basic_auth_removal', true);
159
+			//piggy back off EE_Error::set_content_type, which sets the content type to HTML
160
+			add_filter('wp_mail_content_type', array('EE_Error', 'set_content_type'));
161
+			//and send the message to the site admin too
162
+			wp_mail(get_option('admin_email'),
163
+				__('Notice of Removal of WP API Basic Auth From Event Espresso 4', 'event_espresso'), $message);
164
+			remove_filter('wp_mail_content_type', array('EE_Error', 'set_content_type'));
165
+		}
166
+	}
167
+
168
+
169
+
170
+	/**
171
+	 * Loads all the hooks which make requests to old versions of the API
172
+	 * appear the same as they always did
173
+	 *
174
+	 * @throws EE_Error
175
+	 */
176
+	protected static function _set_hooks_for_changes()
177
+	{
178
+		$folder_contents = EEH_File::get_contents_of_folders(array(EE_LIBRARIES . 'rest_api' . DS . 'changes'), false);
179
+		foreach ($folder_contents as $classname_in_namespace => $filepath) {
180
+			//ignore the base parent class
181
+			//and legacy named classes
182
+			if ($classname_in_namespace === 'ChangesInBase'
183
+				|| strpos($classname_in_namespace, 'Changes_In_') === 0
184
+			) {
185
+				continue;
186
+			}
187
+			$full_classname = 'EventEspresso\core\libraries\rest_api\changes\\' . $classname_in_namespace;
188
+			if (class_exists($full_classname)) {
189
+				$instance_of_class = new $full_classname;
190
+				if ($instance_of_class instanceof ChangesInBase) {
191
+					$instance_of_class->setHooks();
192
+				}
193
+			}
194
+		}
195
+	}
196
+
197
+
198
+
199
+	/**
200
+	 * Filters the WP routes to add our EE-related ones. This takes a bit of time
201
+	 * so we actually prefer to only do it when an EE plugin is activated or upgraded
202
+	 *
203
+	 * @throws \EE_Error
204
+	 */
205
+	public static function register_routes()
206
+	{
207
+		foreach (EED_Core_Rest_Api::get_ee_route_data() as $namespace => $relative_routes) {
208
+			foreach ($relative_routes as $relative_route => $data_for_multiple_endpoints) {
209
+				/**
210
+				 * @var array $data_for_multiple_endpoints numerically indexed array
211
+				 *                                         but can also contain route options like {
212
+				 * @type array    $schema                      {
213
+				 * @type callable $schema_callback
214
+				 * @type array    $callback_args               arguments that will be passed to the callback, after the
215
+				 * WP_REST_Request of course
216
+				 * }
217
+				 * }
218
+				 */
219
+				//when registering routes, register all the endpoints' data at the same time
220
+				$multiple_endpoint_args = array();
221
+				foreach ($data_for_multiple_endpoints as $endpoint_key => $data_for_single_endpoint) {
222
+					/**
223
+					 * @var array     $data_for_single_endpoint {
224
+					 * @type callable $callback
225
+					 * @type string methods
226
+					 * @type array args
227
+					 * @type array _links
228
+					 * @type array    $callback_args            arguments that will be passed to the callback, after the
229
+					 * WP_REST_Request of course
230
+					 * }
231
+					 */
232
+					//skip route options
233
+					if (! is_numeric($endpoint_key)) {
234
+						continue;
235
+					}
236
+					if (! isset($data_for_single_endpoint['callback'], $data_for_single_endpoint['methods'])) {
237
+						throw new EE_Error(
238
+							esc_html__(
239
+								// @codingStandardsIgnoreStart
240
+								'Endpoint configuration data needs to have entries "callback" (callable) and "methods" (comma-separated list of accepts HTTP methods).',
241
+								// @codingStandardsIgnoreEnd
242
+								'event_espresso')
243
+						);
244
+					}
245
+					$callback = $data_for_single_endpoint['callback'];
246
+					$single_endpoint_args = array(
247
+						'methods' => $data_for_single_endpoint['methods'],
248
+						'args'    => isset($data_for_single_endpoint['args']) ? $data_for_single_endpoint['args']
249
+							: array(),
250
+					);
251
+					if (isset($data_for_single_endpoint['_links'])) {
252
+						$single_endpoint_args['_links'] = $data_for_single_endpoint['_links'];
253
+					}
254
+					if (isset($data_for_single_endpoint['callback_args'])) {
255
+						$callback_args = $data_for_single_endpoint['callback_args'];
256
+						$single_endpoint_args['callback'] = function (\WP_REST_Request $request) use (
257
+							$callback,
258
+							$callback_args
259
+						) {
260
+							array_unshift($callback_args, $request);
261
+							return call_user_func_array(
262
+								$callback,
263
+								$callback_args
264
+							);
265
+						};
266
+					} else {
267
+						$single_endpoint_args['callback'] = $data_for_single_endpoint['callback'];
268
+					}
269
+					$multiple_endpoint_args[] = $single_endpoint_args;
270
+				}
271
+				if (isset($data_for_multiple_endpoints['schema'])) {
272
+					$schema_route_data = $data_for_multiple_endpoints['schema'];
273
+					$schema_callback = $schema_route_data['schema_callback'];
274
+					$callback_args = $schema_route_data['callback_args'];
275
+					$multiple_endpoint_args['schema'] = function () use ($schema_callback, $callback_args) {
276
+						return call_user_func_array(
277
+							$schema_callback,
278
+							$callback_args
279
+						);
280
+					};
281
+				}
282
+				register_rest_route(
283
+					$namespace,
284
+					$relative_route,
285
+					$multiple_endpoint_args
286
+				);
287
+			}
288
+		}
289
+	}
290
+
291
+
292
+
293
+	/**
294
+	 * Checks if there was a version change or something that merits invalidating the cached
295
+	 * route data. If so, invalidates the cached route data so that it gets refreshed
296
+	 * next time the WP API is used
297
+	 */
298
+	public static function invalidate_cached_route_data_on_version_change()
299
+	{
300
+		if (EE_System::instance()->detect_req_type() !== EE_System::req_type_normal) {
301
+			EED_Core_Rest_Api::invalidate_cached_route_data();
302
+		}
303
+		foreach (EE_Registry::instance()->addons as $addon) {
304
+			if ($addon instanceof EE_Addon && $addon->detect_req_type() !== EE_System::req_type_normal) {
305
+				EED_Core_Rest_Api::invalidate_cached_route_data();
306
+			}
307
+		}
308
+	}
309
+
310
+
311
+
312
+	/**
313
+	 * Removes the cached route data so it will get refreshed next time the WP API is used
314
+	 */
315
+	public static function invalidate_cached_route_data()
316
+	{
317
+		//delete the saved EE REST API routes
318
+		foreach (EED_Core_Rest_Api::versions_served() as $version => $hidden) {
319
+			delete_option(EED_Core_Rest_Api::saved_routes_option_names . $version);
320
+		}
321
+	}
322
+
323
+
324
+
325
+	/**
326
+	 * Gets the EE route data
327
+	 *
328
+	 * @return array top-level key is the namespace, next-level key is the route and its value is array{
329
+	 * @throws \EE_Error
330
+	 * @type string|array $callback
331
+	 * @type string       $methods
332
+	 * @type boolean      $hidden_endpoint
333
+	 * }
334
+	 */
335
+	public static function get_ee_route_data()
336
+	{
337
+		$ee_routes = array();
338
+		foreach (self::versions_served() as $version => $hidden_endpoints) {
339
+			$ee_routes[self::ee_api_namespace . $version] = self::_get_ee_route_data_for_version(
340
+				$version,
341
+				$hidden_endpoints
342
+			);
343
+		}
344
+		return $ee_routes;
345
+	}
346
+
347
+
348
+
349
+	/**
350
+	 * Gets the EE route data from the wp options if it exists already,
351
+	 * otherwise re-generates it and saves it to the option
352
+	 *
353
+	 * @param string  $version
354
+	 * @param boolean $hidden_endpoints
355
+	 * @return array
356
+	 * @throws \EE_Error
357
+	 */
358
+	protected static function _get_ee_route_data_for_version($version, $hidden_endpoints = false)
359
+	{
360
+		$ee_routes = get_option(self::saved_routes_option_names . $version, null);
361
+		if (! $ee_routes || (defined('EE_REST_API_DEBUG_MODE') && EE_REST_API_DEBUG_MODE)) {
362
+			$ee_routes = self::_save_ee_route_data_for_version($version, $hidden_endpoints);
363
+		}
364
+		return $ee_routes;
365
+	}
366
+
367
+
368
+
369
+	/**
370
+	 * Saves the EE REST API route data to a wp option and returns it
371
+	 *
372
+	 * @param string  $version
373
+	 * @param boolean $hidden_endpoints
374
+	 * @return mixed|null
375
+	 * @throws \EE_Error
376
+	 */
377
+	protected static function _save_ee_route_data_for_version($version, $hidden_endpoints = false)
378
+	{
379
+		$instance = self::instance();
380
+		$routes = apply_filters(
381
+			'EED_Core_Rest_Api__save_ee_route_data_for_version__routes',
382
+			array_replace_recursive(
383
+				$instance->_get_config_route_data_for_version($version, $hidden_endpoints),
384
+				$instance->_get_meta_route_data_for_version($version, $hidden_endpoints),
385
+				$instance->_get_model_route_data_for_version($version, $hidden_endpoints),
386
+				$instance->_get_rpc_route_data_for_version($version, $hidden_endpoints)
387
+			)
388
+		);
389
+		$option_name = self::saved_routes_option_names . $version;
390
+		if (get_option($option_name)) {
391
+			update_option($option_name, $routes, true);
392
+		} else {
393
+			add_option($option_name, $routes, null, 'no');
394
+		}
395
+		return $routes;
396
+	}
397
+
398
+
399
+
400
+	/**
401
+	 * Calculates all the EE routes and saves it to a WordPress option so we don't
402
+	 * need to calculate it on every request
403
+	 *
404
+	 * @deprecated since version 4.9.1
405
+	 * @return void
406
+	 */
407
+	public static function save_ee_routes()
408
+	{
409
+		if (EE_Maintenance_Mode::instance()->models_can_query()) {
410
+			$instance = self::instance();
411
+			$routes = apply_filters(
412
+				'EED_Core_Rest_Api__save_ee_routes__routes',
413
+				array_replace_recursive(
414
+					$instance->_register_config_routes(),
415
+					$instance->_register_meta_routes(),
416
+					$instance->_register_model_routes(),
417
+					$instance->_register_rpc_routes()
418
+				)
419
+			);
420
+			update_option(self::saved_routes_option_names, $routes, true);
421
+		}
422
+	}
423
+
424
+
425
+
426
+	/**
427
+	 * Gets all the route information relating to EE models
428
+	 *
429
+	 * @return array @see get_ee_route_data
430
+	 * @deprecated since version 4.9.1
431
+	 */
432
+	protected function _register_model_routes()
433
+	{
434
+		$model_routes = array();
435
+		foreach (self::versions_served() as $version => $hidden_endpoint) {
436
+			$model_routes[EED_Core_Rest_Api::ee_api_namespace
437
+						  . $version] = $this->_get_config_route_data_for_version($version, $hidden_endpoint);
438
+		}
439
+		return $model_routes;
440
+	}
441
+
442
+
443
+
444
+	/**
445
+	 * Decides whether or not to add write endpoints for this model.
446
+	 *
447
+	 * Currently, this defaults to exclude all global tables and models
448
+	 * which would allow inserting WP core data (we don't want to duplicate
449
+	 * what WP API does, as it's unnecessary, extra work, and potentially extra bugs)
450
+	 * @param EEM_Base $model
451
+	 * @return bool
452
+	 */
453
+	public static function should_have_write_endpoints(EEM_Base $model)
454
+	{
455
+		if ($model->is_wp_core_model()){
456
+			return false;
457
+		}
458
+		foreach($model->get_tables() as $table){
459
+			if( $table->is_global()){
460
+				return false;
461
+			}
462
+		}
463
+		return true;
464
+	}
465
+
466
+
467
+
468
+	/**
469
+	 * Gets the names of all models which should have plural routes (eg `ee/v4.8.36/events`)
470
+	 * in this versioned namespace of EE4
471
+	 * @param $version
472
+	 * @return array keys are model names (eg 'Event') and values ar either classnames (eg 'EEM_Event')
473
+	 */
474
+	public static function model_names_with_plural_routes($version){
475
+		$model_version_info = new ModelVersionInfo($version);
476
+		$models_to_register = $model_version_info->modelsForRequestedVersion();
477
+		//let's not bother having endpoints for extra metas
478
+		unset(
479
+			$models_to_register['Extra_Meta'],
480
+			$models_to_register['Extra_Join'],
481
+			$models_to_register['Post_Meta']
482
+		);
483
+		return apply_filters(
484
+			'FHEE__EED_Core_REST_API___register_model_routes',
485
+			$models_to_register
486
+		);
487
+	}
488
+
489
+
490
+
491
+	/**
492
+	 * Gets the route data for EE models in the specified version
493
+	 *
494
+	 * @param string  $version
495
+	 * @param boolean $hidden_endpoint
496
+	 * @return array
497
+	 * @throws EE_Error
498
+	 */
499
+	protected function _get_model_route_data_for_version($version, $hidden_endpoint = false)
500
+	{
501
+		$model_routes = array();
502
+		$model_version_info = new ModelVersionInfo($version);
503
+		foreach (EED_Core_Rest_Api::model_names_with_plural_routes($version) as $model_name => $model_classname) {
504
+			$model = \EE_Registry::instance()->load_model($model_name);
505
+			//if this isn't a valid model then let's skip iterate to the next item in the loop.
506
+			if (! $model instanceof EEM_Base) {
507
+				continue;
508
+			}
509
+			//yes we could just register one route for ALL models, but then they wouldn't show up in the index
510
+			$plural_model_route = EED_Core_Rest_Api::get_collection_route($model);
511
+			$singular_model_route = EED_Core_Rest_Api::get_entity_route($model, '(?P<id>[^\/]+)');
512
+			$model_routes[$plural_model_route] = array(
513
+				array(
514
+					'callback'        => array(
515
+						'EventEspresso\core\libraries\rest_api\controllers\model\Read',
516
+						'handleRequestGetAll',
517
+					),
518
+					'callback_args'   => array($version, $model_name),
519
+					'methods'         => WP_REST_Server::READABLE,
520
+					'hidden_endpoint' => $hidden_endpoint,
521
+					'args'            => $this->_get_read_query_params($model, $version),
522
+					'_links'          => array(
523
+						'self' => rest_url(EED_Core_Rest_Api::ee_api_namespace . $version . $singular_model_route),
524
+					),
525
+				),
526
+				'schema' => array(
527
+					'schema_callback' => array(
528
+						'EventEspresso\core\libraries\rest_api\controllers\model\Read',
529
+						'handleSchemaRequest',
530
+					),
531
+					'callback_args'   => array($version, $model_name),
532
+				),
533
+			);
534
+			$model_routes[$singular_model_route] = array(
535
+				array(
536
+					'callback'        => array(
537
+						'EventEspresso\core\libraries\rest_api\controllers\model\Read',
538
+						'handleRequestGetOne',
539
+					),
540
+					'callback_args'   => array($version, $model_name),
541
+					'methods'         => WP_REST_Server::READABLE,
542
+					'hidden_endpoint' => $hidden_endpoint,
543
+					'args'            => $this->_get_response_selection_query_params($model, $version),
544
+				),
545
+			);
546
+			if( apply_filters(
547
+				'FHEE__EED_Core_Rest_Api___get_model_route_data_for_version__add_write_endpoints',
548
+				EED_Core_Rest_Api::should_have_write_endpoints($model),
549
+				$model
550
+			)){
551
+				$model_routes[$plural_model_route][] = array(
552
+					'callback'        => array(
553
+						'EventEspresso\core\libraries\rest_api\controllers\model\Write',
554
+						'handleRequestInsert',
555
+					),
556
+					'callback_args'   => array($version, $model_name),
557
+					'methods'         => WP_REST_Server::CREATABLE,
558
+					'hidden_endpoint' => $hidden_endpoint,
559
+					'args'            => $this->_get_write_params($model_name, $model_version_info, true),
560
+				);
561
+				$model_routes[$singular_model_route] = array_merge(
562
+					$model_routes[$singular_model_route],
563
+					array(
564
+						array(
565
+							'callback'        => array(
566
+								'EventEspresso\core\libraries\rest_api\controllers\model\Write',
567
+								'handleRequestUpdate',
568
+							),
569
+							'callback_args'   => array($version, $model_name),
570
+							'methods'         => WP_REST_Server::EDITABLE,
571
+							'hidden_endpoint' => $hidden_endpoint,
572
+							'args'            => $this->_get_write_params($model_name, $model_version_info),
573
+						),
574
+						array(
575
+							'callback'        => array(
576
+								'EventEspresso\core\libraries\rest_api\controllers\model\Write',
577
+								'handleRequestDelete',
578
+							),
579
+							'callback_args'   => array($version, $model_name),
580
+							'methods'         => WP_REST_Server::DELETABLE,
581
+							'hidden_endpoint' => $hidden_endpoint,
582
+							'args'            => $this->_get_delete_query_params($model, $version),
583
+						)
584
+					)
585
+				);
586
+			}
587
+			foreach ($model->relation_settings() as $relation_name => $relation_obj) {
588
+
589
+				$related_route = EED_Core_Rest_Api::get_relation_route_via(
590
+					$model,
591
+					'(?P<id>[^\/]+)',
592
+					$relation_obj
593
+				);
594
+				$endpoints = array(
595
+					array(
596
+						'callback'        => array(
597
+							'EventEspresso\core\libraries\rest_api\controllers\model\Read',
598
+							'handleRequestGetRelated',
599
+						),
600
+						'callback_args'   => array($version, $model_name, $relation_name),
601
+						'methods'         => WP_REST_Server::READABLE,
602
+						'hidden_endpoint' => $hidden_endpoint,
603
+						'args'            => $this->_get_read_query_params($relation_obj->get_other_model(), $version),
604
+					),
605
+				);
606
+				$model_routes[$related_route] = $endpoints;
607
+			}
608
+		}
609
+		return $model_routes;
610
+	}
611
+
612
+
613
+
614
+	/**
615
+	 * Gets the relative URI to a model's REST API plural route, after the EE4 versioned namespace,
616
+	 * excluding the preceding slash.
617
+	 * Eg you pass get_plural_route_to('Event') = 'events'
618
+	 *
619
+	 * @param EEM_Base $model
620
+	 * @return string
621
+	 */
622
+	public static function get_collection_route(EEM_Base $model)
623
+	{
624
+		return EEH_Inflector::pluralize_and_lower($model->get_this_model_name());
625
+	}
626
+
627
+
628
+
629
+	/**
630
+	 * Gets the relative URI to a model's REST API singular route, after the EE4 versioned namespace,
631
+	 * excluding the preceding slash.
632
+	 * Eg you pass get_plural_route_to('Event', 12) = 'events/12'
633
+	 *
634
+	 * @param EEM_Base $model eg Event or Venue
635
+	 * @param string $id
636
+	 * @return string
637
+	 */
638
+	public static function get_entity_route($model, $id)
639
+	{
640
+		return EED_Core_Rest_Api::get_collection_route($model). '/' . $id;
641
+	}
642
+
643
+
644
+	/**
645
+	 * Gets the relative URI to a model's REST API singular route, after the EE4 versioned namespace,
646
+	 * excluding the preceding slash.
647
+	 * Eg you pass get_plural_route_to('Event', 12) = 'events/12'
648
+	 *
649
+	 * @param EEM_Base                 $model eg Event or Venue
650
+	 * @param string                 $id
651
+	 * @param EE_Model_Relation_Base $relation_obj
652
+	 * @return string
653
+	 */
654
+	public static function get_relation_route_via(EEM_Base $model, $id, EE_Model_Relation_Base $relation_obj)
655
+	{
656
+		$related_model_name_endpoint_part = ModelRead::getRelatedEntityName(
657
+			$relation_obj->get_other_model()->get_this_model_name(),
658
+			$relation_obj
659
+		);
660
+		return EED_Core_Rest_Api::get_entity_route($model, $id) . '/' . $related_model_name_endpoint_part;
661
+	}
662
+
663
+
664
+
665
+	/**
666
+	 * Adds onto the $relative_route the EE4 REST API versioned namespace.
667
+	 * Eg if given '4.8.36' and 'events', will return 'ee/v4.8.36/events'
668
+	 * @param string $relative_route
669
+	 * @param string $version
670
+	 * @return string
671
+	 */
672
+	public static function get_versioned_route_to($relative_route, $version = '4.8.36'){
673
+		return '/' . EED_Core_Rest_Api::ee_api_namespace . $version . '/' . $relative_route;
674
+	}
675
+
676
+
677
+
678
+	/**
679
+	 * Adds all the RPC-style routes (remote procedure call-like routes, ie
680
+	 * routes that don't conform to the traditional REST CRUD-style).
681
+	 *
682
+	 * @deprecated since 4.9.1
683
+	 */
684
+	protected function _register_rpc_routes()
685
+	{
686
+		$routes = array();
687
+		foreach (self::versions_served() as $version => $hidden_endpoint) {
688
+			$routes[self::ee_api_namespace . $version] = $this->_get_rpc_route_data_for_version(
689
+				$version,
690
+				$hidden_endpoint
691
+			);
692
+		}
693
+		return $routes;
694
+	}
695
+
696
+
697
+
698
+	/**
699
+	 * @param string  $version
700
+	 * @param boolean $hidden_endpoint
701
+	 * @return array
702
+	 */
703
+	protected function _get_rpc_route_data_for_version($version, $hidden_endpoint = false)
704
+	{
705
+		$this_versions_routes = array();
706
+		//checkin endpoint
707
+		$this_versions_routes['registrations/(?P<REG_ID>\d+)/toggle_checkin_for_datetime/(?P<DTT_ID>\d+)'] = array(
708
+			array(
709
+				'callback'        => array(
710
+					'EventEspresso\core\libraries\rest_api\controllers\rpc\Checkin',
711
+					'handleRequestToggleCheckin',
712
+				),
713
+				'methods'         => WP_REST_Server::CREATABLE,
714
+				'hidden_endpoint' => $hidden_endpoint,
715
+				'args'            => array(
716
+					'force' => array(
717
+						'required'    => false,
718
+						'default'     => false,
719
+						'description' => __(
720
+							// @codingStandardsIgnoreStart
721
+							'Whether to force toggle checkin, or to verify the registration status and allowed ticket uses',
722
+							// @codingStandardsIgnoreEnd
723
+							'event_espresso'
724
+						),
725
+					),
726
+				),
727
+				'callback_args'   => array($version),
728
+			),
729
+		);
730
+		return apply_filters(
731
+			'FHEE__EED_Core_Rest_Api___register_rpc_routes__this_versions_routes',
732
+			$this_versions_routes,
733
+			$version,
734
+			$hidden_endpoint
735
+		);
736
+	}
737
+
738
+
739
+
740
+	/**
741
+	 * Gets the query params that can be used when request one or many
742
+	 *
743
+	 * @param EEM_Base $model
744
+	 * @param string   $version
745
+	 * @return array
746
+	 */
747
+	protected function _get_response_selection_query_params(\EEM_Base $model, $version)
748
+	{
749
+		return apply_filters(
750
+			'FHEE__EED_Core_Rest_Api___get_response_selection_query_params',
751
+			array(
752
+				'include'   => array(
753
+					'required' => false,
754
+					'default'  => '*',
755
+					'type'     => 'string',
756
+				),
757
+				'calculate' => array(
758
+					'required'          => false,
759
+					'default'           => '',
760
+					'enum'              => self::$_field_calculator->retrieveCalculatedFieldsForModel($model),
761
+					'type'              => 'string',
762
+					//because we accept a CSV'd list of the enumerated strings, WP core validation and sanitization
763
+					//freaks out. We'll just validate this argument while handling the request
764
+					'validate_callback' => null,
765
+					'sanitize_callback' => null,
766
+				),
767
+			),
768
+			$model,
769
+			$version
770
+		);
771
+	}
772
+
773
+
774
+
775
+	/**
776
+	 * Gets the parameters acceptable for delete requests
777
+	 *
778
+	 * @param \EEM_Base $model
779
+	 * @param string    $version
780
+	 * @return array
781
+	 */
782
+	protected function _get_delete_query_params(\EEM_Base $model, $version)
783
+	{
784
+		$params_for_delete = array(
785
+			'allow_blocking' => array(
786
+				'required' => false,
787
+				'default'  => true,
788
+				'type'     => 'boolean',
789
+			),
790
+		);
791
+		$params_for_delete['force'] = array(
792
+			'required' => false,
793
+			'default'  => false,
794
+			'type'     => 'boolean',
795
+		);
796
+		return apply_filters(
797
+			'FHEE__EED_Core_Rest_Api___get_delete_query_params',
798
+			$params_for_delete,
799
+			$model,
800
+			$version
801
+		);
802
+	}
803
+
804
+
805
+
806
+	/**
807
+	 * Gets info about reading query params that are acceptable
808
+	 *
809
+	 * @param \EEM_Base $model eg 'Event' or 'Venue'
810
+	 * @param  string   $version
811
+	 * @return array    describing the args acceptable when querying this model
812
+	 * @throws EE_Error
813
+	 */
814
+	protected function _get_read_query_params(\EEM_Base $model, $version)
815
+	{
816
+		$default_orderby = array();
817
+		foreach ($model->get_combined_primary_key_fields() as $key_field) {
818
+			$default_orderby[$key_field->get_name()] = 'ASC';
819
+		}
820
+		return array_merge(
821
+			$this->_get_response_selection_query_params($model, $version),
822
+			array(
823
+				'where'    => array(
824
+					'required' => false,
825
+					'default'  => array(),
826
+					'type'     => 'object',
827
+					//because we accept an almost infinite list of possible where conditions, WP
828
+					// core validation and sanitization freaks out. We'll just validate this argument
829
+					// while handling the request
830
+					'validate_callback' => null,
831
+					'sanitize_callback' => null,
832
+				),
833
+				'limit'    => array(
834
+					'required' => false,
835
+					'default'  => EED_Core_Rest_Api::get_default_query_limit(),
836
+					'type'     => array(
837
+						'array',
838
+						'string',
839
+						'integer',
840
+					),
841
+					//because we accept a variety of types, WP core validation and sanitization
842
+					//freaks out. We'll just validate this argument while handling the request
843
+					'validate_callback' => null,
844
+					'sanitize_callback' => null,
845
+				),
846
+				'order_by' => array(
847
+					'required' => false,
848
+					'default'  => $default_orderby,
849
+					'type'     => array(
850
+						'object',
851
+						'string',
852
+					),//because we accept a variety of types, WP core validation and sanitization
853
+					//freaks out. We'll just validate this argument while handling the request
854
+					'validate_callback' => null,
855
+					'sanitize_callback' => null,
856
+				),
857
+				'group_by' => array(
858
+					'required' => false,
859
+					'default'  => null,
860
+					'type'     => array(
861
+						'object',
862
+						'string',
863
+					),
864
+					//because we accept  an almost infinite list of possible groupings,
865
+					// WP core validation and sanitization
866
+					//freaks out. We'll just validate this argument while handling the request
867
+					'validate_callback' => null,
868
+					'sanitize_callback' => null,
869
+				),
870
+				'having'   => array(
871
+					'required' => false,
872
+					'default'  => null,
873
+					'type'     => 'object',
874
+					//because we accept an almost infinite list of possible where conditions, WP
875
+					// core validation and sanitization freaks out. We'll just validate this argument
876
+					// while handling the request
877
+					'validate_callback' => null,
878
+					'sanitize_callback' => null,
879
+				),
880
+				'caps'     => array(
881
+					'required' => false,
882
+					'default'  => EEM_Base::caps_read,
883
+					'type'     => 'string',
884
+					'enum'     => array(
885
+						EEM_Base::caps_read,
886
+						EEM_Base::caps_read_admin,
887
+						EEM_Base::caps_edit,
888
+						EEM_Base::caps_delete
889
+					)
890
+				),
891
+			)
892
+		);
893
+	}
894
+
895
+
896
+
897
+	/**
898
+	 * Gets parameter information for a model regarding writing data
899
+	 *
900
+	 * @param string           $model_name
901
+	 * @param ModelVersionInfo $model_version_info
902
+	 * @param boolean          $create                                       whether this is for request to create (in which case we need
903
+	 *                                                                       all required params) or just to update (in which case we don't need those on every request)
904
+	 * @return array
905
+	 */
906
+	protected function _get_write_params(
907
+		$model_name,
908
+		ModelVersionInfo $model_version_info,
909
+		$create = false
910
+	) {
911
+		$model = EE_Registry::instance()->load_model($model_name);
912
+		$fields = $model_version_info->fieldsOnModelInThisVersion($model);
913
+		$args_info = array();
914
+		foreach ($fields as $field_name => $field_obj) {
915
+			if ($field_obj->is_auto_increment()) {
916
+				//totally ignore auto increment IDs
917
+				continue;
918
+			}
919
+			$arg_info = $field_obj->getSchema();
920
+			$required = $create && ! $field_obj->is_nullable() && $field_obj->get_default_value() === null;
921
+			$arg_info['required'] = $required;
922
+			//remove the read-only flag. If it were read-only we wouldn't list it as an argument while writing, right?
923
+			unset($arg_info['readonly']);
924
+			$schema_properties = $field_obj->getSchemaProperties();
925
+			if (
926
+				isset($schema_properties['raw'])
927
+				&& $field_obj->getSchemaType() === 'object'
928
+			) {
929
+				//if there's a "raw" form of this argument, use those properties instead
930
+				$arg_info = array_replace(
931
+					$arg_info,
932
+					$schema_properties['raw']
933
+				);
934
+			}
935
+			$arg_info['default'] = ModelDataTranslator::prepareFieldValueForJson(
936
+				$field_obj,
937
+				$field_obj->get_default_value(),
938
+				$model_version_info->requestedVersion()
939
+			);
940
+			//we do our own validation and sanitization within the controller
941
+			$arg_info['sanitize_callback'] =
942
+				array(
943
+					'EED_Core_Rest_Api',
944
+					'default_sanitize_callback',
945
+				);
946
+			$args_info[$field_name] = $arg_info;
947
+			if ($field_obj instanceof EE_Datetime_Field) {
948
+				$gmt_arg_info = $arg_info;
949
+				$gmt_arg_info['description'] = sprintf(
950
+					esc_html__(
951
+						'%1$s - the value for this field in UTC. Ignored if %2$s is provided.',
952
+						'event_espresso'
953
+					),
954
+					$field_obj->get_nicename(),
955
+					$field_name
956
+				);
957
+				$args_info[$field_name . '_gmt'] = $gmt_arg_info;
958
+			}
959
+		}
960
+		return $args_info;
961
+	}
962
+
963
+
964
+
965
+	/**
966
+	 * Replacement for WP API's 'rest_parse_request_arg'.
967
+	 * If the value is blank but not required, don't bother validating it.
968
+	 * Also, it uses our email validation instead of WP API's default.
969
+	 *
970
+	 * @param                 $value
971
+	 * @param WP_REST_Request $request
972
+	 * @param                 $param
973
+	 * @return bool|true|WP_Error
974
+	 * @throws InvalidArgumentException
975
+	 * @throws InvalidInterfaceException
976
+	 * @throws InvalidDataTypeException
977
+	 */
978
+	public static function default_sanitize_callback( $value, WP_REST_Request $request, $param)
979
+	{
980
+		$attributes = $request->get_attributes();
981
+		if (! isset($attributes['args'][$param])
982
+			|| ! is_array($attributes['args'][$param])) {
983
+			$validation_result = true;
984
+		} else {
985
+			$args = $attributes['args'][$param];
986
+			if ((
987
+					$value === ''
988
+					|| $value === null
989
+				)
990
+				&& (! isset($args['required'])
991
+					|| $args['required'] === false
992
+				)
993
+			) {
994
+				//not required and not provided? that's cool
995
+				$validation_result = true;
996
+			} elseif (isset($args['format'])
997
+				&& $args['format'] === 'email'
998
+			) {
999
+				$validation_result = true;
1000
+				if (! self::_validate_email($value)) {
1001
+					$validation_result = new WP_Error(
1002
+						'rest_invalid_param',
1003
+						esc_html__(
1004
+							'The email address is not valid or does not exist.',
1005
+							'event_espresso'
1006
+						)
1007
+					);
1008
+				}
1009
+			} else {
1010
+				$validation_result = rest_validate_value_from_schema($value, $args, $param);
1011
+			}
1012
+		}
1013
+		if (is_wp_error($validation_result)) {
1014
+			return $validation_result;
1015
+		}
1016
+		return rest_sanitize_request_arg($value, $request, $param);
1017
+	}
1018
+
1019
+
1020
+
1021
+	/**
1022
+	 * Returns whether or not this email address is valid. Copied from EE_Email_Validation_Strategy::_validate_email()
1023
+	 *
1024
+	 * @param $email
1025
+	 * @return bool
1026
+	 * @throws InvalidArgumentException
1027
+	 * @throws InvalidInterfaceException
1028
+	 * @throws InvalidDataTypeException
1029
+	 */
1030
+	protected static function _validate_email($email){
1031
+		try {
1032
+			EmailAddressFactory::create($email);
1033
+			return true;
1034
+		} catch (EmailValidationException $e) {
1035
+			return false;
1036
+		}
1037
+	}
1038
+
1039
+
1040
+
1041
+	/**
1042
+	 * Gets routes for the config
1043
+	 *
1044
+	 * @return array @see _register_model_routes
1045
+	 * @deprecated since version 4.9.1
1046
+	 */
1047
+	protected function _register_config_routes()
1048
+	{
1049
+		$config_routes = array();
1050
+		foreach (self::versions_served() as $version => $hidden_endpoint) {
1051
+			$config_routes[self::ee_api_namespace . $version] = $this->_get_config_route_data_for_version(
1052
+				$version,
1053
+				$hidden_endpoint
1054
+			);
1055
+		}
1056
+		return $config_routes;
1057
+	}
1058
+
1059
+
1060
+
1061
+	/**
1062
+	 * Gets routes for the config for the specified version
1063
+	 *
1064
+	 * @param string  $version
1065
+	 * @param boolean $hidden_endpoint
1066
+	 * @return array
1067
+	 */
1068
+	protected function _get_config_route_data_for_version($version, $hidden_endpoint)
1069
+	{
1070
+		return array(
1071
+			'config'    => array(
1072
+				array(
1073
+					'callback'        => array(
1074
+						'EventEspresso\core\libraries\rest_api\controllers\config\Read',
1075
+						'handleRequest',
1076
+					),
1077
+					'methods'         => WP_REST_Server::READABLE,
1078
+					'hidden_endpoint' => $hidden_endpoint,
1079
+					'callback_args'   => array($version),
1080
+				),
1081
+			),
1082
+			'site_info' => array(
1083
+				array(
1084
+					'callback'        => array(
1085
+						'EventEspresso\core\libraries\rest_api\controllers\config\Read',
1086
+						'handleRequestSiteInfo',
1087
+					),
1088
+					'methods'         => WP_REST_Server::READABLE,
1089
+					'hidden_endpoint' => $hidden_endpoint,
1090
+					'callback_args'   => array($version),
1091
+				),
1092
+			),
1093
+		);
1094
+	}
1095
+
1096
+
1097
+
1098
+	/**
1099
+	 * Gets the meta info routes
1100
+	 *
1101
+	 * @return array @see _register_model_routes
1102
+	 * @deprecated since version 4.9.1
1103
+	 */
1104
+	protected function _register_meta_routes()
1105
+	{
1106
+		$meta_routes = array();
1107
+		foreach (self::versions_served() as $version => $hidden_endpoint) {
1108
+			$meta_routes[self::ee_api_namespace . $version] = $this->_get_meta_route_data_for_version(
1109
+				$version,
1110
+				$hidden_endpoint
1111
+			);
1112
+		}
1113
+		return $meta_routes;
1114
+	}
1115
+
1116
+
1117
+
1118
+	/**
1119
+	 * @param string  $version
1120
+	 * @param boolean $hidden_endpoint
1121
+	 * @return array
1122
+	 */
1123
+	protected function _get_meta_route_data_for_version($version, $hidden_endpoint = false)
1124
+	{
1125
+		return array(
1126
+			'resources' => array(
1127
+				array(
1128
+					'callback'        => array(
1129
+						'EventEspresso\core\libraries\rest_api\controllers\model\Meta',
1130
+						'handleRequestModelsMeta',
1131
+					),
1132
+					'methods'         => WP_REST_Server::READABLE,
1133
+					'hidden_endpoint' => $hidden_endpoint,
1134
+					'callback_args'   => array($version),
1135
+				),
1136
+			),
1137
+		);
1138
+	}
1139
+
1140
+
1141
+
1142
+	/**
1143
+	 * Tries to hide old 4.6 endpoints from the
1144
+	 *
1145
+	 * @param array $route_data
1146
+	 * @return array
1147
+	 * @throws \EE_Error
1148
+	 */
1149
+	public static function hide_old_endpoints($route_data)
1150
+	{
1151
+		//allow API clients to override which endpoints get hidden, in case
1152
+		//they want to discover particular endpoints
1153
+		//also, we don't have access to the request so we have to just grab it from the superglobal
1154
+		$force_show_ee_namespace = ltrim(
1155
+			EEH_Array::is_set($_REQUEST, 'force_show_ee_namespace', ''),
1156
+			'/'
1157
+		);
1158
+		foreach (EED_Core_Rest_Api::get_ee_route_data() as $namespace => $relative_urls) {
1159
+			foreach ($relative_urls as $resource_name => $endpoints) {
1160
+				foreach ($endpoints as $key => $endpoint) {
1161
+					//skip schema and other route options
1162
+					if (! is_numeric($key)) {
1163
+						continue;
1164
+					}
1165
+					//by default, hide "hidden_endpoint"s, unless the request indicates
1166
+					//to $force_show_ee_namespace, in which case only show that one
1167
+					//namespace's endpoints (and hide all others)
1168
+					if (
1169
+						($force_show_ee_namespace !== '' && $force_show_ee_namespace !== $namespace)
1170
+						|| ($endpoint['hidden_endpoint'] && $force_show_ee_namespace === '')
1171
+					) {
1172
+						$full_route = '/' . ltrim($namespace, '/');
1173
+						$full_route .= '/' . ltrim($resource_name, '/');
1174
+						unset($route_data[$full_route]);
1175
+					}
1176
+				}
1177
+			}
1178
+		}
1179
+		return $route_data;
1180
+	}
1181
+
1182
+
1183
+
1184
+	/**
1185
+	 * Returns an array describing which versions of core support serving requests for.
1186
+	 * Keys are core versions' major and minor version, and values are the
1187
+	 * LOWEST requested version they can serve. Eg, 4.7 can serve requests for 4.6-like
1188
+	 * data by just removing a few models and fields from the responses. However, 4.15 might remove
1189
+	 * the answers table entirely, in which case it would be very difficult for
1190
+	 * it to serve 4.6-style responses.
1191
+	 * Versions of core that are missing from this array are unknowns.
1192
+	 * previous ver
1193
+	 *
1194
+	 * @return array
1195
+	 */
1196
+	public static function version_compatibilities()
1197
+	{
1198
+		return apply_filters(
1199
+			'FHEE__EED_Core_REST_API__version_compatibilities',
1200
+			array(
1201
+				'4.8.29' => '4.8.29',
1202
+				'4.8.33' => '4.8.29',
1203
+				'4.8.34' => '4.8.29',
1204
+				'4.8.36' => '4.8.29',
1205
+			)
1206
+		);
1207
+	}
1208
+
1209
+
1210
+
1211
+	/**
1212
+	 * Gets the latest API version served. Eg if there
1213
+	 * are two versions served of the API, 4.8.29 and 4.8.32, and
1214
+	 * we are on core version 4.8.34, it will return the string "4.8.32"
1215
+	 *
1216
+	 * @return string
1217
+	 */
1218
+	public static function latest_rest_api_version()
1219
+	{
1220
+		$versions_served = \EED_Core_Rest_Api::versions_served();
1221
+		$versions_served_keys = array_keys($versions_served);
1222
+		return end($versions_served_keys);
1223
+	}
1224
+
1225
+
1226
+
1227
+	/**
1228
+	 * Using EED_Core_Rest_Api::version_compatibilities(), determines what version of
1229
+	 * EE the API can serve requests for. Eg, if we are on 4.15 of core, and
1230
+	 * we can serve requests from 4.12 or later, this will return array( '4.12', '4.13', '4.14', '4.15' ).
1231
+	 * We also indicate whether or not this version should be put in the index or not
1232
+	 *
1233
+	 * @return array keys are API version numbers (just major and minor numbers), and values
1234
+	 * are whether or not they should be hidden
1235
+	 */
1236
+	public static function versions_served()
1237
+	{
1238
+		$versions_served = array();
1239
+		$possibly_served_versions = EED_Core_Rest_Api::version_compatibilities();
1240
+		$lowest_compatible_version = end($possibly_served_versions);
1241
+		reset($possibly_served_versions);
1242
+		$versions_served_historically = array_keys($possibly_served_versions);
1243
+		$latest_version = end($versions_served_historically);
1244
+		reset($versions_served_historically);
1245
+		//for each version of core we have ever served:
1246
+		foreach ($versions_served_historically as $key_versioned_endpoint) {
1247
+			//if it's not above the current core version, and it's compatible with the current version of core
1248
+			if ($key_versioned_endpoint === $latest_version) {
1249
+				//don't hide the latest version in the index
1250
+				$versions_served[$key_versioned_endpoint] = false;
1251
+			} elseif (
1252
+				$key_versioned_endpoint >= $lowest_compatible_version
1253
+				&& $key_versioned_endpoint < EED_Core_Rest_Api::core_version()
1254
+			) {
1255
+				//include, but hide, previous versions which are still supported
1256
+				$versions_served[$key_versioned_endpoint] = true;
1257
+			} elseif (apply_filters(
1258
+				'FHEE__EED_Core_Rest_Api__versions_served__include_incompatible_versions',
1259
+				false,
1260
+				$possibly_served_versions
1261
+			)) {
1262
+				//if a version is no longer supported, don't include it in index or list of versions served
1263
+				$versions_served[$key_versioned_endpoint] = true;
1264
+			}
1265
+		}
1266
+		return $versions_served;
1267
+	}
1268
+
1269
+
1270
+
1271
+	/**
1272
+	 * Gets the major and minor version of EE core's version string
1273
+	 *
1274
+	 * @return string
1275
+	 */
1276
+	public static function core_version()
1277
+	{
1278
+		return apply_filters(
1279
+			'FHEE__EED_Core_REST_API__core_version',
1280
+			implode(
1281
+				'.',
1282
+				array_slice(
1283
+					explode(
1284
+						'.',
1285
+						espresso_version()
1286
+					),
1287
+				0,
1288
+				3
1289
+				)
1290
+			)
1291
+		);
1292
+	}
1293
+
1294
+
1295
+
1296
+	/**
1297
+	 * Gets the default limit that should be used when querying for resources
1298
+	 *
1299
+	 * @return int
1300
+	 */
1301
+	public static function get_default_query_limit()
1302
+	{
1303
+		//we actually don't use a const because we want folks to always use
1304
+		//this method, not the const directly
1305
+		return apply_filters(
1306
+			'FHEE__EED_Core_Rest_Api__get_default_query_limit',
1307
+			50
1308
+		);
1309
+	}
1310
+
1311
+
1312
+
1313
+	/**
1314
+	 *    run - initial module setup
1315
+	 *
1316
+	 * @access    public
1317
+	 * @param  WP $WP
1318
+	 * @return    void
1319
+	 */
1320
+	public function run($WP)
1321
+	{
1322
+	}
1323 1323
 }
1324 1324
 
1325 1325
 // End of file EED_Core_Rest_Api.module.php
Please login to merge, or discard this patch.
core/middleware/EE_Recommended_Versions.core.php 2 patches
Indentation   +145 added lines, -145 removed lines patch added patch discarded remove patch
@@ -21,157 +21,157 @@
 block discarded – undo
21 21
 {
22 22
 
23 23
 
24
-    /**
25
-     * converts a Request to a Response
26
-     *
27
-     * @param EE_Request  $request
28
-     * @param EE_Response $response
29
-     * @return EE_Response
30
-     * @throws InvalidDataTypeException
31
-     */
32
-    public function handle_request(EE_Request $request, EE_Response $response)
33
-    {
34
-        $this->_request  = $request;
35
-        $this->_response = $response;
36
-        //$this->_response->add_output( "\n\t IN >>  " . __CLASS__ );
37
-        //$this->_response->set_notice( 1, 'hey look at this' );
38
-        // check required WP version
39
-        if (! $this->_minimum_wp_version_required()) {
40
-            $this->_request->un_set('activate', true);
41
-            add_action('admin_notices', array($this, 'minimum_wp_version_error'), 1);
42
-            //$this->_response->add_output( "\n<br />" . 'minimum_wp_version_error' );
43
-            $this->_response->terminate_request();
44
-            $this->_response->deactivate_plugin();
45
-        }
46
-        // check recommended PHP version
47
-        if (! $this->_minimum_php_version_recommended()) {
48
-            $this->_display_minimum_recommended_php_version_notice();
49
-        }
50
-        $this->_response = $this->process_request_stack($this->_request, $this->_response);
51
-        //$this->_response->add_output( "\n\t OUT << " . __CLASS__ );
52
-        return $this->_response;
53
-    }
54
-
55
-
56
-    /**
57
-     * Helper method to assess installed wp version against given values.
58
-     * By default this compares the required minimum version of WP for EE against the installed version of WP
59
-     * Note, $wp_version is the first parameter sent into the PHP version_compare function (what is being checked
60
-     * against) so consider that when sending in your values.
61
-     *
62
-     * @param string $version_to_check
63
-     * @param string $operator
64
-     * @return bool
65
-     */
66
-    public static function check_wp_version($version_to_check = EE_MIN_WP_VER_REQUIRED, $operator = '>=')
67
-    {
68
-        global $wp_version;
69
-        return version_compare(
70
-            // first account for wp_version being pre-release
71
-            // (like RC, beta etc) which are usually in the format like 4.7-RC3-39519
72
-            strpos($wp_version, '-') > 0
73
-                ? substr($wp_version, 0, strpos($wp_version, '-'))
74
-                : $wp_version,
75
-            $version_to_check,
76
-            $operator
77
-        );
78
-    }
79
-
80
-
81
-
82
-    /**
83
-     *    _minimum_wp_version_required
84
-     *
85
-     * @access private
86
-     * @return boolean
87
-     */
88
-    private function _minimum_wp_version_required()
89
-    {
90
-        return EE_Recommended_Versions::check_wp_version();
91
-    }
92
-
93
-
94
-
95
-    /**
96
-     *    _check_php_version
97
-     *
98
-     * @access private
99
-     * @param string $min_version
100
-     * @return boolean
101
-     */
102
-    private function _check_php_version($min_version = EE_MIN_PHP_VER_RECOMMENDED)
103
-    {
104
-        return version_compare(PHP_VERSION, $min_version, '>=') ? true : false;
105
-    }
106
-
107
-
108
-
109
-    /**
110
-     *    _minimum_php_version_recommended
111
-     *
112
-     * @access private
113
-     * @return boolean
114
-     */
115
-    private function _minimum_php_version_recommended()
116
-    {
117
-        return $this->_check_php_version();
118
-    }
119
-
120
-
121
-
122
-    /**
123
-     *    minimum_wp_version_error
124
-     *
125
-     * @return void
126
-     */
127
-    public function minimum_wp_version_error()
128
-    {
129
-        global $wp_version;
130
-        ?>
24
+	/**
25
+	 * converts a Request to a Response
26
+	 *
27
+	 * @param EE_Request  $request
28
+	 * @param EE_Response $response
29
+	 * @return EE_Response
30
+	 * @throws InvalidDataTypeException
31
+	 */
32
+	public function handle_request(EE_Request $request, EE_Response $response)
33
+	{
34
+		$this->_request  = $request;
35
+		$this->_response = $response;
36
+		//$this->_response->add_output( "\n\t IN >>  " . __CLASS__ );
37
+		//$this->_response->set_notice( 1, 'hey look at this' );
38
+		// check required WP version
39
+		if (! $this->_minimum_wp_version_required()) {
40
+			$this->_request->un_set('activate', true);
41
+			add_action('admin_notices', array($this, 'minimum_wp_version_error'), 1);
42
+			//$this->_response->add_output( "\n<br />" . 'minimum_wp_version_error' );
43
+			$this->_response->terminate_request();
44
+			$this->_response->deactivate_plugin();
45
+		}
46
+		// check recommended PHP version
47
+		if (! $this->_minimum_php_version_recommended()) {
48
+			$this->_display_minimum_recommended_php_version_notice();
49
+		}
50
+		$this->_response = $this->process_request_stack($this->_request, $this->_response);
51
+		//$this->_response->add_output( "\n\t OUT << " . __CLASS__ );
52
+		return $this->_response;
53
+	}
54
+
55
+
56
+	/**
57
+	 * Helper method to assess installed wp version against given values.
58
+	 * By default this compares the required minimum version of WP for EE against the installed version of WP
59
+	 * Note, $wp_version is the first parameter sent into the PHP version_compare function (what is being checked
60
+	 * against) so consider that when sending in your values.
61
+	 *
62
+	 * @param string $version_to_check
63
+	 * @param string $operator
64
+	 * @return bool
65
+	 */
66
+	public static function check_wp_version($version_to_check = EE_MIN_WP_VER_REQUIRED, $operator = '>=')
67
+	{
68
+		global $wp_version;
69
+		return version_compare(
70
+			// first account for wp_version being pre-release
71
+			// (like RC, beta etc) which are usually in the format like 4.7-RC3-39519
72
+			strpos($wp_version, '-') > 0
73
+				? substr($wp_version, 0, strpos($wp_version, '-'))
74
+				: $wp_version,
75
+			$version_to_check,
76
+			$operator
77
+		);
78
+	}
79
+
80
+
81
+
82
+	/**
83
+	 *    _minimum_wp_version_required
84
+	 *
85
+	 * @access private
86
+	 * @return boolean
87
+	 */
88
+	private function _minimum_wp_version_required()
89
+	{
90
+		return EE_Recommended_Versions::check_wp_version();
91
+	}
92
+
93
+
94
+
95
+	/**
96
+	 *    _check_php_version
97
+	 *
98
+	 * @access private
99
+	 * @param string $min_version
100
+	 * @return boolean
101
+	 */
102
+	private function _check_php_version($min_version = EE_MIN_PHP_VER_RECOMMENDED)
103
+	{
104
+		return version_compare(PHP_VERSION, $min_version, '>=') ? true : false;
105
+	}
106
+
107
+
108
+
109
+	/**
110
+	 *    _minimum_php_version_recommended
111
+	 *
112
+	 * @access private
113
+	 * @return boolean
114
+	 */
115
+	private function _minimum_php_version_recommended()
116
+	{
117
+		return $this->_check_php_version();
118
+	}
119
+
120
+
121
+
122
+	/**
123
+	 *    minimum_wp_version_error
124
+	 *
125
+	 * @return void
126
+	 */
127
+	public function minimum_wp_version_error()
128
+	{
129
+		global $wp_version;
130
+		?>
131 131
         <div class="error">
132 132
             <p>
133 133
                 <?php
134
-                printf(
135
-                    __('We\'re sorry, but Event Espresso requires WordPress version %1$s or greater in order to operate. You are currently running version %2$s.%3$sFor information on how to update your version of WordPress, please go to %4$s.',
136
-                        'event_espresso'),
137
-                    EE_MIN_WP_VER_REQUIRED,
138
-                    $wp_version,
139
-                    '<br/>',
140
-                    '<a href="http://codex.wordpress.org/Updating_WordPress">http://codex.wordpress.org/Updating_WordPress</a>'
141
-                );
142
-                ?>
134
+				printf(
135
+					__('We\'re sorry, but Event Espresso requires WordPress version %1$s or greater in order to operate. You are currently running version %2$s.%3$sFor information on how to update your version of WordPress, please go to %4$s.',
136
+						'event_espresso'),
137
+					EE_MIN_WP_VER_REQUIRED,
138
+					$wp_version,
139
+					'<br/>',
140
+					'<a href="http://codex.wordpress.org/Updating_WordPress">http://codex.wordpress.org/Updating_WordPress</a>'
141
+				);
142
+				?>
143 143
             </p>
144 144
         </div>
145 145
         <?php
146
-    }
147
-
148
-
149
-
150
-    /**
151
-     *    _display_minimum_recommended_php_version_notice
152
-     *
153
-     * @access private
154
-     * @return void
155
-     * @throws InvalidDataTypeException
156
-     */
157
-    private function _display_minimum_recommended_php_version_notice()
158
-    {
159
-        if($this->_request->isAdmin()){
160
-            new PersistentAdminNotice(
161
-                'php_version_' . str_replace('.', '-', EE_MIN_PHP_VER_RECOMMENDED) . '_recommended',
162
-                sprintf(
163
-                    __(
164
-                        'Event Espresso recommends PHP version %1$s or greater for optimal performance. 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.',
165
-                        'event_espresso'
166
-                    ),
167
-                    EE_MIN_PHP_VER_RECOMMENDED,
168
-                    PHP_VERSION,
169
-                    '<br/>',
170
-                    '<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
171
-                )
172
-            );
173
-        }
174
-    }
146
+	}
147
+
148
+
149
+
150
+	/**
151
+	 *    _display_minimum_recommended_php_version_notice
152
+	 *
153
+	 * @access private
154
+	 * @return void
155
+	 * @throws InvalidDataTypeException
156
+	 */
157
+	private function _display_minimum_recommended_php_version_notice()
158
+	{
159
+		if($this->_request->isAdmin()){
160
+			new PersistentAdminNotice(
161
+				'php_version_' . str_replace('.', '-', EE_MIN_PHP_VER_RECOMMENDED) . '_recommended',
162
+				sprintf(
163
+					__(
164
+						'Event Espresso recommends PHP version %1$s or greater for optimal performance. 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.',
165
+						'event_espresso'
166
+					),
167
+					EE_MIN_PHP_VER_RECOMMENDED,
168
+					PHP_VERSION,
169
+					'<br/>',
170
+					'<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
171
+				)
172
+			);
173
+		}
174
+	}
175 175
 
176 176
 
177 177
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -36,7 +36,7 @@  discard block
 block discarded – undo
36 36
         //$this->_response->add_output( "\n\t IN >>  " . __CLASS__ );
37 37
         //$this->_response->set_notice( 1, 'hey look at this' );
38 38
         // check required WP version
39
-        if (! $this->_minimum_wp_version_required()) {
39
+        if ( ! $this->_minimum_wp_version_required()) {
40 40
             $this->_request->un_set('activate', true);
41 41
             add_action('admin_notices', array($this, 'minimum_wp_version_error'), 1);
42 42
             //$this->_response->add_output( "\n<br />" . 'minimum_wp_version_error' );
@@ -44,7 +44,7 @@  discard block
 block discarded – undo
44 44
             $this->_response->deactivate_plugin();
45 45
         }
46 46
         // check recommended PHP version
47
-        if (! $this->_minimum_php_version_recommended()) {
47
+        if ( ! $this->_minimum_php_version_recommended()) {
48 48
             $this->_display_minimum_recommended_php_version_notice();
49 49
         }
50 50
         $this->_response = $this->process_request_stack($this->_request, $this->_response);
@@ -156,9 +156,9 @@  discard block
 block discarded – undo
156 156
      */
157 157
     private function _display_minimum_recommended_php_version_notice()
158 158
     {
159
-        if($this->_request->isAdmin()){
159
+        if ($this->_request->isAdmin()) {
160 160
             new PersistentAdminNotice(
161
-                'php_version_' . str_replace('.', '-', EE_MIN_PHP_VER_RECOMMENDED) . '_recommended',
161
+                'php_version_'.str_replace('.', '-', EE_MIN_PHP_VER_RECOMMENDED).'_recommended',
162 162
                 sprintf(
163 163
                     __(
164 164
                         'Event Espresso recommends PHP version %1$s or greater for optimal performance. 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.',
Please login to merge, or discard this patch.
core/EE_Front_Controller.core.php 1 patch
Indentation   +499 added lines, -499 removed lines patch added patch discarded remove patch
@@ -8,7 +8,7 @@  discard block
 block discarded – undo
8 8
 use EventEspresso\widgets\EspressoWidget;
9 9
 
10 10
 if ( ! defined('EVENT_ESPRESSO_VERSION')) {
11
-    exit('No direct script access allowed');
11
+	exit('No direct script access allowed');
12 12
 }
13 13
 
14 14
 /**
@@ -31,405 +31,405 @@  discard block
 block discarded – undo
31 31
 final class EE_Front_Controller
32 32
 {
33 33
 
34
-    /**
35
-     * @var string $_template_path
36
-     */
37
-    private $_template_path;
38
-
39
-    /**
40
-     * @var string $_template
41
-     */
42
-    private $_template;
43
-
44
-    /**
45
-     * @type EE_Registry $Registry
46
-     */
47
-    protected $Registry;
48
-
49
-    /**
50
-     * @type EE_Request_Handler $Request_Handler
51
-     */
52
-    protected $Request_Handler;
53
-
54
-    /**
55
-     * @type EE_Module_Request_Router $Module_Request_Router
56
-     */
57
-    protected $Module_Request_Router;
58
-
59
-    /**
60
-     * @var PersistentAdminNoticeManager $persistent_admin_notice_manager
61
-     */
62
-    private $persistent_admin_notice_manager;
63
-
64
-
65
-    /**
66
-     *    class constructor
67
-     *    should fire after shortcode, module, addon, or other plugin's default priority init phases have run
68
-     *
69
-     * @access    public
70
-     * @param \EE_Registry              $Registry
71
-     * @param \EE_Request_Handler       $Request_Handler
72
-     * @param \EE_Module_Request_Router $Module_Request_Router
73
-     */
74
-    public function __construct(
75
-        EE_Registry $Registry,
76
-        EE_Request_Handler $Request_Handler,
77
-        EE_Module_Request_Router $Module_Request_Router
78
-    ) {
79
-        $this->Registry              = $Registry;
80
-        $this->Request_Handler       = $Request_Handler;
81
-        $this->Module_Request_Router = $Module_Request_Router;
82
-        // determine how to integrate WP_Query with the EE models
83
-        add_action('AHEE__EE_System__initialize', array($this, 'employ_CPT_Strategy'));
84
-        // just in case any nag notices are created during the request
85
-        add_action('AHEE__EE_System__initialize_last', array($this, 'loadPersistentAdminNoticeManager'));
86
-        // load other resources and begin to actually run shortcodes and modules
87
-        add_action('wp_loaded', array($this, 'wp_loaded'), 5);
88
-        // analyse the incoming WP request
89
-        add_action('parse_request', array($this, 'get_request'), 1, 1);
90
-        // process request with module factory
91
-        add_action('pre_get_posts', array($this, 'pre_get_posts'), 10, 1);
92
-        // before headers sent
93
-        add_action('wp', array($this, 'wp'), 5);
94
-        // primarily used to process any content shortcodes
95
-        add_action('template_redirect', array($this, 'templateRedirect'), 999);
96
-        // header
97
-        add_action('wp_head', array($this, 'header_meta_tag'), 5);
98
-        add_action('wp_print_scripts', array($this, 'wp_print_scripts'), 10);
99
-        add_filter('template_include', array($this, 'template_include'), 1);
100
-        // display errors
101
-        add_action('loop_start', array($this, 'display_errors'), 2);
102
-        // the content
103
-        // add_filter( 'the_content', array( $this, 'the_content' ), 5, 1 );
104
-        //exclude our private cpt comments
105
-        add_filter('comments_clauses', array($this, 'filter_wp_comments'), 10, 1);
106
-        //make sure any ajax requests will respect the url schema when requests are made against admin-ajax.php (http:// or https://)
107
-        add_filter('admin_url', array($this, 'maybe_force_admin_ajax_ssl'), 200, 1);
108
-        // action hook EE
109
-        do_action('AHEE__EE_Front_Controller__construct__done', $this);
110
-        // for checking that browser cookies are enabled
111
-        if (apply_filters('FHEE__EE_Front_Controller____construct__set_test_cookie', true)) {
112
-            setcookie('ee_cookie_test', uniqid('ect',true), time() + DAY_IN_SECONDS, '/');
113
-        }
114
-    }
115
-
116
-
117
-    /**
118
-     * @return EE_Request_Handler
119
-     */
120
-    public function Request_Handler()
121
-    {
122
-        return $this->Request_Handler;
123
-    }
124
-
125
-
126
-    /**
127
-     * @return EE_Module_Request_Router
128
-     */
129
-    public function Module_Request_Router()
130
-    {
131
-        return $this->Module_Request_Router;
132
-    }
133
-
134
-
135
-
136
-    /**
137
-     * @return LegacyShortcodesManager
138
-     */
139
-    public function getLegacyShortcodesManager()
140
-    {
141
-        return EE_Config::getLegacyShortcodesManager();
142
-    }
143
-
144
-
145
-
146
-
147
-
148
-    /***********************************************        INIT ACTION HOOK         ***********************************************/
149
-
150
-
151
-
152
-    /**
153
-     * filter_wp_comments
154
-     * This simply makes sure that any "private" EE CPTs do not have their comments show up in any wp comment
155
-     * widgets/queries done on frontend
156
-     *
157
-     * @param  array $clauses array of comment clauses setup by WP_Comment_Query
158
-     * @return array array of comment clauses with modifications.
159
-     */
160
-    public function filter_wp_comments($clauses)
161
-    {
162
-        global $wpdb;
163
-        if (strpos($clauses['join'], $wpdb->posts) !== false) {
164
-            $cpts = EE_Register_CPTs::get_private_CPTs();
165
-            foreach ($cpts as $cpt => $details) {
166
-                $clauses['where'] .= $wpdb->prepare(" AND $wpdb->posts.post_type != %s", $cpt);
167
-            }
168
-        }
169
-        return $clauses;
170
-    }
171
-
172
-
173
-    /**
174
-     * @return void
175
-     * @throws EE_Error
176
-     * @throws ReflectionException
177
-     */
178
-    public function employ_CPT_Strategy()
179
-    {
180
-        if (apply_filters('FHEE__EE_Front_Controller__employ_CPT_Strategy', true)) {
181
-            $this->Registry->load_core('CPT_Strategy');
182
-        }
183
-    }
184
-
185
-
186
-    /**
187
-     * @return void
188
-     * @throws InvalidArgumentException
189
-     * @throws InvalidDataTypeException
190
-     * @throws InvalidInterfaceException
191
-     */
192
-    public function loadPersistentAdminNoticeManager()
193
-    {
194
-        $this->persistent_admin_notice_manager = LoaderFactory::getLoader()->getShared(
195
-            'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
196
-        );
197
-    }
198
-
199
-
200
-    /**
201
-     * this just makes sure that if the site is using ssl that we force that for any admin ajax calls from frontend
202
-     *
203
-     * @param  string $url incoming url
204
-     * @return string         final assembled url
205
-     */
206
-    public function maybe_force_admin_ajax_ssl($url)
207
-    {
208
-        if (is_ssl() && preg_match('/admin-ajax.php/', $url)) {
209
-            $url = str_replace('http://', 'https://', $url);
210
-        }
211
-        return $url;
212
-    }
34
+	/**
35
+	 * @var string $_template_path
36
+	 */
37
+	private $_template_path;
38
+
39
+	/**
40
+	 * @var string $_template
41
+	 */
42
+	private $_template;
43
+
44
+	/**
45
+	 * @type EE_Registry $Registry
46
+	 */
47
+	protected $Registry;
48
+
49
+	/**
50
+	 * @type EE_Request_Handler $Request_Handler
51
+	 */
52
+	protected $Request_Handler;
53
+
54
+	/**
55
+	 * @type EE_Module_Request_Router $Module_Request_Router
56
+	 */
57
+	protected $Module_Request_Router;
58
+
59
+	/**
60
+	 * @var PersistentAdminNoticeManager $persistent_admin_notice_manager
61
+	 */
62
+	private $persistent_admin_notice_manager;
63
+
64
+
65
+	/**
66
+	 *    class constructor
67
+	 *    should fire after shortcode, module, addon, or other plugin's default priority init phases have run
68
+	 *
69
+	 * @access    public
70
+	 * @param \EE_Registry              $Registry
71
+	 * @param \EE_Request_Handler       $Request_Handler
72
+	 * @param \EE_Module_Request_Router $Module_Request_Router
73
+	 */
74
+	public function __construct(
75
+		EE_Registry $Registry,
76
+		EE_Request_Handler $Request_Handler,
77
+		EE_Module_Request_Router $Module_Request_Router
78
+	) {
79
+		$this->Registry              = $Registry;
80
+		$this->Request_Handler       = $Request_Handler;
81
+		$this->Module_Request_Router = $Module_Request_Router;
82
+		// determine how to integrate WP_Query with the EE models
83
+		add_action('AHEE__EE_System__initialize', array($this, 'employ_CPT_Strategy'));
84
+		// just in case any nag notices are created during the request
85
+		add_action('AHEE__EE_System__initialize_last', array($this, 'loadPersistentAdminNoticeManager'));
86
+		// load other resources and begin to actually run shortcodes and modules
87
+		add_action('wp_loaded', array($this, 'wp_loaded'), 5);
88
+		// analyse the incoming WP request
89
+		add_action('parse_request', array($this, 'get_request'), 1, 1);
90
+		// process request with module factory
91
+		add_action('pre_get_posts', array($this, 'pre_get_posts'), 10, 1);
92
+		// before headers sent
93
+		add_action('wp', array($this, 'wp'), 5);
94
+		// primarily used to process any content shortcodes
95
+		add_action('template_redirect', array($this, 'templateRedirect'), 999);
96
+		// header
97
+		add_action('wp_head', array($this, 'header_meta_tag'), 5);
98
+		add_action('wp_print_scripts', array($this, 'wp_print_scripts'), 10);
99
+		add_filter('template_include', array($this, 'template_include'), 1);
100
+		// display errors
101
+		add_action('loop_start', array($this, 'display_errors'), 2);
102
+		// the content
103
+		// add_filter( 'the_content', array( $this, 'the_content' ), 5, 1 );
104
+		//exclude our private cpt comments
105
+		add_filter('comments_clauses', array($this, 'filter_wp_comments'), 10, 1);
106
+		//make sure any ajax requests will respect the url schema when requests are made against admin-ajax.php (http:// or https://)
107
+		add_filter('admin_url', array($this, 'maybe_force_admin_ajax_ssl'), 200, 1);
108
+		// action hook EE
109
+		do_action('AHEE__EE_Front_Controller__construct__done', $this);
110
+		// for checking that browser cookies are enabled
111
+		if (apply_filters('FHEE__EE_Front_Controller____construct__set_test_cookie', true)) {
112
+			setcookie('ee_cookie_test', uniqid('ect',true), time() + DAY_IN_SECONDS, '/');
113
+		}
114
+	}
115
+
116
+
117
+	/**
118
+	 * @return EE_Request_Handler
119
+	 */
120
+	public function Request_Handler()
121
+	{
122
+		return $this->Request_Handler;
123
+	}
124
+
125
+
126
+	/**
127
+	 * @return EE_Module_Request_Router
128
+	 */
129
+	public function Module_Request_Router()
130
+	{
131
+		return $this->Module_Request_Router;
132
+	}
133
+
134
+
135
+
136
+	/**
137
+	 * @return LegacyShortcodesManager
138
+	 */
139
+	public function getLegacyShortcodesManager()
140
+	{
141
+		return EE_Config::getLegacyShortcodesManager();
142
+	}
143
+
144
+
145
+
146
+
147
+
148
+	/***********************************************        INIT ACTION HOOK         ***********************************************/
149
+
150
+
151
+
152
+	/**
153
+	 * filter_wp_comments
154
+	 * This simply makes sure that any "private" EE CPTs do not have their comments show up in any wp comment
155
+	 * widgets/queries done on frontend
156
+	 *
157
+	 * @param  array $clauses array of comment clauses setup by WP_Comment_Query
158
+	 * @return array array of comment clauses with modifications.
159
+	 */
160
+	public function filter_wp_comments($clauses)
161
+	{
162
+		global $wpdb;
163
+		if (strpos($clauses['join'], $wpdb->posts) !== false) {
164
+			$cpts = EE_Register_CPTs::get_private_CPTs();
165
+			foreach ($cpts as $cpt => $details) {
166
+				$clauses['where'] .= $wpdb->prepare(" AND $wpdb->posts.post_type != %s", $cpt);
167
+			}
168
+		}
169
+		return $clauses;
170
+	}
171
+
172
+
173
+	/**
174
+	 * @return void
175
+	 * @throws EE_Error
176
+	 * @throws ReflectionException
177
+	 */
178
+	public function employ_CPT_Strategy()
179
+	{
180
+		if (apply_filters('FHEE__EE_Front_Controller__employ_CPT_Strategy', true)) {
181
+			$this->Registry->load_core('CPT_Strategy');
182
+		}
183
+	}
184
+
185
+
186
+	/**
187
+	 * @return void
188
+	 * @throws InvalidArgumentException
189
+	 * @throws InvalidDataTypeException
190
+	 * @throws InvalidInterfaceException
191
+	 */
192
+	public function loadPersistentAdminNoticeManager()
193
+	{
194
+		$this->persistent_admin_notice_manager = LoaderFactory::getLoader()->getShared(
195
+			'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
196
+		);
197
+	}
198
+
199
+
200
+	/**
201
+	 * this just makes sure that if the site is using ssl that we force that for any admin ajax calls from frontend
202
+	 *
203
+	 * @param  string $url incoming url
204
+	 * @return string         final assembled url
205
+	 */
206
+	public function maybe_force_admin_ajax_ssl($url)
207
+	{
208
+		if (is_ssl() && preg_match('/admin-ajax.php/', $url)) {
209
+			$url = str_replace('http://', 'https://', $url);
210
+		}
211
+		return $url;
212
+	}
213 213
 
214 214
 
215 215
 
216
-
217
-
218
-
219
-    /***********************************************        WP_LOADED ACTION HOOK         ***********************************************/
220
-
221
-
222
-    /**
223
-     *    wp_loaded - should fire after shortcode, module, addon, or other plugin's have been registered and their
224
-     *    default priority init phases have run
225
-     *
226
-     * @access    public
227
-     * @return    void
228
-     */
229
-    public function wp_loaded()
230
-    {
231
-    }
232
-
233
-
234
-
235
-
236
-
237
-    /***********************************************        PARSE_REQUEST HOOK         ***********************************************/
238
-    /**
239
-     *    _get_request
240
-     *
241
-     * @access public
242
-     * @param WP $WP
243
-     * @return void
244
-     */
245
-    public function get_request(WP $WP)
246
-    {
247
-        do_action('AHEE__EE_Front_Controller__get_request__start');
248
-        $this->Request_Handler->parse_request($WP);
249
-        do_action('AHEE__EE_Front_Controller__get_request__complete');
250
-    }
251
-
252
-
253
-
254
-    /**
255
-     *    pre_get_posts - basically a module factory for instantiating modules and selecting the final view template
256
-     *
257
-     * @access    public
258
-     * @param   WP_Query $WP_Query
259
-     * @return    void
260
-     */
261
-    public function pre_get_posts($WP_Query)
262
-    {
263
-        // only load Module_Request_Router if this is the main query
264
-        if (
265
-            $this->Module_Request_Router instanceof EE_Module_Request_Router
266
-            && $WP_Query->is_main_query()
267
-        ) {
268
-            // cycle thru module routes
269
-            while ($route = $this->Module_Request_Router->get_route($WP_Query)) {
270
-                // determine module and method for route
271
-                $module = $this->Module_Request_Router->resolve_route($route[0], $route[1]);
272
-                if ($module instanceof EED_Module) {
273
-                    // get registered view for route
274
-                    $this->_template_path = $this->Module_Request_Router->get_view($route);
275
-                    // grab module name
276
-                    $module_name = $module->module_name();
277
-                    // map the module to the module objects
278
-                    $this->Registry->modules->{$module_name} = $module;
279
-                }
280
-            }
281
-        }
282
-    }
283
-
284
-
285
-
286
-
287
-
288
-    /***********************************************        WP HOOK         ***********************************************/
289
-
290
-
291
-    /**
292
-     *    wp - basically last chance to do stuff before headers sent
293
-     *
294
-     * @access    public
295
-     * @return    void
296
-     */
297
-    public function wp()
298
-    {
299
-    }
300
-
301
-
302
-
303
-    /***********************     GET_HEADER && WP_HEAD HOOK     ***********************/
304
-
305
-
306
-
307
-    /**
308
-     * callback for the "template_redirect" hook point
309
-     * checks sidebars for EE widgets
310
-     * loads resources and assets accordingly
311
-     *
312
-     * @return void
313
-     */
314
-    public function templateRedirect()
315
-    {
316
-        global $wp_query;
317
-        if (empty($wp_query->posts)){
318
-            return;
319
-        }
320
-        // if we already know this is an espresso page, then load assets
321
-        $load_assets = $this->Request_Handler->is_espresso_page();
322
-        // if we are already loading assets then just move along, otherwise check for widgets
323
-        $load_assets = $load_assets ? $load_assets : $this->espresso_widgets_in_active_sidebars();
324
-        if ( $load_assets){
325
-            add_action('wp_enqueue_scripts', array($this, 'enqueueStyle'), 10);
326
-            add_action('wp_print_footer_scripts', array($this, 'enqueueScripts'), 10);
327
-        }
328
-    }
329
-
330
-
331
-
332
-    /**
333
-     * builds list of active widgets then scans active sidebars looking for them
334
-     * returns true is an EE widget is found in an active sidebar
335
-     * Please Note: this does NOT mean that the sidebar or widget
336
-     * is actually in use in a given template, as that is unfortunately not known
337
-     * until a sidebar and it's widgets are actually loaded
338
-     *
339
-     * @return boolean
340
-     */
341
-    private function espresso_widgets_in_active_sidebars()
342
-    {
343
-        $espresso_widgets = array();
344
-        foreach ($this->Registry->widgets as $widget_class => $widget) {
345
-            $id_base = EspressoWidget::getIdBase($widget_class);
346
-            if (is_active_widget(false, false, $id_base)) {
347
-                $espresso_widgets[] = $id_base;
348
-            }
349
-        }
350
-        $all_sidebar_widgets = wp_get_sidebars_widgets();
351
-        foreach ($all_sidebar_widgets as $sidebar_name => $sidebar_widgets) {
352
-            if (is_array($sidebar_widgets) && ! empty($sidebar_widgets)) {
353
-                foreach ($sidebar_widgets as $sidebar_widget) {
354
-                    foreach ($espresso_widgets as $espresso_widget) {
355
-                        if (strpos($sidebar_widget, $espresso_widget) !== false) {
356
-                            return true;
357
-                        }
358
-                    }
359
-                }
360
-            }
361
-        }
362
-        return false;
363
-    }
364
-
365
-
366
-
367
-
368
-    /**
369
-     *    header_meta_tag
370
-     *
371
-     * @access    public
372
-     * @return    void
373
-     */
374
-    public function header_meta_tag()
375
-    {
376
-        print(
377
-            apply_filters(
378
-                'FHEE__EE_Front_Controller__header_meta_tag',
379
-                '<meta name="generator" content="Event Espresso Version ' . EVENT_ESPRESSO_VERSION . "\" />\n")
380
-        );
381
-
382
-        //let's exclude all event type taxonomy term archive pages from search engine indexing
383
-        //@see https://events.codebasehq.com/projects/event-espresso/tickets/10249
384
-        //also exclude all critical pages from indexing
385
-        if (
386
-            (
387
-                is_tax('espresso_event_type')
388
-                && get_option( 'blog_public' ) !== '0'
389
-            )
390
-            || is_page(EE_Registry::instance()->CFG->core->get_critical_pages_array())
391
-        ) {
392
-            print(
393
-                apply_filters(
394
-                    'FHEE__EE_Front_Controller__header_meta_tag__noindex_for_event_type',
395
-                    '<meta name="robots" content="noindex,follow" />' . "\n"
396
-                )
397
-            );
398
-        }
399
-    }
400
-
401
-
402
-
403
-    /**
404
-     * wp_print_scripts
405
-     *
406
-     * @return void
407
-     */
408
-    public function wp_print_scripts()
409
-    {
410
-        global $post;
411
-        if (
412
-            isset($post->EE_Event)
413
-            && $post->EE_Event instanceof EE_Event
414
-            && get_post_type() === 'espresso_events'
415
-            && is_singular()
416
-        ) {
417
-            \EEH_Schema::add_json_linked_data_for_event($post->EE_Event);
418
-        }
419
-    }
420
-
421
-
422
-
423
-    public function enqueueStyle()
424
-    {
425
-        wp_enqueue_style('espresso_default');
426
-        wp_enqueue_style('espresso_custom_css');
427
-    }
428
-
429
-
430
-
431
-
432
-    /***********************************************        THE_CONTENT FILTER HOOK         **********************************************
216
+
217
+
218
+
219
+	/***********************************************        WP_LOADED ACTION HOOK         ***********************************************/
220
+
221
+
222
+	/**
223
+	 *    wp_loaded - should fire after shortcode, module, addon, or other plugin's have been registered and their
224
+	 *    default priority init phases have run
225
+	 *
226
+	 * @access    public
227
+	 * @return    void
228
+	 */
229
+	public function wp_loaded()
230
+	{
231
+	}
232
+
233
+
234
+
235
+
236
+
237
+	/***********************************************        PARSE_REQUEST HOOK         ***********************************************/
238
+	/**
239
+	 *    _get_request
240
+	 *
241
+	 * @access public
242
+	 * @param WP $WP
243
+	 * @return void
244
+	 */
245
+	public function get_request(WP $WP)
246
+	{
247
+		do_action('AHEE__EE_Front_Controller__get_request__start');
248
+		$this->Request_Handler->parse_request($WP);
249
+		do_action('AHEE__EE_Front_Controller__get_request__complete');
250
+	}
251
+
252
+
253
+
254
+	/**
255
+	 *    pre_get_posts - basically a module factory for instantiating modules and selecting the final view template
256
+	 *
257
+	 * @access    public
258
+	 * @param   WP_Query $WP_Query
259
+	 * @return    void
260
+	 */
261
+	public function pre_get_posts($WP_Query)
262
+	{
263
+		// only load Module_Request_Router if this is the main query
264
+		if (
265
+			$this->Module_Request_Router instanceof EE_Module_Request_Router
266
+			&& $WP_Query->is_main_query()
267
+		) {
268
+			// cycle thru module routes
269
+			while ($route = $this->Module_Request_Router->get_route($WP_Query)) {
270
+				// determine module and method for route
271
+				$module = $this->Module_Request_Router->resolve_route($route[0], $route[1]);
272
+				if ($module instanceof EED_Module) {
273
+					// get registered view for route
274
+					$this->_template_path = $this->Module_Request_Router->get_view($route);
275
+					// grab module name
276
+					$module_name = $module->module_name();
277
+					// map the module to the module objects
278
+					$this->Registry->modules->{$module_name} = $module;
279
+				}
280
+			}
281
+		}
282
+	}
283
+
284
+
285
+
286
+
287
+
288
+	/***********************************************        WP HOOK         ***********************************************/
289
+
290
+
291
+	/**
292
+	 *    wp - basically last chance to do stuff before headers sent
293
+	 *
294
+	 * @access    public
295
+	 * @return    void
296
+	 */
297
+	public function wp()
298
+	{
299
+	}
300
+
301
+
302
+
303
+	/***********************     GET_HEADER && WP_HEAD HOOK     ***********************/
304
+
305
+
306
+
307
+	/**
308
+	 * callback for the "template_redirect" hook point
309
+	 * checks sidebars for EE widgets
310
+	 * loads resources and assets accordingly
311
+	 *
312
+	 * @return void
313
+	 */
314
+	public function templateRedirect()
315
+	{
316
+		global $wp_query;
317
+		if (empty($wp_query->posts)){
318
+			return;
319
+		}
320
+		// if we already know this is an espresso page, then load assets
321
+		$load_assets = $this->Request_Handler->is_espresso_page();
322
+		// if we are already loading assets then just move along, otherwise check for widgets
323
+		$load_assets = $load_assets ? $load_assets : $this->espresso_widgets_in_active_sidebars();
324
+		if ( $load_assets){
325
+			add_action('wp_enqueue_scripts', array($this, 'enqueueStyle'), 10);
326
+			add_action('wp_print_footer_scripts', array($this, 'enqueueScripts'), 10);
327
+		}
328
+	}
329
+
330
+
331
+
332
+	/**
333
+	 * builds list of active widgets then scans active sidebars looking for them
334
+	 * returns true is an EE widget is found in an active sidebar
335
+	 * Please Note: this does NOT mean that the sidebar or widget
336
+	 * is actually in use in a given template, as that is unfortunately not known
337
+	 * until a sidebar and it's widgets are actually loaded
338
+	 *
339
+	 * @return boolean
340
+	 */
341
+	private function espresso_widgets_in_active_sidebars()
342
+	{
343
+		$espresso_widgets = array();
344
+		foreach ($this->Registry->widgets as $widget_class => $widget) {
345
+			$id_base = EspressoWidget::getIdBase($widget_class);
346
+			if (is_active_widget(false, false, $id_base)) {
347
+				$espresso_widgets[] = $id_base;
348
+			}
349
+		}
350
+		$all_sidebar_widgets = wp_get_sidebars_widgets();
351
+		foreach ($all_sidebar_widgets as $sidebar_name => $sidebar_widgets) {
352
+			if (is_array($sidebar_widgets) && ! empty($sidebar_widgets)) {
353
+				foreach ($sidebar_widgets as $sidebar_widget) {
354
+					foreach ($espresso_widgets as $espresso_widget) {
355
+						if (strpos($sidebar_widget, $espresso_widget) !== false) {
356
+							return true;
357
+						}
358
+					}
359
+				}
360
+			}
361
+		}
362
+		return false;
363
+	}
364
+
365
+
366
+
367
+
368
+	/**
369
+	 *    header_meta_tag
370
+	 *
371
+	 * @access    public
372
+	 * @return    void
373
+	 */
374
+	public function header_meta_tag()
375
+	{
376
+		print(
377
+			apply_filters(
378
+				'FHEE__EE_Front_Controller__header_meta_tag',
379
+				'<meta name="generator" content="Event Espresso Version ' . EVENT_ESPRESSO_VERSION . "\" />\n")
380
+		);
381
+
382
+		//let's exclude all event type taxonomy term archive pages from search engine indexing
383
+		//@see https://events.codebasehq.com/projects/event-espresso/tickets/10249
384
+		//also exclude all critical pages from indexing
385
+		if (
386
+			(
387
+				is_tax('espresso_event_type')
388
+				&& get_option( 'blog_public' ) !== '0'
389
+			)
390
+			|| is_page(EE_Registry::instance()->CFG->core->get_critical_pages_array())
391
+		) {
392
+			print(
393
+				apply_filters(
394
+					'FHEE__EE_Front_Controller__header_meta_tag__noindex_for_event_type',
395
+					'<meta name="robots" content="noindex,follow" />' . "\n"
396
+				)
397
+			);
398
+		}
399
+	}
400
+
401
+
402
+
403
+	/**
404
+	 * wp_print_scripts
405
+	 *
406
+	 * @return void
407
+	 */
408
+	public function wp_print_scripts()
409
+	{
410
+		global $post;
411
+		if (
412
+			isset($post->EE_Event)
413
+			&& $post->EE_Event instanceof EE_Event
414
+			&& get_post_type() === 'espresso_events'
415
+			&& is_singular()
416
+		) {
417
+			\EEH_Schema::add_json_linked_data_for_event($post->EE_Event);
418
+		}
419
+	}
420
+
421
+
422
+
423
+	public function enqueueStyle()
424
+	{
425
+		wp_enqueue_style('espresso_default');
426
+		wp_enqueue_style('espresso_custom_css');
427
+	}
428
+
429
+
430
+
431
+
432
+	/***********************************************        THE_CONTENT FILTER HOOK         **********************************************
433 433
 
434 434
 
435 435
 
@@ -440,108 +440,108 @@  discard block
 block discarded – undo
440 440
     //  * @param   $the_content
441 441
     //  * @return    string
442 442
     //  */
443
-    // public function the_content( $the_content ) {
444
-    // 	// nothing gets loaded at this point unless other systems turn this hookpoint on by using:  add_filter( 'FHEE_run_EE_the_content', '__return_true' );
445
-    // 	if ( apply_filters( 'FHEE_run_EE_the_content', FALSE ) ) {
446
-    // 	}
447
-    // 	return $the_content;
448
-    // }
449
-
450
-
451
-
452
-    /***********************************************        WP_FOOTER         ***********************************************/
453
-
454
-
455
-
456
-    public function enqueueScripts()
457
-    {
458
-        wp_enqueue_script('espresso_core');
459
-    }
460
-
461
-
462
-
463
-    /**
464
-     * display_errors
465
-     *
466
-     * @access public
467
-     * @return void
468
-     * @throws DomainException
469
-     */
470
-    public function display_errors()
471
-    {
472
-        static $shown_already = false;
473
-        do_action('AHEE__EE_Front_Controller__display_errors__begin');
474
-        if (
475
-            ! $shown_already
476
-            && apply_filters('FHEE__EE_Front_Controller__display_errors', true)
477
-            && is_main_query()
478
-            && ! is_feed()
479
-            && in_the_loop()
480
-            && $this->Request_Handler->is_espresso_page()
481
-        ) {
482
-            echo EE_Error::get_notices();
483
-            $shown_already = true;
484
-            EEH_Template::display_template(EE_TEMPLATES . 'espresso-ajax-notices.template.php');
485
-        }
486
-        do_action('AHEE__EE_Front_Controller__display_errors__end');
487
-    }
488
-
489
-
490
-
491
-
492
-
493
-    /***********************************************        UTILITIES         ***********************************************/
494
-    /**
495
-     *    template_include
496
-     *
497
-     * @access    public
498
-     * @param   string $template_include_path
499
-     * @return    string
500
-     */
501
-    public function template_include($template_include_path = null)
502
-    {
503
-        if ($this->Request_Handler->is_espresso_page()) {
504
-            $this->_template_path = ! empty($this->_template_path) ? basename($this->_template_path) : basename($template_include_path);
505
-            $template_path        = EEH_Template::locate_template($this->_template_path, array(), false);
506
-            $this->_template_path = ! empty($template_path) ? $template_path : $template_include_path;
507
-            $this->_template      = basename($this->_template_path);
508
-            return $this->_template_path;
509
-        }
510
-        return $template_include_path;
511
-    }
512
-
513
-
514
-    /**
515
-     *    get_selected_template
516
-     *
517
-     * @access    public
518
-     * @param bool $with_path
519
-     * @return    string
520
-     */
521
-    public function get_selected_template($with_path = false)
522
-    {
523
-        return $with_path ? $this->_template_path : $this->_template;
524
-    }
525
-
526
-
527
-
528
-    /**
529
-     * @deprecated 4.9.26
530
-     * @param string $shortcode_class
531
-     * @param \WP    $wp
532
-     */
533
-    public function initialize_shortcode($shortcode_class = '', WP $wp = null)
534
-    {
535
-        \EE_Error::doing_it_wrong(
536
-            __METHOD__,
537
-            __(
538
-                'Usage is deprecated. Please use \EventEspresso\core\services\shortcodes\LegacyShortcodesManager::initializeShortcode() instead.',
539
-                'event_espresso'
540
-            ),
541
-            '4.9.26'
542
-        );
543
-        $this->getLegacyShortcodesManager()->initializeShortcode($shortcode_class, $wp);
544
-    }
443
+	// public function the_content( $the_content ) {
444
+	// 	// nothing gets loaded at this point unless other systems turn this hookpoint on by using:  add_filter( 'FHEE_run_EE_the_content', '__return_true' );
445
+	// 	if ( apply_filters( 'FHEE_run_EE_the_content', FALSE ) ) {
446
+	// 	}
447
+	// 	return $the_content;
448
+	// }
449
+
450
+
451
+
452
+	/***********************************************        WP_FOOTER         ***********************************************/
453
+
454
+
455
+
456
+	public function enqueueScripts()
457
+	{
458
+		wp_enqueue_script('espresso_core');
459
+	}
460
+
461
+
462
+
463
+	/**
464
+	 * display_errors
465
+	 *
466
+	 * @access public
467
+	 * @return void
468
+	 * @throws DomainException
469
+	 */
470
+	public function display_errors()
471
+	{
472
+		static $shown_already = false;
473
+		do_action('AHEE__EE_Front_Controller__display_errors__begin');
474
+		if (
475
+			! $shown_already
476
+			&& apply_filters('FHEE__EE_Front_Controller__display_errors', true)
477
+			&& is_main_query()
478
+			&& ! is_feed()
479
+			&& in_the_loop()
480
+			&& $this->Request_Handler->is_espresso_page()
481
+		) {
482
+			echo EE_Error::get_notices();
483
+			$shown_already = true;
484
+			EEH_Template::display_template(EE_TEMPLATES . 'espresso-ajax-notices.template.php');
485
+		}
486
+		do_action('AHEE__EE_Front_Controller__display_errors__end');
487
+	}
488
+
489
+
490
+
491
+
492
+
493
+	/***********************************************        UTILITIES         ***********************************************/
494
+	/**
495
+	 *    template_include
496
+	 *
497
+	 * @access    public
498
+	 * @param   string $template_include_path
499
+	 * @return    string
500
+	 */
501
+	public function template_include($template_include_path = null)
502
+	{
503
+		if ($this->Request_Handler->is_espresso_page()) {
504
+			$this->_template_path = ! empty($this->_template_path) ? basename($this->_template_path) : basename($template_include_path);
505
+			$template_path        = EEH_Template::locate_template($this->_template_path, array(), false);
506
+			$this->_template_path = ! empty($template_path) ? $template_path : $template_include_path;
507
+			$this->_template      = basename($this->_template_path);
508
+			return $this->_template_path;
509
+		}
510
+		return $template_include_path;
511
+	}
512
+
513
+
514
+	/**
515
+	 *    get_selected_template
516
+	 *
517
+	 * @access    public
518
+	 * @param bool $with_path
519
+	 * @return    string
520
+	 */
521
+	public function get_selected_template($with_path = false)
522
+	{
523
+		return $with_path ? $this->_template_path : $this->_template;
524
+	}
525
+
526
+
527
+
528
+	/**
529
+	 * @deprecated 4.9.26
530
+	 * @param string $shortcode_class
531
+	 * @param \WP    $wp
532
+	 */
533
+	public function initialize_shortcode($shortcode_class = '', WP $wp = null)
534
+	{
535
+		\EE_Error::doing_it_wrong(
536
+			__METHOD__,
537
+			__(
538
+				'Usage is deprecated. Please use \EventEspresso\core\services\shortcodes\LegacyShortcodesManager::initializeShortcode() instead.',
539
+				'event_espresso'
540
+			),
541
+			'4.9.26'
542
+		);
543
+		$this->getLegacyShortcodesManager()->initializeShortcode($shortcode_class, $wp);
544
+	}
545 545
 
546 546
 }
547 547
 // End of file EE_Front_Controller.core.php
Please login to merge, or discard this patch.
core/domain/entities/notifications/PersistentAdminNotice.php 2 patches
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -130,7 +130,7 @@  discard block
 block discarded – undo
130 130
      */
131 131
     private function setName($name)
132 132
     {
133
-        if (! is_string($name)) {
133
+        if ( ! is_string($name)) {
134 134
             throw new InvalidDataTypeException('$name', $name, 'string');
135 135
         }
136 136
         $this->name = sanitize_key($name);
@@ -154,7 +154,7 @@  discard block
 block discarded – undo
154 154
      */
155 155
     private function setMessage($message)
156 156
     {
157
-        if (! is_string($message)) {
157
+        if ( ! is_string($message)) {
158 158
             throw new InvalidDataTypeException('$message', $message, 'string');
159 159
         }
160 160
         global $allowedtags;
@@ -200,7 +200,7 @@  discard block
 block discarded – undo
200 200
      */
201 201
     private function setCapability($capability)
202 202
     {
203
-        if (! is_string($capability)) {
203
+        if ( ! is_string($capability)) {
204 204
             throw new InvalidDataTypeException('$capability', $capability, 'string');
205 205
         }
206 206
         $this->capability = ! empty($capability) ? $capability : 'manage_options';
@@ -224,7 +224,7 @@  discard block
 block discarded – undo
224 224
      */
225 225
     private function setCapContext($cap_context)
226 226
     {
227
-        if (! is_string($cap_context)) {
227
+        if ( ! is_string($cap_context)) {
228 228
             throw new InvalidDataTypeException('$cap_context', $cap_context, 'string');
229 229
         }
230 230
         $this->cap_context = ! empty($cap_context) ? $cap_context : 'view persistent admin notice';
@@ -258,7 +258,7 @@  discard block
 block discarded – undo
258 258
      */
259 259
     public function getCapCheck()
260 260
     {
261
-        if (! $this->cap_check instanceof CapCheckInterface) {
261
+        if ( ! $this->cap_check instanceof CapCheckInterface) {
262 262
             $this->setCapCheck(
263 263
                 new CapCheck(
264 264
                     $this->capability,
@@ -340,7 +340,7 @@  discard block
 block discarded – undo
340 340
      */
341 341
     public function confirmRegistered()
342 342
     {
343
-        if (! $this->registered && WP_DEBUG) {
343
+        if ( ! $this->registered && WP_DEBUG) {
344 344
             new ExceptionStackTraceDisplay(
345 345
                 new DomainException(
346 346
                     sprintf(
Please login to merge, or discard this patch.
Indentation   +325 added lines, -325 removed lines patch added patch discarded remove patch
@@ -28,334 +28,334 @@
 block discarded – undo
28 28
 class PersistentAdminNotice implements RequiresCapCheckInterface
29 29
 {
30 30
 
31
-    /**
32
-     * @var string $name
33
-     */
34
-    protected $name = '';
35
-
36
-    /**
37
-     * @var string $message
38
-     */
39
-    protected $message = '';
40
-
41
-    /**
42
-     * @var boolean $force_update
43
-     */
44
-    protected $force_update = false;
45
-
46
-    /**
47
-     * @var string $capability
48
-     */
49
-    protected $capability = 'manage_options';
50
-
51
-    /**
52
-     * @var string $cap_context
53
-     */
54
-    protected $cap_context = 'view persistent admin notice';
55
-
56
-    /**
57
-     * @var boolean $dismissed
58
-     */
59
-    protected $dismissed = false;
60
-
61
-    /**
62
-     * @var CapCheckInterface $cap_check
63
-     */
64
-    protected $cap_check;
65
-
66
-    /**
67
-     * if true, then this notice will be deleted from the database
68
-     *
69
-     * @var boolean $purge
70
-     */
71
-    protected $purge = false;
72
-
73
-    /**
74
-     * gets set to true if notice is successfully registered with the PersistentAdminNoticeManager
75
-     * if false, and WP_DEBUG is on, then an exception will be thrown in the admin footer
76
-     *
77
-     * @var boolean $registered
78
-     */
79
-    private $registered = false;
80
-
81
-
82
-
83
-    /**
84
-     * PersistentAdminNotice constructor
85
-     *
86
-     * @param string $name         [required] the name, or key of the Persistent Admin Notice to be stored
87
-     * @param string $message      [required] the message to be stored persistently until dismissed
88
-     * @param bool   $force_update enforce the reappearance of a persistent message
89
-     * @param string $capability   user capability required to view this notice
90
-     * @param string $cap_context  description for why the cap check is being performed
91
-     * @param bool   $dismissed    whether or not the user has already dismissed/viewed this notice
92
-     * @throws InvalidDataTypeException
93
-     */
94
-    public function __construct(
95
-        $name,
96
-        $message,
97
-        $force_update = false,
98
-        $capability = 'manage_options',
99
-        $cap_context = 'view persistent admin notice',
100
-        $dismissed = false
101
-    ) {
102
-        $this->setName($name);
103
-        $this->setMessage($message);
104
-        $this->setForceUpdate($force_update);
105
-        $this->setCapability($capability);
106
-        $this->setCapContext($cap_context);
107
-        $this->setDismissed($dismissed);
108
-        add_action(
109
-            'AHEE__EventEspresso_core_services_notifications_PersistentAdminNoticeManager__registerNotices',
110
-            array($this, 'registerPersistentAdminNotice')
111
-        );
112
-        add_action('shutdown', array($this, 'confirmRegistered'), 999);
113
-    }
114
-
115
-
116
-
117
-    /**
118
-     * @return string
119
-     */
120
-    public function getName()
121
-    {
122
-        return $this->name;
123
-    }
124
-
125
-
126
-
127
-    /**
128
-     * @param string $name
129
-     * @throws InvalidDataTypeException
130
-     */
131
-    private function setName($name)
132
-    {
133
-        if (! is_string($name)) {
134
-            throw new InvalidDataTypeException('$name', $name, 'string');
135
-        }
136
-        $this->name = sanitize_key($name);
137
-    }
138
-
139
-
140
-
141
-    /**
142
-     * @return string
143
-     */
144
-    public function getMessage()
145
-    {
146
-        return $this->message;
147
-    }
148
-
149
-
150
-
151
-    /**
152
-     * @param string $message
153
-     * @throws InvalidDataTypeException
154
-     */
155
-    private function setMessage($message)
156
-    {
157
-        if (! is_string($message)) {
158
-            throw new InvalidDataTypeException('$message', $message, 'string');
159
-        }
160
-        global $allowedtags;
161
-        $allowedtags['br'] = array();
162
-        $this->message     = wp_kses($message, $allowedtags);
163
-    }
164
-
165
-
166
-
167
-    /**
168
-     * @return bool
169
-     */
170
-    public function getForceUpdate()
171
-    {
172
-        return $this->force_update;
173
-    }
174
-
175
-
176
-
177
-    /**
178
-     * @param bool $force_update
179
-     */
180
-    private function setForceUpdate($force_update)
181
-    {
182
-        $this->force_update = filter_var($force_update, FILTER_VALIDATE_BOOLEAN);
183
-    }
184
-
185
-
186
-
187
-    /**
188
-     * @return string
189
-     */
190
-    public function getCapability()
191
-    {
192
-        return $this->capability;
193
-    }
194
-
195
-
196
-
197
-    /**
198
-     * @param string $capability
199
-     * @throws InvalidDataTypeException
200
-     */
201
-    private function setCapability($capability)
202
-    {
203
-        if (! is_string($capability)) {
204
-            throw new InvalidDataTypeException('$capability', $capability, 'string');
205
-        }
206
-        $this->capability = ! empty($capability) ? $capability : 'manage_options';
207
-    }
31
+	/**
32
+	 * @var string $name
33
+	 */
34
+	protected $name = '';
35
+
36
+	/**
37
+	 * @var string $message
38
+	 */
39
+	protected $message = '';
40
+
41
+	/**
42
+	 * @var boolean $force_update
43
+	 */
44
+	protected $force_update = false;
45
+
46
+	/**
47
+	 * @var string $capability
48
+	 */
49
+	protected $capability = 'manage_options';
50
+
51
+	/**
52
+	 * @var string $cap_context
53
+	 */
54
+	protected $cap_context = 'view persistent admin notice';
55
+
56
+	/**
57
+	 * @var boolean $dismissed
58
+	 */
59
+	protected $dismissed = false;
60
+
61
+	/**
62
+	 * @var CapCheckInterface $cap_check
63
+	 */
64
+	protected $cap_check;
65
+
66
+	/**
67
+	 * if true, then this notice will be deleted from the database
68
+	 *
69
+	 * @var boolean $purge
70
+	 */
71
+	protected $purge = false;
72
+
73
+	/**
74
+	 * gets set to true if notice is successfully registered with the PersistentAdminNoticeManager
75
+	 * if false, and WP_DEBUG is on, then an exception will be thrown in the admin footer
76
+	 *
77
+	 * @var boolean $registered
78
+	 */
79
+	private $registered = false;
80
+
81
+
82
+
83
+	/**
84
+	 * PersistentAdminNotice constructor
85
+	 *
86
+	 * @param string $name         [required] the name, or key of the Persistent Admin Notice to be stored
87
+	 * @param string $message      [required] the message to be stored persistently until dismissed
88
+	 * @param bool   $force_update enforce the reappearance of a persistent message
89
+	 * @param string $capability   user capability required to view this notice
90
+	 * @param string $cap_context  description for why the cap check is being performed
91
+	 * @param bool   $dismissed    whether or not the user has already dismissed/viewed this notice
92
+	 * @throws InvalidDataTypeException
93
+	 */
94
+	public function __construct(
95
+		$name,
96
+		$message,
97
+		$force_update = false,
98
+		$capability = 'manage_options',
99
+		$cap_context = 'view persistent admin notice',
100
+		$dismissed = false
101
+	) {
102
+		$this->setName($name);
103
+		$this->setMessage($message);
104
+		$this->setForceUpdate($force_update);
105
+		$this->setCapability($capability);
106
+		$this->setCapContext($cap_context);
107
+		$this->setDismissed($dismissed);
108
+		add_action(
109
+			'AHEE__EventEspresso_core_services_notifications_PersistentAdminNoticeManager__registerNotices',
110
+			array($this, 'registerPersistentAdminNotice')
111
+		);
112
+		add_action('shutdown', array($this, 'confirmRegistered'), 999);
113
+	}
114
+
115
+
116
+
117
+	/**
118
+	 * @return string
119
+	 */
120
+	public function getName()
121
+	{
122
+		return $this->name;
123
+	}
124
+
125
+
126
+
127
+	/**
128
+	 * @param string $name
129
+	 * @throws InvalidDataTypeException
130
+	 */
131
+	private function setName($name)
132
+	{
133
+		if (! is_string($name)) {
134
+			throw new InvalidDataTypeException('$name', $name, 'string');
135
+		}
136
+		$this->name = sanitize_key($name);
137
+	}
138
+
139
+
140
+
141
+	/**
142
+	 * @return string
143
+	 */
144
+	public function getMessage()
145
+	{
146
+		return $this->message;
147
+	}
148
+
149
+
150
+
151
+	/**
152
+	 * @param string $message
153
+	 * @throws InvalidDataTypeException
154
+	 */
155
+	private function setMessage($message)
156
+	{
157
+		if (! is_string($message)) {
158
+			throw new InvalidDataTypeException('$message', $message, 'string');
159
+		}
160
+		global $allowedtags;
161
+		$allowedtags['br'] = array();
162
+		$this->message     = wp_kses($message, $allowedtags);
163
+	}
164
+
165
+
166
+
167
+	/**
168
+	 * @return bool
169
+	 */
170
+	public function getForceUpdate()
171
+	{
172
+		return $this->force_update;
173
+	}
174
+
175
+
176
+
177
+	/**
178
+	 * @param bool $force_update
179
+	 */
180
+	private function setForceUpdate($force_update)
181
+	{
182
+		$this->force_update = filter_var($force_update, FILTER_VALIDATE_BOOLEAN);
183
+	}
184
+
185
+
186
+
187
+	/**
188
+	 * @return string
189
+	 */
190
+	public function getCapability()
191
+	{
192
+		return $this->capability;
193
+	}
194
+
195
+
196
+
197
+	/**
198
+	 * @param string $capability
199
+	 * @throws InvalidDataTypeException
200
+	 */
201
+	private function setCapability($capability)
202
+	{
203
+		if (! is_string($capability)) {
204
+			throw new InvalidDataTypeException('$capability', $capability, 'string');
205
+		}
206
+		$this->capability = ! empty($capability) ? $capability : 'manage_options';
207
+	}
208 208
 
209 209
 
210 210
 
211
-    /**
212
-     * @return string
213
-     */
214
-    public function getCapContext()
215
-    {
216
-        return $this->cap_context;
217
-    }
218
-
219
-
220
-
221
-    /**
222
-     * @param string $cap_context
223
-     * @throws InvalidDataTypeException
224
-     */
225
-    private function setCapContext($cap_context)
226
-    {
227
-        if (! is_string($cap_context)) {
228
-            throw new InvalidDataTypeException('$cap_context', $cap_context, 'string');
229
-        }
230
-        $this->cap_context = ! empty($cap_context) ? $cap_context : 'view persistent admin notice';
231
-    }
232
-
233
-
234
-
235
-    /**
236
-     * @return bool
237
-     */
238
-    public function getDismissed()
239
-    {
240
-        return $this->dismissed;
241
-    }
242
-
243
-
244
-
245
-    /**
246
-     * @param bool $dismissed
247
-     */
248
-    public function setDismissed($dismissed)
249
-    {
250
-        $this->dismissed = filter_var($dismissed, FILTER_VALIDATE_BOOLEAN);
251
-    }
252
-
253
-
254
-
255
-    /**
256
-     * @return CapCheckInterface
257
-     * @throws InvalidDataTypeException
258
-     */
259
-    public function getCapCheck()
260
-    {
261
-        if (! $this->cap_check instanceof CapCheckInterface) {
262
-            $this->setCapCheck(
263
-                new CapCheck(
264
-                    $this->capability,
265
-                    $this->cap_context
266
-                )
267
-            );
268
-        }
269
-        return $this->cap_check;
270
-    }
271
-
272
-
273
-
274
-    /**
275
-     * @param CapCheckInterface $cap_check
276
-     */
277
-    private function setCapCheck(CapCheckInterface $cap_check)
278
-    {
279
-        $this->cap_check = $cap_check;
280
-    }
281
-
282
-
283
-
284
-    /**
285
-     * @return bool
286
-     */
287
-    public function getPurge()
288
-    {
289
-        return $this->purge;
290
-    }
291
-
292
-
293
-
294
-    /**
295
-     * @param bool $purge
296
-     */
297
-    public function setPurge($purge)
298
-    {
299
-        $this->purge = filter_var($purge, FILTER_VALIDATE_BOOLEAN);
300
-    }
301
-
302
-
303
-
304
-    /**
305
-     * given a valid PersistentAdminNotice Collection,
306
-     * this notice will be added if it is not already found in the collection (using its name as the identifier)
307
-     * if an existing notice is found that has already been dismissed,
308
-     * but we are overriding with a forced update, then we will toggle its dismissed state,
309
-     * so that the notice is displayed again
310
-     *
311
-     * @param Collection $persistent_admin_notice_collection
312
-     * @throws InvalidEntityException
313
-     */
314
-    public function registerPersistentAdminNotice(Collection $persistent_admin_notice_collection)
315
-    {
316
-        if ($this->registered) {
317
-            return;
318
-        }
319
-        // first check if this notice has already been added to the collection
320
-        if ($persistent_admin_notice_collection->has($this->name)) {
321
-            /** @var PersistentAdminNotice $existing */
322
-            $existing = $persistent_admin_notice_collection->get($this->name);
323
-            // we don't need to add it again (we can't actually)
324
-            // but if it has already been dismissed, and we are overriding with a forced update
325
-            if ($existing->getDismissed() && $this->getForceUpdate()) {
326
-                // then toggle the notice's dismissed state to true
327
-                // so that it gets displayed again
328
-                $existing->setDismissed(false);
329
-                // and make sure the message is set
330
-                $existing->setMessage($this->message);
331
-            }
332
-        } else {
333
-            $persistent_admin_notice_collection->add($this, $this->name);
334
-        }
335
-        $this->registered = true;
336
-    }
337
-
338
-
339
-
340
-    /**
341
-     * @throws Exception
342
-     */
343
-    public function confirmRegistered()
344
-    {
345
-        if (! $this->registered && WP_DEBUG) {
346
-            new ExceptionStackTraceDisplay(
347
-                new DomainException(
348
-                    sprintf(
349
-                        esc_html__(
350
-                            'The "%1$s" PersistentAdminNotice was not successfully registered. Please ensure that it is being created prior to either the "admin_notices" or "network_admin_notices" hooks being triggered.',
351
-                            'event_espresso'
352
-                        ),
353
-                        $this->name
354
-                    )
355
-                )
356
-            );
357
-        }
358
-    }
211
+	/**
212
+	 * @return string
213
+	 */
214
+	public function getCapContext()
215
+	{
216
+		return $this->cap_context;
217
+	}
218
+
219
+
220
+
221
+	/**
222
+	 * @param string $cap_context
223
+	 * @throws InvalidDataTypeException
224
+	 */
225
+	private function setCapContext($cap_context)
226
+	{
227
+		if (! is_string($cap_context)) {
228
+			throw new InvalidDataTypeException('$cap_context', $cap_context, 'string');
229
+		}
230
+		$this->cap_context = ! empty($cap_context) ? $cap_context : 'view persistent admin notice';
231
+	}
232
+
233
+
234
+
235
+	/**
236
+	 * @return bool
237
+	 */
238
+	public function getDismissed()
239
+	{
240
+		return $this->dismissed;
241
+	}
242
+
243
+
244
+
245
+	/**
246
+	 * @param bool $dismissed
247
+	 */
248
+	public function setDismissed($dismissed)
249
+	{
250
+		$this->dismissed = filter_var($dismissed, FILTER_VALIDATE_BOOLEAN);
251
+	}
252
+
253
+
254
+
255
+	/**
256
+	 * @return CapCheckInterface
257
+	 * @throws InvalidDataTypeException
258
+	 */
259
+	public function getCapCheck()
260
+	{
261
+		if (! $this->cap_check instanceof CapCheckInterface) {
262
+			$this->setCapCheck(
263
+				new CapCheck(
264
+					$this->capability,
265
+					$this->cap_context
266
+				)
267
+			);
268
+		}
269
+		return $this->cap_check;
270
+	}
271
+
272
+
273
+
274
+	/**
275
+	 * @param CapCheckInterface $cap_check
276
+	 */
277
+	private function setCapCheck(CapCheckInterface $cap_check)
278
+	{
279
+		$this->cap_check = $cap_check;
280
+	}
281
+
282
+
283
+
284
+	/**
285
+	 * @return bool
286
+	 */
287
+	public function getPurge()
288
+	{
289
+		return $this->purge;
290
+	}
291
+
292
+
293
+
294
+	/**
295
+	 * @param bool $purge
296
+	 */
297
+	public function setPurge($purge)
298
+	{
299
+		$this->purge = filter_var($purge, FILTER_VALIDATE_BOOLEAN);
300
+	}
301
+
302
+
303
+
304
+	/**
305
+	 * given a valid PersistentAdminNotice Collection,
306
+	 * this notice will be added if it is not already found in the collection (using its name as the identifier)
307
+	 * if an existing notice is found that has already been dismissed,
308
+	 * but we are overriding with a forced update, then we will toggle its dismissed state,
309
+	 * so that the notice is displayed again
310
+	 *
311
+	 * @param Collection $persistent_admin_notice_collection
312
+	 * @throws InvalidEntityException
313
+	 */
314
+	public function registerPersistentAdminNotice(Collection $persistent_admin_notice_collection)
315
+	{
316
+		if ($this->registered) {
317
+			return;
318
+		}
319
+		// first check if this notice has already been added to the collection
320
+		if ($persistent_admin_notice_collection->has($this->name)) {
321
+			/** @var PersistentAdminNotice $existing */
322
+			$existing = $persistent_admin_notice_collection->get($this->name);
323
+			// we don't need to add it again (we can't actually)
324
+			// but if it has already been dismissed, and we are overriding with a forced update
325
+			if ($existing->getDismissed() && $this->getForceUpdate()) {
326
+				// then toggle the notice's dismissed state to true
327
+				// so that it gets displayed again
328
+				$existing->setDismissed(false);
329
+				// and make sure the message is set
330
+				$existing->setMessage($this->message);
331
+			}
332
+		} else {
333
+			$persistent_admin_notice_collection->add($this, $this->name);
334
+		}
335
+		$this->registered = true;
336
+	}
337
+
338
+
339
+
340
+	/**
341
+	 * @throws Exception
342
+	 */
343
+	public function confirmRegistered()
344
+	{
345
+		if (! $this->registered && WP_DEBUG) {
346
+			new ExceptionStackTraceDisplay(
347
+				new DomainException(
348
+					sprintf(
349
+						esc_html__(
350
+							'The "%1$s" PersistentAdminNotice was not successfully registered. Please ensure that it is being created prior to either the "admin_notices" or "network_admin_notices" hooks being triggered.',
351
+							'event_espresso'
352
+						),
353
+						$this->name
354
+					)
355
+				)
356
+			);
357
+		}
358
+	}
359 359
 
360 360
 
361 361
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Payment_Method.model.php 2 patches
Indentation   +21 added lines, -21 removed lines patch added patch discarded remove patch
@@ -294,15 +294,15 @@  discard block
 block discarded – undo
294 294
 
295 295
 
296 296
 
297
-    /**
298
-     * Overrides parent to not only turn wpdb results into EE_Payment_Method objects,
299
-     * but also verifies the payment method type of each is a usable object. If not,
300
-     * deactivate it, sets a notification, and deactivates it
301
-     *
302
-     * @param array $rows
303
-     * @return EE_Payment_Method[]
304
-     * @throws InvalidDataTypeException
305
-     */
297
+	/**
298
+	 * Overrides parent to not only turn wpdb results into EE_Payment_Method objects,
299
+	 * but also verifies the payment method type of each is a usable object. If not,
300
+	 * deactivate it, sets a notification, and deactivates it
301
+	 *
302
+	 * @param array $rows
303
+	 * @return EE_Payment_Method[]
304
+	 * @throws InvalidDataTypeException
305
+	 */
306 306
 	protected function _create_objects( $rows = array() ) {
307 307
 		EE_Registry::instance()->load_lib( 'Payment_Method_Manager' );
308 308
 		$payment_methods = parent::_create_objects( $rows );
@@ -319,18 +319,18 @@  discard block
 block discarded – undo
319 319
 				//only deactivate and notify the admin if the payment is active somewhere
320 320
 				$payment_method->deactivate();
321 321
 				$payment_method->save();
322
-                new PersistentAdminNotice(
323
-                    'auto-deactivated-' . $payment_method->type(),
324
-                    sprintf(
325
-                        __('The payment method %1$s was automatically deactivated because it appears its associated Event Espresso Addon was recently deactivated.%2$sIt can be reactivated on the %3$sPlugins admin page%4$s, then you can reactivate the payment method.',
326
-                            'event_espresso'),
327
-                        $payment_method->admin_name(),
328
-                        '<br />',
329
-                        '<a href="' . admin_url('plugins.php') . '">',
330
-                        '</a>'
331
-                    ),
332
-                    true
333
-                );
322
+				new PersistentAdminNotice(
323
+					'auto-deactivated-' . $payment_method->type(),
324
+					sprintf(
325
+						__('The payment method %1$s was automatically deactivated because it appears its associated Event Espresso Addon was recently deactivated.%2$sIt can be reactivated on the %3$sPlugins admin page%4$s, then you can reactivate the payment method.',
326
+							'event_espresso'),
327
+						$payment_method->admin_name(),
328
+						'<br />',
329
+						'<a href="' . admin_url('plugins.php') . '">',
330
+						'</a>'
331
+					),
332
+					true
333
+				);
334 334
 			}
335 335
 		}
336 336
 		return $usable_payment_methods;
Please login to merge, or discard this patch.
Spacing   +90 added lines, -90 removed lines patch added patch discarded remove patch
@@ -1,8 +1,8 @@  discard block
 block discarded – undo
1 1
 <?php use EventEspresso\core\domain\entities\notifications\PersistentAdminNotice;
2 2
 use EventEspresso\core\exceptions\InvalidDataTypeException;
3 3
 
4
-if ( ! defined( 'EVENT_ESPRESSO_VERSION' ) ) {
5
-	exit( 'No direct script access allowed' );
4
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
5
+	exit('No direct script access allowed');
6 6
 }
7 7
 /**
8 8
  *
@@ -40,33 +40,33 @@  discard block
 block discarded – undo
40 40
 	 * @access   protected
41 41
 	 * @return EEM_Payment_Method
42 42
 	 */
43
-	protected function __construct( $timezone = NULL ) {
44
-		$this->singlular_item = __( 'Payment Method', 'event_espresso' );
45
-		$this->plural_item = __( 'Payment Methods', 'event_espresso' );
46
-		$this->_tables = array( 'Payment_Method' => new EE_Primary_Table( 'esp_payment_method', 'PMD_ID' ) );
43
+	protected function __construct($timezone = NULL) {
44
+		$this->singlular_item = __('Payment Method', 'event_espresso');
45
+		$this->plural_item = __('Payment Methods', 'event_espresso');
46
+		$this->_tables = array('Payment_Method' => new EE_Primary_Table('esp_payment_method', 'PMD_ID'));
47 47
 		$this->_fields = array(
48 48
 			'Payment_Method' => array(
49
-				'PMD_ID' => new EE_Primary_Key_Int_Field( 'PMD_ID', __( "ID", 'event_espresso' ) ),
50
-				'PMD_type' => new EE_Plain_Text_Field( 'PMD_type', __( "Payment Method Type", 'event_espresso' ), FALSE, 'Admin_Only' ),
51
-				'PMD_name' => new EE_Plain_Text_Field( 'PMD_name', __( "Name", 'event_espresso' ), FALSE ),
52
-				'PMD_desc' => new EE_Post_Content_Field( 'PMD_desc', __( "Description", 'event_espresso' ), FALSE, '' ),
53
-				'PMD_admin_name' => new EE_Plain_Text_Field( 'PMD_admin_name', __( "Admin-Only Name", 'event_espresso' ), TRUE ),
54
-				'PMD_admin_desc' => new EE_Post_Content_Field( 'PMD_admin_desc', __( "Admin-Only Description", 'event_espresso' ), TRUE ),
55
-				'PMD_slug' => new EE_Slug_Field( 'PMD_slug', __( "Slug", 'event_espresso' ), FALSE ),
56
-				'PMD_order' => new EE_Integer_Field( 'PMD_order', __( "Order", 'event_espresso' ), FALSE, 0 ),
57
-				'PMD_debug_mode' => new EE_Boolean_Field( 'PMD_debug_mode', __( "Debug Mode On?", 'event_espresso' ), FALSE, FALSE ),
58
-				'PMD_wp_user' => new EE_WP_User_Field( 'PMD_wp_user', __( "Payment Method Creator ID", 'event_espresso' ), FALSE ),
59
-				'PMD_open_by_default' => new EE_Boolean_Field( 'PMD_open_by_default', __( "Open by Default?", 'event_espresso' ), FALSE, FALSE ), 'PMD_button_url' => new EE_Plain_Text_Field( 'PMD_button_url', __( "Button URL", 'event_espresso' ), TRUE, '' ),
60
-				'PMD_scope' => new EE_Serialized_Text_Field( 'PMD_scope', __( "Usable From?", 'event_espresso' ), FALSE, array() ), //possible values currently are 'CART','ADMIN','API'
49
+				'PMD_ID' => new EE_Primary_Key_Int_Field('PMD_ID', __("ID", 'event_espresso')),
50
+				'PMD_type' => new EE_Plain_Text_Field('PMD_type', __("Payment Method Type", 'event_espresso'), FALSE, 'Admin_Only'),
51
+				'PMD_name' => new EE_Plain_Text_Field('PMD_name', __("Name", 'event_espresso'), FALSE),
52
+				'PMD_desc' => new EE_Post_Content_Field('PMD_desc', __("Description", 'event_espresso'), FALSE, ''),
53
+				'PMD_admin_name' => new EE_Plain_Text_Field('PMD_admin_name', __("Admin-Only Name", 'event_espresso'), TRUE),
54
+				'PMD_admin_desc' => new EE_Post_Content_Field('PMD_admin_desc', __("Admin-Only Description", 'event_espresso'), TRUE),
55
+				'PMD_slug' => new EE_Slug_Field('PMD_slug', __("Slug", 'event_espresso'), FALSE),
56
+				'PMD_order' => new EE_Integer_Field('PMD_order', __("Order", 'event_espresso'), FALSE, 0),
57
+				'PMD_debug_mode' => new EE_Boolean_Field('PMD_debug_mode', __("Debug Mode On?", 'event_espresso'), FALSE, FALSE),
58
+				'PMD_wp_user' => new EE_WP_User_Field('PMD_wp_user', __("Payment Method Creator ID", 'event_espresso'), FALSE),
59
+				'PMD_open_by_default' => new EE_Boolean_Field('PMD_open_by_default', __("Open by Default?", 'event_espresso'), FALSE, FALSE), 'PMD_button_url' => new EE_Plain_Text_Field('PMD_button_url', __("Button URL", 'event_espresso'), TRUE, ''),
60
+				'PMD_scope' => new EE_Serialized_Text_Field('PMD_scope', __("Usable From?", 'event_espresso'), FALSE, array()), //possible values currently are 'CART','ADMIN','API'
61 61
 		) );
62 62
 		$this->_model_relations = array(
63 63
  //			'Event'=>new EE_HABTM_Relation('Event_Payment_Method'),
64 64
 			'Payment' => new EE_Has_Many_Relation(),
65
-			'Currency' => new EE_HABTM_Relation( 'Currency_Payment_Method' ),
65
+			'Currency' => new EE_HABTM_Relation('Currency_Payment_Method'),
66 66
 			'Transaction' => new EE_Has_Many_Relation(),
67 67
 			'WP_User' => new EE_Belongs_To_Relation(),
68 68
 		);
69
-		parent::__construct( $timezone );
69
+		parent::__construct($timezone);
70 70
 	}
71 71
 
72 72
 
@@ -76,8 +76,8 @@  discard block
 block discarded – undo
76 76
 	 * @param string $slug
77 77
 	 * @return EE_Payment_Method
78 78
 	 */
79
-	public function get_one_by_slug( $slug ) {
80
-		return $this->get_one( array( array( 'PMD_slug' => $slug ) ) );
79
+	public function get_one_by_slug($slug) {
80
+		return $this->get_one(array(array('PMD_slug' => $slug)));
81 81
 	}
82 82
 
83 83
 
@@ -91,8 +91,8 @@  discard block
 block discarded – undo
91 91
 		return apply_filters(
92 92
 			'FHEE__EEM_Payment_Method__scopes',
93 93
 			array(
94
-				self::scope_cart 		=> __( "Front-end Registration Page", 'event_espresso' ),
95
-				self::scope_admin 	=> __( "Admin Registration Page (no online processing)", 'event_espresso' )
94
+				self::scope_cart 		=> __("Front-end Registration Page", 'event_espresso'),
95
+				self::scope_admin 	=> __("Admin Registration Page (no online processing)", 'event_espresso')
96 96
 			)
97 97
 		);
98 98
 	}
@@ -104,9 +104,9 @@  discard block
 block discarded – undo
104 104
 	 * @param string $scope like one of EEM_Payment_Method::instance()->scopes()
105 105
 	 * @return boolean
106 106
 	 */
107
-	public function is_valid_scope( $scope ) {
107
+	public function is_valid_scope($scope) {
108 108
 		$scopes = $this->scopes();
109
-		if ( isset( $scopes[ $scope ] ) ) {
109
+		if (isset($scopes[$scope])) {
110 110
 			return TRUE;
111 111
 		} else {
112 112
 			return FALSE;
@@ -122,11 +122,11 @@  discard block
 block discarded – undo
122 122
 	 * @throws EE_Error
123 123
 	 * @return EE_Payment_Method[]
124 124
 	 */
125
-	public function get_all_active( $scope = NULL, $query_params = array() ) {
126
-		if( ! isset( $query_params[ 'order_by' ] ) && ! isset( $query_params[ 'order' ] ) ) {
127
-			$query_params['order_by'] = array( 'PMD_order' => 'ASC', 'PMD_ID' => 'ASC' );
125
+	public function get_all_active($scope = NULL, $query_params = array()) {
126
+		if ( ! isset($query_params['order_by']) && ! isset($query_params['order'])) {
127
+			$query_params['order_by'] = array('PMD_order' => 'ASC', 'PMD_ID' => 'ASC');
128 128
 		}
129
-		return $this->get_all( $this->_get_query_params_for_all_active( $scope, $query_params ) );
129
+		return $this->get_all($this->_get_query_params_for_all_active($scope, $query_params));
130 130
 	}
131 131
 
132 132
 	/**
@@ -135,8 +135,8 @@  discard block
 block discarded – undo
135 135
 	 * @param array $query_params
136 136
 	 * @return int
137 137
 	 */
138
-	public function count_active( $scope = NULL, $query_params = array() ){
139
-		return $this->count( $this->_get_query_params_for_all_active( $scope, $query_params ) );
138
+	public function count_active($scope = NULL, $query_params = array()) {
139
+		return $this->count($this->_get_query_params_for_all_active($scope, $query_params));
140 140
 	}
141 141
 
142 142
 	/**
@@ -147,21 +147,21 @@  discard block
 block discarded – undo
147 147
 	 * @return array like param of EEM_Base::get_all()
148 148
 	 * @throws EE_Error
149 149
 	 */
150
-	protected function _get_query_params_for_all_active( $scope = NULL, $query_params = array() ){
151
-		if ( $scope ) {
152
-			if ( $this->is_valid_scope( $scope ) ) {
153
-				return array_replace_recursive( array( array( 'PMD_scope' => array( 'LIKE', "%$scope%" ) ) ), $query_params );
150
+	protected function _get_query_params_for_all_active($scope = NULL, $query_params = array()) {
151
+		if ($scope) {
152
+			if ($this->is_valid_scope($scope)) {
153
+				return array_replace_recursive(array(array('PMD_scope' => array('LIKE', "%$scope%"))), $query_params);
154 154
 			} else {
155
-				throw new EE_Error( sprintf( __( "'%s' is not a valid scope for a payment method", "event_espresso" ), $scope ) );
155
+				throw new EE_Error(sprintf(__("'%s' is not a valid scope for a payment method", "event_espresso"), $scope));
156 156
 			}
157 157
 		} else {
158 158
 			$acceptable_scopes = array();
159 159
 			$count = 0;
160
-			foreach ( $this->scopes() as $scope_name => $desc ) {
160
+			foreach ($this->scopes() as $scope_name => $desc) {
161 161
 				$count++;
162
-				$acceptable_scopes[ 'PMD_scope*' . $count ] = array( 'LIKE', '%' . $scope_name . '%' );
162
+				$acceptable_scopes['PMD_scope*'.$count] = array('LIKE', '%'.$scope_name.'%');
163 163
 			}
164
-			return array_replace_recursive( array( array( 'OR*active_scope' => $acceptable_scopes ) ), $query_params );
164
+			return array_replace_recursive(array(array('OR*active_scope' => $acceptable_scopes)), $query_params);
165 165
 		}
166 166
 	}
167 167
 
@@ -173,8 +173,8 @@  discard block
 block discarded – undo
173 173
 	 * @return array like param of EEM_Base::get_all()
174 174
 	 * @throws EE_Error
175 175
 	 */
176
-	public function get_query_params_for_all_active( $scope = NULL, $query_params = array() ) {
177
-		return $this->_get_query_params_for_all_active( $scope, $query_params );
176
+	public function get_query_params_for_all_active($scope = NULL, $query_params = array()) {
177
+		return $this->_get_query_params_for_all_active($scope, $query_params);
178 178
 	}
179 179
 
180 180
 
@@ -184,8 +184,8 @@  discard block
 block discarded – undo
184 184
 	 * @param array  $query_params
185 185
 	 * @return EE_Payment_Method
186 186
 	 */
187
-	public function get_one_active( $scope = NULL, $query_params = array() ) {
188
-		return $this->get_one( $this->_get_query_params_for_all_active( $scope, $query_params ) );
187
+	public function get_one_active($scope = NULL, $query_params = array()) {
188
+		return $this->get_one($this->_get_query_params_for_all_active($scope, $query_params));
189 189
 	}
190 190
 
191 191
 
@@ -195,8 +195,8 @@  discard block
 block discarded – undo
195 195
 	 * @param string $type
196 196
 	 * @return EE_Payment_Method
197 197
 	 */
198
-	public function get_one_of_type( $type ) {
199
-		return $this->get_one( array( array( 'PMD_type' => $type ) ) );
198
+	public function get_one_of_type($type) {
199
+		return $this->get_one(array(array('PMD_type' => $type)));
200 200
 	}
201 201
 
202 202
 
@@ -209,22 +209,22 @@  discard block
 block discarded – undo
209 209
 	 * @return EE_Payment_Method
210 210
 	 * @throws EE_Error
211 211
 	 */
212
-	public function ensure_is_obj( $base_class_obj_or_id, $ensure_is_in_db = FALSE ) {
212
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = FALSE) {
213 213
 		//first: check if it's a slug
214
-		if( is_string( $base_class_obj_or_id ) ) {
215
-			$obj = $this->get_one_by_slug( $base_class_obj_or_id );
216
-			if( $obj ) {
214
+		if (is_string($base_class_obj_or_id)) {
215
+			$obj = $this->get_one_by_slug($base_class_obj_or_id);
216
+			if ($obj) {
217 217
 				return $obj;
218 218
 			}
219 219
 		}
220 220
 		//ok so it wasn't a slug we were passed. try the usual then (ie, it's an object or an ID)
221 221
 		try {
222
-			return parent::ensure_is_obj( $base_class_obj_or_id, $ensure_is_in_db );
222
+			return parent::ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db);
223 223
 		}
224
-		catch ( EE_Error $e ) {
224
+		catch (EE_Error $e) {
225 225
 			//handle it outside the catch
226 226
 		}
227
-		throw new EE_Error( sprintf( __( "'%s' is neither a Payment Method ID, slug, nor object.", "event_espresso" ), $base_class_obj_or_id ) );
227
+		throw new EE_Error(sprintf(__("'%s' is neither a Payment Method ID, slug, nor object.", "event_espresso"), $base_class_obj_or_id));
228 228
 	}
229 229
 
230 230
 
@@ -235,12 +235,12 @@  discard block
 block discarded – undo
235 235
 	 * @param mixed $base_obj_or_id_or_slug
236 236
 	 * @return int
237 237
 	 */
238
-	function ensure_is_ID( $base_obj_or_id_or_slug ) {
239
-		if ( is_string( $base_obj_or_id_or_slug ) ) {
238
+	function ensure_is_ID($base_obj_or_id_or_slug) {
239
+		if (is_string($base_obj_or_id_or_slug)) {
240 240
 			//assume it's a slug
241
-			$base_obj_or_id_or_slug = $this->get_one_by_slug( $base_obj_or_id_or_slug );
241
+			$base_obj_or_id_or_slug = $this->get_one_by_slug($base_obj_or_id_or_slug);
242 242
 		}
243
-		return parent::ensure_is_ID( $base_obj_or_id_or_slug );
243
+		return parent::ensure_is_ID($base_obj_or_id_or_slug);
244 244
 	}
245 245
 
246 246
 
@@ -249,36 +249,36 @@  discard block
 block discarded – undo
249 249
 	 * Verifies the button urls on all the passed payment methods have a valid button url. If not, resets them to their default.
250 250
 	 * @param EE_Payment_Method[] $payment_methods. If NULL is provided defaults to all payment methods active in the cart
251 251
 	 */
252
-	function verify_button_urls( $payment_methods = NULL ) {
253
-		$payment_methods = is_array( $payment_methods ) ? $payment_methods : $this->get_all_active(EEM_Payment_Method::scope_cart);
254
-		foreach ( $payment_methods as $payment_method ) {
252
+	function verify_button_urls($payment_methods = NULL) {
253
+		$payment_methods = is_array($payment_methods) ? $payment_methods : $this->get_all_active(EEM_Payment_Method::scope_cart);
254
+		foreach ($payment_methods as $payment_method) {
255 255
 			try {
256 256
 				$current_button_url = $payment_method->button_url();
257
-				$buttons_urls_to_try = apply_filters( 'FHEE__EEM_Payment_Method__verify_button_urls__button_urls_to_try', array(
258
-					'current_ssl' => str_replace( "http://", "https://", $current_button_url ),
259
-					'current' => str_replace( "https://", "http://", $current_button_url ),
260
-					'default_ssl' => str_replace( "http://", "https://", $payment_method->type_obj()->default_button_url() ),
261
-					'default' => str_replace( "https://", "http://", $payment_method->type_obj()->default_button_url() ),
262
-				) );
263
-				foreach( $buttons_urls_to_try as $button_url_to_try ) {
264
-					if(
257
+				$buttons_urls_to_try = apply_filters('FHEE__EEM_Payment_Method__verify_button_urls__button_urls_to_try', array(
258
+					'current_ssl' => str_replace("http://", "https://", $current_button_url),
259
+					'current' => str_replace("https://", "http://", $current_button_url),
260
+					'default_ssl' => str_replace("http://", "https://", $payment_method->type_obj()->default_button_url()),
261
+					'default' => str_replace("https://", "http://", $payment_method->type_obj()->default_button_url()),
262
+				));
263
+				foreach ($buttons_urls_to_try as $button_url_to_try) {
264
+					if (
265 265
 							(//this is the current url and it exists, regardless of SSL issues
266 266
 								$button_url_to_try == $current_button_url &&
267 267
 								EEH_URL::remote_file_exists(
268 268
 										$button_url_to_try,
269 269
 										array(
270 270
 											'sslverify' => false,
271
-											'limit_response_size' => 4095,//we don't really care for a full response, but we do want headers at least. Lets just ask for a one block
271
+											'limit_response_size' => 4095, //we don't really care for a full response, but we do want headers at least. Lets just ask for a one block
272 272
 											) )
273 273
 							)
274 274
 							||
275 275
 							(//this is NOT the current url and it exists with a working SSL cert
276 276
 								$button_url_to_try != $current_button_url &&
277
-								EEH_URL::remote_file_exists( $button_url_to_try )
277
+								EEH_URL::remote_file_exists($button_url_to_try)
278 278
 							) ) {
279
-						if( $current_button_url != $button_url_to_try ){
280
-							$payment_method->save( array( 'PMD_button_url' => $button_url_to_try ) );
281
-							EE_Error::add_attention( sprintf( __( "Payment Method %s's button url was set to %s, because the old image either didnt exist or SSL was recently enabled.", "event_espresso" ), $payment_method->name(), $button_url_to_try ) );
279
+						if ($current_button_url != $button_url_to_try) {
280
+							$payment_method->save(array('PMD_button_url' => $button_url_to_try));
281
+							EE_Error::add_attention(sprintf(__("Payment Method %s's button url was set to %s, because the old image either didnt exist or SSL was recently enabled.", "event_espresso"), $payment_method->name(), $button_url_to_try));
282 282
 						}
283 283
 						//this image exists. So if wasn't set before, now it is;
284 284
 						//or if it was already set, we have nothing to do
@@ -286,8 +286,8 @@  discard block
 block discarded – undo
286 286
 					}
287 287
 				}
288 288
 			}
289
-			catch ( EE_Error $e ) {
290
-				$payment_method->set_active( FALSE );
289
+			catch (EE_Error $e) {
290
+				$payment_method->set_active(FALSE);
291 291
 			}
292 292
 		}
293 293
 	}
@@ -303,30 +303,30 @@  discard block
 block discarded – undo
303 303
      * @return EE_Payment_Method[]
304 304
      * @throws InvalidDataTypeException
305 305
      */
306
-	protected function _create_objects( $rows = array() ) {
307
-		EE_Registry::instance()->load_lib( 'Payment_Method_Manager' );
308
-		$payment_methods = parent::_create_objects( $rows );
306
+	protected function _create_objects($rows = array()) {
307
+		EE_Registry::instance()->load_lib('Payment_Method_Manager');
308
+		$payment_methods = parent::_create_objects($rows);
309 309
 		/* @var $payment_methods EE_Payment_Method[] */
310 310
 		$usable_payment_methods = array();
311
-		foreach ( $payment_methods as $key => $payment_method ) {
312
-			if ( EE_Payment_Method_Manager::instance()->payment_method_type_exists( $payment_method->type() ) ) {
313
-				$usable_payment_methods[ $key ] = $payment_method;
311
+		foreach ($payment_methods as $key => $payment_method) {
312
+			if (EE_Payment_Method_Manager::instance()->payment_method_type_exists($payment_method->type())) {
313
+				$usable_payment_methods[$key] = $payment_method;
314 314
 				//some payment methods enqueue their scripts in EE_PMT_*::__construct
315 315
 				//which is kinda a no-no (just because it's being constructed doesn't mean we need to enqueue
316 316
 				//its scripts). but for backwards-compat we should continue to do that
317 317
 				$payment_method->type_obj();
318
-			} elseif( $payment_method->active() ) {
318
+			} elseif ($payment_method->active()) {
319 319
 				//only deactivate and notify the admin if the payment is active somewhere
320 320
 				$payment_method->deactivate();
321 321
 				$payment_method->save();
322 322
                 new PersistentAdminNotice(
323
-                    'auto-deactivated-' . $payment_method->type(),
323
+                    'auto-deactivated-'.$payment_method->type(),
324 324
                     sprintf(
325 325
                         __('The payment method %1$s was automatically deactivated because it appears its associated Event Espresso Addon was recently deactivated.%2$sIt can be reactivated on the %3$sPlugins admin page%4$s, then you can reactivate the payment method.',
326 326
                             'event_espresso'),
327 327
                         $payment_method->admin_name(),
328 328
                         '<br />',
329
-                        '<a href="' . admin_url('plugins.php') . '">',
329
+                        '<a href="'.admin_url('plugins.php').'">',
330 330
                         '</a>'
331 331
                     ),
332 332
                     true
@@ -346,11 +346,11 @@  discard block
 block discarded – undo
346 346
 	 * @param string 	$scope @see EEM_Payment_Method::get_all_for_events
347 347
 	 * @return EE_Payment_Method[]
348 348
 	 */
349
-	public function get_all_for_transaction( $transaction, $scope ) {
349
+	public function get_all_for_transaction($transaction, $scope) {
350 350
 		//give addons a chance to override what payment methods are chosen based on the transaction
351 351
 		return apply_filters(
352 352
 			'FHEE__EEM_Payment_Method__get_all_for_transaction__payment_methods',
353
-			$this->get_all_active( $scope, array( 'group_by' => 'PMD_type' ) ),
353
+			$this->get_all_active($scope, array('group_by' => 'PMD_type')),
354 354
 			$transaction,
355 355
 			$scope
356 356
 		);
@@ -366,16 +366,16 @@  discard block
 block discarded – undo
366 366
 	 * @param EE_Registration|int $registration_or_reg_id  Either the EE_Registration object or the id for the registration.
367 367
 	 * @return EE_Payment|null
368 368
 	 */
369
-	public function get_last_used_for_registration( $registration_or_reg_id ) {
370
-		$registration_id = EEM_Registration::instance()->ensure_is_ID( $registration_or_reg_id );
369
+	public function get_last_used_for_registration($registration_or_reg_id) {
370
+		$registration_id = EEM_Registration::instance()->ensure_is_ID($registration_or_reg_id);
371 371
 
372 372
 		$query_params = array(
373 373
 			0 => array(
374 374
 				'Payment.Registration.REG_ID' => $registration_id,
375 375
 			),
376
-			'order_by' => array( 'Payment.PAY_ID' => 'DESC' )
376
+			'order_by' => array('Payment.PAY_ID' => 'DESC')
377 377
 		);
378
-		return $this->get_one( $query_params );
378
+		return $this->get_one($query_params);
379 379
 	}
380 380
 
381 381
 }
Please login to merge, or discard this patch.