Completed
Branch BUG-10878-event-spaces-remaini... (07bd4d)
by
unknown
42:38 queued 31:47
created
core/domain/services/admin/AdminToolBar.php 2 patches
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -120,7 +120,7 @@  discard block
 block discarded – undo
120 120
     {
121 121
         wp_register_style(
122 122
             'espresso-admin-toolbar',
123
-            EE_GLOBAL_ASSETS_URL . 'css/espresso-admin-toolbar.css',
123
+            EE_GLOBAL_ASSETS_URL.'css/espresso-admin-toolbar.css',
124 124
             array('dashicons'),
125 125
             EVENT_ESPRESSO_VERSION
126 126
         );
@@ -143,7 +143,7 @@  discard block
 block discarded – undo
143 143
                 'href'  => $this->events_admin_url,
144 144
                 'meta'  => array(
145 145
                     'title' => esc_html__('Event Espresso', 'event_espresso'),
146
-                    'class' => $this->menu_class . 'first',
146
+                    'class' => $this->menu_class.'first',
147 147
                 ),
148 148
             )
149 149
         );
@@ -491,7 +491,7 @@  discard block
 block discarded – undo
491 491
                     'meta'   => array(
492 492
                         'title'  => esc_html__('Approved', 'event_espresso'),
493 493
                         'target' => '',
494
-                        'class'  => $this->menu_class . ' ee-toolbar-icon-approved',
494
+                        'class'  => $this->menu_class.' ee-toolbar-icon-approved',
495 495
                     ),
496 496
                 )
497 497
             );
@@ -528,7 +528,7 @@  discard block
 block discarded – undo
528 528
                     'meta'   => array(
529 529
                         'title'  => esc_html__('Pending Payment', 'event_espresso'),
530 530
                         'target' => '',
531
-                        'class'  => $this->menu_class . ' ee-toolbar-icon-pending',
531
+                        'class'  => $this->menu_class.' ee-toolbar-icon-pending',
532 532
                     ),
533 533
                 )
534 534
             );
@@ -565,7 +565,7 @@  discard block
 block discarded – undo
565 565
                     'meta'   => array(
566 566
                         'title'  => esc_html__('Not Approved', 'event_espresso'),
567 567
                         'target' => '',
568
-                        'class'  => $this->menu_class . ' ee-toolbar-icon-not-approved',
568
+                        'class'  => $this->menu_class.' ee-toolbar-icon-not-approved',
569 569
                     ),
570 570
                 )
571 571
             );
@@ -602,7 +602,7 @@  discard block
 block discarded – undo
602 602
                     'meta'   => array(
603 603
                         'title'  => esc_html__('Cancelled', 'event_espresso'),
604 604
                         'target' => '',
605
-                        'class'  => $this->menu_class . ' ee-toolbar-icon-cancelled',
605
+                        'class'  => $this->menu_class.' ee-toolbar-icon-cancelled',
606 606
                     ),
607 607
                 )
608 608
             );
@@ -674,7 +674,7 @@  discard block
 block discarded – undo
674 674
                     'meta'   => array(
675 675
                         'title'  => esc_html__('Approved', 'event_espresso'),
676 676
                         'target' => '',
677
-                        'class'  => $this->menu_class . ' ee-toolbar-icon-approved',
677
+                        'class'  => $this->menu_class.' ee-toolbar-icon-approved',
678 678
                     ),
679 679
                 )
680 680
             );
@@ -711,7 +711,7 @@  discard block
 block discarded – undo
711 711
                     'meta'   => array(
712 712
                         'title'  => esc_html__('Pending', 'event_espresso'),
713 713
                         'target' => '',
714
-                        'class'  => $this->menu_class . ' ee-toolbar-icon-pending',
714
+                        'class'  => $this->menu_class.' ee-toolbar-icon-pending',
715 715
                     ),
716 716
                 )
717 717
             );
@@ -748,7 +748,7 @@  discard block
 block discarded – undo
748 748
                     'meta'   => array(
749 749
                         'title'  => esc_html__('Not Approved', 'event_espresso'),
750 750
                         'target' => '',
751
-                        'class'  => $this->menu_class . ' ee-toolbar-icon-not-approved',
751
+                        'class'  => $this->menu_class.' ee-toolbar-icon-not-approved',
752 752
                     ),
753 753
                 )
754 754
             );
@@ -785,7 +785,7 @@  discard block
 block discarded – undo
785 785
                     'meta'   => array(
786 786
                         'title'  => esc_html__('Cancelled', 'event_espresso'),
787 787
                         'target' => '',
788
-                        'class'  => $this->menu_class . ' ee-toolbar-icon-cancelled',
788
+                        'class'  => $this->menu_class.' ee-toolbar-icon-cancelled',
789 789
                     ),
790 790
                 )
791 791
             );
Please login to merge, or discard this patch.
Indentation   +799 added lines, -799 removed lines patch added patch discarded remove patch
@@ -22,804 +22,804 @@
 block discarded – undo
22 22
 class AdminToolBar
23 23
 {
24 24
 
25
-    /**
26
-     * @var WP_Admin_Bar $admin_bar
27
-     */
28
-    private $admin_bar;
29
-
30
-    /**
31
-     * @var EE_Capabilities $capabilities
32
-     */
33
-    private $capabilities;
34
-
35
-    /**
36
-     * @var string $events_admin_url
37
-     */
38
-    private $events_admin_url;
39
-
40
-    /**
41
-     * @var string $menu_class
42
-     */
43
-    private $menu_class = 'espresso_menu_item_class';
44
-
45
-    /**
46
-     * @var string $reg_admin_url
47
-     */
48
-    private $reg_admin_url;
49
-
50
-
51
-
52
-    /**
53
-     * AdminToolBar constructor.
54
-     *
55
-     * @param EE_Capabilities $capabilities
56
-     */
57
-    public function __construct(EE_Capabilities $capabilities)
58
-    {
59
-        $this->capabilities = $capabilities;
60
-        add_action('admin_bar_menu', array($this, 'espressoToolbarItems'), 100);
61
-        $this->enqueueAssets();
62
-    }
63
-
64
-
65
-
66
-    /**
67
-     *    espresso_toolbar_items
68
-     *
69
-     * @access public
70
-     * @param  WP_Admin_Bar $admin_bar
71
-     * @return void
72
-     */
73
-    public function espressoToolbarItems(WP_Admin_Bar $admin_bar)
74
-    {
75
-        // if its an AJAX request, or user is NOT an admin, or in full M-Mode
76
-        if (
77
-            defined('DOING_AJAX')
78
-            || ! $this->capabilities->current_user_can('ee_read_ee', 'ee_admin_bar_menu_top_level')
79
-            || EE_Maintenance_Mode::instance()->level() === EE_Maintenance_Mode::level_2_complete_maintenance
80
-        ) {
81
-            return;
82
-        }
83
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
84
-        $this->admin_bar = $admin_bar;
85
-        //we don't use the constants EVENTS_ADMIN_URL or REG_ADMIN_URL
86
-        //because they're only defined in each of their respective constructors
87
-        //and this might be a frontend request, in which case they aren't available
88
-        $this->events_admin_url = admin_url('admin.php?page=espresso_events');
89
-        $this->reg_admin_url = admin_url('admin.php?page=espresso_registrations');
90
-        // now let's add all of the menu items
91
-        $this->addTopLevelMenu();
92
-        $this->addEventsSubMenu();
93
-        $this->addEventsAddEditHeader();
94
-        $this->addEventsAddNew();
95
-        $this->addEventsEditCurrentEvent();
96
-        $this->addEventsViewHeader();
97
-        $this->addEventsViewAll();
98
-        $this->addEventsViewToday();
99
-        $this->addEventsViewThisMonth();
100
-        $this->addRegistrationSubMenu();
101
-        $this->addRegistrationOverviewToday();
102
-        $this->addRegistrationOverviewTodayApproved();
103
-        $this->addRegistrationOverviewTodayPendingPayment();
104
-        $this->addRegistrationOverviewTodayNotApproved();
105
-        $this->addRegistrationOverviewTodayCancelled();
106
-        $this->addRegistrationOverviewThisMonth();
107
-        $this->addRegistrationOverviewThisMonthApproved();
108
-        $this->addRegistrationOverviewThisMonthPending();
109
-        $this->addRegistrationOverviewThisMonthNotApproved();
110
-        $this->addRegistrationOverviewThisMonthCancelled();
111
-        $this->addExtensionsAndServices();
112
-    }
113
-
114
-
115
-
116
-    /**
117
-     * @return void
118
-     */
119
-    private function enqueueAssets()
120
-    {
121
-        wp_register_style(
122
-            'espresso-admin-toolbar',
123
-            EE_GLOBAL_ASSETS_URL . 'css/espresso-admin-toolbar.css',
124
-            array('dashicons'),
125
-            EVENT_ESPRESSO_VERSION
126
-        );
127
-        wp_enqueue_style('espresso-admin-toolbar');
128
-    }
129
-
130
-
131
-
132
-    /**
133
-     * @return void
134
-     */
135
-    private function addTopLevelMenu()
136
-    {
137
-        $this->admin_bar->add_menu(
138
-            array(
139
-                'id'    => 'espresso-toolbar',
140
-                'title' => '<span class="ee-icon ee-icon-ee-cup-thick ee-icon-size-20"></span><span class="ab-label">'
141
-                    . esc_html_x('Event Espresso', 'admin bar menu group label', 'event_espresso')
142
-                    . '</span>',
143
-                'href'  => $this->events_admin_url,
144
-                'meta'  => array(
145
-                    'title' => esc_html__('Event Espresso', 'event_espresso'),
146
-                    'class' => $this->menu_class . 'first',
147
-                ),
148
-            )
149
-        );
150
-    }
151
-
152
-
153
-
154
-    /**
155
-     * @return void
156
-     */
157
-    private function addEventsSubMenu()
158
-    {
159
-        if (
160
-            $this->capabilities->current_user_can(
161
-                'ee_read_events',
162
-                'ee_admin_bar_menu_espresso-toolbar-events'
163
-            )
164
-        ) {
165
-            $this->admin_bar->add_menu(
166
-                array(
167
-                    'id'     => 'espresso-toolbar-events',
168
-                    'parent' => 'espresso-toolbar',
169
-                    'title'  => '<span class="ee-toolbar-icon"></span>'
170
-                                . esc_html__('Events', 'event_espresso'),
171
-                    'href'   => $this->events_admin_url,
172
-                    'meta'   => array(
173
-                        'title'  => esc_html__('Events', 'event_espresso'),
174
-                        'target' => '',
175
-                        'class'  => $this->menu_class,
176
-                    ),
177
-                )
178
-            );
179
-        }
180
-    }
181
-
182
-
183
-
184
-    /**
185
-     * @return void
186
-     */
187
-    private function addEventsAddEditHeader()
188
-    {
189
-        if (
190
-        $this->capabilities->current_user_can(
191
-            'ee_read_events',
192
-            'ee_admin_bar_menu_espresso-toolbar-events-view'
193
-        )
194
-        ) {
195
-            $this->admin_bar->add_menu(
196
-                array(
197
-                    'id'     => 'espresso-toolbar-events-add-edit',
198
-                    'parent' => 'espresso-toolbar-events',
199
-                    'title'  => esc_html__('Add / Edit', 'event_espresso'),
200
-                    'href'   => '',
201
-                )
202
-            );
203
-        }
204
-    }
205
-
206
-
207
-
208
-    /**
209
-     * @return void
210
-     */
211
-    private function addEventsAddNew()
212
-    {
213
-        if (
214
-            $this->capabilities->current_user_can(
215
-                'ee_edit_events',
216
-                'ee_admin_bar_menu_espresso-toolbar-events-new'
217
-            )
218
-        ) {
219
-            $this->admin_bar->add_menu(
220
-                array(
221
-                    'id'     => 'espresso-toolbar-events-new',
222
-                    'parent' => 'espresso-toolbar-events',
223
-                    'title'  => '<span class="ee-toolbar-icon"></span>'
224
-                                . esc_html__('Add New', 'event_espresso'),
225
-                    'href'   => EEH_URL::add_query_args_and_nonce(
226
-                        array('action' => 'create_new'),
227
-                        $this->events_admin_url
228
-                    ),
229
-                    'meta'   => array(
230
-                        'title'  => esc_html__('Add New', 'event_espresso'),
231
-                        'target' => '',
232
-                        'class'  => $this->menu_class,
233
-                    ),
234
-                )
235
-            );
236
-        }
237
-    }
238
-
239
-
240
-
241
-    /**
242
-     * @return void
243
-     */
244
-    private function addEventsEditCurrentEvent()
245
-    {
246
-        if (is_single() && (get_post_type() === 'espresso_events')) {
247
-            //Current post
248
-            global $post;
249
-            if (
250
-                $this->capabilities->current_user_can(
251
-                    'ee_edit_event',
252
-                    'ee_admin_bar_menu_espresso-toolbar-events-edit', $post->ID
253
-                )
254
-            ) {
255
-                $this->admin_bar->add_menu(
256
-                    array(
257
-                        'id'     => 'espresso-toolbar-events-edit',
258
-                        'parent' => 'espresso-toolbar-events',
259
-                        'title'  => '<span class="ee-toolbar-icon"></span>'
260
-                                    . esc_html__('Edit Event', 'event_espresso'),
261
-                        'href'   => EEH_URL::add_query_args_and_nonce(
262
-                            array(
263
-                                'action' => 'edit',
264
-                                'post' => $post->ID
265
-                            ),
266
-                            $this->events_admin_url
267
-                        ),
268
-                        'meta'   => array(
269
-                            'title'  => esc_html__('Edit Event', 'event_espresso'),
270
-                            'target' => '',
271
-                            'class'  => $this->menu_class,
272
-                        ),
273
-                    )
274
-                );
275
-            }
276
-        }
277
-    }
278
-
279
-
280
-
281
-    /**
282
-     * @return void
283
-     */
284
-    private function addEventsViewHeader()
285
-    {
286
-        if (
287
-            $this->capabilities->current_user_can(
288
-                'ee_read_events',
289
-                'ee_admin_bar_menu_espresso-toolbar-events-view'
290
-            )
291
-        ) {
292
-            $this->admin_bar->add_menu(
293
-                array(
294
-                    'id'     => 'espresso-toolbar-events-view',
295
-                    'parent' => 'espresso-toolbar-events',
296
-                    'title'  => esc_html__('View', 'event_espresso'),
297
-                    'href'   => '',
298
-                )
299
-            );
300
-        }
301
-    }
302
-
303
-
304
-
305
-    /**
306
-     * @return void
307
-     */
308
-    private function addEventsViewAll()
309
-    {
310
-        if (
311
-            $this->capabilities->current_user_can(
312
-                'ee_read_events',
313
-                'ee_admin_bar_menu_espresso-toolbar-events-all'
314
-            )
315
-        ) {
316
-            $this->admin_bar->add_menu(
317
-                array(
318
-                    'id'     => 'espresso-toolbar-events-all',
319
-                    'parent' => 'espresso-toolbar-events',
320
-                    'title'  => '<span class="ee-toolbar-icon"></span>'
321
-                                . esc_html__('All', 'event_espresso'),
322
-                    'href'   => $this->events_admin_url,
323
-                    'meta'   => array(
324
-                        'title'  => esc_html__('All', 'event_espresso'),
325
-                        'target' => '',
326
-                        'class'  => $this->menu_class,
327
-                    ),
328
-                )
329
-            );
330
-        }
331
-    }
332
-
333
-
334
-
335
-    /**
336
-     * @return void
337
-     */
338
-    private function addEventsViewToday()
339
-    {
340
-        if (
341
-            $this->capabilities->current_user_can(
342
-                'ee_read_events',
343
-                'ee_admin_bar_menu_espresso-toolbar-events-today'
344
-            )
345
-        ) {
346
-            $this->admin_bar->add_menu(
347
-                array(
348
-                    'id'     => 'espresso-toolbar-events-today',
349
-                    'parent' => 'espresso-toolbar-events',
350
-                    'title'  => '<span class="ee-toolbar-icon"></span>'
351
-                                . esc_html__('Today', 'event_espresso'),
352
-                    'href'   => EEH_URL::add_query_args_and_nonce(
353
-                        array(
354
-                            'action' => 'default',
355
-                            'status' => 'today'
356
-                        ),
357
-                        $this->events_admin_url
358
-                    ),
359
-                    'meta'   => array(
360
-                        'title'  => esc_html__('Today', 'event_espresso'),
361
-                        'target' => '',
362
-                        'class'  => $this->menu_class,
363
-                    ),
364
-                )
365
-            );
366
-        }
367
-    }
368
-
369
-
370
-
371
-    /**
372
-     * @return void
373
-     */
374
-    private function addEventsViewThisMonth()
375
-    {
376
-        if (
377
-            $this->capabilities->current_user_can(
378
-                'ee_read_events',
379
-                'ee_admin_bar_menu_espresso-toolbar-events-month'
380
-            )
381
-        ) {
382
-            $this->admin_bar->add_menu(
383
-                array(
384
-                    'id'     => 'espresso-toolbar-events-month',
385
-                    'parent' => 'espresso-toolbar-events',
386
-                    'title'  => '<span class="ee-toolbar-icon"></span>'
387
-                                . esc_html__('This Month', 'event_espresso'),
388
-                    'href'   => EEH_URL::add_query_args_and_nonce(
389
-                        array(
390
-                            'action' => 'default',
391
-                            'status' => 'month'
392
-                        ),
393
-                        $this->events_admin_url
394
-                    ),
395
-                    'meta'   => array(
396
-                        'title'  => esc_html__('This Month', 'event_espresso'),
397
-                        'target' => '',
398
-                        'class'  => $this->menu_class,
399
-                    ),
400
-                )
401
-            );
402
-        }
403
-    }
404
-
405
-
406
-
407
-    /**
408
-     * @return void
409
-     */
410
-    private function addRegistrationSubMenu()
411
-    {
412
-        if (
413
-            $this->capabilities->current_user_can(
414
-                'ee_read_registrations',
415
-                'ee_admin_bar_menu_espresso-toolbar-registrations'
416
-            )
417
-        ) {
418
-            $this->admin_bar->add_menu(
419
-                array(
420
-                    'id'     => 'espresso-toolbar-registrations',
421
-                    'parent' => 'espresso-toolbar',
422
-                    'title'  => '<span class="ee-toolbar-icon"></span>'
423
-                                . esc_html__('Registrations', 'event_espresso'),
424
-                    'href'   => $this->reg_admin_url,
425
-                    'meta'   => array(
426
-                        'title'  => esc_html__('Registrations', 'event_espresso'),
427
-                        'target' => '',
428
-                        'class'  => $this->menu_class,
429
-                    ),
430
-                )
431
-            );
432
-        }
433
-    }
434
-
435
-
436
-
437
-    /**
438
-     * @return void
439
-     */
440
-    private function addRegistrationOverviewToday()
441
-    {
442
-        if (
443
-            $this->capabilities->current_user_can(
444
-                'ee_read_registrations',
445
-                'ee_admin_bar_menu_espresso-toolbar-registrations-today'
446
-            )
447
-        ) {
448
-            $this->admin_bar->add_menu(
449
-                array(
450
-                    'id'     => 'espresso-toolbar-registrations-today',
451
-                    'parent' => 'espresso-toolbar-registrations',
452
-                    'title'  => esc_html__('Today', 'event_espresso'),
453
-                    'href'   => '',
454
-                    'meta'   => array(
455
-                        'title'  => esc_html__('Today', 'event_espresso'),
456
-                        'target' => '',
457
-                        'class'  => $this->menu_class,
458
-                    ),
459
-                )
460
-            );
461
-        }
462
-    }
463
-
464
-
465
-
466
-    /**
467
-     * @return void
468
-     */
469
-    private function addRegistrationOverviewTodayApproved()
470
-    {
471
-        if (
472
-            $this->capabilities->current_user_can(
473
-                'ee_read_registrations',
474
-                'ee_admin_bar_menu_espresso-toolbar-registrations-today-approved'
475
-            )
476
-        ) {
477
-            $this->admin_bar->add_menu(
478
-                array(
479
-                    'id'     => 'espresso-toolbar-registrations-today-approved',
480
-                    'parent' => 'espresso-toolbar-registrations',
481
-                    'title'  => '<span class="ee-toolbar-icon"></span>'
482
-                                . esc_html__('Approved', 'event_espresso'),
483
-                    'href'   => EEH_URL::add_query_args_and_nonce(
484
-                        array(
485
-                            'action'      => 'default',
486
-                            'status'      => 'today',
487
-                            '_reg_status' => EEM_Registration::status_id_approved,
488
-                        ),
489
-                        $this->reg_admin_url
490
-                    ),
491
-                    'meta'   => array(
492
-                        'title'  => esc_html__('Approved', 'event_espresso'),
493
-                        'target' => '',
494
-                        'class'  => $this->menu_class . ' ee-toolbar-icon-approved',
495
-                    ),
496
-                )
497
-            );
498
-        }
499
-    }
500
-
501
-
502
-
503
-    /**
504
-     * @return void
505
-     */
506
-    private function addRegistrationOverviewTodayPendingPayment()
507
-    {
508
-        if (
509
-            $this->capabilities->current_user_can(
510
-                'ee_read_registrations',
511
-                'ee_admin_bar_menu_espresso-toolbar-registrations-today-pending'
512
-            )
513
-        ) {
514
-            $this->admin_bar->add_menu(
515
-                array(
516
-                    'id'     => 'espresso-toolbar-registrations-today-pending',
517
-                    'parent' => 'espresso-toolbar-registrations',
518
-                    'title'  => '<span class="ee-toolbar-icon"></span>'
519
-                                . esc_html__('Pending', 'event_espresso'),
520
-                    'href'   => EEH_URL::add_query_args_and_nonce(
521
-                        array(
522
-                            'action'     => 'default',
523
-                            'status'     => 'today',
524
-                            '_reg_status' => EEM_Registration::status_id_pending_payment,
525
-                        ),
526
-                        $this->reg_admin_url
527
-                    ),
528
-                    'meta'   => array(
529
-                        'title'  => esc_html__('Pending Payment', 'event_espresso'),
530
-                        'target' => '',
531
-                        'class'  => $this->menu_class . ' ee-toolbar-icon-pending',
532
-                    ),
533
-                )
534
-            );
535
-        }
536
-    }
537
-
538
-
539
-
540
-    /**
541
-     * @return void
542
-     */
543
-    private function addRegistrationOverviewTodayNotApproved()
544
-    {
545
-        if (
546
-            $this->capabilities->current_user_can(
547
-                'ee_read_registrations',
548
-                'ee_admin_bar_menu_espresso-toolbar-registrations-today-not-approved'
549
-            )
550
-        ) {
551
-            $this->admin_bar->add_menu(
552
-                array(
553
-                    'id'     => 'espresso-toolbar-registrations-today-not-approved',
554
-                    'parent' => 'espresso-toolbar-registrations',
555
-                    'title'  => '<span class="ee-toolbar-icon"></span>'
556
-                                . esc_html__('Not Approved', 'event_espresso'),
557
-                    'href'   => EEH_URL::add_query_args_and_nonce(
558
-                        array(
559
-                            'action'      => 'default',
560
-                            'status'      => 'today',
561
-                            '_reg_status' => EEM_Registration::status_id_not_approved,
562
-                        ),
563
-                        $this->reg_admin_url
564
-                    ),
565
-                    'meta'   => array(
566
-                        'title'  => esc_html__('Not Approved', 'event_espresso'),
567
-                        'target' => '',
568
-                        'class'  => $this->menu_class . ' ee-toolbar-icon-not-approved',
569
-                    ),
570
-                )
571
-            );
572
-        }
573
-    }
574
-
575
-
576
-
577
-    /**
578
-     * @return void
579
-     */
580
-    private function addRegistrationOverviewTodayCancelled()
581
-    {
582
-        if (
583
-            $this->capabilities->current_user_can(
584
-                'ee_read_registrations',
585
-                'ee_admin_bar_menu_espresso-toolbar-registrations-today-cancelled'
586
-            )
587
-        ) {
588
-            $this->admin_bar->add_menu(
589
-                array(
590
-                    'id'     => 'espresso-toolbar-registrations-today-cancelled',
591
-                    'parent' => 'espresso-toolbar-registrations',
592
-                    'title'  => '<span class="ee-toolbar-icon"></span>'
593
-                                . esc_html__('Cancelled', 'event_espresso'),
594
-                    'href'   => EEH_URL::add_query_args_and_nonce(
595
-                        array(
596
-                            'action'      => 'default',
597
-                            'status'      => 'today',
598
-                            '_reg_status' => EEM_Registration::status_id_cancelled,
599
-                        ),
600
-                        $this->reg_admin_url
601
-                    ),
602
-                    'meta'   => array(
603
-                        'title'  => esc_html__('Cancelled', 'event_espresso'),
604
-                        'target' => '',
605
-                        'class'  => $this->menu_class . ' ee-toolbar-icon-cancelled',
606
-                    ),
607
-                )
608
-            );
609
-        }
610
-    }
611
-
612
-
613
-
614
-    /**
615
-     * @return void
616
-     */
617
-    private function addRegistrationOverviewThisMonth()
618
-    {
619
-        if (
620
-            $this->capabilities->current_user_can(
621
-                'ee_read_registrations',
622
-                'ee_admin_bar_menu_espresso-toolbar-registrations-month'
623
-            )
624
-        ) {
625
-            $this->admin_bar->add_menu(
626
-                array(
627
-                    'id'     => 'espresso-toolbar-registrations-month',
628
-                    'parent' => 'espresso-toolbar-registrations',
629
-                    'title'  => esc_html__('This Month', 'event_espresso'),
630
-                    'href'   => '', //EEH_URL::add_query_args_and_nonce(
631
-                    //     array(
632
-                    //         'action' => 'default',
633
-                    //         'status' => 'month'
634
-                    //     ),
635
-                    //     $this->reg_admin_url
636
-                    // ),
637
-                    'meta'   => array(
638
-                        'title'  => esc_html__('This Month', 'event_espresso'),
639
-                        'target' => '',
640
-                        'class'  => $this->menu_class,
641
-                    ),
642
-                )
643
-            );
644
-        }
645
-    }
646
-
647
-
648
-
649
-    /**
650
-     * @return void
651
-     */
652
-    private function addRegistrationOverviewThisMonthApproved()
653
-    {
654
-        if (
655
-            $this->capabilities->current_user_can(
656
-                'ee_read_registrations',
657
-                'ee_admin_bar_menu_espresso-toolbar-registrations-month-approved'
658
-            )
659
-        ) {
660
-            $this->admin_bar->add_menu(
661
-                array(
662
-                    'id'     => 'espresso-toolbar-registrations-month-approved',
663
-                    'parent' => 'espresso-toolbar-registrations',
664
-                    'title'  => '<span class="ee-toolbar-icon"></span>'
665
-                                . esc_html__('Approved', 'event_espresso'),
666
-                    'href'   => EEH_URL::add_query_args_and_nonce(
667
-                        array(
668
-                            'action'      => 'default',
669
-                            'status'      => 'month',
670
-                            '_reg_status' => EEM_Registration::status_id_approved,
671
-                        ),
672
-                        $this->reg_admin_url
673
-                    ),
674
-                    'meta'   => array(
675
-                        'title'  => esc_html__('Approved', 'event_espresso'),
676
-                        'target' => '',
677
-                        'class'  => $this->menu_class . ' ee-toolbar-icon-approved',
678
-                    ),
679
-                )
680
-            );
681
-        }
682
-    }
683
-
684
-
685
-
686
-    /**
687
-     * @return void
688
-     */
689
-    private function addRegistrationOverviewThisMonthPending()
690
-    {
691
-        if (
692
-            $this->capabilities->current_user_can(
693
-                'ee_read_registrations',
694
-                'ee_admin_bar_menu_espresso-toolbar-registrations-month-pending'
695
-            )
696
-        ) {
697
-            $this->admin_bar->add_menu(
698
-                array(
699
-                    'id'     => 'espresso-toolbar-registrations-month-pending',
700
-                    'parent' => 'espresso-toolbar-registrations',
701
-                    'title'  => '<span class="ee-toolbar-icon"></span>'
702
-                                . esc_html__('Pending', 'event_espresso'),
703
-                    'href'   => EEH_URL::add_query_args_and_nonce(
704
-                        array(
705
-                            'action'      => 'default',
706
-                            'status'      => 'month',
707
-                            '_reg_status' => EEM_Registration::status_id_pending_payment,
708
-                        ),
709
-                        $this->reg_admin_url
710
-                    ),
711
-                    'meta'   => array(
712
-                        'title'  => esc_html__('Pending', 'event_espresso'),
713
-                        'target' => '',
714
-                        'class'  => $this->menu_class . ' ee-toolbar-icon-pending',
715
-                    ),
716
-                )
717
-            );
718
-        }
719
-    }
720
-
721
-
722
-
723
-    /**
724
-     * @return void
725
-     */
726
-    private function addRegistrationOverviewThisMonthNotApproved()
727
-    {
728
-        if (
729
-            $this->capabilities->current_user_can(
730
-                'ee_read_registrations',
731
-                'ee_admin_bar_menu_espresso-toolbar-registrations-month-not-approved'
732
-            )
733
-        ) {
734
-            $this->admin_bar->add_menu(
735
-                array(
736
-                    'id'     => 'espresso-toolbar-registrations-month-not-approved',
737
-                    'parent' => 'espresso-toolbar-registrations',
738
-                    'title'  => '<span class="ee-toolbar-icon"></span>'
739
-                                . esc_html__('Not Approved', 'event_espresso'),
740
-                    'href'   => EEH_URL::add_query_args_and_nonce(
741
-                        array(
742
-                            'action'      => 'default',
743
-                            'status'      => 'month',
744
-                            '_reg_status' => EEM_Registration::status_id_not_approved,
745
-                        ),
746
-                        $this->reg_admin_url
747
-                    ),
748
-                    'meta'   => array(
749
-                        'title'  => esc_html__('Not Approved', 'event_espresso'),
750
-                        'target' => '',
751
-                        'class'  => $this->menu_class . ' ee-toolbar-icon-not-approved',
752
-                    ),
753
-                )
754
-            );
755
-        }
756
-    }
757
-
758
-
759
-
760
-    /**
761
-     * @return void
762
-     */
763
-    private function addRegistrationOverviewThisMonthCancelled()
764
-    {
765
-        if (
766
-            $this->capabilities->current_user_can(
767
-                'ee_read_registrations',
768
-                'ee_admin_bar_menu_espresso-toolbar-registrations-month-cancelled'
769
-            )
770
-        ) {
771
-            $this->admin_bar->add_menu(
772
-                array(
773
-                    'id'     => 'espresso-toolbar-registrations-month-cancelled',
774
-                    'parent' => 'espresso-toolbar-registrations',
775
-                    'title'  => '<span class="ee-toolbar-icon"></span>'
776
-                                . esc_html__('Cancelled', 'event_espresso'),
777
-                    'href'   => EEH_URL::add_query_args_and_nonce(
778
-                        array(
779
-                            'action'      => 'default',
780
-                            'status'      => 'month',
781
-                            '_reg_status' => EEM_Registration::status_id_cancelled,
782
-                        ),
783
-                        $this->reg_admin_url
784
-                    ),
785
-                    'meta'   => array(
786
-                        'title'  => esc_html__('Cancelled', 'event_espresso'),
787
-                        'target' => '',
788
-                        'class'  => $this->menu_class . ' ee-toolbar-icon-cancelled',
789
-                    ),
790
-                )
791
-            );
792
-        }
793
-    }
794
-
795
-
796
-
797
-    /**
798
-     * @return void
799
-     */
800
-    private function addExtensionsAndServices()
801
-    {
802
-        if (
803
-            $this->capabilities->current_user_can(
804
-                'ee_read_ee',
805
-                'ee_admin_bar_menu_espresso-toolbar-extensions-and-services'
806
-            )
807
-        ) {
808
-            $this->admin_bar->add_menu(
809
-                array(
810
-                    'id'     => 'espresso-toolbar-extensions-and-services',
811
-                    'parent' => 'espresso-toolbar',
812
-                    'title'  => '<span class="ee-toolbar-icon"></span>'
813
-                                . esc_html__('Extensions & Services', 'event_espresso'),
814
-                    'href'   => admin_url('admin.php?page=espresso_packages'),
815
-                    'meta'   => array(
816
-                        'title'  => esc_html__('Extensions & Services', 'event_espresso'),
817
-                        'target' => '',
818
-                        'class'  => $this->menu_class,
819
-                    ),
820
-                )
821
-            );
822
-        }
823
-    }
25
+	/**
26
+	 * @var WP_Admin_Bar $admin_bar
27
+	 */
28
+	private $admin_bar;
29
+
30
+	/**
31
+	 * @var EE_Capabilities $capabilities
32
+	 */
33
+	private $capabilities;
34
+
35
+	/**
36
+	 * @var string $events_admin_url
37
+	 */
38
+	private $events_admin_url;
39
+
40
+	/**
41
+	 * @var string $menu_class
42
+	 */
43
+	private $menu_class = 'espresso_menu_item_class';
44
+
45
+	/**
46
+	 * @var string $reg_admin_url
47
+	 */
48
+	private $reg_admin_url;
49
+
50
+
51
+
52
+	/**
53
+	 * AdminToolBar constructor.
54
+	 *
55
+	 * @param EE_Capabilities $capabilities
56
+	 */
57
+	public function __construct(EE_Capabilities $capabilities)
58
+	{
59
+		$this->capabilities = $capabilities;
60
+		add_action('admin_bar_menu', array($this, 'espressoToolbarItems'), 100);
61
+		$this->enqueueAssets();
62
+	}
63
+
64
+
65
+
66
+	/**
67
+	 *    espresso_toolbar_items
68
+	 *
69
+	 * @access public
70
+	 * @param  WP_Admin_Bar $admin_bar
71
+	 * @return void
72
+	 */
73
+	public function espressoToolbarItems(WP_Admin_Bar $admin_bar)
74
+	{
75
+		// if its an AJAX request, or user is NOT an admin, or in full M-Mode
76
+		if (
77
+			defined('DOING_AJAX')
78
+			|| ! $this->capabilities->current_user_can('ee_read_ee', 'ee_admin_bar_menu_top_level')
79
+			|| EE_Maintenance_Mode::instance()->level() === EE_Maintenance_Mode::level_2_complete_maintenance
80
+		) {
81
+			return;
82
+		}
83
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
84
+		$this->admin_bar = $admin_bar;
85
+		//we don't use the constants EVENTS_ADMIN_URL or REG_ADMIN_URL
86
+		//because they're only defined in each of their respective constructors
87
+		//and this might be a frontend request, in which case they aren't available
88
+		$this->events_admin_url = admin_url('admin.php?page=espresso_events');
89
+		$this->reg_admin_url = admin_url('admin.php?page=espresso_registrations');
90
+		// now let's add all of the menu items
91
+		$this->addTopLevelMenu();
92
+		$this->addEventsSubMenu();
93
+		$this->addEventsAddEditHeader();
94
+		$this->addEventsAddNew();
95
+		$this->addEventsEditCurrentEvent();
96
+		$this->addEventsViewHeader();
97
+		$this->addEventsViewAll();
98
+		$this->addEventsViewToday();
99
+		$this->addEventsViewThisMonth();
100
+		$this->addRegistrationSubMenu();
101
+		$this->addRegistrationOverviewToday();
102
+		$this->addRegistrationOverviewTodayApproved();
103
+		$this->addRegistrationOverviewTodayPendingPayment();
104
+		$this->addRegistrationOverviewTodayNotApproved();
105
+		$this->addRegistrationOverviewTodayCancelled();
106
+		$this->addRegistrationOverviewThisMonth();
107
+		$this->addRegistrationOverviewThisMonthApproved();
108
+		$this->addRegistrationOverviewThisMonthPending();
109
+		$this->addRegistrationOverviewThisMonthNotApproved();
110
+		$this->addRegistrationOverviewThisMonthCancelled();
111
+		$this->addExtensionsAndServices();
112
+	}
113
+
114
+
115
+
116
+	/**
117
+	 * @return void
118
+	 */
119
+	private function enqueueAssets()
120
+	{
121
+		wp_register_style(
122
+			'espresso-admin-toolbar',
123
+			EE_GLOBAL_ASSETS_URL . 'css/espresso-admin-toolbar.css',
124
+			array('dashicons'),
125
+			EVENT_ESPRESSO_VERSION
126
+		);
127
+		wp_enqueue_style('espresso-admin-toolbar');
128
+	}
129
+
130
+
131
+
132
+	/**
133
+	 * @return void
134
+	 */
135
+	private function addTopLevelMenu()
136
+	{
137
+		$this->admin_bar->add_menu(
138
+			array(
139
+				'id'    => 'espresso-toolbar',
140
+				'title' => '<span class="ee-icon ee-icon-ee-cup-thick ee-icon-size-20"></span><span class="ab-label">'
141
+					. esc_html_x('Event Espresso', 'admin bar menu group label', 'event_espresso')
142
+					. '</span>',
143
+				'href'  => $this->events_admin_url,
144
+				'meta'  => array(
145
+					'title' => esc_html__('Event Espresso', 'event_espresso'),
146
+					'class' => $this->menu_class . 'first',
147
+				),
148
+			)
149
+		);
150
+	}
151
+
152
+
153
+
154
+	/**
155
+	 * @return void
156
+	 */
157
+	private function addEventsSubMenu()
158
+	{
159
+		if (
160
+			$this->capabilities->current_user_can(
161
+				'ee_read_events',
162
+				'ee_admin_bar_menu_espresso-toolbar-events'
163
+			)
164
+		) {
165
+			$this->admin_bar->add_menu(
166
+				array(
167
+					'id'     => 'espresso-toolbar-events',
168
+					'parent' => 'espresso-toolbar',
169
+					'title'  => '<span class="ee-toolbar-icon"></span>'
170
+								. esc_html__('Events', 'event_espresso'),
171
+					'href'   => $this->events_admin_url,
172
+					'meta'   => array(
173
+						'title'  => esc_html__('Events', 'event_espresso'),
174
+						'target' => '',
175
+						'class'  => $this->menu_class,
176
+					),
177
+				)
178
+			);
179
+		}
180
+	}
181
+
182
+
183
+
184
+	/**
185
+	 * @return void
186
+	 */
187
+	private function addEventsAddEditHeader()
188
+	{
189
+		if (
190
+		$this->capabilities->current_user_can(
191
+			'ee_read_events',
192
+			'ee_admin_bar_menu_espresso-toolbar-events-view'
193
+		)
194
+		) {
195
+			$this->admin_bar->add_menu(
196
+				array(
197
+					'id'     => 'espresso-toolbar-events-add-edit',
198
+					'parent' => 'espresso-toolbar-events',
199
+					'title'  => esc_html__('Add / Edit', 'event_espresso'),
200
+					'href'   => '',
201
+				)
202
+			);
203
+		}
204
+	}
205
+
206
+
207
+
208
+	/**
209
+	 * @return void
210
+	 */
211
+	private function addEventsAddNew()
212
+	{
213
+		if (
214
+			$this->capabilities->current_user_can(
215
+				'ee_edit_events',
216
+				'ee_admin_bar_menu_espresso-toolbar-events-new'
217
+			)
218
+		) {
219
+			$this->admin_bar->add_menu(
220
+				array(
221
+					'id'     => 'espresso-toolbar-events-new',
222
+					'parent' => 'espresso-toolbar-events',
223
+					'title'  => '<span class="ee-toolbar-icon"></span>'
224
+								. esc_html__('Add New', 'event_espresso'),
225
+					'href'   => EEH_URL::add_query_args_and_nonce(
226
+						array('action' => 'create_new'),
227
+						$this->events_admin_url
228
+					),
229
+					'meta'   => array(
230
+						'title'  => esc_html__('Add New', 'event_espresso'),
231
+						'target' => '',
232
+						'class'  => $this->menu_class,
233
+					),
234
+				)
235
+			);
236
+		}
237
+	}
238
+
239
+
240
+
241
+	/**
242
+	 * @return void
243
+	 */
244
+	private function addEventsEditCurrentEvent()
245
+	{
246
+		if (is_single() && (get_post_type() === 'espresso_events')) {
247
+			//Current post
248
+			global $post;
249
+			if (
250
+				$this->capabilities->current_user_can(
251
+					'ee_edit_event',
252
+					'ee_admin_bar_menu_espresso-toolbar-events-edit', $post->ID
253
+				)
254
+			) {
255
+				$this->admin_bar->add_menu(
256
+					array(
257
+						'id'     => 'espresso-toolbar-events-edit',
258
+						'parent' => 'espresso-toolbar-events',
259
+						'title'  => '<span class="ee-toolbar-icon"></span>'
260
+									. esc_html__('Edit Event', 'event_espresso'),
261
+						'href'   => EEH_URL::add_query_args_and_nonce(
262
+							array(
263
+								'action' => 'edit',
264
+								'post' => $post->ID
265
+							),
266
+							$this->events_admin_url
267
+						),
268
+						'meta'   => array(
269
+							'title'  => esc_html__('Edit Event', 'event_espresso'),
270
+							'target' => '',
271
+							'class'  => $this->menu_class,
272
+						),
273
+					)
274
+				);
275
+			}
276
+		}
277
+	}
278
+
279
+
280
+
281
+	/**
282
+	 * @return void
283
+	 */
284
+	private function addEventsViewHeader()
285
+	{
286
+		if (
287
+			$this->capabilities->current_user_can(
288
+				'ee_read_events',
289
+				'ee_admin_bar_menu_espresso-toolbar-events-view'
290
+			)
291
+		) {
292
+			$this->admin_bar->add_menu(
293
+				array(
294
+					'id'     => 'espresso-toolbar-events-view',
295
+					'parent' => 'espresso-toolbar-events',
296
+					'title'  => esc_html__('View', 'event_espresso'),
297
+					'href'   => '',
298
+				)
299
+			);
300
+		}
301
+	}
302
+
303
+
304
+
305
+	/**
306
+	 * @return void
307
+	 */
308
+	private function addEventsViewAll()
309
+	{
310
+		if (
311
+			$this->capabilities->current_user_can(
312
+				'ee_read_events',
313
+				'ee_admin_bar_menu_espresso-toolbar-events-all'
314
+			)
315
+		) {
316
+			$this->admin_bar->add_menu(
317
+				array(
318
+					'id'     => 'espresso-toolbar-events-all',
319
+					'parent' => 'espresso-toolbar-events',
320
+					'title'  => '<span class="ee-toolbar-icon"></span>'
321
+								. esc_html__('All', 'event_espresso'),
322
+					'href'   => $this->events_admin_url,
323
+					'meta'   => array(
324
+						'title'  => esc_html__('All', 'event_espresso'),
325
+						'target' => '',
326
+						'class'  => $this->menu_class,
327
+					),
328
+				)
329
+			);
330
+		}
331
+	}
332
+
333
+
334
+
335
+	/**
336
+	 * @return void
337
+	 */
338
+	private function addEventsViewToday()
339
+	{
340
+		if (
341
+			$this->capabilities->current_user_can(
342
+				'ee_read_events',
343
+				'ee_admin_bar_menu_espresso-toolbar-events-today'
344
+			)
345
+		) {
346
+			$this->admin_bar->add_menu(
347
+				array(
348
+					'id'     => 'espresso-toolbar-events-today',
349
+					'parent' => 'espresso-toolbar-events',
350
+					'title'  => '<span class="ee-toolbar-icon"></span>'
351
+								. esc_html__('Today', 'event_espresso'),
352
+					'href'   => EEH_URL::add_query_args_and_nonce(
353
+						array(
354
+							'action' => 'default',
355
+							'status' => 'today'
356
+						),
357
+						$this->events_admin_url
358
+					),
359
+					'meta'   => array(
360
+						'title'  => esc_html__('Today', 'event_espresso'),
361
+						'target' => '',
362
+						'class'  => $this->menu_class,
363
+					),
364
+				)
365
+			);
366
+		}
367
+	}
368
+
369
+
370
+
371
+	/**
372
+	 * @return void
373
+	 */
374
+	private function addEventsViewThisMonth()
375
+	{
376
+		if (
377
+			$this->capabilities->current_user_can(
378
+				'ee_read_events',
379
+				'ee_admin_bar_menu_espresso-toolbar-events-month'
380
+			)
381
+		) {
382
+			$this->admin_bar->add_menu(
383
+				array(
384
+					'id'     => 'espresso-toolbar-events-month',
385
+					'parent' => 'espresso-toolbar-events',
386
+					'title'  => '<span class="ee-toolbar-icon"></span>'
387
+								. esc_html__('This Month', 'event_espresso'),
388
+					'href'   => EEH_URL::add_query_args_and_nonce(
389
+						array(
390
+							'action' => 'default',
391
+							'status' => 'month'
392
+						),
393
+						$this->events_admin_url
394
+					),
395
+					'meta'   => array(
396
+						'title'  => esc_html__('This Month', 'event_espresso'),
397
+						'target' => '',
398
+						'class'  => $this->menu_class,
399
+					),
400
+				)
401
+			);
402
+		}
403
+	}
404
+
405
+
406
+
407
+	/**
408
+	 * @return void
409
+	 */
410
+	private function addRegistrationSubMenu()
411
+	{
412
+		if (
413
+			$this->capabilities->current_user_can(
414
+				'ee_read_registrations',
415
+				'ee_admin_bar_menu_espresso-toolbar-registrations'
416
+			)
417
+		) {
418
+			$this->admin_bar->add_menu(
419
+				array(
420
+					'id'     => 'espresso-toolbar-registrations',
421
+					'parent' => 'espresso-toolbar',
422
+					'title'  => '<span class="ee-toolbar-icon"></span>'
423
+								. esc_html__('Registrations', 'event_espresso'),
424
+					'href'   => $this->reg_admin_url,
425
+					'meta'   => array(
426
+						'title'  => esc_html__('Registrations', 'event_espresso'),
427
+						'target' => '',
428
+						'class'  => $this->menu_class,
429
+					),
430
+				)
431
+			);
432
+		}
433
+	}
434
+
435
+
436
+
437
+	/**
438
+	 * @return void
439
+	 */
440
+	private function addRegistrationOverviewToday()
441
+	{
442
+		if (
443
+			$this->capabilities->current_user_can(
444
+				'ee_read_registrations',
445
+				'ee_admin_bar_menu_espresso-toolbar-registrations-today'
446
+			)
447
+		) {
448
+			$this->admin_bar->add_menu(
449
+				array(
450
+					'id'     => 'espresso-toolbar-registrations-today',
451
+					'parent' => 'espresso-toolbar-registrations',
452
+					'title'  => esc_html__('Today', 'event_espresso'),
453
+					'href'   => '',
454
+					'meta'   => array(
455
+						'title'  => esc_html__('Today', 'event_espresso'),
456
+						'target' => '',
457
+						'class'  => $this->menu_class,
458
+					),
459
+				)
460
+			);
461
+		}
462
+	}
463
+
464
+
465
+
466
+	/**
467
+	 * @return void
468
+	 */
469
+	private function addRegistrationOverviewTodayApproved()
470
+	{
471
+		if (
472
+			$this->capabilities->current_user_can(
473
+				'ee_read_registrations',
474
+				'ee_admin_bar_menu_espresso-toolbar-registrations-today-approved'
475
+			)
476
+		) {
477
+			$this->admin_bar->add_menu(
478
+				array(
479
+					'id'     => 'espresso-toolbar-registrations-today-approved',
480
+					'parent' => 'espresso-toolbar-registrations',
481
+					'title'  => '<span class="ee-toolbar-icon"></span>'
482
+								. esc_html__('Approved', 'event_espresso'),
483
+					'href'   => EEH_URL::add_query_args_and_nonce(
484
+						array(
485
+							'action'      => 'default',
486
+							'status'      => 'today',
487
+							'_reg_status' => EEM_Registration::status_id_approved,
488
+						),
489
+						$this->reg_admin_url
490
+					),
491
+					'meta'   => array(
492
+						'title'  => esc_html__('Approved', 'event_espresso'),
493
+						'target' => '',
494
+						'class'  => $this->menu_class . ' ee-toolbar-icon-approved',
495
+					),
496
+				)
497
+			);
498
+		}
499
+	}
500
+
501
+
502
+
503
+	/**
504
+	 * @return void
505
+	 */
506
+	private function addRegistrationOverviewTodayPendingPayment()
507
+	{
508
+		if (
509
+			$this->capabilities->current_user_can(
510
+				'ee_read_registrations',
511
+				'ee_admin_bar_menu_espresso-toolbar-registrations-today-pending'
512
+			)
513
+		) {
514
+			$this->admin_bar->add_menu(
515
+				array(
516
+					'id'     => 'espresso-toolbar-registrations-today-pending',
517
+					'parent' => 'espresso-toolbar-registrations',
518
+					'title'  => '<span class="ee-toolbar-icon"></span>'
519
+								. esc_html__('Pending', 'event_espresso'),
520
+					'href'   => EEH_URL::add_query_args_and_nonce(
521
+						array(
522
+							'action'     => 'default',
523
+							'status'     => 'today',
524
+							'_reg_status' => EEM_Registration::status_id_pending_payment,
525
+						),
526
+						$this->reg_admin_url
527
+					),
528
+					'meta'   => array(
529
+						'title'  => esc_html__('Pending Payment', 'event_espresso'),
530
+						'target' => '',
531
+						'class'  => $this->menu_class . ' ee-toolbar-icon-pending',
532
+					),
533
+				)
534
+			);
535
+		}
536
+	}
537
+
538
+
539
+
540
+	/**
541
+	 * @return void
542
+	 */
543
+	private function addRegistrationOverviewTodayNotApproved()
544
+	{
545
+		if (
546
+			$this->capabilities->current_user_can(
547
+				'ee_read_registrations',
548
+				'ee_admin_bar_menu_espresso-toolbar-registrations-today-not-approved'
549
+			)
550
+		) {
551
+			$this->admin_bar->add_menu(
552
+				array(
553
+					'id'     => 'espresso-toolbar-registrations-today-not-approved',
554
+					'parent' => 'espresso-toolbar-registrations',
555
+					'title'  => '<span class="ee-toolbar-icon"></span>'
556
+								. esc_html__('Not Approved', 'event_espresso'),
557
+					'href'   => EEH_URL::add_query_args_and_nonce(
558
+						array(
559
+							'action'      => 'default',
560
+							'status'      => 'today',
561
+							'_reg_status' => EEM_Registration::status_id_not_approved,
562
+						),
563
+						$this->reg_admin_url
564
+					),
565
+					'meta'   => array(
566
+						'title'  => esc_html__('Not Approved', 'event_espresso'),
567
+						'target' => '',
568
+						'class'  => $this->menu_class . ' ee-toolbar-icon-not-approved',
569
+					),
570
+				)
571
+			);
572
+		}
573
+	}
574
+
575
+
576
+
577
+	/**
578
+	 * @return void
579
+	 */
580
+	private function addRegistrationOverviewTodayCancelled()
581
+	{
582
+		if (
583
+			$this->capabilities->current_user_can(
584
+				'ee_read_registrations',
585
+				'ee_admin_bar_menu_espresso-toolbar-registrations-today-cancelled'
586
+			)
587
+		) {
588
+			$this->admin_bar->add_menu(
589
+				array(
590
+					'id'     => 'espresso-toolbar-registrations-today-cancelled',
591
+					'parent' => 'espresso-toolbar-registrations',
592
+					'title'  => '<span class="ee-toolbar-icon"></span>'
593
+								. esc_html__('Cancelled', 'event_espresso'),
594
+					'href'   => EEH_URL::add_query_args_and_nonce(
595
+						array(
596
+							'action'      => 'default',
597
+							'status'      => 'today',
598
+							'_reg_status' => EEM_Registration::status_id_cancelled,
599
+						),
600
+						$this->reg_admin_url
601
+					),
602
+					'meta'   => array(
603
+						'title'  => esc_html__('Cancelled', 'event_espresso'),
604
+						'target' => '',
605
+						'class'  => $this->menu_class . ' ee-toolbar-icon-cancelled',
606
+					),
607
+				)
608
+			);
609
+		}
610
+	}
611
+
612
+
613
+
614
+	/**
615
+	 * @return void
616
+	 */
617
+	private function addRegistrationOverviewThisMonth()
618
+	{
619
+		if (
620
+			$this->capabilities->current_user_can(
621
+				'ee_read_registrations',
622
+				'ee_admin_bar_menu_espresso-toolbar-registrations-month'
623
+			)
624
+		) {
625
+			$this->admin_bar->add_menu(
626
+				array(
627
+					'id'     => 'espresso-toolbar-registrations-month',
628
+					'parent' => 'espresso-toolbar-registrations',
629
+					'title'  => esc_html__('This Month', 'event_espresso'),
630
+					'href'   => '', //EEH_URL::add_query_args_and_nonce(
631
+					//     array(
632
+					//         'action' => 'default',
633
+					//         'status' => 'month'
634
+					//     ),
635
+					//     $this->reg_admin_url
636
+					// ),
637
+					'meta'   => array(
638
+						'title'  => esc_html__('This Month', 'event_espresso'),
639
+						'target' => '',
640
+						'class'  => $this->menu_class,
641
+					),
642
+				)
643
+			);
644
+		}
645
+	}
646
+
647
+
648
+
649
+	/**
650
+	 * @return void
651
+	 */
652
+	private function addRegistrationOverviewThisMonthApproved()
653
+	{
654
+		if (
655
+			$this->capabilities->current_user_can(
656
+				'ee_read_registrations',
657
+				'ee_admin_bar_menu_espresso-toolbar-registrations-month-approved'
658
+			)
659
+		) {
660
+			$this->admin_bar->add_menu(
661
+				array(
662
+					'id'     => 'espresso-toolbar-registrations-month-approved',
663
+					'parent' => 'espresso-toolbar-registrations',
664
+					'title'  => '<span class="ee-toolbar-icon"></span>'
665
+								. esc_html__('Approved', 'event_espresso'),
666
+					'href'   => EEH_URL::add_query_args_and_nonce(
667
+						array(
668
+							'action'      => 'default',
669
+							'status'      => 'month',
670
+							'_reg_status' => EEM_Registration::status_id_approved,
671
+						),
672
+						$this->reg_admin_url
673
+					),
674
+					'meta'   => array(
675
+						'title'  => esc_html__('Approved', 'event_espresso'),
676
+						'target' => '',
677
+						'class'  => $this->menu_class . ' ee-toolbar-icon-approved',
678
+					),
679
+				)
680
+			);
681
+		}
682
+	}
683
+
684
+
685
+
686
+	/**
687
+	 * @return void
688
+	 */
689
+	private function addRegistrationOverviewThisMonthPending()
690
+	{
691
+		if (
692
+			$this->capabilities->current_user_can(
693
+				'ee_read_registrations',
694
+				'ee_admin_bar_menu_espresso-toolbar-registrations-month-pending'
695
+			)
696
+		) {
697
+			$this->admin_bar->add_menu(
698
+				array(
699
+					'id'     => 'espresso-toolbar-registrations-month-pending',
700
+					'parent' => 'espresso-toolbar-registrations',
701
+					'title'  => '<span class="ee-toolbar-icon"></span>'
702
+								. esc_html__('Pending', 'event_espresso'),
703
+					'href'   => EEH_URL::add_query_args_and_nonce(
704
+						array(
705
+							'action'      => 'default',
706
+							'status'      => 'month',
707
+							'_reg_status' => EEM_Registration::status_id_pending_payment,
708
+						),
709
+						$this->reg_admin_url
710
+					),
711
+					'meta'   => array(
712
+						'title'  => esc_html__('Pending', 'event_espresso'),
713
+						'target' => '',
714
+						'class'  => $this->menu_class . ' ee-toolbar-icon-pending',
715
+					),
716
+				)
717
+			);
718
+		}
719
+	}
720
+
721
+
722
+
723
+	/**
724
+	 * @return void
725
+	 */
726
+	private function addRegistrationOverviewThisMonthNotApproved()
727
+	{
728
+		if (
729
+			$this->capabilities->current_user_can(
730
+				'ee_read_registrations',
731
+				'ee_admin_bar_menu_espresso-toolbar-registrations-month-not-approved'
732
+			)
733
+		) {
734
+			$this->admin_bar->add_menu(
735
+				array(
736
+					'id'     => 'espresso-toolbar-registrations-month-not-approved',
737
+					'parent' => 'espresso-toolbar-registrations',
738
+					'title'  => '<span class="ee-toolbar-icon"></span>'
739
+								. esc_html__('Not Approved', 'event_espresso'),
740
+					'href'   => EEH_URL::add_query_args_and_nonce(
741
+						array(
742
+							'action'      => 'default',
743
+							'status'      => 'month',
744
+							'_reg_status' => EEM_Registration::status_id_not_approved,
745
+						),
746
+						$this->reg_admin_url
747
+					),
748
+					'meta'   => array(
749
+						'title'  => esc_html__('Not Approved', 'event_espresso'),
750
+						'target' => '',
751
+						'class'  => $this->menu_class . ' ee-toolbar-icon-not-approved',
752
+					),
753
+				)
754
+			);
755
+		}
756
+	}
757
+
758
+
759
+
760
+	/**
761
+	 * @return void
762
+	 */
763
+	private function addRegistrationOverviewThisMonthCancelled()
764
+	{
765
+		if (
766
+			$this->capabilities->current_user_can(
767
+				'ee_read_registrations',
768
+				'ee_admin_bar_menu_espresso-toolbar-registrations-month-cancelled'
769
+			)
770
+		) {
771
+			$this->admin_bar->add_menu(
772
+				array(
773
+					'id'     => 'espresso-toolbar-registrations-month-cancelled',
774
+					'parent' => 'espresso-toolbar-registrations',
775
+					'title'  => '<span class="ee-toolbar-icon"></span>'
776
+								. esc_html__('Cancelled', 'event_espresso'),
777
+					'href'   => EEH_URL::add_query_args_and_nonce(
778
+						array(
779
+							'action'      => 'default',
780
+							'status'      => 'month',
781
+							'_reg_status' => EEM_Registration::status_id_cancelled,
782
+						),
783
+						$this->reg_admin_url
784
+					),
785
+					'meta'   => array(
786
+						'title'  => esc_html__('Cancelled', 'event_espresso'),
787
+						'target' => '',
788
+						'class'  => $this->menu_class . ' ee-toolbar-icon-cancelled',
789
+					),
790
+				)
791
+			);
792
+		}
793
+	}
794
+
795
+
796
+
797
+	/**
798
+	 * @return void
799
+	 */
800
+	private function addExtensionsAndServices()
801
+	{
802
+		if (
803
+			$this->capabilities->current_user_can(
804
+				'ee_read_ee',
805
+				'ee_admin_bar_menu_espresso-toolbar-extensions-and-services'
806
+			)
807
+		) {
808
+			$this->admin_bar->add_menu(
809
+				array(
810
+					'id'     => 'espresso-toolbar-extensions-and-services',
811
+					'parent' => 'espresso-toolbar',
812
+					'title'  => '<span class="ee-toolbar-icon"></span>'
813
+								. esc_html__('Extensions & Services', 'event_espresso'),
814
+					'href'   => admin_url('admin.php?page=espresso_packages'),
815
+					'meta'   => array(
816
+						'title'  => esc_html__('Extensions & Services', 'event_espresso'),
817
+						'target' => '',
818
+						'class'  => $this->menu_class,
819
+					),
820
+				)
821
+			);
822
+		}
823
+	}
824 824
 
825 825
 }
Please login to merge, or discard this patch.
core/exceptions/InvalidEntityException.php 2 patches
Indentation   +27 added lines, -27 removed lines patch added patch discarded remove patch
@@ -3,7 +3,7 @@  discard block
 block discarded – undo
3 3
 namespace EventEspresso\core\exceptions;
4 4
 
5 5
 if (! defined('EVENT_ESPRESSO_VERSION')) {
6
-    exit('No direct script access allowed');
6
+	exit('No direct script access allowed');
7 7
 }
8 8
 
9 9
 
@@ -18,32 +18,32 @@  discard block
 block discarded – undo
18 18
 class InvalidEntityException extends \InvalidArgumentException
19 19
 {
20 20
 
21
-    /**
22
-     * InvalidInterfaceException constructor.
23
-     *
24
-     * @param string     $actual   classname of what we got
25
-     * @param string     $expected classname of the entity we wanted
26
-     * @param string     $message
27
-     * @param int        $code
28
-     * @param \Exception $previous
29
-     */
30
-    public function __construct($actual, $expected, $message = '', $code = 0, \Exception $previous = null)
31
-    {
32
-        if (empty($message)) {
33
-            $message = sprintf(
34
-                __(
35
-                    'The supplied entity is an instance of "%1$s", but an instance of "%2$s" was expected. Object: %3$s',
36
-                    'event_espresso'
37
-                ),
38
-                is_object($actual)
39
-                    ? get_class($actual)
40
-                    : gettype($actual),
41
-                $expected,
42
-                var_export($actual, true)
43
-            );
44
-        }
45
-        parent::__construct($message, $code, $previous);
46
-    }
21
+	/**
22
+	 * InvalidInterfaceException constructor.
23
+	 *
24
+	 * @param string     $actual   classname of what we got
25
+	 * @param string     $expected classname of the entity we wanted
26
+	 * @param string     $message
27
+	 * @param int        $code
28
+	 * @param \Exception $previous
29
+	 */
30
+	public function __construct($actual, $expected, $message = '', $code = 0, \Exception $previous = null)
31
+	{
32
+		if (empty($message)) {
33
+			$message = sprintf(
34
+				__(
35
+					'The supplied entity is an instance of "%1$s", but an instance of "%2$s" was expected. Object: %3$s',
36
+					'event_espresso'
37
+				),
38
+				is_object($actual)
39
+					? get_class($actual)
40
+					: gettype($actual),
41
+				$expected,
42
+				var_export($actual, true)
43
+			);
44
+		}
45
+		parent::__construct($message, $code, $previous);
46
+	}
47 47
 
48 48
 }
49 49
 // End of file InvalidEntityException.php
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -2,7 +2,7 @@
 block discarded – undo
2 2
 
3 3
 namespace EventEspresso\core\exceptions;
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
 
Please login to merge, or discard this patch.
core/domain/services/event/EventSpacesCalculator.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -164,7 +164,7 @@
 block discarded – undo
164 164
 
165 165
 
166 166
     /**
167
-     * @param $ticket
167
+     * @param \EE_Base_Class $ticket
168 168
      * @throws DomainException
169 169
      * @throws EE_Error
170 170
      * @throws UnexpectedEntityException
Please login to merge, or discard this patch.
Indentation   +495 added lines, -495 removed lines patch added patch discarded remove patch
@@ -27,501 +27,501 @@
 block discarded – undo
27 27
 class EventSpacesCalculator
28 28
 {
29 29
 
30
-    /**
31
-     * @var EE_Event $event
32
-     */
33
-    private $event;
34
-
35
-    /**
36
-     * @var array $datetime_query_params
37
-     */
38
-    private $datetime_query_params;
39
-
40
-    /**
41
-     * @var EE_Ticket[] $active_tickets
42
-     */
43
-    private $active_tickets = array();
44
-
45
-    /**
46
-     * @var EE_Datetime[] $datetimes
47
-     */
48
-    private $datetimes = array();
49
-
50
-    /**
51
-     * Array of Ticket IDs grouped by Datetime
52
-     *
53
-     * @var array $datetimes
54
-     */
55
-    private $datetime_tickets = array();
56
-
57
-    /**
58
-     * Max spaces for each Datetime (reg limit - previous sold)
59
-     *
60
-     * @var array $datetime_spaces
61
-     */
62
-    private $datetime_spaces = array();
63
-
64
-    /**
65
-     * Array of Datetime IDs grouped by Ticket
66
-     *
67
-     * @var array $ticket_datetimes
68
-     */
69
-    private $ticket_datetimes = array();
70
-
71
-    /**
72
-     * maximum ticket quantities for each ticket (adjusted for reg limit)
73
-     *
74
-     * @var array $ticket_quantities
75
-     */
76
-    private $ticket_quantities = array();
77
-
78
-    /**
79
-     * total quantity of sold and reserved for each ticket
80
-     *
81
-     * @var array $tickets_sold
82
-     */
83
-    private $tickets_sold = array();
84
-
85
-    /**
86
-     * total spaces available across all datetimes
87
-     *
88
-     * @var array $total_spaces
89
-     */
90
-    private $total_spaces = array();
91
-
92
-    /**
93
-     * @var boolean $debug
94
-     */
95
-    private $debug = false;
96
-
97
-
98
-
99
-    /**
100
-     * EventSpacesCalculator constructor.
101
-     *
102
-     * @param EE_Event $event
103
-     * @param array    $datetime_query_params
104
-     * @throws EE_Error
105
-     */
106
-    public function __construct(EE_Event $event, array $datetime_query_params = array())
107
-    {
108
-        $this->event = $event;
109
-        $this->datetime_query_params = $datetime_query_params + array('order_by' => array('DTT_reg_limit' => 'ASC'));
110
-    }
111
-
112
-
113
-
114
-    /**
115
-     * @return EE_Ticket[]
116
-     * @throws EE_Error
117
-     */
118
-    public function getActiveTickets()
119
-    {
120
-        if(empty($this->active_tickets)) {
121
-            $this->active_tickets = $this->event->tickets(
122
-                array(
123
-                    array(
124
-                        'TKT_end_date' => array('>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')),
125
-                        'TKT_deleted'  => false,
126
-                    ),
127
-                    'order_by' => array('TKT_qty' => 'ASC')
128
-                )
129
-            );
130
-        }
131
-        return $this->active_tickets;
132
-    }
133
-
134
-
135
-
136
-    /**
137
-     * @param EE_Ticket[] $active_tickets
138
-     * @throws EE_Error
139
-     * @throws DomainException
140
-     * @throws UnexpectedEntityException
141
-     */
142
-    public function setActiveTickets(array $active_tickets = array())
143
-    {
144
-        if (! empty($active_tickets)){
145
-            foreach ($active_tickets as $active_ticket) {
146
-                $this->validateTicket($active_ticket);
147
-            }
148
-            // sort incoming array by ticket quantity (asc)
149
-            usort(
150
-                $active_tickets,
151
-                function (EE_Ticket $a, EE_Ticket $b) {
152
-                    if ($a->qty() === $b->qty()) {
153
-                        return 0;
154
-                    }
155
-                    return ($a->qty() < $b->qty())
156
-                        ? -1
157
-                        : 1;
158
-                }
159
-            );
160
-        }
161
-        $this->active_tickets = $active_tickets;
162
-    }
163
-
164
-
165
-
166
-    /**
167
-     * @param $ticket
168
-     * @throws DomainException
169
-     * @throws EE_Error
170
-     * @throws UnexpectedEntityException
171
-     */
172
-    private function validateTicket($ticket)
173
-    {
174
-        if (! $ticket instanceof EE_Ticket) {
175
-            throw new DomainException(
176
-                esc_html__(
177
-                    'Invalid Ticket. Only EE_Ticket objects can be used to calculate event space availability.',
178
-                    'event_espresso'
179
-                )
180
-            );
181
-        }
182
-        if ($ticket->get_event_ID() !== $this->event->ID()) {
183
-            throw new DomainException(
184
-                sprintf(
185
-                    esc_html__(
186
-                        'An EE_Ticket for Event %1$d was supplied while calculating event space availability for Event %2$d.',
187
-                        'event_espresso'
188
-                    ),
189
-                    $ticket->get_event_ID(),
190
-                    $this->event->ID()
191
-                )
192
-            );
193
-        }
194
-    }
195
-
196
-
197
-
198
-    /**
199
-     * @return EE_Datetime[]
200
-     */
201
-    public function getDatetimes()
202
-    {
203
-        return $this->datetimes;
204
-    }
205
-
206
-
207
-
208
-    /**
209
-     * @param EE_Datetime $datetime
210
-     * @throws EE_Error
211
-     * @throws DomainException
212
-     */
213
-    public function setDatetime(EE_Datetime $datetime)
214
-    {
215
-        if ($datetime->event()->ID() !== $this->event->ID()) {
216
-            throw new DomainException(
217
-                sprintf(
218
-                    esc_html__(
219
-                        'An EE_Datetime for Event %1$d was supplied while calculating event space availability for Event %2$d.',
220
-                        'event_espresso'
221
-                    ),
222
-                    $datetime->event()->ID(),
223
-                    $this->event->ID()
224
-                )
225
-            );
226
-        }
227
-        $this->datetimes[$datetime->ID()] = $datetime;
228
-    }
229
-
230
-
231
-
232
-    /**
233
-     * calculate spaces remaining based on "saleable" tickets
234
-     *
235
-     * @return float|int
236
-     * @throws EE_Error
237
-     * @throws DomainException
238
-     * @throws UnexpectedEntityException
239
-     */
240
-    public function spacesRemaining()
241
-    {
242
-        $this->initialize();
243
-        return $this->calculate();
244
-    }
245
-
246
-
247
-
248
-    /**
249
-     * calculates total available spaces for an event with no regard for sold tickets
250
-     *
251
-     * @return int|float
252
-     * @throws EE_Error
253
-     * @throws DomainException
254
-     * @throws UnexpectedEntityException
255
-     */
256
-    public function totalSpacesAvailable()
257
-    {
258
-        $this->initialize();
259
-        return $this->calculate(false);
260
-    }
261
-
262
-
263
-
264
-    /**
265
-     * Loops through the active tickets for the event
266
-     * and builds a series of data arrays that will be used for calculating
267
-     * the total maximum available spaces, as well as the spaces remaining.
268
-     * Because ticket quantities affect datetime spaces and vice versa,
269
-     * we need to be constantly updating these data arrays as things change,
270
-     * which is the entire reason for their existence.
271
-     *
272
-     * @throws EE_Error
273
-     * @throws DomainException
274
-     * @throws UnexpectedEntityException
275
-     */
276
-    private function initialize()
277
-    {
278
-        if ($this->debug) {
279
-            echo "\n\n" . __LINE__ . ') ' . strtoupper(__METHOD__) . '()';
280
-        }
281
-        $this->datetime_tickets = array();
282
-        $this->datetime_spaces = array();
283
-        $this->ticket_datetimes = array();
284
-        $this->ticket_quantities = array();
285
-        $this->tickets_sold = array();
286
-        $this->total_spaces = array();
287
-        $active_tickets = $this->getActiveTickets();
288
-        if (! empty($active_tickets)) {
289
-            foreach ($active_tickets as $ticket) {
290
-                $this->validateTicket($ticket);
291
-                // we need to index our data arrays using strings for the purpose of sorting,
292
-                // but we also need them to be unique, so  we'll just prepend a letter T to the ID
293
-                $ticket_identifier = "T{$ticket->ID()}";
294
-                // to start, we'll just consider the raw qty to be the maximum availability for this ticket
295
-                $max_tickets = $ticket->qty();
296
-                // but we'll adjust that after looping over each datetime for the ticket and checking reg limits
297
-                $ticket_datetimes = $ticket->datetimes($this->datetime_query_params);
298
-                foreach ($ticket_datetimes as $datetime) {
299
-                    // save all datetimes
300
-                    $this->setDatetime($datetime);
301
-                    $datetime_identifier = "D{$datetime->ID()}";
302
-                    $reg_limit = $datetime->reg_limit();
303
-                    // ticket quantity can not exceed datetime reg limit
304
-                    $max_tickets = min($max_tickets, $reg_limit);
305
-                    // as described earlier, because we need to be able to constantly adjust numbers for things,
306
-                    // we are going to move all of our data into the following arrays:
307
-                    // datetime spaces initially represents the reg limit for each datetime,
308
-                    // but this will get adjusted as tickets are accounted for
309
-                    $this->datetime_spaces[$datetime_identifier] = $reg_limit;
310
-                    // just an array of ticket IDs grouped by datetime
311
-                    $this->datetime_tickets[$datetime_identifier][] = $ticket_identifier;
312
-                    // and an array of datetime IDs grouped by ticket
313
-                    $this->ticket_datetimes[$ticket_identifier][] = $datetime_identifier;
314
-                }
315
-                // total quantity of sold and reserved for each ticket
316
-                $this->tickets_sold[$ticket_identifier] = $ticket->sold() + $ticket->reserved();
317
-                // and the maximum ticket quantities for each ticket (adjusted for reg limit)
318
-                $this->ticket_quantities[$ticket_identifier] = $max_tickets;
319
-            }
320
-        }
321
-        // sort datetime spaces by reg limit, but maintain our string indexes
322
-        asort($this->datetime_spaces, SORT_NUMERIC);
323
-        // datetime tickets need to be sorted in the SAME order as the above array...
324
-        // so we'll just use array_merge() to take the structure of datetime_spaces
325
-        // but overwrite all of the data with that from datetime_tickets
326
-        $this->datetime_tickets = array_merge(
327
-            $this->datetime_spaces,
328
-            $this->datetime_tickets
329
-        );
330
-        if ($this->debug) {
331
-            \EEH_Debug_Tools::printr($this->datetime_spaces, 'datetime_spaces', __FILE__, __LINE__);
332
-            \EEH_Debug_Tools::printr($this->datetime_tickets, 'datetime_tickets', __FILE__, __LINE__);
333
-            \EEH_Debug_Tools::printr($this->ticket_quantities, 'ticket_quantities', __FILE__, __LINE__);
334
-        }
335
-    }
336
-
337
-
338
-
339
-    /**
340
-     * performs calculations on initialized data
341
-     *
342
-     * @param bool $consider_sold
343
-     * @return int|float
344
-     */
345
-    private function calculate($consider_sold = true)
346
-    {
347
-        if ($this->debug) {
348
-            echo "\n\n" . __LINE__ . ') ' . strtoupper(__METHOD__) . '()';
349
-        }
350
-        foreach ($this->datetime_tickets as $datetime_identifier => $tickets) {
351
-            $this->trackAvailableSpacesForDatetimes($datetime_identifier, $tickets);
352
-        }
353
-        // total spaces available is just the sum of the spaces available for each datetime
354
-        $spaces_remaining = array_sum($this->total_spaces);
355
-        if($consider_sold) {
356
-            // less the sum of all tickets sold for these datetimes
357
-            $spaces_remaining -= array_sum($this->tickets_sold);
358
-        }
359
-        if ($this->debug) {
360
-            \EEH_Debug_Tools::printr($this->total_spaces, '$this->total_spaces', __FILE__, __LINE__);
361
-            \EEH_Debug_Tools::printr($this->tickets_sold, '$this->tickets_sold', __FILE__, __LINE__);
362
-            \EEH_Debug_Tools::printr($spaces_remaining, '$spaces_remaining', __FILE__, __LINE__);
363
-        }
364
-        return $spaces_remaining;
365
-    }
366
-
367
-
368
-
369
-    /**
370
-     * @param string $datetime_identifier
371
-     * @param array  $tickets
372
-     */
373
-    private function trackAvailableSpacesForDatetimes($datetime_identifier, array $tickets)
374
-    {
375
-        // make sure a reg limit is set for the datetime
376
-        $reg_limit = isset($this->datetime_spaces[$datetime_identifier])
377
-            ? $this->datetime_spaces[$datetime_identifier]
378
-            : 0;
379
-        // and bail if it is not
380
-        if (! $reg_limit) {
381
-            if ($this->debug) {
382
-                echo "\n . {$datetime_identifier} AT CAPACITY";
383
-            }
384
-            return;
385
-        }
386
-        if ($this->debug) {
387
-            echo "\n\n{$datetime_identifier}";
388
-            echo "\n . " . 'REG LIMIT: ' . $reg_limit;
389
-        }
390
-        // set default number of available spaces
391
-        $available_spaces = 0;
392
-        $this->total_spaces[$datetime_identifier] = 0;
393
-        foreach ($tickets as $ticket_identifier) {
394
-            $available_spaces = $this->calculateAvailableSpacesForTicket(
395
-                $datetime_identifier,
396
-                $reg_limit,
397
-                $ticket_identifier,
398
-                $available_spaces
399
-            );
400
-        }
401
-        // spaces can't be negative
402
-        $available_spaces = max($available_spaces, 0);
403
-        if ($available_spaces) {
404
-            // track any non-zero values
405
-            $this->total_spaces[$datetime_identifier] += $available_spaces;
406
-            if ($this->debug) {
407
-                echo "\n . spaces: {$available_spaces}";
408
-            }
409
-        } else {
410
-            if ($this->debug) {
411
-                echo "\n . NO TICKETS AVAILABLE FOR DATETIME";
412
-            }
413
-        }
414
-        if ($this->debug) {
415
-            \EEH_Debug_Tools::printr($this->total_spaces[$datetime_identifier], '$spaces_remaining', __FILE__, __LINE__);
416
-            \EEH_Debug_Tools::printr($this->ticket_quantities, '$ticket_quantities', __FILE__, __LINE__);
417
-            \EEH_Debug_Tools::printr($this->datetime_spaces, 'datetime_spaces', __FILE__, __LINE__);
418
-        }
419
-    }
420
-
421
-
422
-
423
-    /**
424
-     * @param string $datetime_identifier
425
-     * @param int    $reg_limit
426
-     * @param string $ticket_identifier
427
-     * @param int    $available_spaces
428
-     * @return int
429
-     */
430
-    private function calculateAvailableSpacesForTicket($datetime_identifier, $reg_limit,$ticket_identifier, $available_spaces)
431
-    {
432
-        if ($this->debug) {
433
-            echo "\n . {$ticket_identifier}";
434
-        }
435
-        // make sure ticket quantity is set
436
-        $ticket_quantity = isset($this->ticket_quantities[$ticket_identifier])
437
-            ? $this->ticket_quantities[$ticket_identifier]
438
-            : 0;
439
-        if ($ticket_quantity) {
440
-            if ($this->debug) {
441
-                echo "\n . . available_spaces ({$available_spaces}) <= reg_limit ({$reg_limit}) = ";
442
-                echo ($available_spaces <= $reg_limit)
443
-                    ? 'true'
444
-                    : 'false';
445
-            }
446
-            // if the datetime is NOT at full capacity yet
447
-            if ($available_spaces <= $reg_limit) {
448
-                // then the maximum ticket quantity we can allocate is the lowest value of either:
449
-                //  the number of remaining spaces for the datetime, which is the limit - spaces already taken
450
-                //  or the maximum ticket quantity
451
-                $ticket_quantity = min(($reg_limit - $available_spaces), $ticket_quantity);
452
-                // adjust the available quantity in our tracking array
453
-                $this->ticket_quantities[$ticket_identifier] -= $ticket_quantity;
454
-                // and increment spaces allocated for this datetime
455
-                $available_spaces += $ticket_quantity;
456
-                if ($this->debug) {
457
-                    echo "\n . . ticket quantity: {$ticket_quantity} ({$ticket_identifier})";
458
-                    echo "\n . . . allocate {$ticket_quantity} tickets ({$ticket_identifier})";
459
-                    if ($available_spaces >= $reg_limit) {
460
-                        echo "\n . {$datetime_identifier} AT CAPACITY";
461
-                    }
462
-                }
463
-                // now adjust all other datetimes that allow access to this ticket
464
-                $this->adjustDatetimes(
465
-                    $datetime_identifier,
466
-                    $available_spaces,
467
-                    $reg_limit,
468
-                    $ticket_identifier,
469
-                    $ticket_quantity
470
-                );
471
-            }
472
-        }
473
-        return $available_spaces;
474
-    }
475
-
476
-
477
-
478
-    /**
479
-     * subtracts ticket amounts from all datetime reg limits
480
-     * that allow access to the ticket specified,
481
-     * because that ticket could be used
482
-     * to attend any of the datetimes it has access to
483
-     *
484
-     * @param string $datetime_identifier
485
-     * @param int    $available_spaces
486
-     * @param int    $reg_limit
487
-     * @param string $ticket_identifier
488
-     * @param int    $ticket_quantity
489
-     */
490
-    private function adjustDatetimes($datetime_identifier, $available_spaces, $reg_limit, $ticket_identifier, $ticket_quantity)
491
-    {
492
-        foreach ($this->datetime_tickets as $datetime_ID => $datetime_tickets) {
493
-            // if the supplied ticket has access to this datetime
494
-            if (in_array($ticket_identifier, $datetime_tickets, true)) {
495
-                // and datetime has spaces available
496
-                if (isset($this->datetime_spaces[$datetime_ID])) {
497
-                    // then decrement the available spaces for the datetime
498
-                    $this->datetime_spaces[$datetime_ID] -= $ticket_quantity;
499
-                    // but don't let quantities go below zero
500
-                    $this->datetime_spaces[$datetime_ID] = max(
501
-                        $this->datetime_spaces[$datetime_ID],
502
-                        0
503
-                    );
504
-                    if ($this->debug) {
505
-                        echo "\n . . . " . $datetime_ID . " capacity reduced by {$ticket_quantity}";
506
-                        echo " because it allows access to {$ticket_identifier}";
507
-                    }
508
-                }
509
-                // if this datetime is at full capacity
510
-                if ($datetime_ID === $datetime_identifier && $available_spaces >= $reg_limit) {
511
-                    // then all of it's tickets are now unavailable
512
-                    foreach ($datetime_tickets as $datetime_ticket) {
513
-                        // so  set any tracked available quantities to zero
514
-                        if (isset($this->ticket_quantities[$datetime_ticket])) {
515
-                            $this->ticket_quantities[$datetime_ticket] = 0;
516
-                        }
517
-                        if ($this->debug) {
518
-                            echo "\n . . . " . $datetime_ticket . ' unavailable: ';
519
-                        }
520
-                    }
521
-                }
522
-            }
523
-        }
524
-    }
30
+	/**
31
+	 * @var EE_Event $event
32
+	 */
33
+	private $event;
34
+
35
+	/**
36
+	 * @var array $datetime_query_params
37
+	 */
38
+	private $datetime_query_params;
39
+
40
+	/**
41
+	 * @var EE_Ticket[] $active_tickets
42
+	 */
43
+	private $active_tickets = array();
44
+
45
+	/**
46
+	 * @var EE_Datetime[] $datetimes
47
+	 */
48
+	private $datetimes = array();
49
+
50
+	/**
51
+	 * Array of Ticket IDs grouped by Datetime
52
+	 *
53
+	 * @var array $datetimes
54
+	 */
55
+	private $datetime_tickets = array();
56
+
57
+	/**
58
+	 * Max spaces for each Datetime (reg limit - previous sold)
59
+	 *
60
+	 * @var array $datetime_spaces
61
+	 */
62
+	private $datetime_spaces = array();
63
+
64
+	/**
65
+	 * Array of Datetime IDs grouped by Ticket
66
+	 *
67
+	 * @var array $ticket_datetimes
68
+	 */
69
+	private $ticket_datetimes = array();
70
+
71
+	/**
72
+	 * maximum ticket quantities for each ticket (adjusted for reg limit)
73
+	 *
74
+	 * @var array $ticket_quantities
75
+	 */
76
+	private $ticket_quantities = array();
77
+
78
+	/**
79
+	 * total quantity of sold and reserved for each ticket
80
+	 *
81
+	 * @var array $tickets_sold
82
+	 */
83
+	private $tickets_sold = array();
84
+
85
+	/**
86
+	 * total spaces available across all datetimes
87
+	 *
88
+	 * @var array $total_spaces
89
+	 */
90
+	private $total_spaces = array();
91
+
92
+	/**
93
+	 * @var boolean $debug
94
+	 */
95
+	private $debug = false;
96
+
97
+
98
+
99
+	/**
100
+	 * EventSpacesCalculator constructor.
101
+	 *
102
+	 * @param EE_Event $event
103
+	 * @param array    $datetime_query_params
104
+	 * @throws EE_Error
105
+	 */
106
+	public function __construct(EE_Event $event, array $datetime_query_params = array())
107
+	{
108
+		$this->event = $event;
109
+		$this->datetime_query_params = $datetime_query_params + array('order_by' => array('DTT_reg_limit' => 'ASC'));
110
+	}
111
+
112
+
113
+
114
+	/**
115
+	 * @return EE_Ticket[]
116
+	 * @throws EE_Error
117
+	 */
118
+	public function getActiveTickets()
119
+	{
120
+		if(empty($this->active_tickets)) {
121
+			$this->active_tickets = $this->event->tickets(
122
+				array(
123
+					array(
124
+						'TKT_end_date' => array('>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')),
125
+						'TKT_deleted'  => false,
126
+					),
127
+					'order_by' => array('TKT_qty' => 'ASC')
128
+				)
129
+			);
130
+		}
131
+		return $this->active_tickets;
132
+	}
133
+
134
+
135
+
136
+	/**
137
+	 * @param EE_Ticket[] $active_tickets
138
+	 * @throws EE_Error
139
+	 * @throws DomainException
140
+	 * @throws UnexpectedEntityException
141
+	 */
142
+	public function setActiveTickets(array $active_tickets = array())
143
+	{
144
+		if (! empty($active_tickets)){
145
+			foreach ($active_tickets as $active_ticket) {
146
+				$this->validateTicket($active_ticket);
147
+			}
148
+			// sort incoming array by ticket quantity (asc)
149
+			usort(
150
+				$active_tickets,
151
+				function (EE_Ticket $a, EE_Ticket $b) {
152
+					if ($a->qty() === $b->qty()) {
153
+						return 0;
154
+					}
155
+					return ($a->qty() < $b->qty())
156
+						? -1
157
+						: 1;
158
+				}
159
+			);
160
+		}
161
+		$this->active_tickets = $active_tickets;
162
+	}
163
+
164
+
165
+
166
+	/**
167
+	 * @param $ticket
168
+	 * @throws DomainException
169
+	 * @throws EE_Error
170
+	 * @throws UnexpectedEntityException
171
+	 */
172
+	private function validateTicket($ticket)
173
+	{
174
+		if (! $ticket instanceof EE_Ticket) {
175
+			throw new DomainException(
176
+				esc_html__(
177
+					'Invalid Ticket. Only EE_Ticket objects can be used to calculate event space availability.',
178
+					'event_espresso'
179
+				)
180
+			);
181
+		}
182
+		if ($ticket->get_event_ID() !== $this->event->ID()) {
183
+			throw new DomainException(
184
+				sprintf(
185
+					esc_html__(
186
+						'An EE_Ticket for Event %1$d was supplied while calculating event space availability for Event %2$d.',
187
+						'event_espresso'
188
+					),
189
+					$ticket->get_event_ID(),
190
+					$this->event->ID()
191
+				)
192
+			);
193
+		}
194
+	}
195
+
196
+
197
+
198
+	/**
199
+	 * @return EE_Datetime[]
200
+	 */
201
+	public function getDatetimes()
202
+	{
203
+		return $this->datetimes;
204
+	}
205
+
206
+
207
+
208
+	/**
209
+	 * @param EE_Datetime $datetime
210
+	 * @throws EE_Error
211
+	 * @throws DomainException
212
+	 */
213
+	public function setDatetime(EE_Datetime $datetime)
214
+	{
215
+		if ($datetime->event()->ID() !== $this->event->ID()) {
216
+			throw new DomainException(
217
+				sprintf(
218
+					esc_html__(
219
+						'An EE_Datetime for Event %1$d was supplied while calculating event space availability for Event %2$d.',
220
+						'event_espresso'
221
+					),
222
+					$datetime->event()->ID(),
223
+					$this->event->ID()
224
+				)
225
+			);
226
+		}
227
+		$this->datetimes[$datetime->ID()] = $datetime;
228
+	}
229
+
230
+
231
+
232
+	/**
233
+	 * calculate spaces remaining based on "saleable" tickets
234
+	 *
235
+	 * @return float|int
236
+	 * @throws EE_Error
237
+	 * @throws DomainException
238
+	 * @throws UnexpectedEntityException
239
+	 */
240
+	public function spacesRemaining()
241
+	{
242
+		$this->initialize();
243
+		return $this->calculate();
244
+	}
245
+
246
+
247
+
248
+	/**
249
+	 * calculates total available spaces for an event with no regard for sold tickets
250
+	 *
251
+	 * @return int|float
252
+	 * @throws EE_Error
253
+	 * @throws DomainException
254
+	 * @throws UnexpectedEntityException
255
+	 */
256
+	public function totalSpacesAvailable()
257
+	{
258
+		$this->initialize();
259
+		return $this->calculate(false);
260
+	}
261
+
262
+
263
+
264
+	/**
265
+	 * Loops through the active tickets for the event
266
+	 * and builds a series of data arrays that will be used for calculating
267
+	 * the total maximum available spaces, as well as the spaces remaining.
268
+	 * Because ticket quantities affect datetime spaces and vice versa,
269
+	 * we need to be constantly updating these data arrays as things change,
270
+	 * which is the entire reason for their existence.
271
+	 *
272
+	 * @throws EE_Error
273
+	 * @throws DomainException
274
+	 * @throws UnexpectedEntityException
275
+	 */
276
+	private function initialize()
277
+	{
278
+		if ($this->debug) {
279
+			echo "\n\n" . __LINE__ . ') ' . strtoupper(__METHOD__) . '()';
280
+		}
281
+		$this->datetime_tickets = array();
282
+		$this->datetime_spaces = array();
283
+		$this->ticket_datetimes = array();
284
+		$this->ticket_quantities = array();
285
+		$this->tickets_sold = array();
286
+		$this->total_spaces = array();
287
+		$active_tickets = $this->getActiveTickets();
288
+		if (! empty($active_tickets)) {
289
+			foreach ($active_tickets as $ticket) {
290
+				$this->validateTicket($ticket);
291
+				// we need to index our data arrays using strings for the purpose of sorting,
292
+				// but we also need them to be unique, so  we'll just prepend a letter T to the ID
293
+				$ticket_identifier = "T{$ticket->ID()}";
294
+				// to start, we'll just consider the raw qty to be the maximum availability for this ticket
295
+				$max_tickets = $ticket->qty();
296
+				// but we'll adjust that after looping over each datetime for the ticket and checking reg limits
297
+				$ticket_datetimes = $ticket->datetimes($this->datetime_query_params);
298
+				foreach ($ticket_datetimes as $datetime) {
299
+					// save all datetimes
300
+					$this->setDatetime($datetime);
301
+					$datetime_identifier = "D{$datetime->ID()}";
302
+					$reg_limit = $datetime->reg_limit();
303
+					// ticket quantity can not exceed datetime reg limit
304
+					$max_tickets = min($max_tickets, $reg_limit);
305
+					// as described earlier, because we need to be able to constantly adjust numbers for things,
306
+					// we are going to move all of our data into the following arrays:
307
+					// datetime spaces initially represents the reg limit for each datetime,
308
+					// but this will get adjusted as tickets are accounted for
309
+					$this->datetime_spaces[$datetime_identifier] = $reg_limit;
310
+					// just an array of ticket IDs grouped by datetime
311
+					$this->datetime_tickets[$datetime_identifier][] = $ticket_identifier;
312
+					// and an array of datetime IDs grouped by ticket
313
+					$this->ticket_datetimes[$ticket_identifier][] = $datetime_identifier;
314
+				}
315
+				// total quantity of sold and reserved for each ticket
316
+				$this->tickets_sold[$ticket_identifier] = $ticket->sold() + $ticket->reserved();
317
+				// and the maximum ticket quantities for each ticket (adjusted for reg limit)
318
+				$this->ticket_quantities[$ticket_identifier] = $max_tickets;
319
+			}
320
+		}
321
+		// sort datetime spaces by reg limit, but maintain our string indexes
322
+		asort($this->datetime_spaces, SORT_NUMERIC);
323
+		// datetime tickets need to be sorted in the SAME order as the above array...
324
+		// so we'll just use array_merge() to take the structure of datetime_spaces
325
+		// but overwrite all of the data with that from datetime_tickets
326
+		$this->datetime_tickets = array_merge(
327
+			$this->datetime_spaces,
328
+			$this->datetime_tickets
329
+		);
330
+		if ($this->debug) {
331
+			\EEH_Debug_Tools::printr($this->datetime_spaces, 'datetime_spaces', __FILE__, __LINE__);
332
+			\EEH_Debug_Tools::printr($this->datetime_tickets, 'datetime_tickets', __FILE__, __LINE__);
333
+			\EEH_Debug_Tools::printr($this->ticket_quantities, 'ticket_quantities', __FILE__, __LINE__);
334
+		}
335
+	}
336
+
337
+
338
+
339
+	/**
340
+	 * performs calculations on initialized data
341
+	 *
342
+	 * @param bool $consider_sold
343
+	 * @return int|float
344
+	 */
345
+	private function calculate($consider_sold = true)
346
+	{
347
+		if ($this->debug) {
348
+			echo "\n\n" . __LINE__ . ') ' . strtoupper(__METHOD__) . '()';
349
+		}
350
+		foreach ($this->datetime_tickets as $datetime_identifier => $tickets) {
351
+			$this->trackAvailableSpacesForDatetimes($datetime_identifier, $tickets);
352
+		}
353
+		// total spaces available is just the sum of the spaces available for each datetime
354
+		$spaces_remaining = array_sum($this->total_spaces);
355
+		if($consider_sold) {
356
+			// less the sum of all tickets sold for these datetimes
357
+			$spaces_remaining -= array_sum($this->tickets_sold);
358
+		}
359
+		if ($this->debug) {
360
+			\EEH_Debug_Tools::printr($this->total_spaces, '$this->total_spaces', __FILE__, __LINE__);
361
+			\EEH_Debug_Tools::printr($this->tickets_sold, '$this->tickets_sold', __FILE__, __LINE__);
362
+			\EEH_Debug_Tools::printr($spaces_remaining, '$spaces_remaining', __FILE__, __LINE__);
363
+		}
364
+		return $spaces_remaining;
365
+	}
366
+
367
+
368
+
369
+	/**
370
+	 * @param string $datetime_identifier
371
+	 * @param array  $tickets
372
+	 */
373
+	private function trackAvailableSpacesForDatetimes($datetime_identifier, array $tickets)
374
+	{
375
+		// make sure a reg limit is set for the datetime
376
+		$reg_limit = isset($this->datetime_spaces[$datetime_identifier])
377
+			? $this->datetime_spaces[$datetime_identifier]
378
+			: 0;
379
+		// and bail if it is not
380
+		if (! $reg_limit) {
381
+			if ($this->debug) {
382
+				echo "\n . {$datetime_identifier} AT CAPACITY";
383
+			}
384
+			return;
385
+		}
386
+		if ($this->debug) {
387
+			echo "\n\n{$datetime_identifier}";
388
+			echo "\n . " . 'REG LIMIT: ' . $reg_limit;
389
+		}
390
+		// set default number of available spaces
391
+		$available_spaces = 0;
392
+		$this->total_spaces[$datetime_identifier] = 0;
393
+		foreach ($tickets as $ticket_identifier) {
394
+			$available_spaces = $this->calculateAvailableSpacesForTicket(
395
+				$datetime_identifier,
396
+				$reg_limit,
397
+				$ticket_identifier,
398
+				$available_spaces
399
+			);
400
+		}
401
+		// spaces can't be negative
402
+		$available_spaces = max($available_spaces, 0);
403
+		if ($available_spaces) {
404
+			// track any non-zero values
405
+			$this->total_spaces[$datetime_identifier] += $available_spaces;
406
+			if ($this->debug) {
407
+				echo "\n . spaces: {$available_spaces}";
408
+			}
409
+		} else {
410
+			if ($this->debug) {
411
+				echo "\n . NO TICKETS AVAILABLE FOR DATETIME";
412
+			}
413
+		}
414
+		if ($this->debug) {
415
+			\EEH_Debug_Tools::printr($this->total_spaces[$datetime_identifier], '$spaces_remaining', __FILE__, __LINE__);
416
+			\EEH_Debug_Tools::printr($this->ticket_quantities, '$ticket_quantities', __FILE__, __LINE__);
417
+			\EEH_Debug_Tools::printr($this->datetime_spaces, 'datetime_spaces', __FILE__, __LINE__);
418
+		}
419
+	}
420
+
421
+
422
+
423
+	/**
424
+	 * @param string $datetime_identifier
425
+	 * @param int    $reg_limit
426
+	 * @param string $ticket_identifier
427
+	 * @param int    $available_spaces
428
+	 * @return int
429
+	 */
430
+	private function calculateAvailableSpacesForTicket($datetime_identifier, $reg_limit,$ticket_identifier, $available_spaces)
431
+	{
432
+		if ($this->debug) {
433
+			echo "\n . {$ticket_identifier}";
434
+		}
435
+		// make sure ticket quantity is set
436
+		$ticket_quantity = isset($this->ticket_quantities[$ticket_identifier])
437
+			? $this->ticket_quantities[$ticket_identifier]
438
+			: 0;
439
+		if ($ticket_quantity) {
440
+			if ($this->debug) {
441
+				echo "\n . . available_spaces ({$available_spaces}) <= reg_limit ({$reg_limit}) = ";
442
+				echo ($available_spaces <= $reg_limit)
443
+					? 'true'
444
+					: 'false';
445
+			}
446
+			// if the datetime is NOT at full capacity yet
447
+			if ($available_spaces <= $reg_limit) {
448
+				// then the maximum ticket quantity we can allocate is the lowest value of either:
449
+				//  the number of remaining spaces for the datetime, which is the limit - spaces already taken
450
+				//  or the maximum ticket quantity
451
+				$ticket_quantity = min(($reg_limit - $available_spaces), $ticket_quantity);
452
+				// adjust the available quantity in our tracking array
453
+				$this->ticket_quantities[$ticket_identifier] -= $ticket_quantity;
454
+				// and increment spaces allocated for this datetime
455
+				$available_spaces += $ticket_quantity;
456
+				if ($this->debug) {
457
+					echo "\n . . ticket quantity: {$ticket_quantity} ({$ticket_identifier})";
458
+					echo "\n . . . allocate {$ticket_quantity} tickets ({$ticket_identifier})";
459
+					if ($available_spaces >= $reg_limit) {
460
+						echo "\n . {$datetime_identifier} AT CAPACITY";
461
+					}
462
+				}
463
+				// now adjust all other datetimes that allow access to this ticket
464
+				$this->adjustDatetimes(
465
+					$datetime_identifier,
466
+					$available_spaces,
467
+					$reg_limit,
468
+					$ticket_identifier,
469
+					$ticket_quantity
470
+				);
471
+			}
472
+		}
473
+		return $available_spaces;
474
+	}
475
+
476
+
477
+
478
+	/**
479
+	 * subtracts ticket amounts from all datetime reg limits
480
+	 * that allow access to the ticket specified,
481
+	 * because that ticket could be used
482
+	 * to attend any of the datetimes it has access to
483
+	 *
484
+	 * @param string $datetime_identifier
485
+	 * @param int    $available_spaces
486
+	 * @param int    $reg_limit
487
+	 * @param string $ticket_identifier
488
+	 * @param int    $ticket_quantity
489
+	 */
490
+	private function adjustDatetimes($datetime_identifier, $available_spaces, $reg_limit, $ticket_identifier, $ticket_quantity)
491
+	{
492
+		foreach ($this->datetime_tickets as $datetime_ID => $datetime_tickets) {
493
+			// if the supplied ticket has access to this datetime
494
+			if (in_array($ticket_identifier, $datetime_tickets, true)) {
495
+				// and datetime has spaces available
496
+				if (isset($this->datetime_spaces[$datetime_ID])) {
497
+					// then decrement the available spaces for the datetime
498
+					$this->datetime_spaces[$datetime_ID] -= $ticket_quantity;
499
+					// but don't let quantities go below zero
500
+					$this->datetime_spaces[$datetime_ID] = max(
501
+						$this->datetime_spaces[$datetime_ID],
502
+						0
503
+					);
504
+					if ($this->debug) {
505
+						echo "\n . . . " . $datetime_ID . " capacity reduced by {$ticket_quantity}";
506
+						echo " because it allows access to {$ticket_identifier}";
507
+					}
508
+				}
509
+				// if this datetime is at full capacity
510
+				if ($datetime_ID === $datetime_identifier && $available_spaces >= $reg_limit) {
511
+					// then all of it's tickets are now unavailable
512
+					foreach ($datetime_tickets as $datetime_ticket) {
513
+						// so  set any tracked available quantities to zero
514
+						if (isset($this->ticket_quantities[$datetime_ticket])) {
515
+							$this->ticket_quantities[$datetime_ticket] = 0;
516
+						}
517
+						if ($this->debug) {
518
+							echo "\n . . . " . $datetime_ticket . ' unavailable: ';
519
+						}
520
+					}
521
+				}
522
+			}
523
+		}
524
+	}
525 525
 
526 526
 }
527 527
 // Location: EventSpacesCalculator.php
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -117,7 +117,7 @@  discard block
 block discarded – undo
117 117
      */
118 118
     public function getActiveTickets()
119 119
     {
120
-        if(empty($this->active_tickets)) {
120
+        if (empty($this->active_tickets)) {
121 121
             $this->active_tickets = $this->event->tickets(
122 122
                 array(
123 123
                     array(
@@ -141,14 +141,14 @@  discard block
 block discarded – undo
141 141
      */
142 142
     public function setActiveTickets(array $active_tickets = array())
143 143
     {
144
-        if (! empty($active_tickets)){
144
+        if ( ! empty($active_tickets)) {
145 145
             foreach ($active_tickets as $active_ticket) {
146 146
                 $this->validateTicket($active_ticket);
147 147
             }
148 148
             // sort incoming array by ticket quantity (asc)
149 149
             usort(
150 150
                 $active_tickets,
151
-                function (EE_Ticket $a, EE_Ticket $b) {
151
+                function(EE_Ticket $a, EE_Ticket $b) {
152 152
                     if ($a->qty() === $b->qty()) {
153 153
                         return 0;
154 154
                     }
@@ -171,7 +171,7 @@  discard block
 block discarded – undo
171 171
      */
172 172
     private function validateTicket($ticket)
173 173
     {
174
-        if (! $ticket instanceof EE_Ticket) {
174
+        if ( ! $ticket instanceof EE_Ticket) {
175 175
             throw new DomainException(
176 176
                 esc_html__(
177 177
                     'Invalid Ticket. Only EE_Ticket objects can be used to calculate event space availability.',
@@ -276,7 +276,7 @@  discard block
 block discarded – undo
276 276
     private function initialize()
277 277
     {
278 278
         if ($this->debug) {
279
-            echo "\n\n" . __LINE__ . ') ' . strtoupper(__METHOD__) . '()';
279
+            echo "\n\n".__LINE__.') '.strtoupper(__METHOD__).'()';
280 280
         }
281 281
         $this->datetime_tickets = array();
282 282
         $this->datetime_spaces = array();
@@ -285,7 +285,7 @@  discard block
 block discarded – undo
285 285
         $this->tickets_sold = array();
286 286
         $this->total_spaces = array();
287 287
         $active_tickets = $this->getActiveTickets();
288
-        if (! empty($active_tickets)) {
288
+        if ( ! empty($active_tickets)) {
289 289
             foreach ($active_tickets as $ticket) {
290 290
                 $this->validateTicket($ticket);
291 291
                 // we need to index our data arrays using strings for the purpose of sorting,
@@ -345,14 +345,14 @@  discard block
 block discarded – undo
345 345
     private function calculate($consider_sold = true)
346 346
     {
347 347
         if ($this->debug) {
348
-            echo "\n\n" . __LINE__ . ') ' . strtoupper(__METHOD__) . '()';
348
+            echo "\n\n".__LINE__.') '.strtoupper(__METHOD__).'()';
349 349
         }
350 350
         foreach ($this->datetime_tickets as $datetime_identifier => $tickets) {
351 351
             $this->trackAvailableSpacesForDatetimes($datetime_identifier, $tickets);
352 352
         }
353 353
         // total spaces available is just the sum of the spaces available for each datetime
354 354
         $spaces_remaining = array_sum($this->total_spaces);
355
-        if($consider_sold) {
355
+        if ($consider_sold) {
356 356
             // less the sum of all tickets sold for these datetimes
357 357
             $spaces_remaining -= array_sum($this->tickets_sold);
358 358
         }
@@ -377,7 +377,7 @@  discard block
 block discarded – undo
377 377
             ? $this->datetime_spaces[$datetime_identifier]
378 378
             : 0;
379 379
         // and bail if it is not
380
-        if (! $reg_limit) {
380
+        if ( ! $reg_limit) {
381 381
             if ($this->debug) {
382 382
                 echo "\n . {$datetime_identifier} AT CAPACITY";
383 383
             }
@@ -385,7 +385,7 @@  discard block
 block discarded – undo
385 385
         }
386 386
         if ($this->debug) {
387 387
             echo "\n\n{$datetime_identifier}";
388
-            echo "\n . " . 'REG LIMIT: ' . $reg_limit;
388
+            echo "\n . ".'REG LIMIT: '.$reg_limit;
389 389
         }
390 390
         // set default number of available spaces
391 391
         $available_spaces = 0;
@@ -427,7 +427,7 @@  discard block
 block discarded – undo
427 427
      * @param int    $available_spaces
428 428
      * @return int
429 429
      */
430
-    private function calculateAvailableSpacesForTicket($datetime_identifier, $reg_limit,$ticket_identifier, $available_spaces)
430
+    private function calculateAvailableSpacesForTicket($datetime_identifier, $reg_limit, $ticket_identifier, $available_spaces)
431 431
     {
432 432
         if ($this->debug) {
433 433
             echo "\n . {$ticket_identifier}";
@@ -502,7 +502,7 @@  discard block
 block discarded – undo
502 502
                         0
503 503
                     );
504 504
                     if ($this->debug) {
505
-                        echo "\n . . . " . $datetime_ID . " capacity reduced by {$ticket_quantity}";
505
+                        echo "\n . . . ".$datetime_ID." capacity reduced by {$ticket_quantity}";
506 506
                         echo " because it allows access to {$ticket_identifier}";
507 507
                     }
508 508
                 }
@@ -515,7 +515,7 @@  discard block
 block discarded – undo
515 515
                             $this->ticket_quantities[$datetime_ticket] = 0;
516 516
                         }
517 517
                         if ($this->debug) {
518
-                            echo "\n . . . " . $datetime_ticket . ' unavailable: ';
518
+                            echo "\n . . . ".$datetime_ticket.' unavailable: ';
519 519
                         }
520 520
                     }
521 521
                 }
Please login to merge, or discard this patch.
core/db_classes/EE_Event.class.php 2 patches
Indentation   +1285 added lines, -1285 removed lines patch added patch discarded remove patch
@@ -4,7 +4,7 @@  discard block
 block discarded – undo
4 4
 use EventEspresso\core\exceptions\UnexpectedEntityException;
5 5
 
6 6
 if (!defined('EVENT_ESPRESSO_VERSION')) {
7
-    exit('No direct script access allowed');
7
+	exit('No direct script access allowed');
8 8
 }
9 9
 
10 10
 
@@ -18,1289 +18,1289 @@  discard block
 block discarded – undo
18 18
 class EE_Event extends EE_CPT_Base implements EEI_Line_Item_Object, EEI_Admin_Links, EEI_Has_Icon, EEI_Event
19 19
 {
20 20
 
21
-    /**
22
-     * cached value for the the logical active status for the event
23
-     *
24
-     * @see get_active_status()
25
-     * @var string
26
-     */
27
-    protected $_active_status = '';
28
-
29
-    /**
30
-     * This is just used for caching the Primary Datetime for the Event on initial retrieval
31
-     *
32
-     * @var EE_Datetime
33
-     */
34
-    protected $_Primary_Datetime;
35
-
36
-    /**
37
-     * @var EventSpacesCalculator $available_spaces_calculator
38
-     */
39
-    protected $available_spaces_calculator;
40
-
41
-
42
-    /**
43
-     * @param array $props_n_values incoming values
44
-     * @param string $timezone incoming timezone (if not set the timezone set for the website will be
45
-     *                                        used.)
46
-     * @param array $date_formats incoming date_formats in an array where the first value is the
47
-     *                                        date_format and the second value is the time format
48
-     * @return EE_Event
49
-     * @throws EE_Error
50
-     */
51
-    public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
52
-    {
53
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
54
-        return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
55
-    }
56
-
57
-
58
-    /**
59
-     * @param array $props_n_values incoming values from the database
60
-     * @param string $timezone incoming timezone as set by the model.  If not set the timezone for
61
-     *                                the website will be used.
62
-     * @return EE_Event
63
-     * @throws EE_Error
64
-     */
65
-    public static function new_instance_from_db($props_n_values = array(), $timezone = null)
66
-    {
67
-        return new self($props_n_values, true, $timezone);
68
-    }
69
-
70
-
71
-
72
-    /**
73
-     * @return EventSpacesCalculator
74
-     * @throws \EE_Error
75
-     */
76
-    public function getAvailableSpacesCalculator()
77
-    {
78
-        if(! $this->available_spaces_calculator instanceof EventSpacesCalculator){
79
-            $this->available_spaces_calculator = new EventSpacesCalculator($this);
80
-        }
81
-        return $this->available_spaces_calculator;
82
-    }
83
-
84
-
85
-
86
-    /**
87
-     * Overrides parent set() method so that all calls to set( 'status', $status ) can be routed to internal methods
88
-     *
89
-     * @param string $field_name
90
-     * @param mixed $field_value
91
-     * @param bool $use_default
92
-     * @throws EE_Error
93
-     */
94
-    public function set($field_name, $field_value, $use_default = false)
95
-    {
96
-        switch ($field_name) {
97
-            case 'status' :
98
-                $this->set_status($field_value, $use_default);
99
-                break;
100
-            default :
101
-                parent::set($field_name, $field_value, $use_default);
102
-        }
103
-    }
104
-
105
-
106
-    /**
107
-     *    set_status
108
-     * Checks if event status is being changed to SOLD OUT
109
-     * and updates event meta data with previous event status
110
-     * so that we can revert things if/when the event is no longer sold out
111
-     *
112
-     * @access public
113
-     * @param string $new_status
114
-     * @param bool $use_default
115
-     * @return void
116
-     * @throws EE_Error
117
-     */
118
-    public function set_status($new_status = null, $use_default = false)
119
-    {
120
-        // if nothing is set, and we aren't explicitly wanting to reset the status, then just leave
121
-        if (empty($new_status) && !$use_default) {
122
-            return;
123
-        }
124
-        // get current Event status
125
-        $old_status = $this->status();
126
-        // if status has changed
127
-        if ($old_status !== $new_status) {
128
-            // TO sold_out
129
-            if ($new_status === EEM_Event::sold_out) {
130
-                // save the previous event status so that we can revert if the event is no longer sold out
131
-                $this->add_post_meta('_previous_event_status', $old_status);
132
-                do_action('AHEE__EE_Event__set_status__to_sold_out', $this, $old_status, $new_status);
133
-                // OR FROM  sold_out
134
-            } else if ($old_status === EEM_Event::sold_out) {
135
-                $this->delete_post_meta('_previous_event_status');
136
-                do_action('AHEE__EE_Event__set_status__from_sold_out', $this, $old_status, $new_status);
137
-            }
138
-            // update status
139
-            parent::set('status', $new_status, $use_default);
140
-            do_action('AHEE__EE_Event__set_status__after_update', $this);
141
-            return;
142
-        }
143
-        // even though the old value matches the new value, it's still good to
144
-        // allow the parent set method to have a say
145
-        parent::set('status', $new_status, $use_default);
146
-    }
147
-
148
-
149
-    /**
150
-     * Gets all the datetimes for this event
151
-     *
152
-     * @param array $query_params like EEM_Base::get_all
153
-     * @return EE_Base_Class[]|EE_Datetime[]
154
-     * @throws EE_Error
155
-     */
156
-    public function datetimes($query_params = array())
157
-    {
158
-        return $this->get_many_related('Datetime', $query_params);
159
-    }
160
-
161
-
162
-    /**
163
-     * Gets all the datetimes for this event, ordered by DTT_EVT_start in ascending order
164
-     *
165
-     * @return EE_Base_Class[]|EE_Datetime[]
166
-     * @throws EE_Error
167
-     */
168
-    public function datetimes_in_chronological_order()
169
-    {
170
-        return $this->get_many_related('Datetime', array('order_by' => array('DTT_EVT_start' => 'ASC')));
171
-    }
172
-
173
-
174
-    /**
175
-     * Gets all the datetimes for this event, ordered by the DTT_order on the datetime.
176
-     * @darren, we should probably UNSET timezone on the EEM_Datetime model
177
-     * after running our query, so that this timezone isn't set for EVERY query
178
-     * on EEM_Datetime for the rest of the request, no?
179
-     *
180
-     * @param boolean $show_expired whether or not to include expired events
181
-     * @param boolean $show_deleted whether or not to include deleted events
182
-     * @param null $limit
183
-     * @return EE_Datetime[]
184
-     * @throws EE_Error
185
-     */
186
-    public function datetimes_ordered($show_expired = true, $show_deleted = false, $limit = null)
187
-    {
188
-        return EEM_Datetime::instance($this->_timezone)->get_datetimes_for_event_ordered_by_DTT_order(
189
-            $this->ID(),
190
-            $show_expired,
191
-            $show_deleted,
192
-            $limit
193
-        );
194
-    }
195
-
196
-
197
-    /**
198
-     * Returns one related datetime. Mostly only used by some legacy code.
199
-     *
200
-     * @return EE_Base_Class|EE_Datetime
201
-     * @throws EE_Error
202
-     */
203
-    public function first_datetime()
204
-    {
205
-        return $this->get_first_related('Datetime');
206
-    }
207
-
208
-
209
-    /**
210
-     * Returns the 'primary' datetime for the event
211
-     *
212
-     * @param bool $try_to_exclude_expired
213
-     * @param bool $try_to_exclude_deleted
214
-     * @return EE_Datetime
215
-     * @throws EE_Error
216
-     */
217
-    public function primary_datetime($try_to_exclude_expired = true, $try_to_exclude_deleted = true)
218
-    {
219
-        if (!empty ($this->_Primary_Datetime)) {
220
-            return $this->_Primary_Datetime;
221
-        }
222
-        $this->_Primary_Datetime = EEM_Datetime::instance($this->_timezone)->get_primary_datetime_for_event(
223
-            $this->ID(),
224
-            $try_to_exclude_expired,
225
-            $try_to_exclude_deleted
226
-        );
227
-        return $this->_Primary_Datetime;
228
-    }
229
-
230
-
231
-    /**
232
-     * Gets all the tickets available for purchase of this event
233
-     *
234
-     * @param array $query_params like EEM_Base::get_all
235
-     * @return EE_Base_Class[]|EE_Ticket[]
236
-     * @throws EE_Error
237
-     */
238
-    public function tickets($query_params = array())
239
-    {
240
-        //first get all datetimes
241
-        $datetimes = $this->datetimes_ordered();
242
-        if (!$datetimes) {
243
-            return array();
244
-        }
245
-        $datetime_ids = array();
246
-        foreach ($datetimes as $datetime) {
247
-            $datetime_ids[] = $datetime->ID();
248
-        }
249
-        $where_params = array('Datetime.DTT_ID' => array('IN', $datetime_ids));
250
-        //if incoming $query_params has where conditions let's merge but not override existing.
251
-        if (is_array($query_params) && isset($query_params[0])) {
252
-            $where_params = array_merge($query_params[0], $where_params);
253
-            unset($query_params[0]);
254
-        }
255
-        //now add $where_params to $query_params
256
-        $query_params[0] = $where_params;
257
-        return EEM_Ticket::instance()->get_all($query_params);
258
-    }
259
-
260
-
261
-    /**
262
-     * get all unexpired untrashed tickets
263
-     *
264
-     * @return EE_Ticket[]
265
-     * @throws EE_Error
266
-     */
267
-    public function active_tickets()
268
-    {
269
-        return $this->tickets(array(
270
-            array(
271
-                'TKT_end_date' => array('>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')),
272
-                'TKT_deleted' => false,
273
-            ),
274
-        ));
275
-    }
276
-
277
-
278
-    /**
279
-     * @return bool
280
-     * @throws EE_Error
281
-     */
282
-    public function additional_limit()
283
-    {
284
-        return $this->get('EVT_additional_limit');
285
-    }
286
-
287
-
288
-    /**
289
-     * @return bool
290
-     * @throws EE_Error
291
-     */
292
-    public function allow_overflow()
293
-    {
294
-        return $this->get('EVT_allow_overflow');
295
-    }
296
-
297
-
298
-    /**
299
-     * @return bool
300
-     * @throws EE_Error
301
-     */
302
-    public function created()
303
-    {
304
-        return $this->get('EVT_created');
305
-    }
306
-
307
-
308
-    /**
309
-     * @return bool
310
-     * @throws EE_Error
311
-     */
312
-    public function description()
313
-    {
314
-        return $this->get('EVT_desc');
315
-    }
316
-
317
-
318
-    /**
319
-     * Runs do_shortcode and wpautop on the description
320
-     *
321
-     * @return string of html
322
-     * @throws EE_Error
323
-     */
324
-    public function description_filtered()
325
-    {
326
-        return $this->get_pretty('EVT_desc');
327
-    }
328
-
329
-
330
-    /**
331
-     * @return bool
332
-     * @throws EE_Error
333
-     */
334
-    public function display_description()
335
-    {
336
-        return $this->get('EVT_display_desc');
337
-    }
338
-
339
-
340
-    /**
341
-     * @return bool
342
-     * @throws EE_Error
343
-     */
344
-    public function display_ticket_selector()
345
-    {
346
-        return (bool)$this->get('EVT_display_ticket_selector');
347
-    }
348
-
349
-
350
-    /**
351
-     * @return bool
352
-     * @throws EE_Error
353
-     */
354
-    public function external_url()
355
-    {
356
-        return $this->get('EVT_external_URL');
357
-    }
358
-
359
-
360
-    /**
361
-     * @return bool
362
-     * @throws EE_Error
363
-     */
364
-    public function member_only()
365
-    {
366
-        return $this->get('EVT_member_only');
367
-    }
368
-
369
-
370
-    /**
371
-     * @return bool
372
-     * @throws EE_Error
373
-     */
374
-    public function phone()
375
-    {
376
-        return $this->get('EVT_phone');
377
-    }
378
-
379
-
380
-    /**
381
-     * @return bool
382
-     * @throws EE_Error
383
-     */
384
-    public function modified()
385
-    {
386
-        return $this->get('EVT_modified');
387
-    }
388
-
389
-
390
-    /**
391
-     * @return bool
392
-     * @throws EE_Error
393
-     */
394
-    public function name()
395
-    {
396
-        return $this->get('EVT_name');
397
-    }
398
-
399
-
400
-    /**
401
-     * @return bool
402
-     * @throws EE_Error
403
-     */
404
-    public function order()
405
-    {
406
-        return $this->get('EVT_order');
407
-    }
408
-
409
-
410
-    /**
411
-     * @return bool|string
412
-     * @throws EE_Error
413
-     */
414
-    public function default_registration_status()
415
-    {
416
-        $event_default_registration_status = $this->get('EVT_default_registration_status');
417
-        return !empty($event_default_registration_status)
418
-            ? $event_default_registration_status
419
-            : EE_Registry::instance()->CFG->registration->default_STS_ID;
420
-    }
421
-
422
-
423
-    /**
424
-     * @param int $num_words
425
-     * @param null $more
426
-     * @param bool $not_full_desc
427
-     * @return bool|string
428
-     * @throws EE_Error
429
-     */
430
-    public function short_description($num_words = 55, $more = null, $not_full_desc = false)
431
-    {
432
-        $short_desc = $this->get('EVT_short_desc');
433
-        if (!empty($short_desc) || $not_full_desc) {
434
-            return $short_desc;
435
-        }
436
-        $full_desc = $this->get('EVT_desc');
437
-        return wp_trim_words($full_desc, $num_words, $more);
438
-    }
439
-
440
-
441
-    /**
442
-     * @return bool
443
-     * @throws EE_Error
444
-     */
445
-    public function slug()
446
-    {
447
-        return $this->get('EVT_slug');
448
-    }
449
-
450
-
451
-    /**
452
-     * @return bool
453
-     * @throws EE_Error
454
-     */
455
-    public function timezone_string()
456
-    {
457
-        return $this->get('EVT_timezone_string');
458
-    }
459
-
460
-
461
-    /**
462
-     * @return bool
463
-     * @throws EE_Error
464
-     */
465
-    public function visible_on()
466
-    {
467
-        return $this->get('EVT_visible_on');
468
-    }
469
-
470
-
471
-    /**
472
-     * @return int
473
-     * @throws EE_Error
474
-     */
475
-    public function wp_user()
476
-    {
477
-        return $this->get('EVT_wp_user');
478
-    }
479
-
480
-
481
-    /**
482
-     * @return bool
483
-     * @throws EE_Error
484
-     */
485
-    public function donations()
486
-    {
487
-        return $this->get('EVT_donations');
488
-    }
489
-
490
-
491
-    /**
492
-     * @param $limit
493
-     * @throws EE_Error
494
-     */
495
-    public function set_additional_limit($limit)
496
-    {
497
-        $this->set('EVT_additional_limit', $limit);
498
-    }
499
-
500
-
501
-    /**
502
-     * @param $created
503
-     * @throws EE_Error
504
-     */
505
-    public function set_created($created)
506
-    {
507
-        $this->set('EVT_created', $created);
508
-    }
509
-
510
-
511
-    /**
512
-     * @param $desc
513
-     * @throws EE_Error
514
-     */
515
-    public function set_description($desc)
516
-    {
517
-        $this->set('EVT_desc', $desc);
518
-    }
519
-
520
-
521
-    /**
522
-     * @param $display_desc
523
-     * @throws EE_Error
524
-     */
525
-    public function set_display_description($display_desc)
526
-    {
527
-        $this->set('EVT_display_desc', $display_desc);
528
-    }
529
-
530
-
531
-    /**
532
-     * @param $display_ticket_selector
533
-     * @throws EE_Error
534
-     */
535
-    public function set_display_ticket_selector($display_ticket_selector)
536
-    {
537
-        $this->set('EVT_display_ticket_selector', $display_ticket_selector);
538
-    }
539
-
540
-
541
-    /**
542
-     * @param $external_url
543
-     * @throws EE_Error
544
-     */
545
-    public function set_external_url($external_url)
546
-    {
547
-        $this->set('EVT_external_URL', $external_url);
548
-    }
549
-
550
-
551
-    /**
552
-     * @param $member_only
553
-     * @throws EE_Error
554
-     */
555
-    public function set_member_only($member_only)
556
-    {
557
-        $this->set('EVT_member_only', $member_only);
558
-    }
559
-
560
-
561
-    /**
562
-     * @param $event_phone
563
-     * @throws EE_Error
564
-     */
565
-    public function set_event_phone($event_phone)
566
-    {
567
-        $this->set('EVT_phone', $event_phone);
568
-    }
569
-
570
-
571
-    /**
572
-     * @param $modified
573
-     * @throws EE_Error
574
-     */
575
-    public function set_modified($modified)
576
-    {
577
-        $this->set('EVT_modified', $modified);
578
-    }
579
-
580
-
581
-    /**
582
-     * @param $name
583
-     * @throws EE_Error
584
-     */
585
-    public function set_name($name)
586
-    {
587
-        $this->set('EVT_name', $name);
588
-    }
589
-
590
-
591
-    /**
592
-     * @param $order
593
-     * @throws EE_Error
594
-     */
595
-    public function set_order($order)
596
-    {
597
-        $this->set('EVT_order', $order);
598
-    }
599
-
600
-
601
-    /**
602
-     * @param $short_desc
603
-     * @throws EE_Error
604
-     */
605
-    public function set_short_description($short_desc)
606
-    {
607
-        $this->set('EVT_short_desc', $short_desc);
608
-    }
609
-
610
-
611
-    /**
612
-     * @param $slug
613
-     * @throws EE_Error
614
-     */
615
-    public function set_slug($slug)
616
-    {
617
-        $this->set('EVT_slug', $slug);
618
-    }
619
-
620
-
621
-    /**
622
-     * @param $timezone_string
623
-     * @throws EE_Error
624
-     */
625
-    public function set_timezone_string($timezone_string)
626
-    {
627
-        $this->set('EVT_timezone_string', $timezone_string);
628
-    }
629
-
630
-
631
-    /**
632
-     * @param $visible_on
633
-     * @throws EE_Error
634
-     */
635
-    public function set_visible_on($visible_on)
636
-    {
637
-        $this->set('EVT_visible_on', $visible_on);
638
-    }
639
-
640
-
641
-    /**
642
-     * @param $wp_user
643
-     * @throws EE_Error
644
-     */
645
-    public function set_wp_user($wp_user)
646
-    {
647
-        $this->set('EVT_wp_user', $wp_user);
648
-    }
649
-
650
-
651
-    /**
652
-     * @param $default_registration_status
653
-     * @throws EE_Error
654
-     */
655
-    public function set_default_registration_status($default_registration_status)
656
-    {
657
-        $this->set('EVT_default_registration_status', $default_registration_status);
658
-    }
659
-
660
-
661
-    /**
662
-     * @param $donations
663
-     * @throws EE_Error
664
-     */
665
-    public function set_donations($donations)
666
-    {
667
-        $this->set('EVT_donations', $donations);
668
-    }
669
-
670
-
671
-    /**
672
-     * Adds a venue to this event
673
-     *
674
-     * @param EE_Venue /int $venue_id_or_obj
675
-     * @return EE_Base_Class|EE_Venue
676
-     * @throws EE_Error
677
-     */
678
-    public function add_venue($venue_id_or_obj)
679
-    {
680
-        return $this->_add_relation_to($venue_id_or_obj, 'Venue');
681
-    }
682
-
683
-
684
-    /**
685
-     * Removes a venue from the event
686
-     *
687
-     * @param EE_Venue /int $venue_id_or_obj
688
-     * @return EE_Base_Class|EE_Venue
689
-     * @throws EE_Error
690
-     */
691
-    public function remove_venue($venue_id_or_obj)
692
-    {
693
-        return $this->_remove_relation_to($venue_id_or_obj, 'Venue');
694
-    }
695
-
696
-
697
-    /**
698
-     * Gets all the venues related ot the event. May provide additional $query_params if desired
699
-     *
700
-     * @param array $query_params like EEM_Base::get_all's $query_params
701
-     * @return EE_Base_Class[]|EE_Venue[]
702
-     * @throws EE_Error
703
-     */
704
-    public function venues($query_params = array())
705
-    {
706
-        return $this->get_many_related('Venue', $query_params);
707
-    }
708
-
709
-
710
-    /**
711
-     * check if event id is present and if event is published
712
-     *
713
-     * @access public
714
-     * @return boolean true yes, false no
715
-     * @throws EE_Error
716
-     */
717
-    private function _has_ID_and_is_published()
718
-    {
719
-        // first check if event id is present and not NULL,
720
-        // then check if this event is published (or any of the equivalent "published" statuses)
721
-        return
722
-            $this->ID() && $this->ID() !== null
723
-            && (
724
-                $this->status() === 'publish'
725
-                || $this->status() === EEM_Event::sold_out
726
-                || $this->status() === EEM_Event::postponed
727
-                || $this->status() === EEM_Event::cancelled
728
-            );
729
-    }
730
-
731
-
732
-    /**
733
-     * This simply compares the internal dates with NOW and determines if the event is upcoming or not.
734
-     *
735
-     * @access public
736
-     * @return boolean true yes, false no
737
-     * @throws EE_Error
738
-     */
739
-    public function is_upcoming()
740
-    {
741
-        // check if event id is present and if this event is published
742
-        if ($this->is_inactive()) {
743
-            return false;
744
-        }
745
-        // set initial value
746
-        $upcoming = false;
747
-        //next let's get all datetimes and loop through them
748
-        $datetimes = $this->datetimes_in_chronological_order();
749
-        foreach ($datetimes as $datetime) {
750
-            if ($datetime instanceof EE_Datetime) {
751
-                //if this dtt is expired then we continue cause one of the other datetimes might be upcoming.
752
-                if ($datetime->is_expired()) {
753
-                    continue;
754
-                }
755
-                //if this dtt is active then we return false.
756
-                if ($datetime->is_active()) {
757
-                    return false;
758
-                }
759
-                //otherwise let's check upcoming status
760
-                $upcoming = $datetime->is_upcoming();
761
-            }
762
-        }
763
-        return $upcoming;
764
-    }
765
-
766
-
767
-    /**
768
-     * @return bool
769
-     * @throws EE_Error
770
-     */
771
-    public function is_active()
772
-    {
773
-        // check if event id is present and if this event is published
774
-        if ($this->is_inactive()) {
775
-            return false;
776
-        }
777
-        // set initial value
778
-        $active = false;
779
-        //next let's get all datetimes and loop through them
780
-        $datetimes = $this->datetimes_in_chronological_order();
781
-        foreach ($datetimes as $datetime) {
782
-            if ($datetime instanceof EE_Datetime) {
783
-                //if this dtt is expired then we continue cause one of the other datetimes might be active.
784
-                if ($datetime->is_expired()) {
785
-                    continue;
786
-                }
787
-                //if this dtt is upcoming then we return false.
788
-                if ($datetime->is_upcoming()) {
789
-                    return false;
790
-                }
791
-                //otherwise let's check active status
792
-                $active = $datetime->is_active();
793
-            }
794
-        }
795
-        return $active;
796
-    }
797
-
798
-
799
-    /**
800
-     * @return bool
801
-     * @throws EE_Error
802
-     */
803
-    public function is_expired()
804
-    {
805
-        // check if event id is present and if this event is published
806
-        if ($this->is_inactive()) {
807
-            return false;
808
-        }
809
-        // set initial value
810
-        $expired = false;
811
-        //first let's get all datetimes and loop through them
812
-        $datetimes = $this->datetimes_in_chronological_order();
813
-        foreach ($datetimes as $datetime) {
814
-            if ($datetime instanceof EE_Datetime) {
815
-                //if this dtt is upcoming or active then we return false.
816
-                if ($datetime->is_upcoming() || $datetime->is_active()) {
817
-                    return false;
818
-                }
819
-                //otherwise let's check active status
820
-                $expired = $datetime->is_expired();
821
-            }
822
-        }
823
-        return $expired;
824
-    }
825
-
826
-
827
-    /**
828
-     * @return bool
829
-     * @throws EE_Error
830
-     */
831
-    public function is_inactive()
832
-    {
833
-        // check if event id is present and if this event is published
834
-        if ($this->_has_ID_and_is_published()) {
835
-            return false;
836
-        }
837
-        return true;
838
-    }
839
-
840
-
841
-    /**
842
-     * calculate spaces remaining based on "saleable" tickets
843
-     *
844
-     * @param array $tickets
845
-     * @param bool $filtered
846
-     * @return int|float
847
-     * @throws EE_Error
848
-     * @throws DomainException
849
-     * @throws UnexpectedEntityException
850
-     */
851
-    public function spaces_remaining($tickets = array(), $filtered = true)
852
-    {
853
-        $this->getAvailableSpacesCalculator()->setActiveTickets($tickets);
854
-        $spaces_remaining = $this->getAvailableSpacesCalculator()->spacesRemaining();
855
-        return $filtered
856
-            ? apply_filters(
857
-                'FHEE_EE_Event__spaces_remaining',
858
-                $spaces_remaining,
859
-                $this,
860
-                $tickets
861
-            )
862
-            : $spaces_remaining;
863
-    }
864
-
865
-
866
-    /**
867
-     *    perform_sold_out_status_check
868
-     *    checks all of this events's datetime  reg_limit - sold values to determine if ANY datetimes have spaces available...
869
-     *    if NOT, then the event status will get toggled to 'sold_out'
870
-     *
871
-     * @return bool    return the ACTUAL sold out state.
872
-     * @throws EE_Error
873
-     * @throws DomainException
874
-     * @throws UnexpectedEntityException
875
-     */
876
-    public function perform_sold_out_status_check()
877
-    {
878
-        // get all unexpired untrashed tickets
879
-        $tickets = $this->active_tickets();
880
-        // if all the tickets are just expired, then don't update the event status to sold out
881
-        if (empty($tickets)) {
882
-            return true;
883
-        }
884
-        $spaces_remaining = $this->spaces_remaining($tickets);
885
-        if ($spaces_remaining < 1) {
886
-            $this->set_status(EEM_Event::sold_out);
887
-            $this->save();
888
-            $sold_out = true;
889
-        } else {
890
-            $sold_out = false;
891
-            // was event previously marked as sold out ?
892
-            if ($this->status() === EEM_Event::sold_out) {
893
-                // revert status to previous value, if it was set
894
-                $previous_event_status = $this->get_post_meta('_previous_event_status', true);
895
-                if ($previous_event_status) {
896
-                    $this->set_status($previous_event_status);
897
-                    $this->save();
898
-                }
899
-            }
900
-        }
901
-        do_action('AHEE__EE_Event__perform_sold_out_status_check__end', $this, $sold_out, $spaces_remaining, $tickets);
902
-        return $sold_out;
903
-    }
904
-
905
-
906
-
907
-    /**
908
-     * This returns the total remaining spaces for sale on this event.
909
-     *
910
-     * @uses EE_Event::total_available_spaces()
911
-     * @return float|int
912
-     * @throws EE_Error
913
-     * @throws DomainException
914
-     * @throws UnexpectedEntityException
915
-     */
916
-    public function spaces_remaining_for_sale()
917
-    {
918
-        return $this->total_available_spaces(true);
919
-    }
920
-
921
-
922
-
923
-    /**
924
-     * This returns the total spaces available for an event
925
-     * while considering all the qtys on the tickets and the reg limits
926
-     * on the datetimes attached to this event.
927
-     *
928
-     * @param   bool $consider_sold Whether to consider any tickets that have already sold in our calculation.
929
-     *                              If this is false, then we return the most tickets that could ever be sold
930
-     *                              for this event with the datetime and tickets setup on the event under optimal
931
-     *                              selling conditions.  Otherwise we return a live calculation of spaces available
932
-     *                              based on tickets sold.  Depending on setup and stage of sales, this
933
-     *                              may appear to equal remaining tickets.  However, the more tickets are
934
-     *                              sold out, the more accurate the "live" total is.
935
-     * @return float|int
936
-     * @throws EE_Error
937
-     * @throws DomainException
938
-     * @throws UnexpectedEntityException
939
-     */
940
-    public function total_available_spaces($consider_sold = false)
941
-    {
942
-        $spaces_available = $consider_sold
943
-            ? $this->getAvailableSpacesCalculator()->spacesRemaining()
944
-            : $this->getAvailableSpacesCalculator()->totalSpacesAvailable();
945
-        return apply_filters(
946
-            'FHEE_EE_Event__total_available_spaces__spaces_available',
947
-            $spaces_available,
948
-            $this,
949
-            $this->getAvailableSpacesCalculator()->getDatetimes(),
950
-            $this->getAvailableSpacesCalculator()->getActiveTickets()
951
-        );
952
-    }
953
-
954
-
955
-    /**
956
-     * Checks if the event is set to sold out
957
-     *
958
-     * @param  bool $actual whether or not to perform calculations to not only figure the
959
-     *                      actual status but also to flip the status if necessary to sold
960
-     *                      out If false, we just check the existing status of the event
961
-     * @return boolean
962
-     * @throws EE_Error
963
-     */
964
-    public function is_sold_out($actual = false)
965
-    {
966
-        if (!$actual) {
967
-            return $this->status() === EEM_Event::sold_out;
968
-        }
969
-        return $this->perform_sold_out_status_check();
970
-    }
971
-
972
-
973
-    /**
974
-     * Checks if the event is marked as postponed
975
-     *
976
-     * @return boolean
977
-     */
978
-    public function is_postponed()
979
-    {
980
-        return $this->status() === EEM_Event::postponed;
981
-    }
982
-
983
-
984
-    /**
985
-     * Checks if the event is marked as cancelled
986
-     *
987
-     * @return boolean
988
-     */
989
-    public function is_cancelled()
990
-    {
991
-        return $this->status() === EEM_Event::cancelled;
992
-    }
993
-
994
-
995
-    /**
996
-     * Get the logical active status in a hierarchical order for all the datetimes.  Note
997
-     * Basically, we order the datetimes by EVT_start_date.  Then first test on whether the event is published.  If its
998
-     * NOT published then we test for whether its expired or not.  IF it IS published then we test first on whether an
999
-     * event has any active dates.  If no active dates then we check for any upcoming dates.  If no upcoming dates then
1000
-     * the event is considered expired.
1001
-     * NOTE: this method does NOT calculate whether the datetimes are sold out when event is published.  Sold Out is a status
1002
-     * set on the EVENT when it is not published and thus is done
1003
-     *
1004
-     * @param bool $reset
1005
-     * @return bool | string - based on EE_Datetime active constants or FALSE if error.
1006
-     * @throws EE_Error
1007
-     */
1008
-    public function get_active_status($reset = false)
1009
-    {
1010
-        // if the active status has already been set, then just use that value (unless we are resetting it)
1011
-        if (!empty($this->_active_status) && !$reset) {
1012
-            return $this->_active_status;
1013
-        }
1014
-        //first check if event id is present on this object
1015
-        if (!$this->ID()) {
1016
-            return false;
1017
-        }
1018
-        $where_params_for_event = array(array('EVT_ID' => $this->ID()));
1019
-        //if event is published:
1020
-        if ($this->status() === 'publish') {
1021
-            //active?
1022
-            if (EEM_Datetime::instance()->get_datetime_count_for_status(EE_Datetime::active, $where_params_for_event) > 0) {
1023
-                $this->_active_status = EE_Datetime::active;
1024
-            } else {
1025
-                //upcoming?
1026
-                if (EEM_Datetime::instance()->get_datetime_count_for_status(EE_Datetime::upcoming, $where_params_for_event) > 0) {
1027
-                    $this->_active_status = EE_Datetime::upcoming;
1028
-                } else {
1029
-                    //expired?
1030
-                    if (
1031
-                        EEM_Datetime::instance()->get_datetime_count_for_status(EE_Datetime::expired, $where_params_for_event) > 0
1032
-                    ) {
1033
-                        $this->_active_status = EE_Datetime::expired;
1034
-                    } else {
1035
-                        //it would be odd if things make it this far because it basically means there are no datetime's
1036
-                        //attached to the event.  So in this case it will just be considered inactive.
1037
-                        $this->_active_status = EE_Datetime::inactive;
1038
-                    }
1039
-                }
1040
-            }
1041
-        } else {
1042
-            //the event is not published, so let's just set it's active status according to its' post status
1043
-            switch ($this->status()) {
1044
-                case EEM_Event::sold_out :
1045
-                    $this->_active_status = EE_Datetime::sold_out;
1046
-                    break;
1047
-                case EEM_Event::cancelled :
1048
-                    $this->_active_status = EE_Datetime::cancelled;
1049
-                    break;
1050
-                case EEM_Event::postponed :
1051
-                    $this->_active_status = EE_Datetime::postponed;
1052
-                    break;
1053
-                default :
1054
-                    $this->_active_status = EE_Datetime::inactive;
1055
-            }
1056
-        }
1057
-        return $this->_active_status;
1058
-    }
1059
-
1060
-
1061
-    /**
1062
-     *    pretty_active_status
1063
-     *
1064
-     * @access public
1065
-     * @param boolean $echo whether to return (FALSE), or echo out the result (TRUE)
1066
-     * @return mixed void|string
1067
-     * @throws EE_Error
1068
-     */
1069
-    public function pretty_active_status($echo = true)
1070
-    {
1071
-        $active_status = $this->get_active_status();
1072
-        $status = '<span class="ee-status event-active-status-'
1073
-            . $active_status
1074
-            . '">'
1075
-            . EEH_Template::pretty_status($active_status, false, 'sentence')
1076
-            . '</span>';
1077
-        if ($echo) {
1078
-            echo $status;
1079
-            return '';
1080
-        }
1081
-        return $status;
1082
-    }
1083
-
1084
-
1085
-    /**
1086
-     * @return bool|int
1087
-     * @throws EE_Error
1088
-     */
1089
-    public function get_number_of_tickets_sold()
1090
-    {
1091
-        $tkt_sold = 0;
1092
-        if (!$this->ID()) {
1093
-            return 0;
1094
-        }
1095
-        $datetimes = $this->datetimes();
1096
-        foreach ($datetimes as $datetime) {
1097
-            if ($datetime instanceof EE_Datetime) {
1098
-                $tkt_sold += $datetime->sold();
1099
-            }
1100
-        }
1101
-        return $tkt_sold;
1102
-    }
1103
-
1104
-
1105
-    /**
1106
-     * This just returns a count of all the registrations for this event
1107
-     *
1108
-     * @access  public
1109
-     * @return int
1110
-     * @throws EE_Error
1111
-     */
1112
-    public function get_count_of_all_registrations()
1113
-    {
1114
-        return EEM_Event::instance()->count_related($this, 'Registration');
1115
-    }
1116
-
1117
-
1118
-    /**
1119
-     * This returns the ticket with the earliest start time that is
1120
-     * available for this event (across all datetimes attached to the event)
1121
-     *
1122
-     * @return EE_Base_Class|EE_Ticket|null
1123
-     * @throws EE_Error
1124
-     */
1125
-    public function get_ticket_with_earliest_start_time()
1126
-    {
1127
-        $where['Datetime.EVT_ID'] = $this->ID();
1128
-        $query_params = array($where, 'order_by' => array('TKT_start_date' => 'ASC'));
1129
-        return EE_Registry::instance()->load_model('Ticket')->get_one($query_params);
1130
-    }
1131
-
1132
-
1133
-    /**
1134
-     * This returns the ticket with the latest end time that is available
1135
-     * for this event (across all datetimes attached to the event)
1136
-     *
1137
-     * @return EE_Base_Class|EE_Ticket|null
1138
-     * @throws EE_Error
1139
-     */
1140
-    public function get_ticket_with_latest_end_time()
1141
-    {
1142
-        $where['Datetime.EVT_ID'] = $this->ID();
1143
-        $query_params = array($where, 'order_by' => array('TKT_end_date' => 'DESC'));
1144
-        return EE_Registry::instance()->load_model('Ticket')->get_one($query_params);
1145
-    }
1146
-
1147
-
1148
-    /**
1149
-     * This returns whether there are any tickets on sale for this event.
1150
-     *
1151
-     * @return bool true = YES tickets on sale.
1152
-     * @throws EE_Error
1153
-     */
1154
-    public function tickets_on_sale()
1155
-    {
1156
-        $earliest_ticket = $this->get_ticket_with_earliest_start_time();
1157
-        $latest_ticket = $this->get_ticket_with_latest_end_time();
1158
-        if (!$latest_ticket instanceof EE_Ticket && !$earliest_ticket instanceof EE_Ticket) {
1159
-            return false;
1160
-        }
1161
-        //check on sale for these two tickets.
1162
-        if ($latest_ticket->is_on_sale() || $earliest_ticket->is_on_sale()) {
1163
-            return true;
1164
-        }
1165
-        return false;
1166
-    }
1167
-
1168
-
1169
-    /**
1170
-     * Gets the URL for viewing this event on the front-end. Overrides parent
1171
-     * to check for an external URL first
1172
-     *
1173
-     * @return string
1174
-     * @throws EE_Error
1175
-     */
1176
-    public function get_permalink()
1177
-    {
1178
-        if ($this->external_url()) {
1179
-            return $this->external_url();
1180
-        }
1181
-        return parent::get_permalink();
1182
-    }
1183
-
1184
-
1185
-    /**
1186
-     * Gets the first term for 'espresso_event_categories' we can find
1187
-     *
1188
-     * @param array $query_params like EEM_Base::get_all
1189
-     * @return EE_Base_Class|EE_Term|null
1190
-     * @throws EE_Error
1191
-     */
1192
-    public function first_event_category($query_params = array())
1193
-    {
1194
-        $query_params[0]['Term_Taxonomy.taxonomy'] = 'espresso_event_categories';
1195
-        $query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $this->ID();
1196
-        return EEM_Term::instance()->get_one($query_params);
1197
-    }
1198
-
1199
-
1200
-    /**
1201
-     * Gets all terms for 'espresso_event_categories' we can find
1202
-     *
1203
-     * @param array $query_params
1204
-     * @return EE_Base_Class[]|EE_Term[]
1205
-     * @throws EE_Error
1206
-     */
1207
-    public function get_all_event_categories($query_params = array())
1208
-    {
1209
-        $query_params[0]['Term_Taxonomy.taxonomy'] = 'espresso_event_categories';
1210
-        $query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $this->ID();
1211
-        return EEM_Term::instance()->get_all($query_params);
1212
-    }
1213
-
1214
-
1215
-    /**
1216
-     * Gets all the question groups, ordering them by QSG_order ascending
1217
-     *
1218
-     * @param array $query_params @see EEM_Base::get_all
1219
-     * @return EE_Base_Class[]|EE_Question_Group[]
1220
-     * @throws EE_Error
1221
-     */
1222
-    public function question_groups($query_params = array())
1223
-    {
1224
-        $query_params = !empty($query_params) ? $query_params : array('order_by' => array('QSG_order' => 'ASC'));
1225
-        return $this->get_many_related('Question_Group', $query_params);
1226
-    }
1227
-
1228
-
1229
-    /**
1230
-     * Implementation for EEI_Has_Icon interface method.
1231
-     *
1232
-     * @see EEI_Visual_Representation for comments
1233
-     * @return string
1234
-     */
1235
-    public function get_icon()
1236
-    {
1237
-        return '<span class="dashicons dashicons-flag"></span>';
1238
-    }
1239
-
1240
-
1241
-    /**
1242
-     * Implementation for EEI_Admin_Links interface method.
1243
-     *
1244
-     * @see EEI_Admin_Links for comments
1245
-     * @return string
1246
-     * @throws EE_Error
1247
-     */
1248
-    public function get_admin_details_link()
1249
-    {
1250
-        return $this->get_admin_edit_link();
1251
-    }
1252
-
1253
-
1254
-    /**
1255
-     * Implementation for EEI_Admin_Links interface method.
1256
-     *
1257
-     * @see EEI_Admin_Links for comments
1258
-     * @return string
1259
-     * @throws EE_Error
1260
-     */
1261
-    public function get_admin_edit_link()
1262
-    {
1263
-        return EEH_URL::add_query_args_and_nonce(array(
1264
-            'page' => 'espresso_events',
1265
-            'action' => 'edit',
1266
-            'post' => $this->ID(),
1267
-        ),
1268
-            admin_url('admin.php')
1269
-        );
1270
-    }
1271
-
1272
-
1273
-    /**
1274
-     * Implementation for EEI_Admin_Links interface method.
1275
-     *
1276
-     * @see EEI_Admin_Links for comments
1277
-     * @return string
1278
-     */
1279
-    public function get_admin_settings_link()
1280
-    {
1281
-        return EEH_URL::add_query_args_and_nonce(array(
1282
-            'page' => 'espresso_events',
1283
-            'action' => 'default_event_settings',
1284
-        ),
1285
-            admin_url('admin.php')
1286
-        );
1287
-    }
1288
-
1289
-
1290
-    /**
1291
-     * Implementation for EEI_Admin_Links interface method.
1292
-     *
1293
-     * @see EEI_Admin_Links for comments
1294
-     * @return string
1295
-     */
1296
-    public function get_admin_overview_link()
1297
-    {
1298
-        return EEH_URL::add_query_args_and_nonce(array(
1299
-            'page' => 'espresso_events',
1300
-            'action' => 'default',
1301
-        ),
1302
-            admin_url('admin.php')
1303
-        );
1304
-    }
21
+	/**
22
+	 * cached value for the the logical active status for the event
23
+	 *
24
+	 * @see get_active_status()
25
+	 * @var string
26
+	 */
27
+	protected $_active_status = '';
28
+
29
+	/**
30
+	 * This is just used for caching the Primary Datetime for the Event on initial retrieval
31
+	 *
32
+	 * @var EE_Datetime
33
+	 */
34
+	protected $_Primary_Datetime;
35
+
36
+	/**
37
+	 * @var EventSpacesCalculator $available_spaces_calculator
38
+	 */
39
+	protected $available_spaces_calculator;
40
+
41
+
42
+	/**
43
+	 * @param array $props_n_values incoming values
44
+	 * @param string $timezone incoming timezone (if not set the timezone set for the website will be
45
+	 *                                        used.)
46
+	 * @param array $date_formats incoming date_formats in an array where the first value is the
47
+	 *                                        date_format and the second value is the time format
48
+	 * @return EE_Event
49
+	 * @throws EE_Error
50
+	 */
51
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
52
+	{
53
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
54
+		return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
55
+	}
56
+
57
+
58
+	/**
59
+	 * @param array $props_n_values incoming values from the database
60
+	 * @param string $timezone incoming timezone as set by the model.  If not set the timezone for
61
+	 *                                the website will be used.
62
+	 * @return EE_Event
63
+	 * @throws EE_Error
64
+	 */
65
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null)
66
+	{
67
+		return new self($props_n_values, true, $timezone);
68
+	}
69
+
70
+
71
+
72
+	/**
73
+	 * @return EventSpacesCalculator
74
+	 * @throws \EE_Error
75
+	 */
76
+	public function getAvailableSpacesCalculator()
77
+	{
78
+		if(! $this->available_spaces_calculator instanceof EventSpacesCalculator){
79
+			$this->available_spaces_calculator = new EventSpacesCalculator($this);
80
+		}
81
+		return $this->available_spaces_calculator;
82
+	}
83
+
84
+
85
+
86
+	/**
87
+	 * Overrides parent set() method so that all calls to set( 'status', $status ) can be routed to internal methods
88
+	 *
89
+	 * @param string $field_name
90
+	 * @param mixed $field_value
91
+	 * @param bool $use_default
92
+	 * @throws EE_Error
93
+	 */
94
+	public function set($field_name, $field_value, $use_default = false)
95
+	{
96
+		switch ($field_name) {
97
+			case 'status' :
98
+				$this->set_status($field_value, $use_default);
99
+				break;
100
+			default :
101
+				parent::set($field_name, $field_value, $use_default);
102
+		}
103
+	}
104
+
105
+
106
+	/**
107
+	 *    set_status
108
+	 * Checks if event status is being changed to SOLD OUT
109
+	 * and updates event meta data with previous event status
110
+	 * so that we can revert things if/when the event is no longer sold out
111
+	 *
112
+	 * @access public
113
+	 * @param string $new_status
114
+	 * @param bool $use_default
115
+	 * @return void
116
+	 * @throws EE_Error
117
+	 */
118
+	public function set_status($new_status = null, $use_default = false)
119
+	{
120
+		// if nothing is set, and we aren't explicitly wanting to reset the status, then just leave
121
+		if (empty($new_status) && !$use_default) {
122
+			return;
123
+		}
124
+		// get current Event status
125
+		$old_status = $this->status();
126
+		// if status has changed
127
+		if ($old_status !== $new_status) {
128
+			// TO sold_out
129
+			if ($new_status === EEM_Event::sold_out) {
130
+				// save the previous event status so that we can revert if the event is no longer sold out
131
+				$this->add_post_meta('_previous_event_status', $old_status);
132
+				do_action('AHEE__EE_Event__set_status__to_sold_out', $this, $old_status, $new_status);
133
+				// OR FROM  sold_out
134
+			} else if ($old_status === EEM_Event::sold_out) {
135
+				$this->delete_post_meta('_previous_event_status');
136
+				do_action('AHEE__EE_Event__set_status__from_sold_out', $this, $old_status, $new_status);
137
+			}
138
+			// update status
139
+			parent::set('status', $new_status, $use_default);
140
+			do_action('AHEE__EE_Event__set_status__after_update', $this);
141
+			return;
142
+		}
143
+		// even though the old value matches the new value, it's still good to
144
+		// allow the parent set method to have a say
145
+		parent::set('status', $new_status, $use_default);
146
+	}
147
+
148
+
149
+	/**
150
+	 * Gets all the datetimes for this event
151
+	 *
152
+	 * @param array $query_params like EEM_Base::get_all
153
+	 * @return EE_Base_Class[]|EE_Datetime[]
154
+	 * @throws EE_Error
155
+	 */
156
+	public function datetimes($query_params = array())
157
+	{
158
+		return $this->get_many_related('Datetime', $query_params);
159
+	}
160
+
161
+
162
+	/**
163
+	 * Gets all the datetimes for this event, ordered by DTT_EVT_start in ascending order
164
+	 *
165
+	 * @return EE_Base_Class[]|EE_Datetime[]
166
+	 * @throws EE_Error
167
+	 */
168
+	public function datetimes_in_chronological_order()
169
+	{
170
+		return $this->get_many_related('Datetime', array('order_by' => array('DTT_EVT_start' => 'ASC')));
171
+	}
172
+
173
+
174
+	/**
175
+	 * Gets all the datetimes for this event, ordered by the DTT_order on the datetime.
176
+	 * @darren, we should probably UNSET timezone on the EEM_Datetime model
177
+	 * after running our query, so that this timezone isn't set for EVERY query
178
+	 * on EEM_Datetime for the rest of the request, no?
179
+	 *
180
+	 * @param boolean $show_expired whether or not to include expired events
181
+	 * @param boolean $show_deleted whether or not to include deleted events
182
+	 * @param null $limit
183
+	 * @return EE_Datetime[]
184
+	 * @throws EE_Error
185
+	 */
186
+	public function datetimes_ordered($show_expired = true, $show_deleted = false, $limit = null)
187
+	{
188
+		return EEM_Datetime::instance($this->_timezone)->get_datetimes_for_event_ordered_by_DTT_order(
189
+			$this->ID(),
190
+			$show_expired,
191
+			$show_deleted,
192
+			$limit
193
+		);
194
+	}
195
+
196
+
197
+	/**
198
+	 * Returns one related datetime. Mostly only used by some legacy code.
199
+	 *
200
+	 * @return EE_Base_Class|EE_Datetime
201
+	 * @throws EE_Error
202
+	 */
203
+	public function first_datetime()
204
+	{
205
+		return $this->get_first_related('Datetime');
206
+	}
207
+
208
+
209
+	/**
210
+	 * Returns the 'primary' datetime for the event
211
+	 *
212
+	 * @param bool $try_to_exclude_expired
213
+	 * @param bool $try_to_exclude_deleted
214
+	 * @return EE_Datetime
215
+	 * @throws EE_Error
216
+	 */
217
+	public function primary_datetime($try_to_exclude_expired = true, $try_to_exclude_deleted = true)
218
+	{
219
+		if (!empty ($this->_Primary_Datetime)) {
220
+			return $this->_Primary_Datetime;
221
+		}
222
+		$this->_Primary_Datetime = EEM_Datetime::instance($this->_timezone)->get_primary_datetime_for_event(
223
+			$this->ID(),
224
+			$try_to_exclude_expired,
225
+			$try_to_exclude_deleted
226
+		);
227
+		return $this->_Primary_Datetime;
228
+	}
229
+
230
+
231
+	/**
232
+	 * Gets all the tickets available for purchase of this event
233
+	 *
234
+	 * @param array $query_params like EEM_Base::get_all
235
+	 * @return EE_Base_Class[]|EE_Ticket[]
236
+	 * @throws EE_Error
237
+	 */
238
+	public function tickets($query_params = array())
239
+	{
240
+		//first get all datetimes
241
+		$datetimes = $this->datetimes_ordered();
242
+		if (!$datetimes) {
243
+			return array();
244
+		}
245
+		$datetime_ids = array();
246
+		foreach ($datetimes as $datetime) {
247
+			$datetime_ids[] = $datetime->ID();
248
+		}
249
+		$where_params = array('Datetime.DTT_ID' => array('IN', $datetime_ids));
250
+		//if incoming $query_params has where conditions let's merge but not override existing.
251
+		if (is_array($query_params) && isset($query_params[0])) {
252
+			$where_params = array_merge($query_params[0], $where_params);
253
+			unset($query_params[0]);
254
+		}
255
+		//now add $where_params to $query_params
256
+		$query_params[0] = $where_params;
257
+		return EEM_Ticket::instance()->get_all($query_params);
258
+	}
259
+
260
+
261
+	/**
262
+	 * get all unexpired untrashed tickets
263
+	 *
264
+	 * @return EE_Ticket[]
265
+	 * @throws EE_Error
266
+	 */
267
+	public function active_tickets()
268
+	{
269
+		return $this->tickets(array(
270
+			array(
271
+				'TKT_end_date' => array('>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')),
272
+				'TKT_deleted' => false,
273
+			),
274
+		));
275
+	}
276
+
277
+
278
+	/**
279
+	 * @return bool
280
+	 * @throws EE_Error
281
+	 */
282
+	public function additional_limit()
283
+	{
284
+		return $this->get('EVT_additional_limit');
285
+	}
286
+
287
+
288
+	/**
289
+	 * @return bool
290
+	 * @throws EE_Error
291
+	 */
292
+	public function allow_overflow()
293
+	{
294
+		return $this->get('EVT_allow_overflow');
295
+	}
296
+
297
+
298
+	/**
299
+	 * @return bool
300
+	 * @throws EE_Error
301
+	 */
302
+	public function created()
303
+	{
304
+		return $this->get('EVT_created');
305
+	}
306
+
307
+
308
+	/**
309
+	 * @return bool
310
+	 * @throws EE_Error
311
+	 */
312
+	public function description()
313
+	{
314
+		return $this->get('EVT_desc');
315
+	}
316
+
317
+
318
+	/**
319
+	 * Runs do_shortcode and wpautop on the description
320
+	 *
321
+	 * @return string of html
322
+	 * @throws EE_Error
323
+	 */
324
+	public function description_filtered()
325
+	{
326
+		return $this->get_pretty('EVT_desc');
327
+	}
328
+
329
+
330
+	/**
331
+	 * @return bool
332
+	 * @throws EE_Error
333
+	 */
334
+	public function display_description()
335
+	{
336
+		return $this->get('EVT_display_desc');
337
+	}
338
+
339
+
340
+	/**
341
+	 * @return bool
342
+	 * @throws EE_Error
343
+	 */
344
+	public function display_ticket_selector()
345
+	{
346
+		return (bool)$this->get('EVT_display_ticket_selector');
347
+	}
348
+
349
+
350
+	/**
351
+	 * @return bool
352
+	 * @throws EE_Error
353
+	 */
354
+	public function external_url()
355
+	{
356
+		return $this->get('EVT_external_URL');
357
+	}
358
+
359
+
360
+	/**
361
+	 * @return bool
362
+	 * @throws EE_Error
363
+	 */
364
+	public function member_only()
365
+	{
366
+		return $this->get('EVT_member_only');
367
+	}
368
+
369
+
370
+	/**
371
+	 * @return bool
372
+	 * @throws EE_Error
373
+	 */
374
+	public function phone()
375
+	{
376
+		return $this->get('EVT_phone');
377
+	}
378
+
379
+
380
+	/**
381
+	 * @return bool
382
+	 * @throws EE_Error
383
+	 */
384
+	public function modified()
385
+	{
386
+		return $this->get('EVT_modified');
387
+	}
388
+
389
+
390
+	/**
391
+	 * @return bool
392
+	 * @throws EE_Error
393
+	 */
394
+	public function name()
395
+	{
396
+		return $this->get('EVT_name');
397
+	}
398
+
399
+
400
+	/**
401
+	 * @return bool
402
+	 * @throws EE_Error
403
+	 */
404
+	public function order()
405
+	{
406
+		return $this->get('EVT_order');
407
+	}
408
+
409
+
410
+	/**
411
+	 * @return bool|string
412
+	 * @throws EE_Error
413
+	 */
414
+	public function default_registration_status()
415
+	{
416
+		$event_default_registration_status = $this->get('EVT_default_registration_status');
417
+		return !empty($event_default_registration_status)
418
+			? $event_default_registration_status
419
+			: EE_Registry::instance()->CFG->registration->default_STS_ID;
420
+	}
421
+
422
+
423
+	/**
424
+	 * @param int $num_words
425
+	 * @param null $more
426
+	 * @param bool $not_full_desc
427
+	 * @return bool|string
428
+	 * @throws EE_Error
429
+	 */
430
+	public function short_description($num_words = 55, $more = null, $not_full_desc = false)
431
+	{
432
+		$short_desc = $this->get('EVT_short_desc');
433
+		if (!empty($short_desc) || $not_full_desc) {
434
+			return $short_desc;
435
+		}
436
+		$full_desc = $this->get('EVT_desc');
437
+		return wp_trim_words($full_desc, $num_words, $more);
438
+	}
439
+
440
+
441
+	/**
442
+	 * @return bool
443
+	 * @throws EE_Error
444
+	 */
445
+	public function slug()
446
+	{
447
+		return $this->get('EVT_slug');
448
+	}
449
+
450
+
451
+	/**
452
+	 * @return bool
453
+	 * @throws EE_Error
454
+	 */
455
+	public function timezone_string()
456
+	{
457
+		return $this->get('EVT_timezone_string');
458
+	}
459
+
460
+
461
+	/**
462
+	 * @return bool
463
+	 * @throws EE_Error
464
+	 */
465
+	public function visible_on()
466
+	{
467
+		return $this->get('EVT_visible_on');
468
+	}
469
+
470
+
471
+	/**
472
+	 * @return int
473
+	 * @throws EE_Error
474
+	 */
475
+	public function wp_user()
476
+	{
477
+		return $this->get('EVT_wp_user');
478
+	}
479
+
480
+
481
+	/**
482
+	 * @return bool
483
+	 * @throws EE_Error
484
+	 */
485
+	public function donations()
486
+	{
487
+		return $this->get('EVT_donations');
488
+	}
489
+
490
+
491
+	/**
492
+	 * @param $limit
493
+	 * @throws EE_Error
494
+	 */
495
+	public function set_additional_limit($limit)
496
+	{
497
+		$this->set('EVT_additional_limit', $limit);
498
+	}
499
+
500
+
501
+	/**
502
+	 * @param $created
503
+	 * @throws EE_Error
504
+	 */
505
+	public function set_created($created)
506
+	{
507
+		$this->set('EVT_created', $created);
508
+	}
509
+
510
+
511
+	/**
512
+	 * @param $desc
513
+	 * @throws EE_Error
514
+	 */
515
+	public function set_description($desc)
516
+	{
517
+		$this->set('EVT_desc', $desc);
518
+	}
519
+
520
+
521
+	/**
522
+	 * @param $display_desc
523
+	 * @throws EE_Error
524
+	 */
525
+	public function set_display_description($display_desc)
526
+	{
527
+		$this->set('EVT_display_desc', $display_desc);
528
+	}
529
+
530
+
531
+	/**
532
+	 * @param $display_ticket_selector
533
+	 * @throws EE_Error
534
+	 */
535
+	public function set_display_ticket_selector($display_ticket_selector)
536
+	{
537
+		$this->set('EVT_display_ticket_selector', $display_ticket_selector);
538
+	}
539
+
540
+
541
+	/**
542
+	 * @param $external_url
543
+	 * @throws EE_Error
544
+	 */
545
+	public function set_external_url($external_url)
546
+	{
547
+		$this->set('EVT_external_URL', $external_url);
548
+	}
549
+
550
+
551
+	/**
552
+	 * @param $member_only
553
+	 * @throws EE_Error
554
+	 */
555
+	public function set_member_only($member_only)
556
+	{
557
+		$this->set('EVT_member_only', $member_only);
558
+	}
559
+
560
+
561
+	/**
562
+	 * @param $event_phone
563
+	 * @throws EE_Error
564
+	 */
565
+	public function set_event_phone($event_phone)
566
+	{
567
+		$this->set('EVT_phone', $event_phone);
568
+	}
569
+
570
+
571
+	/**
572
+	 * @param $modified
573
+	 * @throws EE_Error
574
+	 */
575
+	public function set_modified($modified)
576
+	{
577
+		$this->set('EVT_modified', $modified);
578
+	}
579
+
580
+
581
+	/**
582
+	 * @param $name
583
+	 * @throws EE_Error
584
+	 */
585
+	public function set_name($name)
586
+	{
587
+		$this->set('EVT_name', $name);
588
+	}
589
+
590
+
591
+	/**
592
+	 * @param $order
593
+	 * @throws EE_Error
594
+	 */
595
+	public function set_order($order)
596
+	{
597
+		$this->set('EVT_order', $order);
598
+	}
599
+
600
+
601
+	/**
602
+	 * @param $short_desc
603
+	 * @throws EE_Error
604
+	 */
605
+	public function set_short_description($short_desc)
606
+	{
607
+		$this->set('EVT_short_desc', $short_desc);
608
+	}
609
+
610
+
611
+	/**
612
+	 * @param $slug
613
+	 * @throws EE_Error
614
+	 */
615
+	public function set_slug($slug)
616
+	{
617
+		$this->set('EVT_slug', $slug);
618
+	}
619
+
620
+
621
+	/**
622
+	 * @param $timezone_string
623
+	 * @throws EE_Error
624
+	 */
625
+	public function set_timezone_string($timezone_string)
626
+	{
627
+		$this->set('EVT_timezone_string', $timezone_string);
628
+	}
629
+
630
+
631
+	/**
632
+	 * @param $visible_on
633
+	 * @throws EE_Error
634
+	 */
635
+	public function set_visible_on($visible_on)
636
+	{
637
+		$this->set('EVT_visible_on', $visible_on);
638
+	}
639
+
640
+
641
+	/**
642
+	 * @param $wp_user
643
+	 * @throws EE_Error
644
+	 */
645
+	public function set_wp_user($wp_user)
646
+	{
647
+		$this->set('EVT_wp_user', $wp_user);
648
+	}
649
+
650
+
651
+	/**
652
+	 * @param $default_registration_status
653
+	 * @throws EE_Error
654
+	 */
655
+	public function set_default_registration_status($default_registration_status)
656
+	{
657
+		$this->set('EVT_default_registration_status', $default_registration_status);
658
+	}
659
+
660
+
661
+	/**
662
+	 * @param $donations
663
+	 * @throws EE_Error
664
+	 */
665
+	public function set_donations($donations)
666
+	{
667
+		$this->set('EVT_donations', $donations);
668
+	}
669
+
670
+
671
+	/**
672
+	 * Adds a venue to this event
673
+	 *
674
+	 * @param EE_Venue /int $venue_id_or_obj
675
+	 * @return EE_Base_Class|EE_Venue
676
+	 * @throws EE_Error
677
+	 */
678
+	public function add_venue($venue_id_or_obj)
679
+	{
680
+		return $this->_add_relation_to($venue_id_or_obj, 'Venue');
681
+	}
682
+
683
+
684
+	/**
685
+	 * Removes a venue from the event
686
+	 *
687
+	 * @param EE_Venue /int $venue_id_or_obj
688
+	 * @return EE_Base_Class|EE_Venue
689
+	 * @throws EE_Error
690
+	 */
691
+	public function remove_venue($venue_id_or_obj)
692
+	{
693
+		return $this->_remove_relation_to($venue_id_or_obj, 'Venue');
694
+	}
695
+
696
+
697
+	/**
698
+	 * Gets all the venues related ot the event. May provide additional $query_params if desired
699
+	 *
700
+	 * @param array $query_params like EEM_Base::get_all's $query_params
701
+	 * @return EE_Base_Class[]|EE_Venue[]
702
+	 * @throws EE_Error
703
+	 */
704
+	public function venues($query_params = array())
705
+	{
706
+		return $this->get_many_related('Venue', $query_params);
707
+	}
708
+
709
+
710
+	/**
711
+	 * check if event id is present and if event is published
712
+	 *
713
+	 * @access public
714
+	 * @return boolean true yes, false no
715
+	 * @throws EE_Error
716
+	 */
717
+	private function _has_ID_and_is_published()
718
+	{
719
+		// first check if event id is present and not NULL,
720
+		// then check if this event is published (or any of the equivalent "published" statuses)
721
+		return
722
+			$this->ID() && $this->ID() !== null
723
+			&& (
724
+				$this->status() === 'publish'
725
+				|| $this->status() === EEM_Event::sold_out
726
+				|| $this->status() === EEM_Event::postponed
727
+				|| $this->status() === EEM_Event::cancelled
728
+			);
729
+	}
730
+
731
+
732
+	/**
733
+	 * This simply compares the internal dates with NOW and determines if the event is upcoming or not.
734
+	 *
735
+	 * @access public
736
+	 * @return boolean true yes, false no
737
+	 * @throws EE_Error
738
+	 */
739
+	public function is_upcoming()
740
+	{
741
+		// check if event id is present and if this event is published
742
+		if ($this->is_inactive()) {
743
+			return false;
744
+		}
745
+		// set initial value
746
+		$upcoming = false;
747
+		//next let's get all datetimes and loop through them
748
+		$datetimes = $this->datetimes_in_chronological_order();
749
+		foreach ($datetimes as $datetime) {
750
+			if ($datetime instanceof EE_Datetime) {
751
+				//if this dtt is expired then we continue cause one of the other datetimes might be upcoming.
752
+				if ($datetime->is_expired()) {
753
+					continue;
754
+				}
755
+				//if this dtt is active then we return false.
756
+				if ($datetime->is_active()) {
757
+					return false;
758
+				}
759
+				//otherwise let's check upcoming status
760
+				$upcoming = $datetime->is_upcoming();
761
+			}
762
+		}
763
+		return $upcoming;
764
+	}
765
+
766
+
767
+	/**
768
+	 * @return bool
769
+	 * @throws EE_Error
770
+	 */
771
+	public function is_active()
772
+	{
773
+		// check if event id is present and if this event is published
774
+		if ($this->is_inactive()) {
775
+			return false;
776
+		}
777
+		// set initial value
778
+		$active = false;
779
+		//next let's get all datetimes and loop through them
780
+		$datetimes = $this->datetimes_in_chronological_order();
781
+		foreach ($datetimes as $datetime) {
782
+			if ($datetime instanceof EE_Datetime) {
783
+				//if this dtt is expired then we continue cause one of the other datetimes might be active.
784
+				if ($datetime->is_expired()) {
785
+					continue;
786
+				}
787
+				//if this dtt is upcoming then we return false.
788
+				if ($datetime->is_upcoming()) {
789
+					return false;
790
+				}
791
+				//otherwise let's check active status
792
+				$active = $datetime->is_active();
793
+			}
794
+		}
795
+		return $active;
796
+	}
797
+
798
+
799
+	/**
800
+	 * @return bool
801
+	 * @throws EE_Error
802
+	 */
803
+	public function is_expired()
804
+	{
805
+		// check if event id is present and if this event is published
806
+		if ($this->is_inactive()) {
807
+			return false;
808
+		}
809
+		// set initial value
810
+		$expired = false;
811
+		//first let's get all datetimes and loop through them
812
+		$datetimes = $this->datetimes_in_chronological_order();
813
+		foreach ($datetimes as $datetime) {
814
+			if ($datetime instanceof EE_Datetime) {
815
+				//if this dtt is upcoming or active then we return false.
816
+				if ($datetime->is_upcoming() || $datetime->is_active()) {
817
+					return false;
818
+				}
819
+				//otherwise let's check active status
820
+				$expired = $datetime->is_expired();
821
+			}
822
+		}
823
+		return $expired;
824
+	}
825
+
826
+
827
+	/**
828
+	 * @return bool
829
+	 * @throws EE_Error
830
+	 */
831
+	public function is_inactive()
832
+	{
833
+		// check if event id is present and if this event is published
834
+		if ($this->_has_ID_and_is_published()) {
835
+			return false;
836
+		}
837
+		return true;
838
+	}
839
+
840
+
841
+	/**
842
+	 * calculate spaces remaining based on "saleable" tickets
843
+	 *
844
+	 * @param array $tickets
845
+	 * @param bool $filtered
846
+	 * @return int|float
847
+	 * @throws EE_Error
848
+	 * @throws DomainException
849
+	 * @throws UnexpectedEntityException
850
+	 */
851
+	public function spaces_remaining($tickets = array(), $filtered = true)
852
+	{
853
+		$this->getAvailableSpacesCalculator()->setActiveTickets($tickets);
854
+		$spaces_remaining = $this->getAvailableSpacesCalculator()->spacesRemaining();
855
+		return $filtered
856
+			? apply_filters(
857
+				'FHEE_EE_Event__spaces_remaining',
858
+				$spaces_remaining,
859
+				$this,
860
+				$tickets
861
+			)
862
+			: $spaces_remaining;
863
+	}
864
+
865
+
866
+	/**
867
+	 *    perform_sold_out_status_check
868
+	 *    checks all of this events's datetime  reg_limit - sold values to determine if ANY datetimes have spaces available...
869
+	 *    if NOT, then the event status will get toggled to 'sold_out'
870
+	 *
871
+	 * @return bool    return the ACTUAL sold out state.
872
+	 * @throws EE_Error
873
+	 * @throws DomainException
874
+	 * @throws UnexpectedEntityException
875
+	 */
876
+	public function perform_sold_out_status_check()
877
+	{
878
+		// get all unexpired untrashed tickets
879
+		$tickets = $this->active_tickets();
880
+		// if all the tickets are just expired, then don't update the event status to sold out
881
+		if (empty($tickets)) {
882
+			return true;
883
+		}
884
+		$spaces_remaining = $this->spaces_remaining($tickets);
885
+		if ($spaces_remaining < 1) {
886
+			$this->set_status(EEM_Event::sold_out);
887
+			$this->save();
888
+			$sold_out = true;
889
+		} else {
890
+			$sold_out = false;
891
+			// was event previously marked as sold out ?
892
+			if ($this->status() === EEM_Event::sold_out) {
893
+				// revert status to previous value, if it was set
894
+				$previous_event_status = $this->get_post_meta('_previous_event_status', true);
895
+				if ($previous_event_status) {
896
+					$this->set_status($previous_event_status);
897
+					$this->save();
898
+				}
899
+			}
900
+		}
901
+		do_action('AHEE__EE_Event__perform_sold_out_status_check__end', $this, $sold_out, $spaces_remaining, $tickets);
902
+		return $sold_out;
903
+	}
904
+
905
+
906
+
907
+	/**
908
+	 * This returns the total remaining spaces for sale on this event.
909
+	 *
910
+	 * @uses EE_Event::total_available_spaces()
911
+	 * @return float|int
912
+	 * @throws EE_Error
913
+	 * @throws DomainException
914
+	 * @throws UnexpectedEntityException
915
+	 */
916
+	public function spaces_remaining_for_sale()
917
+	{
918
+		return $this->total_available_spaces(true);
919
+	}
920
+
921
+
922
+
923
+	/**
924
+	 * This returns the total spaces available for an event
925
+	 * while considering all the qtys on the tickets and the reg limits
926
+	 * on the datetimes attached to this event.
927
+	 *
928
+	 * @param   bool $consider_sold Whether to consider any tickets that have already sold in our calculation.
929
+	 *                              If this is false, then we return the most tickets that could ever be sold
930
+	 *                              for this event with the datetime and tickets setup on the event under optimal
931
+	 *                              selling conditions.  Otherwise we return a live calculation of spaces available
932
+	 *                              based on tickets sold.  Depending on setup and stage of sales, this
933
+	 *                              may appear to equal remaining tickets.  However, the more tickets are
934
+	 *                              sold out, the more accurate the "live" total is.
935
+	 * @return float|int
936
+	 * @throws EE_Error
937
+	 * @throws DomainException
938
+	 * @throws UnexpectedEntityException
939
+	 */
940
+	public function total_available_spaces($consider_sold = false)
941
+	{
942
+		$spaces_available = $consider_sold
943
+			? $this->getAvailableSpacesCalculator()->spacesRemaining()
944
+			: $this->getAvailableSpacesCalculator()->totalSpacesAvailable();
945
+		return apply_filters(
946
+			'FHEE_EE_Event__total_available_spaces__spaces_available',
947
+			$spaces_available,
948
+			$this,
949
+			$this->getAvailableSpacesCalculator()->getDatetimes(),
950
+			$this->getAvailableSpacesCalculator()->getActiveTickets()
951
+		);
952
+	}
953
+
954
+
955
+	/**
956
+	 * Checks if the event is set to sold out
957
+	 *
958
+	 * @param  bool $actual whether or not to perform calculations to not only figure the
959
+	 *                      actual status but also to flip the status if necessary to sold
960
+	 *                      out If false, we just check the existing status of the event
961
+	 * @return boolean
962
+	 * @throws EE_Error
963
+	 */
964
+	public function is_sold_out($actual = false)
965
+	{
966
+		if (!$actual) {
967
+			return $this->status() === EEM_Event::sold_out;
968
+		}
969
+		return $this->perform_sold_out_status_check();
970
+	}
971
+
972
+
973
+	/**
974
+	 * Checks if the event is marked as postponed
975
+	 *
976
+	 * @return boolean
977
+	 */
978
+	public function is_postponed()
979
+	{
980
+		return $this->status() === EEM_Event::postponed;
981
+	}
982
+
983
+
984
+	/**
985
+	 * Checks if the event is marked as cancelled
986
+	 *
987
+	 * @return boolean
988
+	 */
989
+	public function is_cancelled()
990
+	{
991
+		return $this->status() === EEM_Event::cancelled;
992
+	}
993
+
994
+
995
+	/**
996
+	 * Get the logical active status in a hierarchical order for all the datetimes.  Note
997
+	 * Basically, we order the datetimes by EVT_start_date.  Then first test on whether the event is published.  If its
998
+	 * NOT published then we test for whether its expired or not.  IF it IS published then we test first on whether an
999
+	 * event has any active dates.  If no active dates then we check for any upcoming dates.  If no upcoming dates then
1000
+	 * the event is considered expired.
1001
+	 * NOTE: this method does NOT calculate whether the datetimes are sold out when event is published.  Sold Out is a status
1002
+	 * set on the EVENT when it is not published and thus is done
1003
+	 *
1004
+	 * @param bool $reset
1005
+	 * @return bool | string - based on EE_Datetime active constants or FALSE if error.
1006
+	 * @throws EE_Error
1007
+	 */
1008
+	public function get_active_status($reset = false)
1009
+	{
1010
+		// if the active status has already been set, then just use that value (unless we are resetting it)
1011
+		if (!empty($this->_active_status) && !$reset) {
1012
+			return $this->_active_status;
1013
+		}
1014
+		//first check if event id is present on this object
1015
+		if (!$this->ID()) {
1016
+			return false;
1017
+		}
1018
+		$where_params_for_event = array(array('EVT_ID' => $this->ID()));
1019
+		//if event is published:
1020
+		if ($this->status() === 'publish') {
1021
+			//active?
1022
+			if (EEM_Datetime::instance()->get_datetime_count_for_status(EE_Datetime::active, $where_params_for_event) > 0) {
1023
+				$this->_active_status = EE_Datetime::active;
1024
+			} else {
1025
+				//upcoming?
1026
+				if (EEM_Datetime::instance()->get_datetime_count_for_status(EE_Datetime::upcoming, $where_params_for_event) > 0) {
1027
+					$this->_active_status = EE_Datetime::upcoming;
1028
+				} else {
1029
+					//expired?
1030
+					if (
1031
+						EEM_Datetime::instance()->get_datetime_count_for_status(EE_Datetime::expired, $where_params_for_event) > 0
1032
+					) {
1033
+						$this->_active_status = EE_Datetime::expired;
1034
+					} else {
1035
+						//it would be odd if things make it this far because it basically means there are no datetime's
1036
+						//attached to the event.  So in this case it will just be considered inactive.
1037
+						$this->_active_status = EE_Datetime::inactive;
1038
+					}
1039
+				}
1040
+			}
1041
+		} else {
1042
+			//the event is not published, so let's just set it's active status according to its' post status
1043
+			switch ($this->status()) {
1044
+				case EEM_Event::sold_out :
1045
+					$this->_active_status = EE_Datetime::sold_out;
1046
+					break;
1047
+				case EEM_Event::cancelled :
1048
+					$this->_active_status = EE_Datetime::cancelled;
1049
+					break;
1050
+				case EEM_Event::postponed :
1051
+					$this->_active_status = EE_Datetime::postponed;
1052
+					break;
1053
+				default :
1054
+					$this->_active_status = EE_Datetime::inactive;
1055
+			}
1056
+		}
1057
+		return $this->_active_status;
1058
+	}
1059
+
1060
+
1061
+	/**
1062
+	 *    pretty_active_status
1063
+	 *
1064
+	 * @access public
1065
+	 * @param boolean $echo whether to return (FALSE), or echo out the result (TRUE)
1066
+	 * @return mixed void|string
1067
+	 * @throws EE_Error
1068
+	 */
1069
+	public function pretty_active_status($echo = true)
1070
+	{
1071
+		$active_status = $this->get_active_status();
1072
+		$status = '<span class="ee-status event-active-status-'
1073
+			. $active_status
1074
+			. '">'
1075
+			. EEH_Template::pretty_status($active_status, false, 'sentence')
1076
+			. '</span>';
1077
+		if ($echo) {
1078
+			echo $status;
1079
+			return '';
1080
+		}
1081
+		return $status;
1082
+	}
1083
+
1084
+
1085
+	/**
1086
+	 * @return bool|int
1087
+	 * @throws EE_Error
1088
+	 */
1089
+	public function get_number_of_tickets_sold()
1090
+	{
1091
+		$tkt_sold = 0;
1092
+		if (!$this->ID()) {
1093
+			return 0;
1094
+		}
1095
+		$datetimes = $this->datetimes();
1096
+		foreach ($datetimes as $datetime) {
1097
+			if ($datetime instanceof EE_Datetime) {
1098
+				$tkt_sold += $datetime->sold();
1099
+			}
1100
+		}
1101
+		return $tkt_sold;
1102
+	}
1103
+
1104
+
1105
+	/**
1106
+	 * This just returns a count of all the registrations for this event
1107
+	 *
1108
+	 * @access  public
1109
+	 * @return int
1110
+	 * @throws EE_Error
1111
+	 */
1112
+	public function get_count_of_all_registrations()
1113
+	{
1114
+		return EEM_Event::instance()->count_related($this, 'Registration');
1115
+	}
1116
+
1117
+
1118
+	/**
1119
+	 * This returns the ticket with the earliest start time that is
1120
+	 * available for this event (across all datetimes attached to the event)
1121
+	 *
1122
+	 * @return EE_Base_Class|EE_Ticket|null
1123
+	 * @throws EE_Error
1124
+	 */
1125
+	public function get_ticket_with_earliest_start_time()
1126
+	{
1127
+		$where['Datetime.EVT_ID'] = $this->ID();
1128
+		$query_params = array($where, 'order_by' => array('TKT_start_date' => 'ASC'));
1129
+		return EE_Registry::instance()->load_model('Ticket')->get_one($query_params);
1130
+	}
1131
+
1132
+
1133
+	/**
1134
+	 * This returns the ticket with the latest end time that is available
1135
+	 * for this event (across all datetimes attached to the event)
1136
+	 *
1137
+	 * @return EE_Base_Class|EE_Ticket|null
1138
+	 * @throws EE_Error
1139
+	 */
1140
+	public function get_ticket_with_latest_end_time()
1141
+	{
1142
+		$where['Datetime.EVT_ID'] = $this->ID();
1143
+		$query_params = array($where, 'order_by' => array('TKT_end_date' => 'DESC'));
1144
+		return EE_Registry::instance()->load_model('Ticket')->get_one($query_params);
1145
+	}
1146
+
1147
+
1148
+	/**
1149
+	 * This returns whether there are any tickets on sale for this event.
1150
+	 *
1151
+	 * @return bool true = YES tickets on sale.
1152
+	 * @throws EE_Error
1153
+	 */
1154
+	public function tickets_on_sale()
1155
+	{
1156
+		$earliest_ticket = $this->get_ticket_with_earliest_start_time();
1157
+		$latest_ticket = $this->get_ticket_with_latest_end_time();
1158
+		if (!$latest_ticket instanceof EE_Ticket && !$earliest_ticket instanceof EE_Ticket) {
1159
+			return false;
1160
+		}
1161
+		//check on sale for these two tickets.
1162
+		if ($latest_ticket->is_on_sale() || $earliest_ticket->is_on_sale()) {
1163
+			return true;
1164
+		}
1165
+		return false;
1166
+	}
1167
+
1168
+
1169
+	/**
1170
+	 * Gets the URL for viewing this event on the front-end. Overrides parent
1171
+	 * to check for an external URL first
1172
+	 *
1173
+	 * @return string
1174
+	 * @throws EE_Error
1175
+	 */
1176
+	public function get_permalink()
1177
+	{
1178
+		if ($this->external_url()) {
1179
+			return $this->external_url();
1180
+		}
1181
+		return parent::get_permalink();
1182
+	}
1183
+
1184
+
1185
+	/**
1186
+	 * Gets the first term for 'espresso_event_categories' we can find
1187
+	 *
1188
+	 * @param array $query_params like EEM_Base::get_all
1189
+	 * @return EE_Base_Class|EE_Term|null
1190
+	 * @throws EE_Error
1191
+	 */
1192
+	public function first_event_category($query_params = array())
1193
+	{
1194
+		$query_params[0]['Term_Taxonomy.taxonomy'] = 'espresso_event_categories';
1195
+		$query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $this->ID();
1196
+		return EEM_Term::instance()->get_one($query_params);
1197
+	}
1198
+
1199
+
1200
+	/**
1201
+	 * Gets all terms for 'espresso_event_categories' we can find
1202
+	 *
1203
+	 * @param array $query_params
1204
+	 * @return EE_Base_Class[]|EE_Term[]
1205
+	 * @throws EE_Error
1206
+	 */
1207
+	public function get_all_event_categories($query_params = array())
1208
+	{
1209
+		$query_params[0]['Term_Taxonomy.taxonomy'] = 'espresso_event_categories';
1210
+		$query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $this->ID();
1211
+		return EEM_Term::instance()->get_all($query_params);
1212
+	}
1213
+
1214
+
1215
+	/**
1216
+	 * Gets all the question groups, ordering them by QSG_order ascending
1217
+	 *
1218
+	 * @param array $query_params @see EEM_Base::get_all
1219
+	 * @return EE_Base_Class[]|EE_Question_Group[]
1220
+	 * @throws EE_Error
1221
+	 */
1222
+	public function question_groups($query_params = array())
1223
+	{
1224
+		$query_params = !empty($query_params) ? $query_params : array('order_by' => array('QSG_order' => 'ASC'));
1225
+		return $this->get_many_related('Question_Group', $query_params);
1226
+	}
1227
+
1228
+
1229
+	/**
1230
+	 * Implementation for EEI_Has_Icon interface method.
1231
+	 *
1232
+	 * @see EEI_Visual_Representation for comments
1233
+	 * @return string
1234
+	 */
1235
+	public function get_icon()
1236
+	{
1237
+		return '<span class="dashicons dashicons-flag"></span>';
1238
+	}
1239
+
1240
+
1241
+	/**
1242
+	 * Implementation for EEI_Admin_Links interface method.
1243
+	 *
1244
+	 * @see EEI_Admin_Links for comments
1245
+	 * @return string
1246
+	 * @throws EE_Error
1247
+	 */
1248
+	public function get_admin_details_link()
1249
+	{
1250
+		return $this->get_admin_edit_link();
1251
+	}
1252
+
1253
+
1254
+	/**
1255
+	 * Implementation for EEI_Admin_Links interface method.
1256
+	 *
1257
+	 * @see EEI_Admin_Links for comments
1258
+	 * @return string
1259
+	 * @throws EE_Error
1260
+	 */
1261
+	public function get_admin_edit_link()
1262
+	{
1263
+		return EEH_URL::add_query_args_and_nonce(array(
1264
+			'page' => 'espresso_events',
1265
+			'action' => 'edit',
1266
+			'post' => $this->ID(),
1267
+		),
1268
+			admin_url('admin.php')
1269
+		);
1270
+	}
1271
+
1272
+
1273
+	/**
1274
+	 * Implementation for EEI_Admin_Links interface method.
1275
+	 *
1276
+	 * @see EEI_Admin_Links for comments
1277
+	 * @return string
1278
+	 */
1279
+	public function get_admin_settings_link()
1280
+	{
1281
+		return EEH_URL::add_query_args_and_nonce(array(
1282
+			'page' => 'espresso_events',
1283
+			'action' => 'default_event_settings',
1284
+		),
1285
+			admin_url('admin.php')
1286
+		);
1287
+	}
1288
+
1289
+
1290
+	/**
1291
+	 * Implementation for EEI_Admin_Links interface method.
1292
+	 *
1293
+	 * @see EEI_Admin_Links for comments
1294
+	 * @return string
1295
+	 */
1296
+	public function get_admin_overview_link()
1297
+	{
1298
+		return EEH_URL::add_query_args_and_nonce(array(
1299
+			'page' => 'espresso_events',
1300
+			'action' => 'default',
1301
+		),
1302
+			admin_url('admin.php')
1303
+		);
1304
+	}
1305 1305
 
1306 1306
 }
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -3,7 +3,7 @@  discard block
 block discarded – undo
3 3
 use EventEspresso\core\domain\services\event\EventSpacesCalculator;
4 4
 use EventEspresso\core\exceptions\UnexpectedEntityException;
5 5
 
6
-if (!defined('EVENT_ESPRESSO_VERSION')) {
6
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
7 7
     exit('No direct script access allowed');
8 8
 }
9 9
 
@@ -75,7 +75,7 @@  discard block
 block discarded – undo
75 75
      */
76 76
     public function getAvailableSpacesCalculator()
77 77
     {
78
-        if(! $this->available_spaces_calculator instanceof EventSpacesCalculator){
78
+        if ( ! $this->available_spaces_calculator instanceof EventSpacesCalculator) {
79 79
             $this->available_spaces_calculator = new EventSpacesCalculator($this);
80 80
         }
81 81
         return $this->available_spaces_calculator;
@@ -118,7 +118,7 @@  discard block
 block discarded – undo
118 118
     public function set_status($new_status = null, $use_default = false)
119 119
     {
120 120
         // if nothing is set, and we aren't explicitly wanting to reset the status, then just leave
121
-        if (empty($new_status) && !$use_default) {
121
+        if (empty($new_status) && ! $use_default) {
122 122
             return;
123 123
         }
124 124
         // get current Event status
@@ -216,7 +216,7 @@  discard block
 block discarded – undo
216 216
      */
217 217
     public function primary_datetime($try_to_exclude_expired = true, $try_to_exclude_deleted = true)
218 218
     {
219
-        if (!empty ($this->_Primary_Datetime)) {
219
+        if ( ! empty ($this->_Primary_Datetime)) {
220 220
             return $this->_Primary_Datetime;
221 221
         }
222 222
         $this->_Primary_Datetime = EEM_Datetime::instance($this->_timezone)->get_primary_datetime_for_event(
@@ -239,7 +239,7 @@  discard block
 block discarded – undo
239 239
     {
240 240
         //first get all datetimes
241 241
         $datetimes = $this->datetimes_ordered();
242
-        if (!$datetimes) {
242
+        if ( ! $datetimes) {
243 243
             return array();
244 244
         }
245 245
         $datetime_ids = array();
@@ -343,7 +343,7 @@  discard block
 block discarded – undo
343 343
      */
344 344
     public function display_ticket_selector()
345 345
     {
346
-        return (bool)$this->get('EVT_display_ticket_selector');
346
+        return (bool) $this->get('EVT_display_ticket_selector');
347 347
     }
348 348
 
349 349
 
@@ -414,7 +414,7 @@  discard block
 block discarded – undo
414 414
     public function default_registration_status()
415 415
     {
416 416
         $event_default_registration_status = $this->get('EVT_default_registration_status');
417
-        return !empty($event_default_registration_status)
417
+        return ! empty($event_default_registration_status)
418 418
             ? $event_default_registration_status
419 419
             : EE_Registry::instance()->CFG->registration->default_STS_ID;
420 420
     }
@@ -430,7 +430,7 @@  discard block
 block discarded – undo
430 430
     public function short_description($num_words = 55, $more = null, $not_full_desc = false)
431 431
     {
432 432
         $short_desc = $this->get('EVT_short_desc');
433
-        if (!empty($short_desc) || $not_full_desc) {
433
+        if ( ! empty($short_desc) || $not_full_desc) {
434 434
             return $short_desc;
435 435
         }
436 436
         $full_desc = $this->get('EVT_desc');
@@ -963,7 +963,7 @@  discard block
 block discarded – undo
963 963
      */
964 964
     public function is_sold_out($actual = false)
965 965
     {
966
-        if (!$actual) {
966
+        if ( ! $actual) {
967 967
             return $this->status() === EEM_Event::sold_out;
968 968
         }
969 969
         return $this->perform_sold_out_status_check();
@@ -1008,11 +1008,11 @@  discard block
 block discarded – undo
1008 1008
     public function get_active_status($reset = false)
1009 1009
     {
1010 1010
         // if the active status has already been set, then just use that value (unless we are resetting it)
1011
-        if (!empty($this->_active_status) && !$reset) {
1011
+        if ( ! empty($this->_active_status) && ! $reset) {
1012 1012
             return $this->_active_status;
1013 1013
         }
1014 1014
         //first check if event id is present on this object
1015
-        if (!$this->ID()) {
1015
+        if ( ! $this->ID()) {
1016 1016
             return false;
1017 1017
         }
1018 1018
         $where_params_for_event = array(array('EVT_ID' => $this->ID()));
@@ -1089,7 +1089,7 @@  discard block
 block discarded – undo
1089 1089
     public function get_number_of_tickets_sold()
1090 1090
     {
1091 1091
         $tkt_sold = 0;
1092
-        if (!$this->ID()) {
1092
+        if ( ! $this->ID()) {
1093 1093
             return 0;
1094 1094
         }
1095 1095
         $datetimes = $this->datetimes();
@@ -1155,7 +1155,7 @@  discard block
 block discarded – undo
1155 1155
     {
1156 1156
         $earliest_ticket = $this->get_ticket_with_earliest_start_time();
1157 1157
         $latest_ticket = $this->get_ticket_with_latest_end_time();
1158
-        if (!$latest_ticket instanceof EE_Ticket && !$earliest_ticket instanceof EE_Ticket) {
1158
+        if ( ! $latest_ticket instanceof EE_Ticket && ! $earliest_ticket instanceof EE_Ticket) {
1159 1159
             return false;
1160 1160
         }
1161 1161
         //check on sale for these two tickets.
@@ -1221,7 +1221,7 @@  discard block
 block discarded – undo
1221 1221
      */
1222 1222
     public function question_groups($query_params = array())
1223 1223
     {
1224
-        $query_params = !empty($query_params) ? $query_params : array('order_by' => array('QSG_order' => 'ASC'));
1224
+        $query_params = ! empty($query_params) ? $query_params : array('order_by' => array('QSG_order' => 'ASC'));
1225 1225
         return $this->get_many_related('Question_Group', $query_params);
1226 1226
     }
1227 1227
 
Please login to merge, or discard this patch.
core/libraries/shortcodes/EE_Venue_Shortcodes.lib.php 4 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -157,7 +157,7 @@
 block discarded – undo
157 157
     /**
158 158
      * This retrieves the EE_Venue from the available data object.
159 159
      *
160
-     * @return EE_Venue|null
160
+     * @return EE_Base_Class|null
161 161
      */
162 162
     private function _get_venue() {
163 163
 
Please login to merge, or discard this patch.
Indentation   +284 added lines, -284 removed lines patch added patch discarded remove patch
@@ -16,288 +16,288 @@
 block discarded – undo
16 16
 {
17 17
 
18 18
 
19
-    /**
20
-     * Will hold the EE_Event if available
21
-     *
22
-     * @var EE_Event
23
-     */
24
-    protected $_event;
25
-
26
-    /**
27
-     * Will hold the EE_Venue if available
28
-     *
29
-     * @var EE_Venue
30
-     */
31
-    protected $_venue;
32
-
33
-
34
-    /**
35
-     * Initialize properties
36
-     */
37
-    protected function _init_props()
38
-    {
39
-        $this->label       = esc_html__('Venue Shortcodes', 'event_espresso');
40
-        $this->description = esc_html__('All shortcodes specific to venue related data', 'event_espresso');
41
-        $this->_shortcodes = array(
42
-            '[VENUE_TITLE]'             => esc_html__('The title for the event venue', 'event_espresso'),
43
-            '[VENUE_DESCRIPTION]'       => esc_html__('The description for the event venue', 'event_espresso'),
44
-            '[VENUE_URL]'               => esc_html__('A url to a webpage for the venue', 'event_espresso'),
45
-            '[VENUE_IMAGE]'             => esc_html__('An image representing the event venue', 'event_espresso'),
46
-            '[VENUE_PHONE]'             => esc_html__('The phone number for the venue', 'event_espresso'),
47
-            '[VENUE_ADDRESS]'           => esc_html__('The address for the venue', 'event_espresso'),
48
-            '[VENUE_ADDRESS2]'          => esc_html__('Address 2 for the venue', 'event_espresso'),
49
-            '[VENUE_CITY]'              => esc_html__('The city the venue is in', 'event_espresso'),
50
-            '[VENUE_STATE]'             => esc_html__('The state the venue is located in', 'event_espresso'),
51
-            '[VENUE_COUNTRY]'           => esc_html__('The country the venue is located in', 'event_espresso'),
52
-            '[VENUE_FORMATTED_ADDRESS]' => esc_html__(
53
-                'This just outputs the venue address in a semantic address format.',
54
-                'event_espresso'
55
-            ),
56
-            '[VENUE_ZIP]'               => esc_html__('The zip code for the venue address', 'event_espresso'),
57
-            '[VENUE_META_*]'            => esc_html__(
58
-                'This is a special dynamic shortcode. After the "*", add the exact name for your custom field, if there is a value set for that custom field within the venue then it will be output in place of this shortcode.', 
59
-                'event_espresso'
60
-            ),
61
-            '[GOOGLE_MAP_URL]'          => esc_html__(
62
-                'URL for the google map associated with the venue.', 
63
-                'event_espresso'
64
-            ),
65
-            '[GOOGLE_MAP_LINK]'         => esc_html__('Link to a google map for the venue', 'event_espresso'),
66
-            '[GOOGLE_MAP_IMAGE]'        => esc_html__('Google map for venue wrapped in image tags', 'event_espresso'),
67
-        );
68
-    }
69
-
70
-
71
-    /**
72
-     * Parse incoming shortcode
73
-     * @param string $shortcode
74
-     * @return string
75
-     */
76
-    protected function _parser($shortcode)
77
-    {
78
-        $this->_venue = $this->_get_venue();
79
-        //If there is no venue object by now then get out.
80
-        if ( ! $this->_venue instanceof EE_Venue )
81
-            return '';
82
-
83
-        switch ($shortcode) {
84
-            case '[VENUE_TITLE]':
85
-                return $this->_venue('title');
86
-                break;
87
-
88
-            case '[VENUE_DESCRIPTION]':
89
-                return $this->_venue('description');
90
-                break;
91
-
92
-            case '[VENUE_URL]':
93
-                return $this->_venue('url');
94
-                break;
95
-
96
-            case '[VENUE_IMAGE]':
97
-                return $this->_venue('image');
98
-                break;
99
-
100
-            case '[VENUE_PHONE]':
101
-                return $this->_venue('phone');
102
-                break;
103
-
104
-            case '[VENUE_ADDRESS]':
105
-                return $this->_venue('address');
106
-                break;
107
-
108
-            case '[VENUE_ADDRESS2]':
109
-                return $this->_venue('address2');
110
-                break;
111
-
112
-            case '[VENUE_CITY]':
113
-                return $this->_venue('city');
114
-                break;
115
-
116
-            case '[VENUE_COUNTRY]':
117
-                return $this->_venue('country');
118
-                break;
119
-
120
-            case '[VENUE_STATE]':
121
-                return $this->_venue('state');
122
-                break;
123
-
124
-            case '[VENUE_ZIP]':
125
-                return $this->_venue('zip');
126
-                break;
127
-
128
-            case '[VENUE_FORMATTED_ADDRESS]':
129
-                return $this->_venue('formatted_address');
130
-                break;
131
-
132
-            case '[GOOGLE_MAP_URL]':
133
-                return $this->_venue('gmap_url');
134
-                break;
135
-
136
-            case '[GOOGLE_MAP_LINK]':
137
-                return $this->_venue('gmap_link');
138
-                break;
139
-
140
-            case '[GOOGLE_MAP_IMAGE]':
141
-                return $this->_venue('gmap_link_img');
142
-                break;
143
-
144
-        }
145
-
146
-        if ( strpos( $shortcode, '[VENUE_META_*' ) !== false ) {
147
-            $shortcode = str_replace( '[VENUE_META_*', '', $shortcode );
148
-            $shortcode = trim( str_replace( ']', '', $shortcode ) );
149
-
150
-            //pull the meta value from the venue post
151
-            $venue_meta = $this->_venue->get_post_meta( $shortcode, true );
152
-
153
-            return ! empty( $venue_meta ) ? $venue_meta : '';
154
-
155
-        }
156
-    }
157
-    /**
158
-     * This retrieves the EE_Venue from the available data object.
159
-     *
160
-     * @return EE_Venue|null
161
-     */
162
-    private function _get_venue() {
163
-
164
-        //we need the EE_Event object to get the venue.
165
-        $this->_event = $this->_data instanceof EE_Event ? $this->_data : null;
166
-
167
-        //if no event, then let's see if there is a reg_obj.  If there IS, then we'll try and grab the event from the reg_obj instead.
168
-        if (empty($this->_event)) {
169
-            $aee = $this->_data instanceof EE_Messages_Addressee ? $this->_data : null;
170
-            $aee = $this->_extra_data instanceof EE_Messages_Addressee ? $this->_extra_data : $aee;
171
-
172
-            $this->_event = $aee instanceof EE_Messages_Addressee && $aee->reg_obj instanceof EE_Registration ? $aee->reg_obj->event() : null;
173
-
174
-            //if still empty do we have a ticket data item?
175
-            $this->_event = empty($this->_event)
176
-                            && $this->_data instanceof EE_Ticket
177
-                            && $this->_extra_data['data'] instanceof EE_Messages_Addressee
178
-                ? $this->_extra_data['data']->tickets[$this->_data->ID()]['EE_Event']
179
-                : $this->_event;
180
-
181
-            //if STILL empty event, let's try to get the first event in the list of events via EE_Messages_Addressee and use that.
182
-            $event        = $aee instanceof EE_Messages_Addressee ? reset($aee->events) : array();
183
-            $this->_event = empty($this->_event) && ! empty($events) ? $event : $this->_event;
184
-        }
185
-
186
-        //If we have an event object use it to pull the venue.
187
-        if ($this->_event instanceof EE_Event) {
188
-            return $this->_event->get_first_related('Venue');
189
-        } 
190
-
191
-        return null;
192
-    }
193
-
194
-    /**
195
-     * This retrieves the specified venue information
196
-     *
197
-     * @param string $field  What Venue field to retrieve
198
-     * @return string What was retrieved!
199
-     * @throws EE_Error
200
-     * @throws \EventEspresso\core\exceptions\EntityNotFoundException
201
-     */
202
-    private function _venue($field)
203
-    {
204
-
205
-        if (empty($this->_venue)) {
206
-            return '';
207
-        } //no venue so get out.
208
-
209
-        switch ($field) {
210
-            case 'title':
211
-                return $this->_venue->get('VNU_name');
212
-                break;
213
-
214
-            case 'description':
215
-                return $this->_venue->get('VNU_desc');
216
-                break;
217
-
218
-            case 'url':
219
-                $url = $this->_venue->get('VNU_url');
220
-                return empty($url) ? $this->_venue->get_permalink() : $url;
221
-                break;
222
-
223
-            case 'image':
224
-                return '<img src="' . $this->_venue->feature_image_url(array(200, 200,))
225
-                       . '" alt="' . sprintf(
226
-                           esc_attr__('%s Feature Image', 'event_espresso'),
227
-                           $this->_venue->get('VNU_name')
228
-                       ) . '" />';
229
-                break;
230
-
231
-            case 'phone':
232
-                return $this->_venue->get('VNU_phone');
233
-                break;
234
-
235
-            case 'address':
236
-                return $this->_venue->get('VNU_address');
237
-                break;
238
-
239
-            case 'address2':
240
-                return $this->_venue->get('VNU_address2');
241
-                break;
242
-
243
-            case 'city':
244
-                return $this->_venue->get('VNU_city');
245
-                break;
246
-
247
-            case 'state':
248
-                $state = $this->_venue->state_obj();
249
-                return is_object($state) ? $state->get('STA_name') : '';
250
-                break;
251
-
252
-            case 'country':
253
-                $country = $this->_venue->country_obj();
254
-                return is_object($country) ? $country->get('CNT_name') : '';
255
-                break;
256
-
257
-            case 'zip':
258
-                return $this->_venue->get('VNU_zip');
259
-                break;
260
-
261
-            case 'formatted_address':
262
-                return EEH_Address::format($this->_venue);
263
-                break;
264
-
265
-            case 'gmap_link':
266
-            case 'gmap_url':
267
-            case 'gmap_link_img':
268
-                $atts = $this->get_map_attributes($this->_venue, $field);
269
-                return EEH_Maps::google_map_link($atts);
270
-                break;
271
-        }
272
-        return '';
273
-    }
274
-
275
-
276
-    /**
277
-     * Generates the attributes for retrieving a google_map artifact.
278
-     * @param EE_Venue $venue
279
-     * @param string   $field
280
-     * @return array
281
-     * @throws EE_Error
282
-     */
283
-    protected function get_map_attributes(EE_Venue $venue, $field = 'gmap_link')
284
-    {
285
-        $state   = $venue->state_obj();
286
-        $country = $venue->country_obj();
287
-        $atts    = array(
288
-            'id'      => $venue->ID(),
289
-            'address' => $venue->get('VNU_address'),
290
-            'city'    => $venue->get('VNU_city'),
291
-            'state'   => is_object($state) ? $state->get('STA_name') : '',
292
-            'zip'     => $venue->get('VNU_zip'),
293
-            'country' => is_object($country) ? $country->get('CNT_name') : '',
294
-            'type'    => $field === 'gmap_link' ? 'url' : 'map',
295
-            'map_w'   => 200,
296
-            'map_h'   => 200,
297
-        );
298
-        if ($field === 'gmap_url') {
299
-            $atts['type'] = 'url_only';
300
-        }
301
-        return $atts;
302
-    }
19
+	/**
20
+	 * Will hold the EE_Event if available
21
+	 *
22
+	 * @var EE_Event
23
+	 */
24
+	protected $_event;
25
+
26
+	/**
27
+	 * Will hold the EE_Venue if available
28
+	 *
29
+	 * @var EE_Venue
30
+	 */
31
+	protected $_venue;
32
+
33
+
34
+	/**
35
+	 * Initialize properties
36
+	 */
37
+	protected function _init_props()
38
+	{
39
+		$this->label       = esc_html__('Venue Shortcodes', 'event_espresso');
40
+		$this->description = esc_html__('All shortcodes specific to venue related data', 'event_espresso');
41
+		$this->_shortcodes = array(
42
+			'[VENUE_TITLE]'             => esc_html__('The title for the event venue', 'event_espresso'),
43
+			'[VENUE_DESCRIPTION]'       => esc_html__('The description for the event venue', 'event_espresso'),
44
+			'[VENUE_URL]'               => esc_html__('A url to a webpage for the venue', 'event_espresso'),
45
+			'[VENUE_IMAGE]'             => esc_html__('An image representing the event venue', 'event_espresso'),
46
+			'[VENUE_PHONE]'             => esc_html__('The phone number for the venue', 'event_espresso'),
47
+			'[VENUE_ADDRESS]'           => esc_html__('The address for the venue', 'event_espresso'),
48
+			'[VENUE_ADDRESS2]'          => esc_html__('Address 2 for the venue', 'event_espresso'),
49
+			'[VENUE_CITY]'              => esc_html__('The city the venue is in', 'event_espresso'),
50
+			'[VENUE_STATE]'             => esc_html__('The state the venue is located in', 'event_espresso'),
51
+			'[VENUE_COUNTRY]'           => esc_html__('The country the venue is located in', 'event_espresso'),
52
+			'[VENUE_FORMATTED_ADDRESS]' => esc_html__(
53
+				'This just outputs the venue address in a semantic address format.',
54
+				'event_espresso'
55
+			),
56
+			'[VENUE_ZIP]'               => esc_html__('The zip code for the venue address', 'event_espresso'),
57
+			'[VENUE_META_*]'            => esc_html__(
58
+				'This is a special dynamic shortcode. After the "*", add the exact name for your custom field, if there is a value set for that custom field within the venue then it will be output in place of this shortcode.', 
59
+				'event_espresso'
60
+			),
61
+			'[GOOGLE_MAP_URL]'          => esc_html__(
62
+				'URL for the google map associated with the venue.', 
63
+				'event_espresso'
64
+			),
65
+			'[GOOGLE_MAP_LINK]'         => esc_html__('Link to a google map for the venue', 'event_espresso'),
66
+			'[GOOGLE_MAP_IMAGE]'        => esc_html__('Google map for venue wrapped in image tags', 'event_espresso'),
67
+		);
68
+	}
69
+
70
+
71
+	/**
72
+	 * Parse incoming shortcode
73
+	 * @param string $shortcode
74
+	 * @return string
75
+	 */
76
+	protected function _parser($shortcode)
77
+	{
78
+		$this->_venue = $this->_get_venue();
79
+		//If there is no venue object by now then get out.
80
+		if ( ! $this->_venue instanceof EE_Venue )
81
+			return '';
82
+
83
+		switch ($shortcode) {
84
+			case '[VENUE_TITLE]':
85
+				return $this->_venue('title');
86
+				break;
87
+
88
+			case '[VENUE_DESCRIPTION]':
89
+				return $this->_venue('description');
90
+				break;
91
+
92
+			case '[VENUE_URL]':
93
+				return $this->_venue('url');
94
+				break;
95
+
96
+			case '[VENUE_IMAGE]':
97
+				return $this->_venue('image');
98
+				break;
99
+
100
+			case '[VENUE_PHONE]':
101
+				return $this->_venue('phone');
102
+				break;
103
+
104
+			case '[VENUE_ADDRESS]':
105
+				return $this->_venue('address');
106
+				break;
107
+
108
+			case '[VENUE_ADDRESS2]':
109
+				return $this->_venue('address2');
110
+				break;
111
+
112
+			case '[VENUE_CITY]':
113
+				return $this->_venue('city');
114
+				break;
115
+
116
+			case '[VENUE_COUNTRY]':
117
+				return $this->_venue('country');
118
+				break;
119
+
120
+			case '[VENUE_STATE]':
121
+				return $this->_venue('state');
122
+				break;
123
+
124
+			case '[VENUE_ZIP]':
125
+				return $this->_venue('zip');
126
+				break;
127
+
128
+			case '[VENUE_FORMATTED_ADDRESS]':
129
+				return $this->_venue('formatted_address');
130
+				break;
131
+
132
+			case '[GOOGLE_MAP_URL]':
133
+				return $this->_venue('gmap_url');
134
+				break;
135
+
136
+			case '[GOOGLE_MAP_LINK]':
137
+				return $this->_venue('gmap_link');
138
+				break;
139
+
140
+			case '[GOOGLE_MAP_IMAGE]':
141
+				return $this->_venue('gmap_link_img');
142
+				break;
143
+
144
+		}
145
+
146
+		if ( strpos( $shortcode, '[VENUE_META_*' ) !== false ) {
147
+			$shortcode = str_replace( '[VENUE_META_*', '', $shortcode );
148
+			$shortcode = trim( str_replace( ']', '', $shortcode ) );
149
+
150
+			//pull the meta value from the venue post
151
+			$venue_meta = $this->_venue->get_post_meta( $shortcode, true );
152
+
153
+			return ! empty( $venue_meta ) ? $venue_meta : '';
154
+
155
+		}
156
+	}
157
+	/**
158
+	 * This retrieves the EE_Venue from the available data object.
159
+	 *
160
+	 * @return EE_Venue|null
161
+	 */
162
+	private function _get_venue() {
163
+
164
+		//we need the EE_Event object to get the venue.
165
+		$this->_event = $this->_data instanceof EE_Event ? $this->_data : null;
166
+
167
+		//if no event, then let's see if there is a reg_obj.  If there IS, then we'll try and grab the event from the reg_obj instead.
168
+		if (empty($this->_event)) {
169
+			$aee = $this->_data instanceof EE_Messages_Addressee ? $this->_data : null;
170
+			$aee = $this->_extra_data instanceof EE_Messages_Addressee ? $this->_extra_data : $aee;
171
+
172
+			$this->_event = $aee instanceof EE_Messages_Addressee && $aee->reg_obj instanceof EE_Registration ? $aee->reg_obj->event() : null;
173
+
174
+			//if still empty do we have a ticket data item?
175
+			$this->_event = empty($this->_event)
176
+							&& $this->_data instanceof EE_Ticket
177
+							&& $this->_extra_data['data'] instanceof EE_Messages_Addressee
178
+				? $this->_extra_data['data']->tickets[$this->_data->ID()]['EE_Event']
179
+				: $this->_event;
180
+
181
+			//if STILL empty event, let's try to get the first event in the list of events via EE_Messages_Addressee and use that.
182
+			$event        = $aee instanceof EE_Messages_Addressee ? reset($aee->events) : array();
183
+			$this->_event = empty($this->_event) && ! empty($events) ? $event : $this->_event;
184
+		}
185
+
186
+		//If we have an event object use it to pull the venue.
187
+		if ($this->_event instanceof EE_Event) {
188
+			return $this->_event->get_first_related('Venue');
189
+		} 
190
+
191
+		return null;
192
+	}
193
+
194
+	/**
195
+	 * This retrieves the specified venue information
196
+	 *
197
+	 * @param string $field  What Venue field to retrieve
198
+	 * @return string What was retrieved!
199
+	 * @throws EE_Error
200
+	 * @throws \EventEspresso\core\exceptions\EntityNotFoundException
201
+	 */
202
+	private function _venue($field)
203
+	{
204
+
205
+		if (empty($this->_venue)) {
206
+			return '';
207
+		} //no venue so get out.
208
+
209
+		switch ($field) {
210
+			case 'title':
211
+				return $this->_venue->get('VNU_name');
212
+				break;
213
+
214
+			case 'description':
215
+				return $this->_venue->get('VNU_desc');
216
+				break;
217
+
218
+			case 'url':
219
+				$url = $this->_venue->get('VNU_url');
220
+				return empty($url) ? $this->_venue->get_permalink() : $url;
221
+				break;
222
+
223
+			case 'image':
224
+				return '<img src="' . $this->_venue->feature_image_url(array(200, 200,))
225
+					   . '" alt="' . sprintf(
226
+						   esc_attr__('%s Feature Image', 'event_espresso'),
227
+						   $this->_venue->get('VNU_name')
228
+					   ) . '" />';
229
+				break;
230
+
231
+			case 'phone':
232
+				return $this->_venue->get('VNU_phone');
233
+				break;
234
+
235
+			case 'address':
236
+				return $this->_venue->get('VNU_address');
237
+				break;
238
+
239
+			case 'address2':
240
+				return $this->_venue->get('VNU_address2');
241
+				break;
242
+
243
+			case 'city':
244
+				return $this->_venue->get('VNU_city');
245
+				break;
246
+
247
+			case 'state':
248
+				$state = $this->_venue->state_obj();
249
+				return is_object($state) ? $state->get('STA_name') : '';
250
+				break;
251
+
252
+			case 'country':
253
+				$country = $this->_venue->country_obj();
254
+				return is_object($country) ? $country->get('CNT_name') : '';
255
+				break;
256
+
257
+			case 'zip':
258
+				return $this->_venue->get('VNU_zip');
259
+				break;
260
+
261
+			case 'formatted_address':
262
+				return EEH_Address::format($this->_venue);
263
+				break;
264
+
265
+			case 'gmap_link':
266
+			case 'gmap_url':
267
+			case 'gmap_link_img':
268
+				$atts = $this->get_map_attributes($this->_venue, $field);
269
+				return EEH_Maps::google_map_link($atts);
270
+				break;
271
+		}
272
+		return '';
273
+	}
274
+
275
+
276
+	/**
277
+	 * Generates the attributes for retrieving a google_map artifact.
278
+	 * @param EE_Venue $venue
279
+	 * @param string   $field
280
+	 * @return array
281
+	 * @throws EE_Error
282
+	 */
283
+	protected function get_map_attributes(EE_Venue $venue, $field = 'gmap_link')
284
+	{
285
+		$state   = $venue->state_obj();
286
+		$country = $venue->country_obj();
287
+		$atts    = array(
288
+			'id'      => $venue->ID(),
289
+			'address' => $venue->get('VNU_address'),
290
+			'city'    => $venue->get('VNU_city'),
291
+			'state'   => is_object($state) ? $state->get('STA_name') : '',
292
+			'zip'     => $venue->get('VNU_zip'),
293
+			'country' => is_object($country) ? $country->get('CNT_name') : '',
294
+			'type'    => $field === 'gmap_link' ? 'url' : 'map',
295
+			'map_w'   => 200,
296
+			'map_h'   => 200,
297
+		);
298
+		if ($field === 'gmap_url') {
299
+			$atts['type'] = 'url_only';
300
+		}
301
+		return $atts;
302
+	}
303 303
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -77,7 +77,7 @@  discard block
 block discarded – undo
77 77
     {
78 78
         $this->_venue = $this->_get_venue();
79 79
         //If there is no venue object by now then get out.
80
-        if ( ! $this->_venue instanceof EE_Venue )
80
+        if ( ! $this->_venue instanceof EE_Venue)
81 81
             return '';
82 82
 
83 83
         switch ($shortcode) {
@@ -143,14 +143,14 @@  discard block
 block discarded – undo
143 143
 
144 144
         }
145 145
 
146
-        if ( strpos( $shortcode, '[VENUE_META_*' ) !== false ) {
147
-            $shortcode = str_replace( '[VENUE_META_*', '', $shortcode );
148
-            $shortcode = trim( str_replace( ']', '', $shortcode ) );
146
+        if (strpos($shortcode, '[VENUE_META_*') !== false) {
147
+            $shortcode = str_replace('[VENUE_META_*', '', $shortcode);
148
+            $shortcode = trim(str_replace(']', '', $shortcode));
149 149
 
150 150
             //pull the meta value from the venue post
151
-            $venue_meta = $this->_venue->get_post_meta( $shortcode, true );
151
+            $venue_meta = $this->_venue->get_post_meta($shortcode, true);
152 152
 
153
-            return ! empty( $venue_meta ) ? $venue_meta : '';
153
+            return ! empty($venue_meta) ? $venue_meta : '';
154 154
 
155 155
         }
156 156
     }
@@ -221,11 +221,11 @@  discard block
 block discarded – undo
221 221
                 break;
222 222
 
223 223
             case 'image':
224
-                return '<img src="' . $this->_venue->feature_image_url(array(200, 200,))
225
-                       . '" alt="' . sprintf(
224
+                return '<img src="'.$this->_venue->feature_image_url(array(200, 200,))
225
+                       . '" alt="'.sprintf(
226 226
                            esc_attr__('%s Feature Image', 'event_espresso'),
227 227
                            $this->_venue->get('VNU_name')
228
-                       ) . '" />';
228
+                       ).'" />';
229 229
                 break;
230 230
 
231 231
             case 'phone':
Please login to merge, or discard this patch.
Braces   +3 added lines, -2 removed lines patch added patch discarded remove patch
@@ -77,8 +77,9 @@
 block discarded – undo
77 77
     {
78 78
         $this->_venue = $this->_get_venue();
79 79
         //If there is no venue object by now then get out.
80
-        if ( ! $this->_venue instanceof EE_Venue )
81
-            return '';
80
+        if ( ! $this->_venue instanceof EE_Venue ) {
81
+                    return '';
82
+        }
82 83
 
83 84
         switch ($shortcode) {
84 85
             case '[VENUE_TITLE]':
Please login to merge, or discard this patch.
core/EE_System.core.php 2 patches
Spacing   +22 added lines, -22 removed lines patch added patch discarded remove patch
@@ -132,7 +132,7 @@  discard block
 block discarded – undo
132 132
         EE_Maintenance_Mode $maintenance_mode = null
133 133
     ) {
134 134
         // check if class object is instantiated
135
-        if (! self::$_instance instanceof EE_System) {
135
+        if ( ! self::$_instance instanceof EE_System) {
136 136
             self::$_instance = new self($registry, $loader, $capabilities, $request, $maintenance_mode);
137 137
         }
138 138
         return self::$_instance;
@@ -299,7 +299,7 @@  discard block
 block discarded – undo
299 299
     {
300 300
         // set autoloaders for all of the classes implementing EEI_Plugin_API
301 301
         // which provide helpers for EE plugin authors to more easily register certain components with EE.
302
-        EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'plugin_api');
302
+        EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_LIBRARIES.'plugin_api');
303 303
     }
304 304
 
305 305
 
@@ -336,7 +336,7 @@  discard block
 block discarded – undo
336 336
                 && in_array($_GET['action'], array('activate', 'activate-selected'), true)
337 337
             )
338 338
         ) {
339
-            include_once EE_THIRD_PARTY . 'wp-api-basic-auth' . DS . 'basic-auth.php';
339
+            include_once EE_THIRD_PARTY.'wp-api-basic-auth'.DS.'basic-auth.php';
340 340
         }
341 341
         do_action('AHEE__EE_System__load_espresso_addons__complete');
342 342
     }
@@ -444,11 +444,11 @@  discard block
 block discarded – undo
444 444
     private function fix_espresso_db_upgrade_option($espresso_db_update = null)
445 445
     {
446 446
         do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__begin', $espresso_db_update);
447
-        if (! $espresso_db_update) {
447
+        if ( ! $espresso_db_update) {
448 448
             $espresso_db_update = get_option('espresso_db_update');
449 449
         }
450 450
         // check that option is an array
451
-        if (! is_array($espresso_db_update)) {
451
+        if ( ! is_array($espresso_db_update)) {
452 452
             // if option is FALSE, then it never existed
453 453
             if ($espresso_db_update === false) {
454 454
                 // make $espresso_db_update an array and save option with autoload OFF
@@ -553,7 +553,7 @@  discard block
 block discarded – undo
553 553
      */
554 554
     public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null)
555 555
     {
556
-        if (! $version_history) {
556
+        if ( ! $version_history) {
557 557
             $version_history = $this->fix_espresso_db_upgrade_option($version_history);
558 558
         }
559 559
         if ($current_version_to_add === null) {
@@ -651,7 +651,7 @@  discard block
 block discarded – undo
651 651
         if ($activation_history_for_addon) {
652 652
             //it exists, so this isn't a completely new install
653 653
             //check if this version already in that list of previously installed versions
654
-            if (! isset($activation_history_for_addon[$version_to_upgrade_to])) {
654
+            if ( ! isset($activation_history_for_addon[$version_to_upgrade_to])) {
655 655
                 //it a version we haven't seen before
656 656
                 if ($version_is_higher === 1) {
657 657
                     $req_type = EE_System::req_type_upgrade;
@@ -731,7 +731,7 @@  discard block
 block discarded – undo
731 731
             foreach ($activation_history as $version => $times_activated) {
732 732
                 //check there is a record of when this version was activated. Otherwise,
733 733
                 //mark it as unknown
734
-                if (! $times_activated) {
734
+                if ( ! $times_activated) {
735 735
                     $times_activated = array('unknown-date');
736 736
                 }
737 737
                 if (is_string($times_activated)) {
@@ -831,7 +831,7 @@  discard block
 block discarded – undo
831 831
     private function _parse_model_names()
832 832
     {
833 833
         //get all the files in the EE_MODELS folder that end in .model.php
834
-        $models = glob(EE_MODELS . '*.model.php');
834
+        $models = glob(EE_MODELS.'*.model.php');
835 835
         $model_names = array();
836 836
         $non_abstract_db_models = array();
837 837
         foreach ($models as $model) {
@@ -861,8 +861,8 @@  discard block
 block discarded – undo
861 861
      */
862 862
     private function _maybe_brew_regular()
863 863
     {
864
-        if ((! defined('EE_DECAF') || EE_DECAF !== true) && is_readable(EE_CAFF_PATH . 'brewing_regular.php')) {
865
-            require_once EE_CAFF_PATH . 'brewing_regular.php';
864
+        if (( ! defined('EE_DECAF') || EE_DECAF !== true) && is_readable(EE_CAFF_PATH.'brewing_regular.php')) {
865
+            require_once EE_CAFF_PATH.'brewing_regular.php';
866 866
         }
867 867
     }
868 868
 
@@ -910,17 +910,17 @@  discard block
 block discarded – undo
910 910
         $class_names = EEH_Class_Tools::get_class_names_for_all_callbacks_on_hook(
911 911
             'AHEE__EE_System__register_shortcodes_modules_and_addons'
912 912
         );
913
-        if (! empty($class_names)) {
913
+        if ( ! empty($class_names)) {
914 914
             $msg = __(
915 915
                 'The following plugins, addons, or modules appear to be incompatible with this version of Event Espresso and were automatically deactivated to avoid fatal errors:',
916 916
                 'event_espresso'
917 917
             );
918 918
             $msg .= '<ul>';
919 919
             foreach ($class_names as $class_name) {
920
-                $msg .= '<li><b>Event Espresso - ' . str_replace(
920
+                $msg .= '<li><b>Event Espresso - '.str_replace(
921 921
                         array('EE_', 'EEM_', 'EED_', 'EES_', 'EEW_'), '',
922 922
                         $class_name
923
-                    ) . '</b></li>';
923
+                    ).'</b></li>';
924 924
             }
925 925
             $msg .= '</ul>';
926 926
             $msg .= __(
@@ -991,7 +991,7 @@  discard block
 block discarded – undo
991 991
     private function _deactivate_incompatible_addons()
992 992
     {
993 993
         $incompatible_addons = get_option('ee_incompatible_addons', array());
994
-        if (! empty($incompatible_addons)) {
994
+        if ( ! empty($incompatible_addons)) {
995 995
             $active_plugins = get_option('active_plugins', array());
996 996
             foreach ($active_plugins as $active_plugin) {
997 997
                 foreach ($incompatible_addons as $incompatible_addon) {
@@ -1052,10 +1052,10 @@  discard block
 block discarded – undo
1052 1052
     {
1053 1053
         do_action('AHEE__EE_System__load_controllers__start');
1054 1054
         // let's get it started
1055
-        if (! is_admin() && ! $this->maintenance_mode->level()) {
1055
+        if ( ! is_admin() && ! $this->maintenance_mode->level()) {
1056 1056
             do_action('AHEE__EE_System__load_controllers__load_front_controllers');
1057 1057
             $this->loader->getShared('EE_Front_Controller');
1058
-        } else if (! EE_FRONT_AJAX) {
1058
+        } else if ( ! EE_FRONT_AJAX) {
1059 1059
             do_action('AHEE__EE_System__load_controllers__load_admin_controllers');
1060 1060
             $this->loader->getShared('EE_Admin');
1061 1061
         }
@@ -1076,8 +1076,8 @@  discard block
 block discarded – undo
1076 1076
         $this->loader->getShared('EE_Session');
1077 1077
         do_action('AHEE__EE_System__core_loaded_and_ready');
1078 1078
         // load_espresso_template_tags
1079
-        if (is_readable(EE_PUBLIC . 'template_tags.php')) {
1080
-            require_once(EE_PUBLIC . 'template_tags.php');
1079
+        if (is_readable(EE_PUBLIC.'template_tags.php')) {
1080
+            require_once(EE_PUBLIC.'template_tags.php');
1081 1081
         }
1082 1082
         do_action('AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons');
1083 1083
         $this->loader->getShared('EventEspresso\core\services\assets\Registry');
@@ -1139,13 +1139,13 @@  discard block
 block discarded – undo
1139 1139
     public static function do_not_cache()
1140 1140
     {
1141 1141
         // set no cache constants
1142
-        if (! defined('DONOTCACHEPAGE')) {
1142
+        if ( ! defined('DONOTCACHEPAGE')) {
1143 1143
             define('DONOTCACHEPAGE', true);
1144 1144
         }
1145
-        if (! defined('DONOTCACHCEOBJECT')) {
1145
+        if ( ! defined('DONOTCACHCEOBJECT')) {
1146 1146
             define('DONOTCACHCEOBJECT', true);
1147 1147
         }
1148
-        if (! defined('DONOTCACHEDB')) {
1148
+        if ( ! defined('DONOTCACHEDB')) {
1149 1149
             define('DONOTCACHEDB', true);
1150 1150
         }
1151 1151
         // add no cache headers
Please login to merge, or discard this patch.
Indentation   +1182 added lines, -1182 removed lines patch added patch discarded remove patch
@@ -21,1188 +21,1188 @@
 block discarded – undo
21 21
 {
22 22
 
23 23
 
24
-    /**
25
-     * indicates this is a 'normal' request. Ie, not activation, nor upgrade, nor activation.
26
-     * So examples of this would be a normal GET request on the frontend or backend, or a POST, etc
27
-     */
28
-    const req_type_normal = 0;
29
-
30
-    /**
31
-     * Indicates this is a brand new installation of EE so we should install
32
-     * tables and default data etc
33
-     */
34
-    const req_type_new_activation = 1;
35
-
36
-    /**
37
-     * we've detected that EE has been reactivated (or EE was activated during maintenance mode,
38
-     * and we just exited maintenance mode). We MUST check the database is setup properly
39
-     * and that default data is setup too
40
-     */
41
-    const req_type_reactivation = 2;
42
-
43
-    /**
44
-     * indicates that EE has been upgraded since its previous request.
45
-     * We may have data migration scripts to call and will want to trigger maintenance mode
46
-     */
47
-    const req_type_upgrade = 3;
48
-
49
-    /**
50
-     * TODO  will detect that EE has been DOWNGRADED. We probably don't want to run in this case...
51
-     */
52
-    const req_type_downgrade = 4;
53
-
54
-    /**
55
-     * @deprecated since version 4.6.0.dev.006
56
-     * Now whenever a new_activation is detected the request type is still just
57
-     * new_activation (same for reactivation, upgrade, downgrade etc), but if we'r ein maintenance mode
58
-     * EE_System::initialize_db_if_no_migrations_required and EE_Addon::initialize_db_if_no_migrations_required
59
-     * will instead enqueue that EE plugin's db initialization for when we're taken out of maintenance mode.
60
-     * (Specifically, when the migration manager indicates migrations are finished
61
-     * EE_Data_Migration_Manager::initialize_db_for_enqueued_ee_plugins() will be called)
62
-     */
63
-    const req_type_activation_but_not_installed = 5;
64
-
65
-    /**
66
-     * option prefix for recording the activation history (like core's "espresso_db_update") of addons
67
-     */
68
-    const addon_activation_history_option_prefix = 'ee_addon_activation_history_';
69
-
70
-
71
-    /**
72
-     * @var EE_System $_instance
73
-     */
74
-    private static $_instance;
75
-
76
-    /**
77
-     * @var EE_Registry $registry
78
-     */
79
-    private $registry;
80
-
81
-    /**
82
-     * @var LoaderInterface $loader
83
-     */
84
-    private $loader;
85
-
86
-    /**
87
-     * @var EE_Capabilities $capabilities
88
-     */
89
-    private $capabilities;
90
-
91
-    /**
92
-     * @var EE_Request $request
93
-     */
94
-    private $request;
95
-
96
-    /**
97
-     * @var EE_Maintenance_Mode $maintenance_mode
98
-     */
99
-    private $maintenance_mode;
100
-
101
-    /**
102
-     * Stores which type of request this is, options being one of the constants on EE_System starting with req_type_*.
103
-     * It can be a brand-new activation, a reactivation, an upgrade, a downgrade, or a normal request.
104
-     *
105
-     * @var int $_req_type
106
-     */
107
-    private $_req_type;
108
-
109
-    /**
110
-     * Whether or not there was a non-micro version change in EE core version during this request
111
-     *
112
-     * @var boolean $_major_version_change
113
-     */
114
-    private $_major_version_change = false;
115
-
116
-
117
-
118
-    /**
119
-     * @singleton method used to instantiate class object
120
-     * @param EE_Registry|null         $registry
121
-     * @param LoaderInterface|null     $loader
122
-     * @param EE_Capabilities|null     $capabilities
123
-     * @param EE_Request|null          $request
124
-     * @param EE_Maintenance_Mode|null $maintenance_mode
125
-     * @return EE_System
126
-     */
127
-    public static function instance(
128
-        EE_Registry $registry = null,
129
-        LoaderInterface $loader = null,
130
-        EE_Capabilities $capabilities = null,
131
-        EE_Request $request = null,
132
-        EE_Maintenance_Mode $maintenance_mode = null
133
-    ) {
134
-        // check if class object is instantiated
135
-        if (! self::$_instance instanceof EE_System) {
136
-            self::$_instance = new self($registry, $loader, $capabilities, $request, $maintenance_mode);
137
-        }
138
-        return self::$_instance;
139
-    }
140
-
141
-
142
-
143
-    /**
144
-     * resets the instance and returns it
145
-     *
146
-     * @return EE_System
147
-     */
148
-    public static function reset()
149
-    {
150
-        self::$_instance->_req_type = null;
151
-        //make sure none of the old hooks are left hanging around
152
-        remove_all_actions('AHEE__EE_System__perform_activations_upgrades_and_migrations');
153
-        //we need to reset the migration manager in order for it to detect DMSs properly
154
-        EE_Data_Migration_Manager::reset();
155
-        self::instance()->detect_activations_or_upgrades();
156
-        self::instance()->perform_activations_upgrades_and_migrations();
157
-        return self::instance();
158
-    }
159
-
160
-
161
-
162
-    /**
163
-     * sets hooks for running rest of system
164
-     * provides "AHEE__EE_System__construct__complete" hook for EE Addons to use as their starting point
165
-     * starting EE Addons from any other point may lead to problems
166
-     *
167
-     * @param EE_Registry         $registry
168
-     * @param LoaderInterface     $loader
169
-     * @param EE_Capabilities     $capabilities
170
-     * @param EE_Request          $request
171
-     * @param EE_Maintenance_Mode $maintenance_mode
172
-     */
173
-    private function __construct(
174
-        EE_Registry $registry,
175
-        LoaderInterface $loader,
176
-        EE_Capabilities $capabilities,
177
-        EE_Request $request,
178
-        EE_Maintenance_Mode $maintenance_mode
179
-    ) {
180
-        $this->registry = $registry;
181
-        $this->loader = $loader;
182
-        $this->capabilities = $capabilities;
183
-        $this->request = $request;
184
-        $this->maintenance_mode = $maintenance_mode;
185
-        do_action('AHEE__EE_System__construct__begin', $this);
186
-        add_action(
187
-            'AHEE__EE_Bootstrap__load_espresso_addons',
188
-            array($this, 'loadCapabilities'),
189
-            5
190
-        );
191
-        add_action(
192
-            'AHEE__EE_Bootstrap__load_espresso_addons',
193
-            array($this, 'loadCommandBus'),
194
-            7
195
-        );
196
-        add_action(
197
-            'AHEE__EE_Bootstrap__load_espresso_addons',
198
-            array($this, 'loadPluginApi'),
199
-            9
200
-        );
201
-        // allow addons to load first so that they can register autoloaders, set hooks for running DMS's, etc
202
-        add_action(
203
-            'AHEE__EE_Bootstrap__load_espresso_addons',
204
-            array($this, 'load_espresso_addons')
205
-        );
206
-        // when an ee addon is activated, we want to call the core hook(s) again
207
-        // because the newly-activated addon didn't get a chance to run at all
208
-        add_action('activate_plugin', array($this, 'load_espresso_addons'), 1);
209
-        // detect whether install or upgrade
210
-        add_action(
211
-            'AHEE__EE_Bootstrap__detect_activations_or_upgrades',
212
-            array($this, 'detect_activations_or_upgrades'),
213
-            3
214
-        );
215
-        // load EE_Config, EE_Textdomain, etc
216
-        add_action(
217
-            'AHEE__EE_Bootstrap__load_core_configuration',
218
-            array($this, 'load_core_configuration'),
219
-            5
220
-        );
221
-        // load EE_Config, EE_Textdomain, etc
222
-        add_action(
223
-            'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets',
224
-            array($this, 'register_shortcodes_modules_and_widgets'),
225
-            7
226
-        );
227
-        // you wanna get going? I wanna get going... let's get going!
228
-        add_action(
229
-            'AHEE__EE_Bootstrap__brew_espresso',
230
-            array($this, 'brew_espresso'),
231
-            9
232
-        );
233
-        //other housekeeping
234
-        //exclude EE critical pages from wp_list_pages
235
-        add_filter(
236
-            'wp_list_pages_excludes',
237
-            array($this, 'remove_pages_from_wp_list_pages'),
238
-            10
239
-        );
240
-        // ALL EE Addons should use the following hook point to attach their initial setup too
241
-        // it's extremely important for EE Addons to register any class autoloaders so that they can be available when the EE_Config loads
242
-        do_action('AHEE__EE_System__construct__complete', $this);
243
-    }
244
-
245
-
246
-
247
-    /**
248
-     * load and setup EE_Capabilities
249
-     *
250
-     * @return void
251
-     * @throws EE_Error
252
-     */
253
-    public function loadCapabilities()
254
-    {
255
-        $this->loader->getShared('EE_Capabilities');
256
-        add_action(
257
-            'AHEE__EE_Capabilities__init_caps__before_initialization',
258
-            function() {
259
-                LoaderFactory::getLoader()->getShared('Payment_Method_Manager');
260
-            }
261
-        );
262
-    }
263
-
264
-
265
-
266
-    /**
267
-     * create and cache the CommandBus, and also add middleware
268
-     * The CapChecker middleware requires the use of EE_Capabilities
269
-     * which is why we need to load the CommandBus after Caps are set up
270
-     *
271
-     * @return void
272
-     * @throws EE_Error
273
-     */
274
-    public function loadCommandBus()
275
-    {
276
-        $this->loader->getShared(
277
-            'CommandBusInterface',
278
-            array(
279
-                null,
280
-                apply_filters(
281
-                    'FHEE__EE_Load_Espresso_Core__handle_request__CommandBus_middleware',
282
-                    array(
283
-                        $this->loader->getShared('EventEspresso\core\services\commands\middleware\CapChecker'),
284
-                        $this->loader->getShared('EventEspresso\core\services\commands\middleware\AddActionHook'),
285
-                    )
286
-                ),
287
-            )
288
-        );
289
-    }
290
-
291
-
292
-
293
-    /**
294
-     * @return void
295
-     * @throws EE_Error
296
-     */
297
-    public function loadPluginApi()
298
-    {
299
-        // set autoloaders for all of the classes implementing EEI_Plugin_API
300
-        // which provide helpers for EE plugin authors to more easily register certain components with EE.
301
-        EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'plugin_api');
302
-    }
303
-
304
-
305
-
306
-    /**
307
-     * load_espresso_addons
308
-     * allow addons to load first so that they can set hooks for running DMS's, etc
309
-     * this is hooked into both:
310
-     *    'AHEE__EE_Bootstrap__load_core_configuration'
311
-     *        which runs during the WP 'plugins_loaded' action at priority 5
312
-     *    and the WP 'activate_plugin' hook point
313
-     *
314
-     * @access public
315
-     * @return void
316
-     * @throws EE_Error
317
-     */
318
-    public function load_espresso_addons()
319
-    {
320
-        do_action('AHEE__EE_System__load_espresso_addons');
321
-        //if the WP API basic auth plugin isn't already loaded, load it now.
322
-        //We want it for mobile apps. Just include the entire plugin
323
-        //also, don't load the basic auth when a plugin is getting activated, because
324
-        //it could be the basic auth plugin, and it doesn't check if its methods are already defined
325
-        //and causes a fatal error
326
-        if (
327
-            ! (
328
-                isset($_GET['activate'])
329
-                && $_GET['activate'] === 'true'
330
-            )
331
-            && ! function_exists('json_basic_auth_handler')
332
-            && ! function_exists('json_basic_auth_error')
333
-            && ! (
334
-                isset($_GET['action'])
335
-                && in_array($_GET['action'], array('activate', 'activate-selected'), true)
336
-            )
337
-        ) {
338
-            include_once EE_THIRD_PARTY . 'wp-api-basic-auth' . DS . 'basic-auth.php';
339
-        }
340
-        do_action('AHEE__EE_System__load_espresso_addons__complete');
341
-    }
342
-
343
-
344
-
345
-    /**
346
-     * detect_activations_or_upgrades
347
-     * Checks for activation or upgrade of core first;
348
-     * then also checks if any registered addons have been activated or upgraded
349
-     * This is hooked into 'AHEE__EE_Bootstrap__detect_activations_or_upgrades'
350
-     * which runs during the WP 'plugins_loaded' action at priority 3
351
-     *
352
-     * @access public
353
-     * @return void
354
-     */
355
-    public function detect_activations_or_upgrades()
356
-    {
357
-        //first off: let's make sure to handle core
358
-        $this->detect_if_activation_or_upgrade();
359
-        foreach ($this->registry->addons as $addon) {
360
-            if ($addon instanceof EE_Addon) {
361
-                //detect teh request type for that addon
362
-                $addon->detect_activation_or_upgrade();
363
-            }
364
-        }
365
-    }
366
-
367
-
368
-
369
-    /**
370
-     * detect_if_activation_or_upgrade
371
-     * Takes care of detecting whether this is a brand new install or code upgrade,
372
-     * and either setting up the DB or setting up maintenance mode etc.
373
-     *
374
-     * @access public
375
-     * @return void
376
-     */
377
-    public function detect_if_activation_or_upgrade()
378
-    {
379
-        do_action('AHEE__EE_System___detect_if_activation_or_upgrade__begin');
380
-        // check if db has been updated, or if its a brand-new installation
381
-        $espresso_db_update = $this->fix_espresso_db_upgrade_option();
382
-        $request_type = $this->detect_req_type($espresso_db_update);
383
-        //EEH_Debug_Tools::printr( $request_type, '$request_type', __FILE__, __LINE__ );
384
-        switch ($request_type) {
385
-            case EE_System::req_type_new_activation:
386
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__new_activation');
387
-                $this->_handle_core_version_change($espresso_db_update);
388
-                break;
389
-            case EE_System::req_type_reactivation:
390
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__reactivation');
391
-                $this->_handle_core_version_change($espresso_db_update);
392
-                break;
393
-            case EE_System::req_type_upgrade:
394
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__upgrade');
395
-                //migrations may be required now that we've upgraded
396
-                $this->maintenance_mode->set_maintenance_mode_if_db_old();
397
-                $this->_handle_core_version_change($espresso_db_update);
398
-                //				echo "done upgrade";die;
399
-                break;
400
-            case EE_System::req_type_downgrade:
401
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__downgrade');
402
-                //its possible migrations are no longer required
403
-                $this->maintenance_mode->set_maintenance_mode_if_db_old();
404
-                $this->_handle_core_version_change($espresso_db_update);
405
-                break;
406
-            case EE_System::req_type_normal:
407
-            default:
408
-                //				$this->_maybe_redirect_to_ee_about();
409
-                break;
410
-        }
411
-        do_action('AHEE__EE_System__detect_if_activation_or_upgrade__complete');
412
-    }
413
-
414
-
415
-
416
-    /**
417
-     * Updates the list of installed versions and sets hooks for
418
-     * initializing the database later during the request
419
-     *
420
-     * @param array $espresso_db_update
421
-     */
422
-    private function _handle_core_version_change($espresso_db_update)
423
-    {
424
-        $this->update_list_of_installed_versions($espresso_db_update);
425
-        //get ready to verify the DB is ok (provided we aren't in maintenance mode, of course)
426
-        add_action(
427
-            'AHEE__EE_System__perform_activations_upgrades_and_migrations',
428
-            array($this, 'initialize_db_if_no_migrations_required')
429
-        );
430
-    }
431
-
432
-
433
-
434
-    /**
435
-     * standardizes the wp option 'espresso_db_upgrade' which actually stores
436
-     * information about what versions of EE have been installed and activated,
437
-     * NOT necessarily the state of the database
438
-     *
439
-     * @param mixed $espresso_db_update the value of the WordPress option.
440
-     *                                            If not supplied, fetches it from the options table
441
-     * @return array the correct value of 'espresso_db_upgrade', after saving it, if it needed correction
442
-     */
443
-    private function fix_espresso_db_upgrade_option($espresso_db_update = null)
444
-    {
445
-        do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__begin', $espresso_db_update);
446
-        if (! $espresso_db_update) {
447
-            $espresso_db_update = get_option('espresso_db_update');
448
-        }
449
-        // check that option is an array
450
-        if (! is_array($espresso_db_update)) {
451
-            // if option is FALSE, then it never existed
452
-            if ($espresso_db_update === false) {
453
-                // make $espresso_db_update an array and save option with autoload OFF
454
-                $espresso_db_update = array();
455
-                add_option('espresso_db_update', $espresso_db_update, '', 'no');
456
-            } else {
457
-                // option is NOT FALSE but also is NOT an array, so make it an array and save it
458
-                $espresso_db_update = array($espresso_db_update => array());
459
-                update_option('espresso_db_update', $espresso_db_update);
460
-            }
461
-        } else {
462
-            $corrected_db_update = array();
463
-            //if IS an array, but is it an array where KEYS are version numbers, and values are arrays?
464
-            foreach ($espresso_db_update as $should_be_version_string => $should_be_array) {
465
-                if (is_int($should_be_version_string) && ! is_array($should_be_array)) {
466
-                    //the key is an int, and the value IS NOT an array
467
-                    //so it must be numerically-indexed, where values are versions installed...
468
-                    //fix it!
469
-                    $version_string = $should_be_array;
470
-                    $corrected_db_update[$version_string] = array('unknown-date');
471
-                } else {
472
-                    //ok it checks out
473
-                    $corrected_db_update[$should_be_version_string] = $should_be_array;
474
-                }
475
-            }
476
-            $espresso_db_update = $corrected_db_update;
477
-            update_option('espresso_db_update', $espresso_db_update);
478
-        }
479
-        do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__complete', $espresso_db_update);
480
-        return $espresso_db_update;
481
-    }
482
-
483
-
484
-
485
-    /**
486
-     * Does the traditional work of setting up the plugin's database and adding default data.
487
-     * If migration script/process did not exist, this is what would happen on every activation/reactivation/upgrade.
488
-     * NOTE: if we're in maintenance mode (which would be the case if we detect there are data
489
-     * migration scripts that need to be run and a version change happens), enqueues core for database initialization,
490
-     * so that it will be done when migrations are finished
491
-     *
492
-     * @param boolean $initialize_addons_too if true, we double-check addons' database tables etc too;
493
-     * @param boolean $verify_schema         if true will re-check the database tables have the correct schema.
494
-     *                                       This is a resource-intensive job
495
-     *                                       so we prefer to only do it when necessary
496
-     * @return void
497
-     * @throws EE_Error
498
-     */
499
-    public function initialize_db_if_no_migrations_required($initialize_addons_too = false, $verify_schema = true)
500
-    {
501
-        $request_type = $this->detect_req_type();
502
-        //only initialize system if we're not in maintenance mode.
503
-        if ($this->maintenance_mode->level() !== EE_Maintenance_Mode::level_2_complete_maintenance) {
504
-            update_option('ee_flush_rewrite_rules', true);
505
-            if ($verify_schema) {
506
-                EEH_Activation::initialize_db_and_folders();
507
-            }
508
-            EEH_Activation::initialize_db_content();
509
-            EEH_Activation::system_initialization();
510
-            if ($initialize_addons_too) {
511
-                $this->initialize_addons();
512
-            }
513
-        } else {
514
-            EE_Data_Migration_Manager::instance()->enqueue_db_initialization_for('Core');
515
-        }
516
-        if ($request_type === EE_System::req_type_new_activation
517
-            || $request_type === EE_System::req_type_reactivation
518
-            || (
519
-                $request_type === EE_System::req_type_upgrade
520
-                && $this->is_major_version_change()
521
-            )
522
-        ) {
523
-            add_action('AHEE__EE_System__initialize_last', array($this, 'redirect_to_about_ee'), 9);
524
-        }
525
-    }
526
-
527
-
528
-
529
-    /**
530
-     * Initializes the db for all registered addons
531
-     *
532
-     * @throws EE_Error
533
-     */
534
-    public function initialize_addons()
535
-    {
536
-        //foreach registered addon, make sure its db is up-to-date too
537
-        foreach ($this->registry->addons as $addon) {
538
-            if ($addon instanceof EE_Addon) {
539
-                $addon->initialize_db_if_no_migrations_required();
540
-            }
541
-        }
542
-    }
543
-
544
-
545
-
546
-    /**
547
-     * Adds the current code version to the saved wp option which stores a list of all ee versions ever installed.
548
-     *
549
-     * @param    array  $version_history
550
-     * @param    string $current_version_to_add version to be added to the version history
551
-     * @return    boolean success as to whether or not this option was changed
552
-     */
553
-    public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null)
554
-    {
555
-        if (! $version_history) {
556
-            $version_history = $this->fix_espresso_db_upgrade_option($version_history);
557
-        }
558
-        if ($current_version_to_add === null) {
559
-            $current_version_to_add = espresso_version();
560
-        }
561
-        $version_history[$current_version_to_add][] = date('Y-m-d H:i:s', time());
562
-        // re-save
563
-        return update_option('espresso_db_update', $version_history);
564
-    }
565
-
566
-
567
-
568
-    /**
569
-     * Detects if the current version indicated in the has existed in the list of
570
-     * previously-installed versions of EE (espresso_db_update). Does NOT modify it (ie, no side-effect)
571
-     *
572
-     * @param array $espresso_db_update array from the wp option stored under the name 'espresso_db_update'.
573
-     *                                  If not supplied, fetches it from the options table.
574
-     *                                  Also, caches its result so later parts of the code can also know whether
575
-     *                                  there's been an update or not. This way we can add the current version to
576
-     *                                  espresso_db_update, but still know if this is a new install or not
577
-     * @return int one of the constants on EE_System::req_type_
578
-     */
579
-    public function detect_req_type($espresso_db_update = null)
580
-    {
581
-        if ($this->_req_type === null) {
582
-            $espresso_db_update = ! empty($espresso_db_update)
583
-                ? $espresso_db_update
584
-                : $this->fix_espresso_db_upgrade_option();
585
-            $this->_req_type = EE_System::detect_req_type_given_activation_history(
586
-                $espresso_db_update,
587
-                'ee_espresso_activation', espresso_version()
588
-            );
589
-            $this->_major_version_change = $this->_detect_major_version_change($espresso_db_update);
590
-        }
591
-        return $this->_req_type;
592
-    }
593
-
594
-
595
-
596
-    /**
597
-     * Returns whether or not there was a non-micro version change (ie, change in either
598
-     * the first or second number in the version. Eg 4.9.0.rc.001 to 4.10.0.rc.000,
599
-     * but not 4.9.0.rc.0001 to 4.9.1.rc.0001
600
-     *
601
-     * @param $activation_history
602
-     * @return bool
603
-     */
604
-    private function _detect_major_version_change($activation_history)
605
-    {
606
-        $previous_version = EE_System::_get_most_recently_active_version_from_activation_history($activation_history);
607
-        $previous_version_parts = explode('.', $previous_version);
608
-        $current_version_parts = explode('.', espresso_version());
609
-        return isset($previous_version_parts[0], $previous_version_parts[1], $current_version_parts[0], $current_version_parts[1])
610
-               && ($previous_version_parts[0] !== $current_version_parts[0]
611
-                   || $previous_version_parts[1] !== $current_version_parts[1]
612
-               );
613
-    }
614
-
615
-
616
-
617
-    /**
618
-     * Returns true if either the major or minor version of EE changed during this request.
619
-     * Eg 4.9.0.rc.001 to 4.10.0.rc.000, but not 4.9.0.rc.0001 to 4.9.1.rc.0001
620
-     *
621
-     * @return bool
622
-     */
623
-    public function is_major_version_change()
624
-    {
625
-        return $this->_major_version_change;
626
-    }
627
-
628
-
629
-
630
-    /**
631
-     * Determines the request type for any ee addon, given three piece of info: the current array of activation
632
-     * histories (for core that' 'espresso_db_update' wp option); the name of the WordPress option which is temporarily
633
-     * set upon activation of the plugin (for core it's 'ee_espresso_activation'); and the version that this plugin was
634
-     * just activated to (for core that will always be espresso_version())
635
-     *
636
-     * @param array  $activation_history_for_addon     the option's value which stores the activation history for this
637
-     *                                                 ee plugin. for core that's 'espresso_db_update'
638
-     * @param string $activation_indicator_option_name the name of the WordPress option that is temporarily set to
639
-     *                                                 indicate that this plugin was just activated
640
-     * @param string $version_to_upgrade_to            the version that was just upgraded to (for core that will be
641
-     *                                                 espresso_version())
642
-     * @return int one of the constants on EE_System::req_type_*
643
-     */
644
-    public static function detect_req_type_given_activation_history(
645
-        $activation_history_for_addon,
646
-        $activation_indicator_option_name,
647
-        $version_to_upgrade_to
648
-    ) {
649
-        $version_is_higher = self::_new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to);
650
-        if ($activation_history_for_addon) {
651
-            //it exists, so this isn't a completely new install
652
-            //check if this version already in that list of previously installed versions
653
-            if (! isset($activation_history_for_addon[$version_to_upgrade_to])) {
654
-                //it a version we haven't seen before
655
-                if ($version_is_higher === 1) {
656
-                    $req_type = EE_System::req_type_upgrade;
657
-                } else {
658
-                    $req_type = EE_System::req_type_downgrade;
659
-                }
660
-                delete_option($activation_indicator_option_name);
661
-            } else {
662
-                // its not an update. maybe a reactivation?
663
-                if (get_option($activation_indicator_option_name, false)) {
664
-                    if ($version_is_higher === -1) {
665
-                        $req_type = EE_System::req_type_downgrade;
666
-                    } else if ($version_is_higher === 0) {
667
-                        //we've seen this version before, but it's an activation. must be a reactivation
668
-                        $req_type = EE_System::req_type_reactivation;
669
-                    } else {//$version_is_higher === 1
670
-                        $req_type = EE_System::req_type_upgrade;
671
-                    }
672
-                    delete_option($activation_indicator_option_name);
673
-                } else {
674
-                    //we've seen this version before and the activation indicate doesn't show it was just activated
675
-                    if ($version_is_higher === -1) {
676
-                        $req_type = EE_System::req_type_downgrade;
677
-                    } else if ($version_is_higher === 0) {
678
-                        //we've seen this version before and it's not an activation. its normal request
679
-                        $req_type = EE_System::req_type_normal;
680
-                    } else {//$version_is_higher === 1
681
-                        $req_type = EE_System::req_type_upgrade;
682
-                    }
683
-                }
684
-            }
685
-        } else {
686
-            //brand new install
687
-            $req_type = EE_System::req_type_new_activation;
688
-            delete_option($activation_indicator_option_name);
689
-        }
690
-        return $req_type;
691
-    }
692
-
693
-
694
-
695
-    /**
696
-     * Detects if the $version_to_upgrade_to is higher than the most recent version in
697
-     * the $activation_history_for_addon
698
-     *
699
-     * @param array  $activation_history_for_addon (keys are versions, values are arrays of times activated,
700
-     *                                             sometimes containing 'unknown-date'
701
-     * @param string $version_to_upgrade_to        (current version)
702
-     * @return int results of version_compare( $version_to_upgrade_to, $most_recently_active_version ).
703
-     *                                             ie, -1 if $version_to_upgrade_to is LOWER (downgrade);
704
-     *                                             0 if $version_to_upgrade_to MATCHES (reactivation or normal request);
705
-     *                                             1 if $version_to_upgrade_to is HIGHER (upgrade) ;
706
-     */
707
-    private static function _new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to)
708
-    {
709
-        //find the most recently-activated version
710
-        $most_recently_active_version =
711
-            EE_System::_get_most_recently_active_version_from_activation_history($activation_history_for_addon);
712
-        return version_compare($version_to_upgrade_to, $most_recently_active_version);
713
-    }
714
-
715
-
716
-
717
-    /**
718
-     * Gets the most recently active version listed in the activation history,
719
-     * and if none are found (ie, it's a brand new install) returns '0.0.0.dev.000'.
720
-     *
721
-     * @param array $activation_history  (keys are versions, values are arrays of times activated,
722
-     *                                   sometimes containing 'unknown-date'
723
-     * @return string
724
-     */
725
-    private static function _get_most_recently_active_version_from_activation_history($activation_history)
726
-    {
727
-        $most_recently_active_version_activation = '1970-01-01 00:00:00';
728
-        $most_recently_active_version = '0.0.0.dev.000';
729
-        if (is_array($activation_history)) {
730
-            foreach ($activation_history as $version => $times_activated) {
731
-                //check there is a record of when this version was activated. Otherwise,
732
-                //mark it as unknown
733
-                if (! $times_activated) {
734
-                    $times_activated = array('unknown-date');
735
-                }
736
-                if (is_string($times_activated)) {
737
-                    $times_activated = array($times_activated);
738
-                }
739
-                foreach ($times_activated as $an_activation) {
740
-                    if ($an_activation !== 'unknown-date' && $an_activation > $most_recently_active_version_activation) {
741
-                        $most_recently_active_version = $version;
742
-                        $most_recently_active_version_activation = $an_activation === 'unknown-date'
743
-                            ? '1970-01-01 00:00:00'
744
-                            : $an_activation;
745
-                    }
746
-                }
747
-            }
748
-        }
749
-        return $most_recently_active_version;
750
-    }
751
-
752
-
753
-
754
-    /**
755
-     * This redirects to the about EE page after activation
756
-     *
757
-     * @return void
758
-     */
759
-    public function redirect_to_about_ee()
760
-    {
761
-        $notices = EE_Error::get_notices(false);
762
-        //if current user is an admin and it's not an ajax or rest request
763
-        if (
764
-            ! (defined('DOING_AJAX') && DOING_AJAX)
765
-            && ! (defined('REST_REQUEST') && REST_REQUEST)
766
-            && ! isset($notices['errors'])
767
-            && apply_filters(
768
-                'FHEE__EE_System__redirect_to_about_ee__do_redirect',
769
-                $this->capabilities->current_user_can('manage_options', 'espresso_about_default')
770
-            )
771
-        ) {
772
-            $query_params = array('page' => 'espresso_about');
773
-            if (EE_System::instance()->detect_req_type() === EE_System::req_type_new_activation) {
774
-                $query_params['new_activation'] = true;
775
-            }
776
-            if (EE_System::instance()->detect_req_type() === EE_System::req_type_reactivation) {
777
-                $query_params['reactivation'] = true;
778
-            }
779
-            $url = add_query_arg($query_params, admin_url('admin.php'));
780
-            wp_safe_redirect($url);
781
-            exit();
782
-        }
783
-    }
784
-
785
-
786
-
787
-    /**
788
-     * load_core_configuration
789
-     * this is hooked into 'AHEE__EE_Bootstrap__load_core_configuration'
790
-     * which runs during the WP 'plugins_loaded' action at priority 5
791
-     *
792
-     * @return void
793
-     * @throws ReflectionException
794
-     */
795
-    public function load_core_configuration()
796
-    {
797
-        do_action('AHEE__EE_System__load_core_configuration__begin', $this);
798
-        $this->loader->getShared('EE_Load_Textdomain');
799
-        //load textdomain
800
-        EE_Load_Textdomain::load_textdomain();
801
-        // load and setup EE_Config and EE_Network_Config
802
-        $config = $this->loader->getShared('EE_Config');
803
-        $this->loader->getShared('EE_Network_Config');
804
-        // setup autoloaders
805
-        // enable logging?
806
-        if ($config->admin->use_full_logging) {
807
-            $this->loader->getShared('EE_Log');
808
-        }
809
-        // check for activation errors
810
-        $activation_errors = get_option('ee_plugin_activation_errors', false);
811
-        if ($activation_errors) {
812
-            EE_Error::add_error($activation_errors, __FILE__, __FUNCTION__, __LINE__);
813
-            update_option('ee_plugin_activation_errors', false);
814
-        }
815
-        // get model names
816
-        $this->_parse_model_names();
817
-        //load caf stuff a chance to play during the activation process too.
818
-        $this->_maybe_brew_regular();
819
-        do_action('AHEE__EE_System__load_core_configuration__complete', $this);
820
-    }
821
-
822
-
823
-
824
-    /**
825
-     * cycles through all of the models/*.model.php files, and assembles an array of model names
826
-     *
827
-     * @return void
828
-     * @throws ReflectionException
829
-     */
830
-    private function _parse_model_names()
831
-    {
832
-        //get all the files in the EE_MODELS folder that end in .model.php
833
-        $models = glob(EE_MODELS . '*.model.php');
834
-        $model_names = array();
835
-        $non_abstract_db_models = array();
836
-        foreach ($models as $model) {
837
-            // get model classname
838
-            $classname = EEH_File::get_classname_from_filepath_with_standard_filename($model);
839
-            $short_name = str_replace('EEM_', '', $classname);
840
-            $reflectionClass = new ReflectionClass($classname);
841
-            if ($reflectionClass->isSubclassOf('EEM_Base') && ! $reflectionClass->isAbstract()) {
842
-                $non_abstract_db_models[$short_name] = $classname;
843
-            }
844
-            $model_names[$short_name] = $classname;
845
-        }
846
-        $this->registry->models = apply_filters('FHEE__EE_System__parse_model_names', $model_names);
847
-        $this->registry->non_abstract_db_models = apply_filters(
848
-            'FHEE__EE_System__parse_implemented_model_names',
849
-            $non_abstract_db_models
850
-        );
851
-    }
852
-
853
-
854
-
855
-    /**
856
-     * The purpose of this method is to simply check for a file named "caffeinated/brewing_regular.php" for any hooks
857
-     * that need to be setup before our EE_System launches.
858
-     *
859
-     * @return void
860
-     */
861
-    private function _maybe_brew_regular()
862
-    {
863
-        if ((! defined('EE_DECAF') || EE_DECAF !== true) && is_readable(EE_CAFF_PATH . 'brewing_regular.php')) {
864
-            require_once EE_CAFF_PATH . 'brewing_regular.php';
865
-        }
866
-    }
867
-
868
-
869
-
870
-    /**
871
-     * register_shortcodes_modules_and_widgets
872
-     * generate lists of shortcodes and modules, then verify paths and classes
873
-     * This is hooked into 'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets'
874
-     * which runs during the WP 'plugins_loaded' action at priority 7
875
-     *
876
-     * @access public
877
-     * @return void
878
-     * @throws Exception
879
-     */
880
-    public function register_shortcodes_modules_and_widgets()
881
-    {
882
-        try {
883
-            // load, register, and add shortcodes the new way
884
-            $this->loader->getShared(
885
-                'EventEspresso\core\services\shortcodes\ShortcodesManager',
886
-                array(
887
-                    // and the old way, but we'll put it under control of the new system
888
-                    EE_Config::getLegacyShortcodesManager()
889
-                )
890
-            );
891
-        } catch (Exception $exception) {
892
-            new ExceptionStackTraceDisplay($exception);
893
-        }
894
-        do_action('AHEE__EE_System__register_shortcodes_modules_and_widgets');
895
-        // check for addons using old hook point
896
-        if (has_action('AHEE__EE_System__register_shortcodes_modules_and_addons')) {
897
-            $this->_incompatible_addon_error();
898
-        }
899
-    }
900
-
901
-
902
-
903
-    /**
904
-     * _incompatible_addon_error
905
-     *
906
-     * @access public
907
-     * @return void
908
-     */
909
-    private function _incompatible_addon_error()
910
-    {
911
-        // get array of classes hooking into here
912
-        $class_names = EEH_Class_Tools::get_class_names_for_all_callbacks_on_hook(
913
-            'AHEE__EE_System__register_shortcodes_modules_and_addons'
914
-        );
915
-        if (! empty($class_names)) {
916
-            $msg = __(
917
-                'The following plugins, addons, or modules appear to be incompatible with this version of Event Espresso and were automatically deactivated to avoid fatal errors:',
918
-                'event_espresso'
919
-            );
920
-            $msg .= '<ul>';
921
-            foreach ($class_names as $class_name) {
922
-                $msg .= '<li><b>Event Espresso - ' . str_replace(
923
-                        array('EE_', 'EEM_', 'EED_', 'EES_', 'EEW_'), '',
924
-                        $class_name
925
-                    ) . '</b></li>';
926
-            }
927
-            $msg .= '</ul>';
928
-            $msg .= __(
929
-                'Compatibility issues can be avoided and/or resolved by keeping addons and plugins updated to the latest version.',
930
-                'event_espresso'
931
-            );
932
-            // save list of incompatible addons to wp-options for later use
933
-            add_option('ee_incompatible_addons', $class_names, '', 'no');
934
-            if (is_admin()) {
935
-                EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
936
-            }
937
-        }
938
-    }
939
-
940
-
941
-
942
-    /**
943
-     * brew_espresso
944
-     * begins the process of setting hooks for initializing EE in the correct order
945
-     * This is happening on the 'AHEE__EE_Bootstrap__brew_espresso' hook point
946
-     * which runs during the WP 'plugins_loaded' action at priority 9
947
-     *
948
-     * @return void
949
-     */
950
-    public function brew_espresso()
951
-    {
952
-        do_action('AHEE__EE_System__brew_espresso__begin', $this);
953
-        // load some final core systems
954
-        add_action('init', array($this, 'set_hooks_for_core'), 1);
955
-        add_action('init', array($this, 'perform_activations_upgrades_and_migrations'), 3);
956
-        add_action('init', array($this, 'load_CPTs_and_session'), 5);
957
-        add_action('init', array($this, 'load_controllers'), 7);
958
-        add_action('init', array($this, 'core_loaded_and_ready'), 9);
959
-        add_action('init', array($this, 'initialize'), 10);
960
-        add_action('init', array($this, 'initialize_last'), 100);
961
-        if (is_admin() && apply_filters('FHEE__EE_System__brew_espresso__load_pue', true)) {
962
-            // pew pew pew
963
-            $this->loader->getShared('EE_PUE');
964
-            do_action('AHEE__EE_System__brew_espresso__after_pue_init');
965
-        }
966
-        do_action('AHEE__EE_System__brew_espresso__complete', $this);
967
-    }
968
-
969
-
970
-
971
-    /**
972
-     *    set_hooks_for_core
973
-     *
974
-     * @access public
975
-     * @return    void
976
-     * @throws EE_Error
977
-     */
978
-    public function set_hooks_for_core()
979
-    {
980
-        $this->_deactivate_incompatible_addons();
981
-        do_action('AHEE__EE_System__set_hooks_for_core');
982
-        //caps need to be initialized on every request so that capability maps are set.
983
-        //@see https://events.codebasehq.com/projects/event-espresso/tickets/8674
984
-        $this->registry->CAP->init_caps();
985
-    }
986
-
987
-
988
-
989
-    /**
990
-     * Using the information gathered in EE_System::_incompatible_addon_error,
991
-     * deactivates any addons considered incompatible with the current version of EE
992
-     */
993
-    private function _deactivate_incompatible_addons()
994
-    {
995
-        $incompatible_addons = get_option('ee_incompatible_addons', array());
996
-        if (! empty($incompatible_addons)) {
997
-            $active_plugins = get_option('active_plugins', array());
998
-            foreach ($active_plugins as $active_plugin) {
999
-                foreach ($incompatible_addons as $incompatible_addon) {
1000
-                    if (strpos($active_plugin, $incompatible_addon) !== false) {
1001
-                        unset($_GET['activate']);
1002
-                        espresso_deactivate_plugin($active_plugin);
1003
-                    }
1004
-                }
1005
-            }
1006
-        }
1007
-    }
1008
-
1009
-
1010
-
1011
-    /**
1012
-     *    perform_activations_upgrades_and_migrations
1013
-     *
1014
-     * @access public
1015
-     * @return    void
1016
-     */
1017
-    public function perform_activations_upgrades_and_migrations()
1018
-    {
1019
-        //first check if we had previously attempted to setup EE's directories but failed
1020
-        if (EEH_Activation::upload_directories_incomplete()) {
1021
-            EEH_Activation::create_upload_directories();
1022
-        }
1023
-        do_action('AHEE__EE_System__perform_activations_upgrades_and_migrations');
1024
-    }
1025
-
1026
-
1027
-
1028
-    /**
1029
-     *    load_CPTs_and_session
1030
-     *
1031
-     * @access public
1032
-     * @return    void
1033
-     */
1034
-    public function load_CPTs_and_session()
1035
-    {
1036
-        do_action('AHEE__EE_System__load_CPTs_and_session__start');
1037
-        // register Custom Post Types
1038
-        $this->loader->getShared('EE_Register_CPTs');
1039
-        do_action('AHEE__EE_System__load_CPTs_and_session__complete');
1040
-    }
1041
-
1042
-
1043
-
1044
-    /**
1045
-     * load_controllers
1046
-     * this is the best place to load any additional controllers that needs access to EE core.
1047
-     * it is expected that all basic core EE systems, that are not dependant on the current request are loaded at this
1048
-     * time
1049
-     *
1050
-     * @access public
1051
-     * @return void
1052
-     */
1053
-    public function load_controllers()
1054
-    {
1055
-        do_action('AHEE__EE_System__load_controllers__start');
1056
-        // let's get it started
1057
-        if (! is_admin() && ! $this->maintenance_mode->level()) {
1058
-            do_action('AHEE__EE_System__load_controllers__load_front_controllers');
1059
-            $this->loader->getShared('EE_Front_Controller');
1060
-        } else if (! EE_FRONT_AJAX) {
1061
-            do_action('AHEE__EE_System__load_controllers__load_admin_controllers');
1062
-            $this->loader->getShared('EE_Admin');
1063
-        }
1064
-        do_action('AHEE__EE_System__load_controllers__complete');
1065
-    }
1066
-
1067
-
1068
-
1069
-    /**
1070
-     * core_loaded_and_ready
1071
-     * all of the basic EE core should be loaded at this point and available regardless of M-Mode
1072
-     *
1073
-     * @access public
1074
-     * @return void
1075
-     */
1076
-    public function core_loaded_and_ready()
1077
-    {
1078
-        $this->loader->getShared('EE_Session');
1079
-        do_action('AHEE__EE_System__core_loaded_and_ready');
1080
-        // load_espresso_template_tags
1081
-        if (is_readable(EE_PUBLIC . 'template_tags.php')) {
1082
-            require_once(EE_PUBLIC . 'template_tags.php');
1083
-        }
1084
-        do_action('AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons');
1085
-        $this->loader->getShared('EventEspresso\core\services\assets\Registry');
1086
-    }
1087
-
1088
-
1089
-
1090
-    /**
1091
-     * initialize
1092
-     * this is the best place to begin initializing client code
1093
-     *
1094
-     * @access public
1095
-     * @return void
1096
-     */
1097
-    public function initialize()
1098
-    {
1099
-        do_action('AHEE__EE_System__initialize');
1100
-    }
1101
-
1102
-
1103
-
1104
-    /**
1105
-     * initialize_last
1106
-     * this is run really late during the WP init hook point, and ensures that mostly everything else that needs to
1107
-     * initialize has done so
1108
-     *
1109
-     * @access public
1110
-     * @return void
1111
-     */
1112
-    public function initialize_last()
1113
-    {
1114
-        do_action('AHEE__EE_System__initialize_last');
1115
-        add_action('admin_bar_init', array($this, 'addEspressoToolbar'));
1116
-    }
1117
-
1118
-
1119
-
1120
-    /**
1121
-     * @return void
1122
-     * @throws EE_Error
1123
-     */
1124
-    public function addEspressoToolbar()
1125
-    {
1126
-        $this->loader->getShared(
1127
-            'EventEspresso\core\domain\services\admin\AdminToolBar',
1128
-            array($this->registry->CAP)
1129
-        );
1130
-    }
1131
-
1132
-
1133
-
1134
-    /**
1135
-     * do_not_cache
1136
-     * sets no cache headers and defines no cache constants for WP plugins
1137
-     *
1138
-     * @access public
1139
-     * @return void
1140
-     */
1141
-    public static function do_not_cache()
1142
-    {
1143
-        // set no cache constants
1144
-        if (! defined('DONOTCACHEPAGE')) {
1145
-            define('DONOTCACHEPAGE', true);
1146
-        }
1147
-        if (! defined('DONOTCACHCEOBJECT')) {
1148
-            define('DONOTCACHCEOBJECT', true);
1149
-        }
1150
-        if (! defined('DONOTCACHEDB')) {
1151
-            define('DONOTCACHEDB', true);
1152
-        }
1153
-        // add no cache headers
1154
-        add_action('send_headers', array('EE_System', 'nocache_headers'), 10);
1155
-        // plus a little extra for nginx and Google Chrome
1156
-        add_filter('nocache_headers', array('EE_System', 'extra_nocache_headers'), 10, 1);
1157
-        // prevent browsers from prefetching of the rel='next' link, because it may contain content that interferes with the registration process
1158
-        remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');
1159
-    }
1160
-
1161
-
1162
-
1163
-    /**
1164
-     *    extra_nocache_headers
1165
-     *
1166
-     * @access    public
1167
-     * @param $headers
1168
-     * @return    array
1169
-     */
1170
-    public static function extra_nocache_headers($headers)
1171
-    {
1172
-        // for NGINX
1173
-        $headers['X-Accel-Expires'] = 0;
1174
-        // plus extra for Google Chrome since it doesn't seem to respect "no-cache", but WILL respect "no-store"
1175
-        $headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0';
1176
-        return $headers;
1177
-    }
1178
-
1179
-
1180
-
1181
-    /**
1182
-     *    nocache_headers
1183
-     *
1184
-     * @access    public
1185
-     * @return    void
1186
-     */
1187
-    public static function nocache_headers()
1188
-    {
1189
-        nocache_headers();
1190
-    }
1191
-
1192
-
1193
-
1194
-
1195
-    /**
1196
-     * simply hooks into "wp_list_pages_exclude" filter (for wp_list_pages method) and makes sure EE critical pages are
1197
-     * never returned with the function.
1198
-     *
1199
-     * @param  array $exclude_array any existing pages being excluded are in this array.
1200
-     * @return array
1201
-     */
1202
-    public function remove_pages_from_wp_list_pages($exclude_array)
1203
-    {
1204
-        return array_merge($exclude_array, $this->registry->CFG->core->get_critical_pages_array());
1205
-    }
24
+	/**
25
+	 * indicates this is a 'normal' request. Ie, not activation, nor upgrade, nor activation.
26
+	 * So examples of this would be a normal GET request on the frontend or backend, or a POST, etc
27
+	 */
28
+	const req_type_normal = 0;
29
+
30
+	/**
31
+	 * Indicates this is a brand new installation of EE so we should install
32
+	 * tables and default data etc
33
+	 */
34
+	const req_type_new_activation = 1;
35
+
36
+	/**
37
+	 * we've detected that EE has been reactivated (or EE was activated during maintenance mode,
38
+	 * and we just exited maintenance mode). We MUST check the database is setup properly
39
+	 * and that default data is setup too
40
+	 */
41
+	const req_type_reactivation = 2;
42
+
43
+	/**
44
+	 * indicates that EE has been upgraded since its previous request.
45
+	 * We may have data migration scripts to call and will want to trigger maintenance mode
46
+	 */
47
+	const req_type_upgrade = 3;
48
+
49
+	/**
50
+	 * TODO  will detect that EE has been DOWNGRADED. We probably don't want to run in this case...
51
+	 */
52
+	const req_type_downgrade = 4;
53
+
54
+	/**
55
+	 * @deprecated since version 4.6.0.dev.006
56
+	 * Now whenever a new_activation is detected the request type is still just
57
+	 * new_activation (same for reactivation, upgrade, downgrade etc), but if we'r ein maintenance mode
58
+	 * EE_System::initialize_db_if_no_migrations_required and EE_Addon::initialize_db_if_no_migrations_required
59
+	 * will instead enqueue that EE plugin's db initialization for when we're taken out of maintenance mode.
60
+	 * (Specifically, when the migration manager indicates migrations are finished
61
+	 * EE_Data_Migration_Manager::initialize_db_for_enqueued_ee_plugins() will be called)
62
+	 */
63
+	const req_type_activation_but_not_installed = 5;
64
+
65
+	/**
66
+	 * option prefix for recording the activation history (like core's "espresso_db_update") of addons
67
+	 */
68
+	const addon_activation_history_option_prefix = 'ee_addon_activation_history_';
69
+
70
+
71
+	/**
72
+	 * @var EE_System $_instance
73
+	 */
74
+	private static $_instance;
75
+
76
+	/**
77
+	 * @var EE_Registry $registry
78
+	 */
79
+	private $registry;
80
+
81
+	/**
82
+	 * @var LoaderInterface $loader
83
+	 */
84
+	private $loader;
85
+
86
+	/**
87
+	 * @var EE_Capabilities $capabilities
88
+	 */
89
+	private $capabilities;
90
+
91
+	/**
92
+	 * @var EE_Request $request
93
+	 */
94
+	private $request;
95
+
96
+	/**
97
+	 * @var EE_Maintenance_Mode $maintenance_mode
98
+	 */
99
+	private $maintenance_mode;
100
+
101
+	/**
102
+	 * Stores which type of request this is, options being one of the constants on EE_System starting with req_type_*.
103
+	 * It can be a brand-new activation, a reactivation, an upgrade, a downgrade, or a normal request.
104
+	 *
105
+	 * @var int $_req_type
106
+	 */
107
+	private $_req_type;
108
+
109
+	/**
110
+	 * Whether or not there was a non-micro version change in EE core version during this request
111
+	 *
112
+	 * @var boolean $_major_version_change
113
+	 */
114
+	private $_major_version_change = false;
115
+
116
+
117
+
118
+	/**
119
+	 * @singleton method used to instantiate class object
120
+	 * @param EE_Registry|null         $registry
121
+	 * @param LoaderInterface|null     $loader
122
+	 * @param EE_Capabilities|null     $capabilities
123
+	 * @param EE_Request|null          $request
124
+	 * @param EE_Maintenance_Mode|null $maintenance_mode
125
+	 * @return EE_System
126
+	 */
127
+	public static function instance(
128
+		EE_Registry $registry = null,
129
+		LoaderInterface $loader = null,
130
+		EE_Capabilities $capabilities = null,
131
+		EE_Request $request = null,
132
+		EE_Maintenance_Mode $maintenance_mode = null
133
+	) {
134
+		// check if class object is instantiated
135
+		if (! self::$_instance instanceof EE_System) {
136
+			self::$_instance = new self($registry, $loader, $capabilities, $request, $maintenance_mode);
137
+		}
138
+		return self::$_instance;
139
+	}
140
+
141
+
142
+
143
+	/**
144
+	 * resets the instance and returns it
145
+	 *
146
+	 * @return EE_System
147
+	 */
148
+	public static function reset()
149
+	{
150
+		self::$_instance->_req_type = null;
151
+		//make sure none of the old hooks are left hanging around
152
+		remove_all_actions('AHEE__EE_System__perform_activations_upgrades_and_migrations');
153
+		//we need to reset the migration manager in order for it to detect DMSs properly
154
+		EE_Data_Migration_Manager::reset();
155
+		self::instance()->detect_activations_or_upgrades();
156
+		self::instance()->perform_activations_upgrades_and_migrations();
157
+		return self::instance();
158
+	}
159
+
160
+
161
+
162
+	/**
163
+	 * sets hooks for running rest of system
164
+	 * provides "AHEE__EE_System__construct__complete" hook for EE Addons to use as their starting point
165
+	 * starting EE Addons from any other point may lead to problems
166
+	 *
167
+	 * @param EE_Registry         $registry
168
+	 * @param LoaderInterface     $loader
169
+	 * @param EE_Capabilities     $capabilities
170
+	 * @param EE_Request          $request
171
+	 * @param EE_Maintenance_Mode $maintenance_mode
172
+	 */
173
+	private function __construct(
174
+		EE_Registry $registry,
175
+		LoaderInterface $loader,
176
+		EE_Capabilities $capabilities,
177
+		EE_Request $request,
178
+		EE_Maintenance_Mode $maintenance_mode
179
+	) {
180
+		$this->registry = $registry;
181
+		$this->loader = $loader;
182
+		$this->capabilities = $capabilities;
183
+		$this->request = $request;
184
+		$this->maintenance_mode = $maintenance_mode;
185
+		do_action('AHEE__EE_System__construct__begin', $this);
186
+		add_action(
187
+			'AHEE__EE_Bootstrap__load_espresso_addons',
188
+			array($this, 'loadCapabilities'),
189
+			5
190
+		);
191
+		add_action(
192
+			'AHEE__EE_Bootstrap__load_espresso_addons',
193
+			array($this, 'loadCommandBus'),
194
+			7
195
+		);
196
+		add_action(
197
+			'AHEE__EE_Bootstrap__load_espresso_addons',
198
+			array($this, 'loadPluginApi'),
199
+			9
200
+		);
201
+		// allow addons to load first so that they can register autoloaders, set hooks for running DMS's, etc
202
+		add_action(
203
+			'AHEE__EE_Bootstrap__load_espresso_addons',
204
+			array($this, 'load_espresso_addons')
205
+		);
206
+		// when an ee addon is activated, we want to call the core hook(s) again
207
+		// because the newly-activated addon didn't get a chance to run at all
208
+		add_action('activate_plugin', array($this, 'load_espresso_addons'), 1);
209
+		// detect whether install or upgrade
210
+		add_action(
211
+			'AHEE__EE_Bootstrap__detect_activations_or_upgrades',
212
+			array($this, 'detect_activations_or_upgrades'),
213
+			3
214
+		);
215
+		// load EE_Config, EE_Textdomain, etc
216
+		add_action(
217
+			'AHEE__EE_Bootstrap__load_core_configuration',
218
+			array($this, 'load_core_configuration'),
219
+			5
220
+		);
221
+		// load EE_Config, EE_Textdomain, etc
222
+		add_action(
223
+			'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets',
224
+			array($this, 'register_shortcodes_modules_and_widgets'),
225
+			7
226
+		);
227
+		// you wanna get going? I wanna get going... let's get going!
228
+		add_action(
229
+			'AHEE__EE_Bootstrap__brew_espresso',
230
+			array($this, 'brew_espresso'),
231
+			9
232
+		);
233
+		//other housekeeping
234
+		//exclude EE critical pages from wp_list_pages
235
+		add_filter(
236
+			'wp_list_pages_excludes',
237
+			array($this, 'remove_pages_from_wp_list_pages'),
238
+			10
239
+		);
240
+		// ALL EE Addons should use the following hook point to attach their initial setup too
241
+		// it's extremely important for EE Addons to register any class autoloaders so that they can be available when the EE_Config loads
242
+		do_action('AHEE__EE_System__construct__complete', $this);
243
+	}
244
+
245
+
246
+
247
+	/**
248
+	 * load and setup EE_Capabilities
249
+	 *
250
+	 * @return void
251
+	 * @throws EE_Error
252
+	 */
253
+	public function loadCapabilities()
254
+	{
255
+		$this->loader->getShared('EE_Capabilities');
256
+		add_action(
257
+			'AHEE__EE_Capabilities__init_caps__before_initialization',
258
+			function() {
259
+				LoaderFactory::getLoader()->getShared('Payment_Method_Manager');
260
+			}
261
+		);
262
+	}
263
+
264
+
265
+
266
+	/**
267
+	 * create and cache the CommandBus, and also add middleware
268
+	 * The CapChecker middleware requires the use of EE_Capabilities
269
+	 * which is why we need to load the CommandBus after Caps are set up
270
+	 *
271
+	 * @return void
272
+	 * @throws EE_Error
273
+	 */
274
+	public function loadCommandBus()
275
+	{
276
+		$this->loader->getShared(
277
+			'CommandBusInterface',
278
+			array(
279
+				null,
280
+				apply_filters(
281
+					'FHEE__EE_Load_Espresso_Core__handle_request__CommandBus_middleware',
282
+					array(
283
+						$this->loader->getShared('EventEspresso\core\services\commands\middleware\CapChecker'),
284
+						$this->loader->getShared('EventEspresso\core\services\commands\middleware\AddActionHook'),
285
+					)
286
+				),
287
+			)
288
+		);
289
+	}
290
+
291
+
292
+
293
+	/**
294
+	 * @return void
295
+	 * @throws EE_Error
296
+	 */
297
+	public function loadPluginApi()
298
+	{
299
+		// set autoloaders for all of the classes implementing EEI_Plugin_API
300
+		// which provide helpers for EE plugin authors to more easily register certain components with EE.
301
+		EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'plugin_api');
302
+	}
303
+
304
+
305
+
306
+	/**
307
+	 * load_espresso_addons
308
+	 * allow addons to load first so that they can set hooks for running DMS's, etc
309
+	 * this is hooked into both:
310
+	 *    'AHEE__EE_Bootstrap__load_core_configuration'
311
+	 *        which runs during the WP 'plugins_loaded' action at priority 5
312
+	 *    and the WP 'activate_plugin' hook point
313
+	 *
314
+	 * @access public
315
+	 * @return void
316
+	 * @throws EE_Error
317
+	 */
318
+	public function load_espresso_addons()
319
+	{
320
+		do_action('AHEE__EE_System__load_espresso_addons');
321
+		//if the WP API basic auth plugin isn't already loaded, load it now.
322
+		//We want it for mobile apps. Just include the entire plugin
323
+		//also, don't load the basic auth when a plugin is getting activated, because
324
+		//it could be the basic auth plugin, and it doesn't check if its methods are already defined
325
+		//and causes a fatal error
326
+		if (
327
+			! (
328
+				isset($_GET['activate'])
329
+				&& $_GET['activate'] === 'true'
330
+			)
331
+			&& ! function_exists('json_basic_auth_handler')
332
+			&& ! function_exists('json_basic_auth_error')
333
+			&& ! (
334
+				isset($_GET['action'])
335
+				&& in_array($_GET['action'], array('activate', 'activate-selected'), true)
336
+			)
337
+		) {
338
+			include_once EE_THIRD_PARTY . 'wp-api-basic-auth' . DS . 'basic-auth.php';
339
+		}
340
+		do_action('AHEE__EE_System__load_espresso_addons__complete');
341
+	}
342
+
343
+
344
+
345
+	/**
346
+	 * detect_activations_or_upgrades
347
+	 * Checks for activation or upgrade of core first;
348
+	 * then also checks if any registered addons have been activated or upgraded
349
+	 * This is hooked into 'AHEE__EE_Bootstrap__detect_activations_or_upgrades'
350
+	 * which runs during the WP 'plugins_loaded' action at priority 3
351
+	 *
352
+	 * @access public
353
+	 * @return void
354
+	 */
355
+	public function detect_activations_or_upgrades()
356
+	{
357
+		//first off: let's make sure to handle core
358
+		$this->detect_if_activation_or_upgrade();
359
+		foreach ($this->registry->addons as $addon) {
360
+			if ($addon instanceof EE_Addon) {
361
+				//detect teh request type for that addon
362
+				$addon->detect_activation_or_upgrade();
363
+			}
364
+		}
365
+	}
366
+
367
+
368
+
369
+	/**
370
+	 * detect_if_activation_or_upgrade
371
+	 * Takes care of detecting whether this is a brand new install or code upgrade,
372
+	 * and either setting up the DB or setting up maintenance mode etc.
373
+	 *
374
+	 * @access public
375
+	 * @return void
376
+	 */
377
+	public function detect_if_activation_or_upgrade()
378
+	{
379
+		do_action('AHEE__EE_System___detect_if_activation_or_upgrade__begin');
380
+		// check if db has been updated, or if its a brand-new installation
381
+		$espresso_db_update = $this->fix_espresso_db_upgrade_option();
382
+		$request_type = $this->detect_req_type($espresso_db_update);
383
+		//EEH_Debug_Tools::printr( $request_type, '$request_type', __FILE__, __LINE__ );
384
+		switch ($request_type) {
385
+			case EE_System::req_type_new_activation:
386
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__new_activation');
387
+				$this->_handle_core_version_change($espresso_db_update);
388
+				break;
389
+			case EE_System::req_type_reactivation:
390
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__reactivation');
391
+				$this->_handle_core_version_change($espresso_db_update);
392
+				break;
393
+			case EE_System::req_type_upgrade:
394
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__upgrade');
395
+				//migrations may be required now that we've upgraded
396
+				$this->maintenance_mode->set_maintenance_mode_if_db_old();
397
+				$this->_handle_core_version_change($espresso_db_update);
398
+				//				echo "done upgrade";die;
399
+				break;
400
+			case EE_System::req_type_downgrade:
401
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__downgrade');
402
+				//its possible migrations are no longer required
403
+				$this->maintenance_mode->set_maintenance_mode_if_db_old();
404
+				$this->_handle_core_version_change($espresso_db_update);
405
+				break;
406
+			case EE_System::req_type_normal:
407
+			default:
408
+				//				$this->_maybe_redirect_to_ee_about();
409
+				break;
410
+		}
411
+		do_action('AHEE__EE_System__detect_if_activation_or_upgrade__complete');
412
+	}
413
+
414
+
415
+
416
+	/**
417
+	 * Updates the list of installed versions and sets hooks for
418
+	 * initializing the database later during the request
419
+	 *
420
+	 * @param array $espresso_db_update
421
+	 */
422
+	private function _handle_core_version_change($espresso_db_update)
423
+	{
424
+		$this->update_list_of_installed_versions($espresso_db_update);
425
+		//get ready to verify the DB is ok (provided we aren't in maintenance mode, of course)
426
+		add_action(
427
+			'AHEE__EE_System__perform_activations_upgrades_and_migrations',
428
+			array($this, 'initialize_db_if_no_migrations_required')
429
+		);
430
+	}
431
+
432
+
433
+
434
+	/**
435
+	 * standardizes the wp option 'espresso_db_upgrade' which actually stores
436
+	 * information about what versions of EE have been installed and activated,
437
+	 * NOT necessarily the state of the database
438
+	 *
439
+	 * @param mixed $espresso_db_update the value of the WordPress option.
440
+	 *                                            If not supplied, fetches it from the options table
441
+	 * @return array the correct value of 'espresso_db_upgrade', after saving it, if it needed correction
442
+	 */
443
+	private function fix_espresso_db_upgrade_option($espresso_db_update = null)
444
+	{
445
+		do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__begin', $espresso_db_update);
446
+		if (! $espresso_db_update) {
447
+			$espresso_db_update = get_option('espresso_db_update');
448
+		}
449
+		// check that option is an array
450
+		if (! is_array($espresso_db_update)) {
451
+			// if option is FALSE, then it never existed
452
+			if ($espresso_db_update === false) {
453
+				// make $espresso_db_update an array and save option with autoload OFF
454
+				$espresso_db_update = array();
455
+				add_option('espresso_db_update', $espresso_db_update, '', 'no');
456
+			} else {
457
+				// option is NOT FALSE but also is NOT an array, so make it an array and save it
458
+				$espresso_db_update = array($espresso_db_update => array());
459
+				update_option('espresso_db_update', $espresso_db_update);
460
+			}
461
+		} else {
462
+			$corrected_db_update = array();
463
+			//if IS an array, but is it an array where KEYS are version numbers, and values are arrays?
464
+			foreach ($espresso_db_update as $should_be_version_string => $should_be_array) {
465
+				if (is_int($should_be_version_string) && ! is_array($should_be_array)) {
466
+					//the key is an int, and the value IS NOT an array
467
+					//so it must be numerically-indexed, where values are versions installed...
468
+					//fix it!
469
+					$version_string = $should_be_array;
470
+					$corrected_db_update[$version_string] = array('unknown-date');
471
+				} else {
472
+					//ok it checks out
473
+					$corrected_db_update[$should_be_version_string] = $should_be_array;
474
+				}
475
+			}
476
+			$espresso_db_update = $corrected_db_update;
477
+			update_option('espresso_db_update', $espresso_db_update);
478
+		}
479
+		do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__complete', $espresso_db_update);
480
+		return $espresso_db_update;
481
+	}
482
+
483
+
484
+
485
+	/**
486
+	 * Does the traditional work of setting up the plugin's database and adding default data.
487
+	 * If migration script/process did not exist, this is what would happen on every activation/reactivation/upgrade.
488
+	 * NOTE: if we're in maintenance mode (which would be the case if we detect there are data
489
+	 * migration scripts that need to be run and a version change happens), enqueues core for database initialization,
490
+	 * so that it will be done when migrations are finished
491
+	 *
492
+	 * @param boolean $initialize_addons_too if true, we double-check addons' database tables etc too;
493
+	 * @param boolean $verify_schema         if true will re-check the database tables have the correct schema.
494
+	 *                                       This is a resource-intensive job
495
+	 *                                       so we prefer to only do it when necessary
496
+	 * @return void
497
+	 * @throws EE_Error
498
+	 */
499
+	public function initialize_db_if_no_migrations_required($initialize_addons_too = false, $verify_schema = true)
500
+	{
501
+		$request_type = $this->detect_req_type();
502
+		//only initialize system if we're not in maintenance mode.
503
+		if ($this->maintenance_mode->level() !== EE_Maintenance_Mode::level_2_complete_maintenance) {
504
+			update_option('ee_flush_rewrite_rules', true);
505
+			if ($verify_schema) {
506
+				EEH_Activation::initialize_db_and_folders();
507
+			}
508
+			EEH_Activation::initialize_db_content();
509
+			EEH_Activation::system_initialization();
510
+			if ($initialize_addons_too) {
511
+				$this->initialize_addons();
512
+			}
513
+		} else {
514
+			EE_Data_Migration_Manager::instance()->enqueue_db_initialization_for('Core');
515
+		}
516
+		if ($request_type === EE_System::req_type_new_activation
517
+			|| $request_type === EE_System::req_type_reactivation
518
+			|| (
519
+				$request_type === EE_System::req_type_upgrade
520
+				&& $this->is_major_version_change()
521
+			)
522
+		) {
523
+			add_action('AHEE__EE_System__initialize_last', array($this, 'redirect_to_about_ee'), 9);
524
+		}
525
+	}
526
+
527
+
528
+
529
+	/**
530
+	 * Initializes the db for all registered addons
531
+	 *
532
+	 * @throws EE_Error
533
+	 */
534
+	public function initialize_addons()
535
+	{
536
+		//foreach registered addon, make sure its db is up-to-date too
537
+		foreach ($this->registry->addons as $addon) {
538
+			if ($addon instanceof EE_Addon) {
539
+				$addon->initialize_db_if_no_migrations_required();
540
+			}
541
+		}
542
+	}
543
+
544
+
545
+
546
+	/**
547
+	 * Adds the current code version to the saved wp option which stores a list of all ee versions ever installed.
548
+	 *
549
+	 * @param    array  $version_history
550
+	 * @param    string $current_version_to_add version to be added to the version history
551
+	 * @return    boolean success as to whether or not this option was changed
552
+	 */
553
+	public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null)
554
+	{
555
+		if (! $version_history) {
556
+			$version_history = $this->fix_espresso_db_upgrade_option($version_history);
557
+		}
558
+		if ($current_version_to_add === null) {
559
+			$current_version_to_add = espresso_version();
560
+		}
561
+		$version_history[$current_version_to_add][] = date('Y-m-d H:i:s', time());
562
+		// re-save
563
+		return update_option('espresso_db_update', $version_history);
564
+	}
565
+
566
+
567
+
568
+	/**
569
+	 * Detects if the current version indicated in the has existed in the list of
570
+	 * previously-installed versions of EE (espresso_db_update). Does NOT modify it (ie, no side-effect)
571
+	 *
572
+	 * @param array $espresso_db_update array from the wp option stored under the name 'espresso_db_update'.
573
+	 *                                  If not supplied, fetches it from the options table.
574
+	 *                                  Also, caches its result so later parts of the code can also know whether
575
+	 *                                  there's been an update or not. This way we can add the current version to
576
+	 *                                  espresso_db_update, but still know if this is a new install or not
577
+	 * @return int one of the constants on EE_System::req_type_
578
+	 */
579
+	public function detect_req_type($espresso_db_update = null)
580
+	{
581
+		if ($this->_req_type === null) {
582
+			$espresso_db_update = ! empty($espresso_db_update)
583
+				? $espresso_db_update
584
+				: $this->fix_espresso_db_upgrade_option();
585
+			$this->_req_type = EE_System::detect_req_type_given_activation_history(
586
+				$espresso_db_update,
587
+				'ee_espresso_activation', espresso_version()
588
+			);
589
+			$this->_major_version_change = $this->_detect_major_version_change($espresso_db_update);
590
+		}
591
+		return $this->_req_type;
592
+	}
593
+
594
+
595
+
596
+	/**
597
+	 * Returns whether or not there was a non-micro version change (ie, change in either
598
+	 * the first or second number in the version. Eg 4.9.0.rc.001 to 4.10.0.rc.000,
599
+	 * but not 4.9.0.rc.0001 to 4.9.1.rc.0001
600
+	 *
601
+	 * @param $activation_history
602
+	 * @return bool
603
+	 */
604
+	private function _detect_major_version_change($activation_history)
605
+	{
606
+		$previous_version = EE_System::_get_most_recently_active_version_from_activation_history($activation_history);
607
+		$previous_version_parts = explode('.', $previous_version);
608
+		$current_version_parts = explode('.', espresso_version());
609
+		return isset($previous_version_parts[0], $previous_version_parts[1], $current_version_parts[0], $current_version_parts[1])
610
+			   && ($previous_version_parts[0] !== $current_version_parts[0]
611
+				   || $previous_version_parts[1] !== $current_version_parts[1]
612
+			   );
613
+	}
614
+
615
+
616
+
617
+	/**
618
+	 * Returns true if either the major or minor version of EE changed during this request.
619
+	 * Eg 4.9.0.rc.001 to 4.10.0.rc.000, but not 4.9.0.rc.0001 to 4.9.1.rc.0001
620
+	 *
621
+	 * @return bool
622
+	 */
623
+	public function is_major_version_change()
624
+	{
625
+		return $this->_major_version_change;
626
+	}
627
+
628
+
629
+
630
+	/**
631
+	 * Determines the request type for any ee addon, given three piece of info: the current array of activation
632
+	 * histories (for core that' 'espresso_db_update' wp option); the name of the WordPress option which is temporarily
633
+	 * set upon activation of the plugin (for core it's 'ee_espresso_activation'); and the version that this plugin was
634
+	 * just activated to (for core that will always be espresso_version())
635
+	 *
636
+	 * @param array  $activation_history_for_addon     the option's value which stores the activation history for this
637
+	 *                                                 ee plugin. for core that's 'espresso_db_update'
638
+	 * @param string $activation_indicator_option_name the name of the WordPress option that is temporarily set to
639
+	 *                                                 indicate that this plugin was just activated
640
+	 * @param string $version_to_upgrade_to            the version that was just upgraded to (for core that will be
641
+	 *                                                 espresso_version())
642
+	 * @return int one of the constants on EE_System::req_type_*
643
+	 */
644
+	public static function detect_req_type_given_activation_history(
645
+		$activation_history_for_addon,
646
+		$activation_indicator_option_name,
647
+		$version_to_upgrade_to
648
+	) {
649
+		$version_is_higher = self::_new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to);
650
+		if ($activation_history_for_addon) {
651
+			//it exists, so this isn't a completely new install
652
+			//check if this version already in that list of previously installed versions
653
+			if (! isset($activation_history_for_addon[$version_to_upgrade_to])) {
654
+				//it a version we haven't seen before
655
+				if ($version_is_higher === 1) {
656
+					$req_type = EE_System::req_type_upgrade;
657
+				} else {
658
+					$req_type = EE_System::req_type_downgrade;
659
+				}
660
+				delete_option($activation_indicator_option_name);
661
+			} else {
662
+				// its not an update. maybe a reactivation?
663
+				if (get_option($activation_indicator_option_name, false)) {
664
+					if ($version_is_higher === -1) {
665
+						$req_type = EE_System::req_type_downgrade;
666
+					} else if ($version_is_higher === 0) {
667
+						//we've seen this version before, but it's an activation. must be a reactivation
668
+						$req_type = EE_System::req_type_reactivation;
669
+					} else {//$version_is_higher === 1
670
+						$req_type = EE_System::req_type_upgrade;
671
+					}
672
+					delete_option($activation_indicator_option_name);
673
+				} else {
674
+					//we've seen this version before and the activation indicate doesn't show it was just activated
675
+					if ($version_is_higher === -1) {
676
+						$req_type = EE_System::req_type_downgrade;
677
+					} else if ($version_is_higher === 0) {
678
+						//we've seen this version before and it's not an activation. its normal request
679
+						$req_type = EE_System::req_type_normal;
680
+					} else {//$version_is_higher === 1
681
+						$req_type = EE_System::req_type_upgrade;
682
+					}
683
+				}
684
+			}
685
+		} else {
686
+			//brand new install
687
+			$req_type = EE_System::req_type_new_activation;
688
+			delete_option($activation_indicator_option_name);
689
+		}
690
+		return $req_type;
691
+	}
692
+
693
+
694
+
695
+	/**
696
+	 * Detects if the $version_to_upgrade_to is higher than the most recent version in
697
+	 * the $activation_history_for_addon
698
+	 *
699
+	 * @param array  $activation_history_for_addon (keys are versions, values are arrays of times activated,
700
+	 *                                             sometimes containing 'unknown-date'
701
+	 * @param string $version_to_upgrade_to        (current version)
702
+	 * @return int results of version_compare( $version_to_upgrade_to, $most_recently_active_version ).
703
+	 *                                             ie, -1 if $version_to_upgrade_to is LOWER (downgrade);
704
+	 *                                             0 if $version_to_upgrade_to MATCHES (reactivation or normal request);
705
+	 *                                             1 if $version_to_upgrade_to is HIGHER (upgrade) ;
706
+	 */
707
+	private static function _new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to)
708
+	{
709
+		//find the most recently-activated version
710
+		$most_recently_active_version =
711
+			EE_System::_get_most_recently_active_version_from_activation_history($activation_history_for_addon);
712
+		return version_compare($version_to_upgrade_to, $most_recently_active_version);
713
+	}
714
+
715
+
716
+
717
+	/**
718
+	 * Gets the most recently active version listed in the activation history,
719
+	 * and if none are found (ie, it's a brand new install) returns '0.0.0.dev.000'.
720
+	 *
721
+	 * @param array $activation_history  (keys are versions, values are arrays of times activated,
722
+	 *                                   sometimes containing 'unknown-date'
723
+	 * @return string
724
+	 */
725
+	private static function _get_most_recently_active_version_from_activation_history($activation_history)
726
+	{
727
+		$most_recently_active_version_activation = '1970-01-01 00:00:00';
728
+		$most_recently_active_version = '0.0.0.dev.000';
729
+		if (is_array($activation_history)) {
730
+			foreach ($activation_history as $version => $times_activated) {
731
+				//check there is a record of when this version was activated. Otherwise,
732
+				//mark it as unknown
733
+				if (! $times_activated) {
734
+					$times_activated = array('unknown-date');
735
+				}
736
+				if (is_string($times_activated)) {
737
+					$times_activated = array($times_activated);
738
+				}
739
+				foreach ($times_activated as $an_activation) {
740
+					if ($an_activation !== 'unknown-date' && $an_activation > $most_recently_active_version_activation) {
741
+						$most_recently_active_version = $version;
742
+						$most_recently_active_version_activation = $an_activation === 'unknown-date'
743
+							? '1970-01-01 00:00:00'
744
+							: $an_activation;
745
+					}
746
+				}
747
+			}
748
+		}
749
+		return $most_recently_active_version;
750
+	}
751
+
752
+
753
+
754
+	/**
755
+	 * This redirects to the about EE page after activation
756
+	 *
757
+	 * @return void
758
+	 */
759
+	public function redirect_to_about_ee()
760
+	{
761
+		$notices = EE_Error::get_notices(false);
762
+		//if current user is an admin and it's not an ajax or rest request
763
+		if (
764
+			! (defined('DOING_AJAX') && DOING_AJAX)
765
+			&& ! (defined('REST_REQUEST') && REST_REQUEST)
766
+			&& ! isset($notices['errors'])
767
+			&& apply_filters(
768
+				'FHEE__EE_System__redirect_to_about_ee__do_redirect',
769
+				$this->capabilities->current_user_can('manage_options', 'espresso_about_default')
770
+			)
771
+		) {
772
+			$query_params = array('page' => 'espresso_about');
773
+			if (EE_System::instance()->detect_req_type() === EE_System::req_type_new_activation) {
774
+				$query_params['new_activation'] = true;
775
+			}
776
+			if (EE_System::instance()->detect_req_type() === EE_System::req_type_reactivation) {
777
+				$query_params['reactivation'] = true;
778
+			}
779
+			$url = add_query_arg($query_params, admin_url('admin.php'));
780
+			wp_safe_redirect($url);
781
+			exit();
782
+		}
783
+	}
784
+
785
+
786
+
787
+	/**
788
+	 * load_core_configuration
789
+	 * this is hooked into 'AHEE__EE_Bootstrap__load_core_configuration'
790
+	 * which runs during the WP 'plugins_loaded' action at priority 5
791
+	 *
792
+	 * @return void
793
+	 * @throws ReflectionException
794
+	 */
795
+	public function load_core_configuration()
796
+	{
797
+		do_action('AHEE__EE_System__load_core_configuration__begin', $this);
798
+		$this->loader->getShared('EE_Load_Textdomain');
799
+		//load textdomain
800
+		EE_Load_Textdomain::load_textdomain();
801
+		// load and setup EE_Config and EE_Network_Config
802
+		$config = $this->loader->getShared('EE_Config');
803
+		$this->loader->getShared('EE_Network_Config');
804
+		// setup autoloaders
805
+		// enable logging?
806
+		if ($config->admin->use_full_logging) {
807
+			$this->loader->getShared('EE_Log');
808
+		}
809
+		// check for activation errors
810
+		$activation_errors = get_option('ee_plugin_activation_errors', false);
811
+		if ($activation_errors) {
812
+			EE_Error::add_error($activation_errors, __FILE__, __FUNCTION__, __LINE__);
813
+			update_option('ee_plugin_activation_errors', false);
814
+		}
815
+		// get model names
816
+		$this->_parse_model_names();
817
+		//load caf stuff a chance to play during the activation process too.
818
+		$this->_maybe_brew_regular();
819
+		do_action('AHEE__EE_System__load_core_configuration__complete', $this);
820
+	}
821
+
822
+
823
+
824
+	/**
825
+	 * cycles through all of the models/*.model.php files, and assembles an array of model names
826
+	 *
827
+	 * @return void
828
+	 * @throws ReflectionException
829
+	 */
830
+	private function _parse_model_names()
831
+	{
832
+		//get all the files in the EE_MODELS folder that end in .model.php
833
+		$models = glob(EE_MODELS . '*.model.php');
834
+		$model_names = array();
835
+		$non_abstract_db_models = array();
836
+		foreach ($models as $model) {
837
+			// get model classname
838
+			$classname = EEH_File::get_classname_from_filepath_with_standard_filename($model);
839
+			$short_name = str_replace('EEM_', '', $classname);
840
+			$reflectionClass = new ReflectionClass($classname);
841
+			if ($reflectionClass->isSubclassOf('EEM_Base') && ! $reflectionClass->isAbstract()) {
842
+				$non_abstract_db_models[$short_name] = $classname;
843
+			}
844
+			$model_names[$short_name] = $classname;
845
+		}
846
+		$this->registry->models = apply_filters('FHEE__EE_System__parse_model_names', $model_names);
847
+		$this->registry->non_abstract_db_models = apply_filters(
848
+			'FHEE__EE_System__parse_implemented_model_names',
849
+			$non_abstract_db_models
850
+		);
851
+	}
852
+
853
+
854
+
855
+	/**
856
+	 * The purpose of this method is to simply check for a file named "caffeinated/brewing_regular.php" for any hooks
857
+	 * that need to be setup before our EE_System launches.
858
+	 *
859
+	 * @return void
860
+	 */
861
+	private function _maybe_brew_regular()
862
+	{
863
+		if ((! defined('EE_DECAF') || EE_DECAF !== true) && is_readable(EE_CAFF_PATH . 'brewing_regular.php')) {
864
+			require_once EE_CAFF_PATH . 'brewing_regular.php';
865
+		}
866
+	}
867
+
868
+
869
+
870
+	/**
871
+	 * register_shortcodes_modules_and_widgets
872
+	 * generate lists of shortcodes and modules, then verify paths and classes
873
+	 * This is hooked into 'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets'
874
+	 * which runs during the WP 'plugins_loaded' action at priority 7
875
+	 *
876
+	 * @access public
877
+	 * @return void
878
+	 * @throws Exception
879
+	 */
880
+	public function register_shortcodes_modules_and_widgets()
881
+	{
882
+		try {
883
+			// load, register, and add shortcodes the new way
884
+			$this->loader->getShared(
885
+				'EventEspresso\core\services\shortcodes\ShortcodesManager',
886
+				array(
887
+					// and the old way, but we'll put it under control of the new system
888
+					EE_Config::getLegacyShortcodesManager()
889
+				)
890
+			);
891
+		} catch (Exception $exception) {
892
+			new ExceptionStackTraceDisplay($exception);
893
+		}
894
+		do_action('AHEE__EE_System__register_shortcodes_modules_and_widgets');
895
+		// check for addons using old hook point
896
+		if (has_action('AHEE__EE_System__register_shortcodes_modules_and_addons')) {
897
+			$this->_incompatible_addon_error();
898
+		}
899
+	}
900
+
901
+
902
+
903
+	/**
904
+	 * _incompatible_addon_error
905
+	 *
906
+	 * @access public
907
+	 * @return void
908
+	 */
909
+	private function _incompatible_addon_error()
910
+	{
911
+		// get array of classes hooking into here
912
+		$class_names = EEH_Class_Tools::get_class_names_for_all_callbacks_on_hook(
913
+			'AHEE__EE_System__register_shortcodes_modules_and_addons'
914
+		);
915
+		if (! empty($class_names)) {
916
+			$msg = __(
917
+				'The following plugins, addons, or modules appear to be incompatible with this version of Event Espresso and were automatically deactivated to avoid fatal errors:',
918
+				'event_espresso'
919
+			);
920
+			$msg .= '<ul>';
921
+			foreach ($class_names as $class_name) {
922
+				$msg .= '<li><b>Event Espresso - ' . str_replace(
923
+						array('EE_', 'EEM_', 'EED_', 'EES_', 'EEW_'), '',
924
+						$class_name
925
+					) . '</b></li>';
926
+			}
927
+			$msg .= '</ul>';
928
+			$msg .= __(
929
+				'Compatibility issues can be avoided and/or resolved by keeping addons and plugins updated to the latest version.',
930
+				'event_espresso'
931
+			);
932
+			// save list of incompatible addons to wp-options for later use
933
+			add_option('ee_incompatible_addons', $class_names, '', 'no');
934
+			if (is_admin()) {
935
+				EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
936
+			}
937
+		}
938
+	}
939
+
940
+
941
+
942
+	/**
943
+	 * brew_espresso
944
+	 * begins the process of setting hooks for initializing EE in the correct order
945
+	 * This is happening on the 'AHEE__EE_Bootstrap__brew_espresso' hook point
946
+	 * which runs during the WP 'plugins_loaded' action at priority 9
947
+	 *
948
+	 * @return void
949
+	 */
950
+	public function brew_espresso()
951
+	{
952
+		do_action('AHEE__EE_System__brew_espresso__begin', $this);
953
+		// load some final core systems
954
+		add_action('init', array($this, 'set_hooks_for_core'), 1);
955
+		add_action('init', array($this, 'perform_activations_upgrades_and_migrations'), 3);
956
+		add_action('init', array($this, 'load_CPTs_and_session'), 5);
957
+		add_action('init', array($this, 'load_controllers'), 7);
958
+		add_action('init', array($this, 'core_loaded_and_ready'), 9);
959
+		add_action('init', array($this, 'initialize'), 10);
960
+		add_action('init', array($this, 'initialize_last'), 100);
961
+		if (is_admin() && apply_filters('FHEE__EE_System__brew_espresso__load_pue', true)) {
962
+			// pew pew pew
963
+			$this->loader->getShared('EE_PUE');
964
+			do_action('AHEE__EE_System__brew_espresso__after_pue_init');
965
+		}
966
+		do_action('AHEE__EE_System__brew_espresso__complete', $this);
967
+	}
968
+
969
+
970
+
971
+	/**
972
+	 *    set_hooks_for_core
973
+	 *
974
+	 * @access public
975
+	 * @return    void
976
+	 * @throws EE_Error
977
+	 */
978
+	public function set_hooks_for_core()
979
+	{
980
+		$this->_deactivate_incompatible_addons();
981
+		do_action('AHEE__EE_System__set_hooks_for_core');
982
+		//caps need to be initialized on every request so that capability maps are set.
983
+		//@see https://events.codebasehq.com/projects/event-espresso/tickets/8674
984
+		$this->registry->CAP->init_caps();
985
+	}
986
+
987
+
988
+
989
+	/**
990
+	 * Using the information gathered in EE_System::_incompatible_addon_error,
991
+	 * deactivates any addons considered incompatible with the current version of EE
992
+	 */
993
+	private function _deactivate_incompatible_addons()
994
+	{
995
+		$incompatible_addons = get_option('ee_incompatible_addons', array());
996
+		if (! empty($incompatible_addons)) {
997
+			$active_plugins = get_option('active_plugins', array());
998
+			foreach ($active_plugins as $active_plugin) {
999
+				foreach ($incompatible_addons as $incompatible_addon) {
1000
+					if (strpos($active_plugin, $incompatible_addon) !== false) {
1001
+						unset($_GET['activate']);
1002
+						espresso_deactivate_plugin($active_plugin);
1003
+					}
1004
+				}
1005
+			}
1006
+		}
1007
+	}
1008
+
1009
+
1010
+
1011
+	/**
1012
+	 *    perform_activations_upgrades_and_migrations
1013
+	 *
1014
+	 * @access public
1015
+	 * @return    void
1016
+	 */
1017
+	public function perform_activations_upgrades_and_migrations()
1018
+	{
1019
+		//first check if we had previously attempted to setup EE's directories but failed
1020
+		if (EEH_Activation::upload_directories_incomplete()) {
1021
+			EEH_Activation::create_upload_directories();
1022
+		}
1023
+		do_action('AHEE__EE_System__perform_activations_upgrades_and_migrations');
1024
+	}
1025
+
1026
+
1027
+
1028
+	/**
1029
+	 *    load_CPTs_and_session
1030
+	 *
1031
+	 * @access public
1032
+	 * @return    void
1033
+	 */
1034
+	public function load_CPTs_and_session()
1035
+	{
1036
+		do_action('AHEE__EE_System__load_CPTs_and_session__start');
1037
+		// register Custom Post Types
1038
+		$this->loader->getShared('EE_Register_CPTs');
1039
+		do_action('AHEE__EE_System__load_CPTs_and_session__complete');
1040
+	}
1041
+
1042
+
1043
+
1044
+	/**
1045
+	 * load_controllers
1046
+	 * this is the best place to load any additional controllers that needs access to EE core.
1047
+	 * it is expected that all basic core EE systems, that are not dependant on the current request are loaded at this
1048
+	 * time
1049
+	 *
1050
+	 * @access public
1051
+	 * @return void
1052
+	 */
1053
+	public function load_controllers()
1054
+	{
1055
+		do_action('AHEE__EE_System__load_controllers__start');
1056
+		// let's get it started
1057
+		if (! is_admin() && ! $this->maintenance_mode->level()) {
1058
+			do_action('AHEE__EE_System__load_controllers__load_front_controllers');
1059
+			$this->loader->getShared('EE_Front_Controller');
1060
+		} else if (! EE_FRONT_AJAX) {
1061
+			do_action('AHEE__EE_System__load_controllers__load_admin_controllers');
1062
+			$this->loader->getShared('EE_Admin');
1063
+		}
1064
+		do_action('AHEE__EE_System__load_controllers__complete');
1065
+	}
1066
+
1067
+
1068
+
1069
+	/**
1070
+	 * core_loaded_and_ready
1071
+	 * all of the basic EE core should be loaded at this point and available regardless of M-Mode
1072
+	 *
1073
+	 * @access public
1074
+	 * @return void
1075
+	 */
1076
+	public function core_loaded_and_ready()
1077
+	{
1078
+		$this->loader->getShared('EE_Session');
1079
+		do_action('AHEE__EE_System__core_loaded_and_ready');
1080
+		// load_espresso_template_tags
1081
+		if (is_readable(EE_PUBLIC . 'template_tags.php')) {
1082
+			require_once(EE_PUBLIC . 'template_tags.php');
1083
+		}
1084
+		do_action('AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons');
1085
+		$this->loader->getShared('EventEspresso\core\services\assets\Registry');
1086
+	}
1087
+
1088
+
1089
+
1090
+	/**
1091
+	 * initialize
1092
+	 * this is the best place to begin initializing client code
1093
+	 *
1094
+	 * @access public
1095
+	 * @return void
1096
+	 */
1097
+	public function initialize()
1098
+	{
1099
+		do_action('AHEE__EE_System__initialize');
1100
+	}
1101
+
1102
+
1103
+
1104
+	/**
1105
+	 * initialize_last
1106
+	 * this is run really late during the WP init hook point, and ensures that mostly everything else that needs to
1107
+	 * initialize has done so
1108
+	 *
1109
+	 * @access public
1110
+	 * @return void
1111
+	 */
1112
+	public function initialize_last()
1113
+	{
1114
+		do_action('AHEE__EE_System__initialize_last');
1115
+		add_action('admin_bar_init', array($this, 'addEspressoToolbar'));
1116
+	}
1117
+
1118
+
1119
+
1120
+	/**
1121
+	 * @return void
1122
+	 * @throws EE_Error
1123
+	 */
1124
+	public function addEspressoToolbar()
1125
+	{
1126
+		$this->loader->getShared(
1127
+			'EventEspresso\core\domain\services\admin\AdminToolBar',
1128
+			array($this->registry->CAP)
1129
+		);
1130
+	}
1131
+
1132
+
1133
+
1134
+	/**
1135
+	 * do_not_cache
1136
+	 * sets no cache headers and defines no cache constants for WP plugins
1137
+	 *
1138
+	 * @access public
1139
+	 * @return void
1140
+	 */
1141
+	public static function do_not_cache()
1142
+	{
1143
+		// set no cache constants
1144
+		if (! defined('DONOTCACHEPAGE')) {
1145
+			define('DONOTCACHEPAGE', true);
1146
+		}
1147
+		if (! defined('DONOTCACHCEOBJECT')) {
1148
+			define('DONOTCACHCEOBJECT', true);
1149
+		}
1150
+		if (! defined('DONOTCACHEDB')) {
1151
+			define('DONOTCACHEDB', true);
1152
+		}
1153
+		// add no cache headers
1154
+		add_action('send_headers', array('EE_System', 'nocache_headers'), 10);
1155
+		// plus a little extra for nginx and Google Chrome
1156
+		add_filter('nocache_headers', array('EE_System', 'extra_nocache_headers'), 10, 1);
1157
+		// prevent browsers from prefetching of the rel='next' link, because it may contain content that interferes with the registration process
1158
+		remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');
1159
+	}
1160
+
1161
+
1162
+
1163
+	/**
1164
+	 *    extra_nocache_headers
1165
+	 *
1166
+	 * @access    public
1167
+	 * @param $headers
1168
+	 * @return    array
1169
+	 */
1170
+	public static function extra_nocache_headers($headers)
1171
+	{
1172
+		// for NGINX
1173
+		$headers['X-Accel-Expires'] = 0;
1174
+		// plus extra for Google Chrome since it doesn't seem to respect "no-cache", but WILL respect "no-store"
1175
+		$headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0';
1176
+		return $headers;
1177
+	}
1178
+
1179
+
1180
+
1181
+	/**
1182
+	 *    nocache_headers
1183
+	 *
1184
+	 * @access    public
1185
+	 * @return    void
1186
+	 */
1187
+	public static function nocache_headers()
1188
+	{
1189
+		nocache_headers();
1190
+	}
1191
+
1192
+
1193
+
1194
+
1195
+	/**
1196
+	 * simply hooks into "wp_list_pages_exclude" filter (for wp_list_pages method) and makes sure EE critical pages are
1197
+	 * never returned with the function.
1198
+	 *
1199
+	 * @param  array $exclude_array any existing pages being excluded are in this array.
1200
+	 * @return array
1201
+	 */
1202
+	public function remove_pages_from_wp_list_pages($exclude_array)
1203
+	{
1204
+		return array_merge($exclude_array, $this->registry->CFG->core->get_critical_pages_array());
1205
+	}
1206 1206
 
1207 1207
 
1208 1208
 
Please login to merge, or discard this patch.
core/EE_Registry.core.php 2 patches
Indentation   +1529 added lines, -1529 removed lines patch added patch discarded remove patch
@@ -22,1535 +22,1535 @@
 block discarded – undo
22 22
 class EE_Registry implements ResettableInterface
23 23
 {
24 24
 
25
-    /**
26
-     * @var EE_Registry $_instance
27
-     */
28
-    private static $_instance;
29
-
30
-    /**
31
-     * @var EE_Dependency_Map $_dependency_map
32
-     */
33
-    protected $_dependency_map;
34
-
35
-    /**
36
-     * @var array $_class_abbreviations
37
-     */
38
-    protected $_class_abbreviations = array();
39
-
40
-    /**
41
-     * @var CommandBusInterface $BUS
42
-     */
43
-    public $BUS;
44
-
45
-    /**
46
-     * @var EE_Cart $CART
47
-     */
48
-    public $CART;
49
-
50
-    /**
51
-     * @var EE_Config $CFG
52
-     */
53
-    public $CFG;
54
-
55
-    /**
56
-     * @var EE_Network_Config $NET_CFG
57
-     */
58
-    public $NET_CFG;
59
-
60
-    /**
61
-     * StdClass object for storing library classes in
62
-     *
63
-     * @var StdClass $LIB
64
-     */
65
-    public $LIB;
66
-
67
-    /**
68
-     * @var EE_Request_Handler $REQ
69
-     */
70
-    public $REQ;
71
-
72
-    /**
73
-     * @var EE_Session $SSN
74
-     */
75
-    public $SSN;
76
-
77
-    /**
78
-     * @since 4.5.0
79
-     * @var EE_Capabilities $CAP
80
-     */
81
-    public $CAP;
82
-
83
-    /**
84
-     * @since 4.9.0
85
-     * @var EE_Message_Resource_Manager $MRM
86
-     */
87
-    public $MRM;
88
-
89
-
90
-    /**
91
-     * @var Registry $AssetsRegistry
92
-     */
93
-    public $AssetsRegistry;
94
-
95
-    /**
96
-     * StdClass object for holding addons which have registered themselves to work with EE core
97
-     *
98
-     * @var EE_Addon[] $addons
99
-     */
100
-    public $addons;
101
-
102
-    /**
103
-     * keys are 'short names' (eg Event), values are class names (eg 'EEM_Event')
104
-     *
105
-     * @var EEM_Base[] $models
106
-     */
107
-    public $models = array();
108
-
109
-    /**
110
-     * @var EED_Module[] $modules
111
-     */
112
-    public $modules;
113
-
114
-    /**
115
-     * @var EES_Shortcode[] $shortcodes
116
-     */
117
-    public $shortcodes;
118
-
119
-    /**
120
-     * @var WP_Widget[] $widgets
121
-     */
122
-    public $widgets;
123
-
124
-    /**
125
-     * this is an array of all implemented model names (i.e. not the parent abstract models, or models
126
-     * which don't actually fetch items from the DB in the normal way (ie, are not children of EEM_Base)).
127
-     * Keys are model "short names" (eg "Event") as used in model relations, and values are
128
-     * classnames (eg "EEM_Event")
129
-     *
130
-     * @var array $non_abstract_db_models
131
-     */
132
-    public $non_abstract_db_models = array();
133
-
134
-
135
-    /**
136
-     * internationalization for JS strings
137
-     *    usage:   EE_Registry::i18n_js_strings['string_key'] = esc_html__( 'string to translate.', 'event_espresso' );
138
-     *    in js file:  var translatedString = eei18n.string_key;
139
-     *
140
-     * @var array $i18n_js_strings
141
-     */
142
-    public static $i18n_js_strings = array();
143
-
144
-
145
-    /**
146
-     * $main_file - path to espresso.php
147
-     *
148
-     * @var array $main_file
149
-     */
150
-    public $main_file;
151
-
152
-    /**
153
-     * array of ReflectionClass objects where the key is the class name
154
-     *
155
-     * @var ReflectionClass[] $_reflectors
156
-     */
157
-    public $_reflectors;
158
-
159
-    /**
160
-     * boolean flag to indicate whether or not to load/save dependencies from/to the cache
161
-     *
162
-     * @var boolean $_cache_on
163
-     */
164
-    protected $_cache_on = true;
165
-
166
-
167
-
168
-    /**
169
-     * @singleton method used to instantiate class object
170
-     * @param  EE_Dependency_Map $dependency_map
171
-     * @return EE_Registry instance
172
-     * @throws InvalidArgumentException
173
-     * @throws InvalidInterfaceException
174
-     * @throws InvalidDataTypeException
175
-     */
176
-    public static function instance(EE_Dependency_Map $dependency_map = null)
177
-    {
178
-        // check if class object is instantiated
179
-        if (! self::$_instance instanceof EE_Registry) {
180
-            self::$_instance = new self($dependency_map);
181
-        }
182
-        return self::$_instance;
183
-    }
184
-
185
-
186
-
187
-    /**
188
-     * protected constructor to prevent direct creation
189
-     *
190
-     * @Constructor
191
-     * @param  EE_Dependency_Map $dependency_map
192
-     * @throws InvalidDataTypeException
193
-     * @throws InvalidInterfaceException
194
-     * @throws InvalidArgumentException
195
-     */
196
-    protected function __construct(EE_Dependency_Map $dependency_map)
197
-    {
198
-        $this->_dependency_map = $dependency_map;
199
-        $this->LIB = new stdClass();
200
-        $this->addons = new stdClass();
201
-        $this->modules = new stdClass();
202
-        $this->shortcodes = new stdClass();
203
-        $this->widgets = new stdClass();
204
-        add_action('EE_Load_Espresso_Core__handle_request__initialize_core_loading', array($this, 'initialize'));
205
-    }
206
-
207
-
208
-
209
-    /**
210
-     * initialize
211
-     *
212
-     * @throws EE_Error
213
-     * @throws ReflectionException
214
-     */
215
-    public function initialize()
216
-    {
217
-        $this->_class_abbreviations = apply_filters(
218
-            'FHEE__EE_Registry____construct___class_abbreviations',
219
-            array(
220
-                'EE_Config'                                       => 'CFG',
221
-                'EE_Session'                                      => 'SSN',
222
-                'EE_Capabilities'                                 => 'CAP',
223
-                'EE_Cart'                                         => 'CART',
224
-                'EE_Network_Config'                               => 'NET_CFG',
225
-                'EE_Request_Handler'                              => 'REQ',
226
-                'EE_Message_Resource_Manager'                     => 'MRM',
227
-                'EventEspresso\core\services\commands\CommandBus' => 'BUS',
228
-                'EventEspresso\core\services\assets\Registry'     => 'AssetsRegistry',
229
-            )
230
-        );
231
-        $this->load_core('Base', array(), true);
232
-        // add our request and response objects to the cache
233
-        $request_loader = $this->_dependency_map->class_loader('EE_Request');
234
-        $this->_set_cached_class(
235
-            $request_loader(),
236
-            'EE_Request'
237
-        );
238
-        $response_loader = $this->_dependency_map->class_loader('EE_Response');
239
-        $this->_set_cached_class(
240
-            $response_loader(),
241
-            'EE_Response'
242
-        );
243
-        add_action('AHEE__EE_System__set_hooks_for_core', array($this, 'init'));
244
-    }
245
-
246
-
247
-
248
-    /**
249
-     * @return void
250
-     */
251
-    public function init()
252
-    {
253
-        // Get current page protocol
254
-        $protocol = isset($_SERVER['HTTPS']) ? 'https://' : 'http://';
255
-        // Output admin-ajax.php URL with same protocol as current page
256
-        self::$i18n_js_strings['ajax_url'] = admin_url('admin-ajax.php', $protocol);
257
-        self::$i18n_js_strings['wp_debug'] = defined('WP_DEBUG') ? WP_DEBUG : false;
258
-    }
259
-
260
-
261
-
262
-    /**
263
-     * localize_i18n_js_strings
264
-     *
265
-     * @return string
266
-     */
267
-    public static function localize_i18n_js_strings()
268
-    {
269
-        $i18n_js_strings = (array)self::$i18n_js_strings;
270
-        foreach ($i18n_js_strings as $key => $value) {
271
-            if (is_scalar($value)) {
272
-                $i18n_js_strings[$key] = html_entity_decode((string)$value, ENT_QUOTES, 'UTF-8');
273
-            }
274
-        }
275
-        return '/* <![CDATA[ */ var eei18n = ' . wp_json_encode($i18n_js_strings) . '; /* ]]> */';
276
-    }
277
-
278
-
279
-
280
-    /**
281
-     * @param mixed string | EED_Module $module
282
-     * @throws EE_Error
283
-     * @throws ReflectionException
284
-     */
285
-    public function add_module($module)
286
-    {
287
-        if ($module instanceof EED_Module) {
288
-            $module_class = get_class($module);
289
-            $this->modules->{$module_class} = $module;
290
-        } else {
291
-            if (! class_exists('EE_Module_Request_Router')) {
292
-                $this->load_core('Module_Request_Router');
293
-            }
294
-            EE_Module_Request_Router::module_factory($module);
295
-        }
296
-    }
297
-
298
-
299
-
300
-    /**
301
-     * @param string $module_name
302
-     * @return mixed EED_Module | NULL
303
-     */
304
-    public function get_module($module_name = '')
305
-    {
306
-        return isset($this->modules->{$module_name})
307
-            ? $this->modules->{$module_name}
308
-            : null;
309
-    }
310
-
311
-
312
-
313
-    /**
314
-     * loads core classes - must be singletons
315
-     *
316
-     * @param string $class_name - simple class name ie: session
317
-     * @param mixed  $arguments
318
-     * @param bool   $load_only
319
-     * @return mixed
320
-     * @throws EE_Error
321
-     * @throws ReflectionException
322
-     */
323
-    public function load_core($class_name, $arguments = array(), $load_only = false)
324
-    {
325
-        $core_paths = apply_filters(
326
-            'FHEE__EE_Registry__load_core__core_paths',
327
-            array(
328
-                EE_CORE,
329
-                EE_ADMIN,
330
-                EE_CPTS,
331
-                EE_CORE . 'data_migration_scripts' . DS,
332
-                EE_CORE . 'capabilities' . DS,
333
-                EE_CORE . 'request_stack' . DS,
334
-                EE_CORE . 'middleware' . DS,
335
-            )
336
-        );
337
-        // retrieve instantiated class
338
-        return $this->_load(
339
-            $core_paths,
340
-            'EE_',
341
-            $class_name,
342
-            'core',
343
-            $arguments,
344
-            false,
345
-            true,
346
-            $load_only
347
-        );
348
-    }
349
-
350
-
351
-
352
-    /**
353
-     * loads service classes
354
-     *
355
-     * @param string $class_name - simple class name ie: session
356
-     * @param mixed  $arguments
357
-     * @param bool   $load_only
358
-     * @return mixed
359
-     * @throws EE_Error
360
-     * @throws ReflectionException
361
-     */
362
-    public function load_service($class_name, $arguments = array(), $load_only = false)
363
-    {
364
-        $service_paths = apply_filters(
365
-            'FHEE__EE_Registry__load_service__service_paths',
366
-            array(
367
-                EE_CORE . 'services' . DS,
368
-            )
369
-        );
370
-        // retrieve instantiated class
371
-        return $this->_load(
372
-            $service_paths,
373
-            'EE_',
374
-            $class_name,
375
-            'class',
376
-            $arguments,
377
-            false,
378
-            true,
379
-            $load_only
380
-        );
381
-    }
382
-
383
-
384
-
385
-    /**
386
-     * loads data_migration_scripts
387
-     *
388
-     * @param string $class_name - class name for the DMS ie: EE_DMS_Core_4_2_0
389
-     * @param mixed  $arguments
390
-     * @return EE_Data_Migration_Script_Base|mixed
391
-     * @throws EE_Error
392
-     * @throws ReflectionException
393
-     */
394
-    public function load_dms($class_name, $arguments = array())
395
-    {
396
-        // retrieve instantiated class
397
-        return $this->_load(
398
-            EE_Data_Migration_Manager::instance()->get_data_migration_script_folders(),
399
-            'EE_DMS_',
400
-            $class_name,
401
-            'dms',
402
-            $arguments,
403
-            false,
404
-            false
405
-        );
406
-    }
407
-
408
-
409
-
410
-    /**
411
-     * loads object creating classes - must be singletons
412
-     *
413
-     * @param string $class_name - simple class name ie: attendee
414
-     * @param mixed  $arguments  - an array of arguments to pass to the class
415
-     * @param bool   $from_db    - some classes are instantiated from the db and thus call a different method to
416
-     *                           instantiate
417
-     * @param bool   $cache      if you don't want the class to be stored in the internal cache (non-persistent) then
418
-     *                           set this to FALSE (ie. when instantiating model objects from client in a loop)
419
-     * @param bool   $load_only  whether or not to just load the file and NOT instantiate, or load AND instantiate
420
-     *                           (default)
421
-     * @return EE_Base_Class | bool
422
-     * @throws EE_Error
423
-     * @throws ReflectionException
424
-     */
425
-    public function load_class($class_name, $arguments = array(), $from_db = false, $cache = true, $load_only = false)
426
-    {
427
-        $paths = apply_filters(
428
-            'FHEE__EE_Registry__load_class__paths', array(
429
-            EE_CORE,
430
-            EE_CLASSES,
431
-            EE_BUSINESS,
432
-        )
433
-        );
434
-        // retrieve instantiated class
435
-        return $this->_load(
436
-            $paths,
437
-            'EE_',
438
-            $class_name,
439
-            'class',
440
-            $arguments,
441
-            $from_db,
442
-            $cache,
443
-            $load_only
444
-        );
445
-    }
446
-
447
-
448
-
449
-    /**
450
-     * loads helper classes - must be singletons
451
-     *
452
-     * @param string $class_name - simple class name ie: price
453
-     * @param mixed  $arguments
454
-     * @param bool   $load_only
455
-     * @return EEH_Base | bool
456
-     * @throws EE_Error
457
-     * @throws ReflectionException
458
-     */
459
-    public function load_helper($class_name, $arguments = array(), $load_only = true)
460
-    {
461
-        // todo: add doing_it_wrong() in a few versions after all addons have had calls to this method removed
462
-        $helper_paths = apply_filters('FHEE__EE_Registry__load_helper__helper_paths', array(EE_HELPERS));
463
-        // retrieve instantiated class
464
-        return $this->_load(
465
-            $helper_paths,
466
-            'EEH_',
467
-            $class_name,
468
-            'helper',
469
-            $arguments,
470
-            false,
471
-            true,
472
-            $load_only
473
-        );
474
-    }
475
-
476
-
477
-
478
-    /**
479
-     * loads core classes - must be singletons
480
-     *
481
-     * @param string $class_name - simple class name ie: session
482
-     * @param mixed  $arguments
483
-     * @param bool   $load_only
484
-     * @param bool   $cache      whether to cache the object or not.
485
-     * @return mixed
486
-     * @throws EE_Error
487
-     * @throws ReflectionException
488
-     */
489
-    public function load_lib($class_name, $arguments = array(), $load_only = false, $cache = true)
490
-    {
491
-        $paths = array(
492
-            EE_LIBRARIES,
493
-            EE_LIBRARIES . 'messages' . DS,
494
-            EE_LIBRARIES . 'shortcodes' . DS,
495
-            EE_LIBRARIES . 'qtips' . DS,
496
-            EE_LIBRARIES . 'payment_methods' . DS,
497
-        );
498
-        // retrieve instantiated class
499
-        return $this->_load(
500
-            $paths,
501
-            'EE_',
502
-            $class_name,
503
-            'lib',
504
-            $arguments,
505
-            false,
506
-            $cache,
507
-            $load_only
508
-        );
509
-    }
510
-
511
-
512
-
513
-    /**
514
-     * loads model classes - must be singletons
515
-     *
516
-     * @param string $class_name - simple class name ie: price
517
-     * @param mixed  $arguments
518
-     * @param bool   $load_only
519
-     * @return EEM_Base | bool
520
-     * @throws EE_Error
521
-     * @throws ReflectionException
522
-     */
523
-    public function load_model($class_name, $arguments = array(), $load_only = false)
524
-    {
525
-        $paths = apply_filters(
526
-            'FHEE__EE_Registry__load_model__paths', array(
527
-            EE_MODELS,
528
-            EE_CORE,
529
-        )
530
-        );
531
-        // retrieve instantiated class
532
-        return $this->_load(
533
-            $paths,
534
-            'EEM_',
535
-            $class_name,
536
-            'model',
537
-            $arguments,
538
-            false,
539
-            true,
540
-            $load_only
541
-        );
542
-    }
543
-
544
-
545
-
546
-    /**
547
-     * loads model classes - must be singletons
548
-     *
549
-     * @param string $class_name - simple class name ie: price
550
-     * @param mixed  $arguments
551
-     * @param bool   $load_only
552
-     * @return mixed | bool
553
-     * @throws EE_Error
554
-     * @throws ReflectionException
555
-     */
556
-    public function load_model_class($class_name, $arguments = array(), $load_only = true)
557
-    {
558
-        $paths = array(
559
-            EE_MODELS . 'fields' . DS,
560
-            EE_MODELS . 'helpers' . DS,
561
-            EE_MODELS . 'relations' . DS,
562
-            EE_MODELS . 'strategies' . DS,
563
-        );
564
-        // retrieve instantiated class
565
-        return $this->_load(
566
-            $paths,
567
-            'EE_',
568
-            $class_name,
569
-            '',
570
-            $arguments,
571
-            false,
572
-            true,
573
-            $load_only
574
-        );
575
-    }
576
-
577
-
578
-
579
-    /**
580
-     * Determines if $model_name is the name of an actual EE model.
581
-     *
582
-     * @param string $model_name like Event, Attendee, Question_Group_Question, etc.
583
-     * @return boolean
584
-     */
585
-    public function is_model_name($model_name)
586
-    {
587
-        return isset($this->models[$model_name]);
588
-    }
589
-
590
-
591
-
592
-    /**
593
-     * generic class loader
594
-     *
595
-     * @param string $path_to_file - directory path to file location, not including filename
596
-     * @param string $file_name    - file name  ie:  my_file.php, including extension
597
-     * @param string $type         - file type - core? class? helper? model?
598
-     * @param mixed  $arguments
599
-     * @param bool   $load_only
600
-     * @return mixed
601
-     * @throws EE_Error
602
-     * @throws ReflectionException
603
-     */
604
-    public function load_file($path_to_file, $file_name, $type = '', $arguments = array(), $load_only = true)
605
-    {
606
-        // retrieve instantiated class
607
-        return $this->_load(
608
-            $path_to_file,
609
-            '',
610
-            $file_name,
611
-            $type,
612
-            $arguments,
613
-            false,
614
-            true,
615
-            $load_only
616
-        );
617
-    }
618
-
619
-
620
-
621
-    /**
622
-     * @param string $path_to_file - directory path to file location, not including filename
623
-     * @param string $class_name   - full class name  ie:  My_Class
624
-     * @param string $type         - file type - core? class? helper? model?
625
-     * @param mixed  $arguments
626
-     * @param bool   $load_only
627
-     * @return bool|EE_Addon|object
628
-     * @throws EE_Error
629
-     * @throws ReflectionException
630
-     */
631
-    public function load_addon($path_to_file, $class_name, $type = 'class', $arguments = array(), $load_only = false)
632
-    {
633
-        // retrieve instantiated class
634
-        return $this->_load(
635
-            $path_to_file,
636
-            'addon',
637
-            $class_name,
638
-            $type,
639
-            $arguments,
640
-            false,
641
-            true,
642
-            $load_only
643
-        );
644
-    }
645
-
646
-
647
-
648
-    /**
649
-     * instantiates, caches, and automatically resolves dependencies
650
-     * for classes that use a Fully Qualified Class Name.
651
-     * if the class is not capable of being loaded using PSR-4 autoloading,
652
-     * then you need to use one of the existing load_*() methods
653
-     * which can resolve the classname and filepath from the passed arguments
654
-     *
655
-     * @param bool|string $class_name   Fully Qualified Class Name
656
-     * @param array       $arguments    an argument, or array of arguments to pass to the class upon instantiation
657
-     * @param bool        $cache        whether to cache the instantiated object for reuse
658
-     * @param bool        $from_db      some classes are instantiated from the db
659
-     *                                  and thus call a different method to instantiate
660
-     * @param bool        $load_only    if true, will only load the file, but will NOT instantiate an object
661
-     * @param bool|string $addon        if true, will cache the object in the EE_Registry->$addons array
662
-     * @return bool|null|mixed          null = failure to load or instantiate class object.
663
-     *                                  object = class loaded and instantiated successfully.
664
-     *                                  bool = fail or success when $load_only is true
665
-     * @throws EE_Error
666
-     * @throws ReflectionException
667
-     */
668
-    public function create(
669
-        $class_name = false,
670
-        $arguments = array(),
671
-        $cache = false,
672
-        $from_db = false,
673
-        $load_only = false,
674
-        $addon = false
675
-    ) {
676
-        $class_name = ltrim($class_name, '\\');
677
-        $class_name = $this->_dependency_map->get_alias($class_name);
678
-        $class_exists = $this->loadOrVerifyClassExists($class_name, $arguments);
679
-        // if a non-FQCN was passed, then verifyClassExists() might return an object
680
-        // or it could return null if the class just could not be found anywhere
681
-        if ($class_exists instanceof $class_name || $class_exists === null){
682
-            // either way, return the results
683
-            return $class_exists;
684
-        }
685
-        $class_name = $class_exists;
686
-        // if we're only loading the class and it already exists, then let's just return true immediately
687
-        if ($load_only) {
688
-            return true;
689
-        }
690
-        $addon = $addon
691
-            ? 'addon'
692
-            : '';
693
-        // $this->_cache_on is toggled during the recursive loading that can occur with dependency injection
694
-        // $cache is controlled by individual calls to separate Registry loader methods like load_class()
695
-        // $load_only is also controlled by individual calls to separate Registry loader methods like load_file()
696
-        if ($this->_cache_on && $cache && ! $load_only) {
697
-            // return object if it's already cached
698
-            $cached_class = $this->_get_cached_class($class_name, $addon);
699
-            if ($cached_class !== null) {
700
-                return $cached_class;
701
-            }
702
-        }
703
-        // obtain the loader method from the dependency map
704
-        $loader = $this->_dependency_map->class_loader($class_name);
705
-        // instantiate the requested object
706
-        if ($loader instanceof Closure) {
707
-            $class_obj = $loader($arguments);
708
-        } else if ($loader && method_exists($this, $loader)) {
709
-            $class_obj = $this->{$loader}($class_name, $arguments);
710
-        } else {
711
-            $class_obj = $this->_create_object($class_name, $arguments, $addon, $from_db);
712
-        }
713
-        if (($this->_cache_on && $cache) || $this->get_class_abbreviation($class_name, '')) {
714
-            // save it for later... kinda like gum  { : $
715
-            $this->_set_cached_class($class_obj, $class_name, $addon, $from_db);
716
-        }
717
-        $this->_cache_on = true;
718
-        return $class_obj;
719
-    }
720
-
721
-
722
-
723
-    /**
724
-     * Recursively checks that a class exists and potentially attempts to load classes with non-FQCNs
725
-     *
726
-     * @param string $class_name
727
-     * @param array  $arguments
728
-     * @param int    $attempt
729
-     * @return mixed
730
-     */
731
-    private function loadOrVerifyClassExists($class_name, array $arguments, $attempt = 1) {
732
-        if (is_object($class_name) || class_exists($class_name)) {
733
-            return $class_name;
734
-        }
735
-        switch ($attempt) {
736
-            case 1:
737
-                // if it's a FQCN then maybe the class is registered with a preceding \
738
-                $class_name = strpos($class_name, '\\') !== false
739
-                    ? '\\' . ltrim($class_name, '\\')
740
-                    : $class_name;
741
-                break;
742
-            case 2:
743
-                //
744
-                $loader = $this->_dependency_map->class_loader($class_name);
745
-                if ($loader && method_exists($this, $loader)) {
746
-                    return $this->{$loader}($class_name, $arguments);
747
-                }
748
-                break;
749
-            case 3:
750
-            default;
751
-                return null;
752
-        }
753
-        $attempt++;
754
-        return $this->loadOrVerifyClassExists($class_name, $arguments, $attempt);
755
-    }
756
-
757
-
758
-
759
-    /**
760
-     * instantiates, caches, and injects dependencies for classes
761
-     *
762
-     * @param array       $file_paths   an array of paths to folders to look in
763
-     * @param string      $class_prefix EE  or EEM or... ???
764
-     * @param bool|string $class_name   $class name
765
-     * @param string      $type         file type - core? class? helper? model?
766
-     * @param mixed       $arguments    an argument or array of arguments to pass to the class upon instantiation
767
-     * @param bool        $from_db      some classes are instantiated from the db
768
-     *                                  and thus call a different method to instantiate
769
-     * @param bool        $cache        whether to cache the instantiated object for reuse
770
-     * @param bool        $load_only    if true, will only load the file, but will NOT instantiate an object
771
-     * @return bool|null|object null = failure to load or instantiate class object.
772
-     *                                  object = class loaded and instantiated successfully.
773
-     *                                  bool = fail or success when $load_only is true
774
-     * @throws EE_Error
775
-     * @throws ReflectionException
776
-     */
777
-    protected function _load(
778
-        $file_paths = array(),
779
-        $class_prefix = 'EE_',
780
-        $class_name = false,
781
-        $type = 'class',
782
-        $arguments = array(),
783
-        $from_db = false,
784
-        $cache = true,
785
-        $load_only = false
786
-    ) {
787
-        $class_name = ltrim($class_name, '\\');
788
-        // strip php file extension
789
-        $class_name = str_replace('.php', '', trim($class_name));
790
-        // does the class have a prefix ?
791
-        if (! empty($class_prefix) && $class_prefix !== 'addon') {
792
-            // make sure $class_prefix is uppercase
793
-            $class_prefix = strtoupper(trim($class_prefix));
794
-            // add class prefix ONCE!!!
795
-            $class_name = $class_prefix . str_replace($class_prefix, '', $class_name);
796
-        }
797
-        $class_name = $this->_dependency_map->get_alias($class_name);
798
-        $class_exists = class_exists($class_name);
799
-        // if we're only loading the class and it already exists, then let's just return true immediately
800
-        if ($load_only && $class_exists) {
801
-            return true;
802
-        }
803
-        // $this->_cache_on is toggled during the recursive loading that can occur with dependency injection
804
-        // $cache is controlled by individual calls to separate Registry loader methods like load_class()
805
-        // $load_only is also controlled by individual calls to separate Registry loader methods like load_file()
806
-        if ($this->_cache_on && $cache && ! $load_only) {
807
-            // return object if it's already cached
808
-            $cached_class = $this->_get_cached_class($class_name, $class_prefix);
809
-            if ($cached_class !== null) {
810
-                return $cached_class;
811
-            }
812
-        }
813
-        // if the class doesn't already exist.. then we need to try and find the file and load it
814
-        if (! $class_exists) {
815
-            // get full path to file
816
-            $path = $this->_resolve_path($class_name, $type, $file_paths);
817
-            // load the file
818
-            $loaded = $this->_require_file($path, $class_name, $type, $file_paths);
819
-            // if loading failed, or we are only loading a file but NOT instantiating an object
820
-            if (! $loaded || $load_only) {
821
-                // return boolean if only loading, or null if an object was expected
822
-                return $load_only
823
-                    ? $loaded
824
-                    : null;
825
-            }
826
-        }
827
-        // instantiate the requested object
828
-        $class_obj = $this->_create_object($class_name, $arguments, $type, $from_db);
829
-        if ($this->_cache_on && $cache) {
830
-            // save it for later... kinda like gum  { : $
831
-            $this->_set_cached_class($class_obj, $class_name, $class_prefix, $from_db);
832
-        }
833
-        $this->_cache_on = true;
834
-        return $class_obj;
835
-    }
836
-
837
-
838
-
839
-    /**
840
-     * @param string $class_name
841
-     * @param string $default have to specify something, but not anything that will conflict
842
-     * @return mixed|string
843
-     */
844
-    protected function get_class_abbreviation($class_name, $default = 'FANCY_BATMAN_PANTS')
845
-    {
846
-        return isset($this->_class_abbreviations[$class_name])
847
-            ? $this->_class_abbreviations[$class_name]
848
-            : $default;
849
-    }
850
-
851
-    /**
852
-     * attempts to find a cached version of the requested class
853
-     * by looking in the following places:
854
-     *        $this->{$class_abbreviation}            ie:    $this->CART
855
-     *        $this->{$class_name}                        ie:    $this->Some_Class
856
-     *        $this->LIB->{$class_name}                ie:    $this->LIB->Some_Class
857
-     *        $this->addon->{$class_name}    ie:    $this->addon->Some_Addon_Class
858
-     *
859
-     * @param string $class_name
860
-     * @param string $class_prefix
861
-     * @return mixed
862
-     */
863
-    protected function _get_cached_class($class_name, $class_prefix = '')
864
-    {
865
-        if ($class_name === 'EE_Registry') {
866
-            return $this;
867
-        }
868
-        $class_abbreviation = $this->get_class_abbreviation($class_name);
869
-        $class_name = str_replace('\\', '_', $class_name);
870
-        // check if class has already been loaded, and return it if it has been
871
-        if (isset($this->{$class_abbreviation})) {
872
-            return $this->{$class_abbreviation};
873
-        }
874
-        if (isset ($this->{$class_name})) {
875
-            return $this->{$class_name};
876
-        }
877
-        if (isset ($this->LIB->{$class_name})) {
878
-            return $this->LIB->{$class_name};
879
-        }
880
-        if ($class_prefix === 'addon' && isset ($this->addons->{$class_name})) {
881
-            return $this->addons->{$class_name};
882
-        }
883
-        return null;
884
-    }
885
-
886
-
887
-
888
-    /**
889
-     * removes a cached version of the requested class
890
-     *
891
-     * @param string  $class_name
892
-     * @param boolean $addon
893
-     * @return boolean
894
-     */
895
-    public function clear_cached_class($class_name, $addon = false)
896
-    {
897
-        $class_abbreviation = $this->get_class_abbreviation($class_name);
898
-        $class_name = str_replace('\\', '_', $class_name);
899
-        // check if class has already been loaded, and return it if it has been
900
-        if (isset($this->{$class_abbreviation})) {
901
-            $this->{$class_abbreviation} = null;
902
-            return true;
903
-        }
904
-        if (isset($this->{$class_name})) {
905
-            $this->{$class_name} = null;
906
-            return true;
907
-        }
908
-        if (isset($this->LIB->{$class_name})) {
909
-            unset($this->LIB->{$class_name});
910
-            return true;
911
-        }
912
-        if ($addon && isset($this->addons->{$class_name})) {
913
-            unset($this->addons->{$class_name});
914
-            return true;
915
-        }
916
-        return false;
917
-    }
918
-
919
-
920
-
921
-    /**
922
-     * attempts to find a full valid filepath for the requested class.
923
-     * loops thru each of the base paths in the $file_paths array and appends : "{classname} . {file type} . php"
924
-     * then returns that path if the target file has been found and is readable
925
-     *
926
-     * @param string $class_name
927
-     * @param string $type
928
-     * @param array  $file_paths
929
-     * @return string | bool
930
-     */
931
-    protected function _resolve_path($class_name, $type = '', $file_paths = array())
932
-    {
933
-        // make sure $file_paths is an array
934
-        $file_paths = is_array($file_paths)
935
-            ? $file_paths
936
-            : array($file_paths);
937
-        // cycle thru paths
938
-        foreach ($file_paths as $key => $file_path) {
939
-            // convert all separators to proper DS, if no filepath, then use EE_CLASSES
940
-            $file_path = $file_path
941
-                ? str_replace(array('/', '\\'), DS, $file_path)
942
-                : EE_CLASSES;
943
-            // prep file type
944
-            $type = ! empty($type)
945
-                ? trim($type, '.') . '.'
946
-                : '';
947
-            // build full file path
948
-            $file_paths[$key] = rtrim($file_path, DS) . DS . $class_name . '.' . $type . 'php';
949
-            //does the file exist and can be read ?
950
-            if (is_readable($file_paths[$key])) {
951
-                return $file_paths[$key];
952
-            }
953
-        }
954
-        return false;
955
-    }
956
-
957
-
958
-
959
-    /**
960
-     * basically just performs a require_once()
961
-     * but with some error handling
962
-     *
963
-     * @param  string $path
964
-     * @param  string $class_name
965
-     * @param  string $type
966
-     * @param  array  $file_paths
967
-     * @return bool
968
-     * @throws EE_Error
969
-     * @throws ReflectionException
970
-     */
971
-    protected function _require_file($path, $class_name, $type = '', $file_paths = array())
972
-    {
973
-        // don't give up! you gotta...
974
-        try {
975
-            //does the file exist and can it be read ?
976
-            if (! $path) {
977
-                // so sorry, can't find the file
978
-                throw new EE_Error (
979
-                    sprintf(
980
-                        esc_html__(
981
-                            'The %1$s file %2$s could not be located or is not readable due to file permissions. Please ensure that the following filepath(s) are correct: %3$s',
982
-                            'event_espresso'
983
-                        ),
984
-                        trim($type, '.'),
985
-                        $class_name,
986
-                        '<br />' . implode(',<br />', $file_paths)
987
-                    )
988
-                );
989
-            }
990
-            // get the file
991
-            require_once($path);
992
-            // if the class isn't already declared somewhere
993
-            if (class_exists($class_name, false) === false) {
994
-                // so sorry, not a class
995
-                throw new EE_Error(
996
-                    sprintf(
997
-                        esc_html__('The %s file %s does not appear to contain the %s Class.', 'event_espresso'),
998
-                        $type,
999
-                        $path,
1000
-                        $class_name
1001
-                    )
1002
-                );
1003
-            }
1004
-        } catch (EE_Error $e) {
1005
-            $e->get_error();
1006
-            return false;
1007
-        }
1008
-        return true;
1009
-    }
1010
-
1011
-
1012
-
1013
-    /**
1014
-     * _create_object
1015
-     * Attempts to instantiate the requested class via any of the
1016
-     * commonly used instantiation methods employed throughout EE.
1017
-     * The priority for instantiation is as follows:
1018
-     *        - abstract classes or any class flagged as "load only" (no instantiation occurs)
1019
-     *        - model objects via their 'new_instance_from_db' method
1020
-     *        - model objects via their 'new_instance' method
1021
-     *        - "singleton" classes" via their 'instance' method
1022
-     *    - standard instantiable classes via their __constructor
1023
-     * Prior to instantiation, if the classname exists in the dependency_map,
1024
-     * then the constructor for the requested class will be examined to determine
1025
-     * if any dependencies exist, and if they can be injected.
1026
-     * If so, then those classes will be added to the array of arguments passed to the constructor
1027
-     *
1028
-     * @param string $class_name
1029
-     * @param array  $arguments
1030
-     * @param string $type
1031
-     * @param bool   $from_db
1032
-     * @return null|object
1033
-     * @throws EE_Error
1034
-     * @throws ReflectionException
1035
-     */
1036
-    protected function _create_object($class_name, $arguments = array(), $type = '', $from_db = false)
1037
-    {
1038
-        $class_obj = null;
1039
-        $instantiation_mode = '0) none';
1040
-        // don't give up! you gotta...
1041
-        try {
1042
-            // create reflection
1043
-            $reflector = $this->get_ReflectionClass($class_name);
1044
-            // make sure arguments are an array
1045
-            $arguments = is_array($arguments)
1046
-                ? $arguments
1047
-                : array($arguments);
1048
-            // and if arguments array is numerically and sequentially indexed, then we want it to remain as is,
1049
-            // else wrap it in an additional array so that it doesn't get split into multiple parameters
1050
-            $arguments = $this->_array_is_numerically_and_sequentially_indexed($arguments)
1051
-                ? $arguments
1052
-                : array($arguments);
1053
-            // attempt to inject dependencies ?
1054
-            if ($this->_dependency_map->has($class_name)) {
1055
-                $arguments = $this->_resolve_dependencies($reflector, $class_name, $arguments);
1056
-            }
1057
-            // instantiate the class if possible
1058
-            if ($reflector->isAbstract()) {
1059
-                // nothing to instantiate, loading file was enough
1060
-                // does not throw an exception so $instantiation_mode is unused
1061
-                // $instantiation_mode = "1) no constructor abstract class";
1062
-                $class_obj = true;
1063
-            } else if (empty($arguments) && $reflector->getConstructor() === null && $reflector->isInstantiable()) {
1064
-                // no constructor = static methods only... nothing to instantiate, loading file was enough
1065
-                $instantiation_mode = '2) no constructor but instantiable';
1066
-                $class_obj = $reflector->newInstance();
1067
-            } else if ($from_db && method_exists($class_name, 'new_instance_from_db')) {
1068
-                $instantiation_mode = '3) new_instance_from_db()';
1069
-                $class_obj = call_user_func_array(array($class_name, 'new_instance_from_db'), $arguments);
1070
-            } else if (method_exists($class_name, 'new_instance')) {
1071
-                $instantiation_mode = '4) new_instance()';
1072
-                $class_obj = call_user_func_array(array($class_name, 'new_instance'), $arguments);
1073
-            } else if (method_exists($class_name, 'instance')) {
1074
-                $instantiation_mode = '5) instance()';
1075
-                $class_obj = call_user_func_array(array($class_name, 'instance'), $arguments);
1076
-            } else if ($reflector->isInstantiable()) {
1077
-                $instantiation_mode = '6) constructor';
1078
-                $class_obj = $reflector->newInstanceArgs($arguments);
1079
-            } else {
1080
-                // heh ? something's not right !
1081
-                throw new EE_Error(
1082
-                    sprintf(
1083
-                        esc_html__('The %s file %s could not be instantiated.', 'event_espresso'),
1084
-                        $type,
1085
-                        $class_name
1086
-                    )
1087
-                );
1088
-            }
1089
-        } catch (Exception $e) {
1090
-            if (! $e instanceof EE_Error) {
1091
-                $e = new EE_Error(
1092
-                    sprintf(
1093
-                        esc_html__(
1094
-                            'The following error occurred while attempting to instantiate "%1$s": %2$s %3$s %2$s instantiation mode : %4$s',
1095
-                            'event_espresso'
1096
-                        ),
1097
-                        $class_name,
1098
-                        '<br />',
1099
-                        $e->getMessage(),
1100
-                        $instantiation_mode
1101
-                    )
1102
-                );
1103
-            }
1104
-            $e->get_error();
1105
-        }
1106
-        return $class_obj;
1107
-    }
1108
-
1109
-
1110
-
1111
-    /**
1112
-     * @see http://stackoverflow.com/questions/173400/how-to-check-if-php-array-is-associative-or-sequential
1113
-     * @param array $array
1114
-     * @return bool
1115
-     */
1116
-    protected function _array_is_numerically_and_sequentially_indexed(array $array)
1117
-    {
1118
-        return ! empty($array)
1119
-            ? array_keys($array) === range(0, count($array) - 1)
1120
-            : true;
1121
-    }
1122
-
1123
-
1124
-
1125
-    /**
1126
-     * getReflectionClass
1127
-     * checks if a ReflectionClass object has already been generated for a class
1128
-     * and returns that instead of creating a new one
1129
-     *
1130
-     * @param string $class_name
1131
-     * @return ReflectionClass
1132
-     * @throws ReflectionException
1133
-     */
1134
-    public function get_ReflectionClass($class_name)
1135
-    {
1136
-        if (
1137
-            ! isset($this->_reflectors[$class_name])
1138
-            || ! $this->_reflectors[$class_name] instanceof ReflectionClass
1139
-        ) {
1140
-            $this->_reflectors[$class_name] = new ReflectionClass($class_name);
1141
-        }
1142
-        return $this->_reflectors[$class_name];
1143
-    }
1144
-
1145
-
1146
-
1147
-    /**
1148
-     * _resolve_dependencies
1149
-     * examines the constructor for the requested class to determine
1150
-     * if any dependencies exist, and if they can be injected.
1151
-     * If so, then those classes will be added to the array of arguments passed to the constructor
1152
-     * PLZ NOTE: this is achieved by type hinting the constructor params
1153
-     * For example:
1154
-     *        if attempting to load a class "Foo" with the following constructor:
1155
-     *        __construct( Bar $bar_class, Fighter $grohl_class )
1156
-     *        then $bar_class and $grohl_class will be added to the $arguments array,
1157
-     *        but only IF they are NOT already present in the incoming arguments array,
1158
-     *        and the correct classes can be loaded
1159
-     *
1160
-     * @param ReflectionClass $reflector
1161
-     * @param string          $class_name
1162
-     * @param array           $arguments
1163
-     * @return array
1164
-     * @throws EE_Error
1165
-     * @throws ReflectionException
1166
-     */
1167
-    protected function _resolve_dependencies(ReflectionClass $reflector, $class_name, $arguments = array())
1168
-    {
1169
-        // let's examine the constructor
1170
-        $constructor = $reflector->getConstructor();
1171
-        // whu? huh? nothing?
1172
-        if (! $constructor) {
1173
-            return $arguments;
1174
-        }
1175
-        // get constructor parameters
1176
-        $params = $constructor->getParameters();
1177
-        // and the keys for the incoming arguments array so that we can compare existing arguments with what is expected
1178
-        $argument_keys = array_keys($arguments);
1179
-        // now loop thru all of the constructors expected parameters
1180
-        foreach ($params as $index => $param) {
1181
-            // is this a dependency for a specific class ?
1182
-            $param_class = $param->getClass()
1183
-                ? $param->getClass()->name
1184
-                : null;
1185
-            // BUT WAIT !!! This class may be an alias for something else (or getting replaced at runtime)
1186
-            $param_class = $this->_dependency_map->has_alias($param_class, $class_name)
1187
-                ? $this->_dependency_map->get_alias($param_class, $class_name)
1188
-                : $param_class;
1189
-            if (
1190
-                // param is not even a class
1191
-                $param_class === null
1192
-                // and something already exists in the incoming arguments for this param
1193
-                && isset($argument_keys[$index], $arguments[$argument_keys[$index]])
1194
-            ) {
1195
-                // so let's skip this argument and move on to the next
1196
-                continue;
1197
-            }
1198
-            if (
1199
-                // parameter is type hinted as a class, exists as an incoming argument, AND it's the correct class
1200
-                $param_class !== null
1201
-                && isset($argument_keys[$index], $arguments[$argument_keys[$index]])
1202
-                && $arguments[$argument_keys[$index]] instanceof $param_class
1203
-            ) {
1204
-                // skip this argument and move on to the next
1205
-                continue;
1206
-            }
1207
-            if (
1208
-                // parameter is type hinted as a class, and should be injected
1209
-                $param_class !== null
1210
-                && $this->_dependency_map->has_dependency_for_class($class_name, $param_class)
1211
-            ) {
1212
-                $arguments = $this->_resolve_dependency(
1213
-                    $class_name,
1214
-                    $param_class,
1215
-                    $arguments,
1216
-                    $index,
1217
-                    $argument_keys
1218
-                );
1219
-            } else {
1220
-                try {
1221
-                    $arguments[$index] = $param->isDefaultValueAvailable()
1222
-                        ? $param->getDefaultValue()
1223
-                        : null;
1224
-                } catch (ReflectionException $e) {
1225
-                    throw new ReflectionException(
1226
-                        sprintf(
1227
-                            esc_html__('%1$s for parameter "$%2$s"', 'event_espresso'),
1228
-                            $e->getMessage(),
1229
-                            $param->getName()
1230
-                        )
1231
-                    );
1232
-                }
1233
-            }
1234
-        }
1235
-        return $arguments;
1236
-    }
1237
-
1238
-
1239
-
1240
-    /**
1241
-     * @param string $class_name
1242
-     * @param string $param_class
1243
-     * @param array  $arguments
1244
-     * @param mixed  $index
1245
-     * @param array  $argument_keys
1246
-     * @return array
1247
-     * @throws EE_Error
1248
-     * @throws ReflectionException
1249
-     * @throws InvalidArgumentException
1250
-     * @throws InvalidInterfaceException
1251
-     * @throws InvalidDataTypeException
1252
-     */
1253
-    protected function _resolve_dependency($class_name, $param_class, $arguments, $index, array $argument_keys)
1254
-    {
1255
-        $dependency = null;
1256
-        // should dependency be loaded from cache ?
1257
-        $cache_on = $this->_dependency_map->loading_strategy_for_class_dependency(
1258
-            $class_name,
1259
-            $param_class
1260
-        );
1261
-        $cache_on = $cache_on !== EE_Dependency_Map::load_new_object;
1262
-        // we might have a dependency...
1263
-        // let's MAYBE try and find it in our cache if that's what's been requested
1264
-        $cached_class = $cache_on
1265
-            ? $this->_get_cached_class($param_class)
1266
-            : null;
1267
-        // and grab it if it exists
1268
-        if ($cached_class instanceof $param_class) {
1269
-            $dependency = $cached_class;
1270
-        } else if ($param_class !== $class_name) {
1271
-            // obtain the loader method from the dependency map
1272
-            $loader = $this->_dependency_map->class_loader($param_class);
1273
-            // is loader a custom closure ?
1274
-            if ($loader instanceof Closure) {
1275
-                $dependency = $loader($arguments);
1276
-            } else {
1277
-                // set the cache on property for the recursive loading call
1278
-                $this->_cache_on = $cache_on;
1279
-                // if not, then let's try and load it via the registry
1280
-                if ($loader && method_exists($this, $loader)) {
1281
-                    $dependency = $this->{$loader}($param_class);
1282
-                } else {
1283
-                    $dependency = LoaderFactory::getLoader()->load(
1284
-                        $param_class,
1285
-                        array(),
1286
-                        $cache_on
1287
-                    );
1288
-                }
1289
-            }
1290
-        }
1291
-        // did we successfully find the correct dependency ?
1292
-        if ($dependency instanceof $param_class) {
1293
-            // then let's inject it into the incoming array of arguments at the correct location
1294
-            $arguments[$index] = $dependency;
1295
-        }
1296
-        return $arguments;
1297
-    }
1298
-
1299
-
1300
-
1301
-    /**
1302
-     * _set_cached_class
1303
-     * attempts to cache the instantiated class locally
1304
-     * in one of the following places, in the following order:
1305
-     *        $this->{class_abbreviation}   ie:    $this->CART
1306
-     *        $this->{$class_name}          ie:    $this->Some_Class
1307
-     *        $this->addon->{$$class_name}    ie:    $this->addon->Some_Addon_Class
1308
-     *        $this->LIB->{$class_name}     ie:    $this->LIB->Some_Class
1309
-     *
1310
-     * @param object $class_obj
1311
-     * @param string $class_name
1312
-     * @param string $class_prefix
1313
-     * @param bool   $from_db
1314
-     * @return void
1315
-     */
1316
-    protected function _set_cached_class($class_obj, $class_name, $class_prefix = '', $from_db = false)
1317
-    {
1318
-        if ($class_name === 'EE_Registry' || empty($class_obj)) {
1319
-            return;
1320
-        }
1321
-        // return newly instantiated class
1322
-        $class_abbreviation = $this->get_class_abbreviation($class_name, '');
1323
-        if ($class_abbreviation) {
1324
-            $this->{$class_abbreviation} = $class_obj;
1325
-            return;
1326
-        }
1327
-        $class_name = str_replace('\\', '_', $class_name);
1328
-        if (property_exists($this, $class_name)) {
1329
-            $this->{$class_name} = $class_obj;
1330
-            return;
1331
-        }
1332
-        if ($class_prefix === 'addon') {
1333
-            $this->addons->{$class_name} = $class_obj;
1334
-            return;
1335
-        }
1336
-        if (! $from_db) {
1337
-            $this->LIB->{$class_name} = $class_obj;
1338
-        }
1339
-    }
1340
-
1341
-
1342
-
1343
-    /**
1344
-     * call any loader that's been registered in the EE_Dependency_Map::$_class_loaders array
1345
-     *
1346
-     * @param string $classname PLEASE NOTE: the class name needs to match what's registered
1347
-     *                          in the EE_Dependency_Map::$_class_loaders array,
1348
-     *                          including the class prefix, ie: "EE_", "EEM_", "EEH_", etc
1349
-     * @param array  $arguments
1350
-     * @return object
1351
-     */
1352
-    public static function factory($classname, $arguments = array())
1353
-    {
1354
-        $loader = self::instance()->_dependency_map->class_loader($classname);
1355
-        if ($loader instanceof Closure) {
1356
-            return $loader($arguments);
1357
-        }
1358
-        if (method_exists(self::instance(), $loader)) {
1359
-            return self::instance()->{$loader}($classname, $arguments);
1360
-        }
1361
-        return null;
1362
-    }
1363
-
1364
-
1365
-
1366
-    /**
1367
-     * Gets the addon by its name/slug (not classname. For that, just
1368
-     * use the classname as the property name on EE_Config::instance()->addons)
1369
-     *
1370
-     * @param string $name
1371
-     * @return EE_Addon
1372
-     */
1373
-    public function get_addon_by_name($name)
1374
-    {
1375
-        foreach ($this->addons as $addon) {
1376
-            if ($addon->name() === $name) {
1377
-                return $addon;
1378
-            }
1379
-        }
1380
-        return null;
1381
-    }
1382
-
1383
-
1384
-
1385
-    /**
1386
-     * Gets an array of all the registered addons, where the keys are their names. (ie, what each returns for their
1387
-     * name() function) They're already available on EE_Config::instance()->addons as properties, where each property's
1388
-     * name is the addon's classname. So if you just want to get the addon by classname, use
1389
-     * EE_Config::instance()->addons->{classname}
1390
-     *
1391
-     * @return EE_Addon[] where the KEYS are the addon's name()
1392
-     */
1393
-    public function get_addons_by_name()
1394
-    {
1395
-        $addons = array();
1396
-        foreach ($this->addons as $addon) {
1397
-            $addons[$addon->name()] = $addon;
1398
-        }
1399
-        return $addons;
1400
-    }
1401
-
1402
-
1403
-
1404
-    /**
1405
-     * Resets the specified model's instance AND makes sure EE_Registry doesn't keep
1406
-     * a stale copy of it around
1407
-     *
1408
-     * @param string $model_name
1409
-     * @return \EEM_Base
1410
-     * @throws \EE_Error
1411
-     */
1412
-    public function reset_model($model_name)
1413
-    {
1414
-        $model_class_name = strpos($model_name, 'EEM_') !== 0
1415
-            ? "EEM_{$model_name}"
1416
-            : $model_name;
1417
-        if (! isset($this->LIB->{$model_class_name}) || ! $this->LIB->{$model_class_name} instanceof EEM_Base) {
1418
-            return null;
1419
-        }
1420
-        //get that model reset it and make sure we nuke the old reference to it
1421
-        if ($this->LIB->{$model_class_name} instanceof $model_class_name
1422
-            && is_callable(
1423
-                array($model_class_name, 'reset')
1424
-            )) {
1425
-            $this->LIB->{$model_class_name} = $this->LIB->{$model_class_name}->reset();
1426
-        } else {
1427
-            throw new EE_Error(sprintf(esc_html__('Model %s does not have a method "reset"', 'event_espresso'), $model_name));
1428
-        }
1429
-        return $this->LIB->{$model_class_name};
1430
-    }
1431
-
1432
-
1433
-
1434
-    /**
1435
-     * Resets the registry.
1436
-     * The criteria for what gets reset is based on what can be shared between sites on the same request when
1437
-     * switch_to_blog is used in a multisite install.  Here is a list of things that are NOT reset.
1438
-     * - $_dependency_map
1439
-     * - $_class_abbreviations
1440
-     * - $NET_CFG (EE_Network_Config): The config is shared network wide so no need to reset.
1441
-     * - $REQ:  Still on the same request so no need to change.
1442
-     * - $CAP: There is no site specific state in the EE_Capability class.
1443
-     * - $SSN: Although ideally, the session should not be shared between site switches, we can't reset it because only
1444
-     * one Session can be active in a single request.  Resetting could resolve in "headers already sent" errors.
1445
-     * - $addons:  In multisite, the state of the addons is something controlled via hooks etc in a normal request.  So
1446
-     *             for now, we won't reset the addons because it could break calls to an add-ons class/methods in the
1447
-     *             switch or on the restore.
1448
-     * - $modules
1449
-     * - $shortcodes
1450
-     * - $widgets
1451
-     *
1452
-     * @param boolean $hard             [deprecated]
1453
-     * @param boolean $reinstantiate    whether to create new instances of EE_Registry's singletons too,
1454
-     *                                  or just reset without re-instantiating (handy to set to FALSE if you're not
1455
-     *                                  sure if you CAN currently reinstantiate the singletons at the moment)
1456
-     * @param   bool  $reset_models     Defaults to true.  When false, then the models are not reset.  This is so
1457
-     *                                  client
1458
-     *                                  code instead can just change the model context to a different blog id if
1459
-     *                                  necessary
1460
-     * @return EE_Registry
1461
-     * @throws EE_Error
1462
-     * @throws ReflectionException
1463
-     */
1464
-    public static function reset($hard = false, $reinstantiate = true, $reset_models = true)
1465
-    {
1466
-        $instance = self::instance();
1467
-        $instance->_cache_on = true;
1468
-        // reset some "special" classes
1469
-        EEH_Activation::reset();
1470
-        $hard = apply_filters( 'FHEE__EE_Registry__reset__hard', $hard);
1471
-        $instance->CFG = EE_Config::reset($hard, $reinstantiate);
1472
-        $instance->CART = null;
1473
-        $instance->MRM = null;
1474
-        $instance->AssetsRegistry = $instance->create('EventEspresso\core\services\assets\Registry');
1475
-        //messages reset
1476
-        EED_Messages::reset();
1477
-        //handle of objects cached on LIB
1478
-        foreach (array('LIB', 'modules') as $cache) {
1479
-            foreach ($instance->{$cache} as $class_name => $class) {
1480
-                if (self::_reset_and_unset_object($class, $reset_models)) {
1481
-                    unset($instance->{$cache}->{$class_name});
1482
-                }
1483
-            }
1484
-        }
1485
-        return $instance;
1486
-    }
1487
-
1488
-
1489
-
1490
-    /**
1491
-     * if passed object implements ResettableInterface, then call it's reset() method
1492
-     * if passed object implements InterminableInterface, then return false,
1493
-     * to indicate that it should NOT be cleared from the Registry cache
1494
-     *
1495
-     * @param      $object
1496
-     * @param bool $reset_models
1497
-     * @return bool returns true if cached object should be unset
1498
-     */
1499
-    private static function _reset_and_unset_object($object, $reset_models)
1500
-    {
1501
-        if (! is_object($object)) {
1502
-            // don't unset anything that's not an object
1503
-            return false;
1504
-        }
1505
-        if ($object instanceof EED_Module) {
1506
-            $object::reset();
1507
-            // don't unset modules
1508
-            return false;
1509
-        }
1510
-        if ($object instanceof ResettableInterface) {
1511
-            if ($object instanceof EEM_Base) {
1512
-                if ($reset_models) {
1513
-                    $object->reset();
1514
-                    return true;
1515
-                }
1516
-                return false;
1517
-            }
1518
-            $object->reset();
1519
-            return true;
1520
-        }
1521
-        if (! $object instanceof InterminableInterface) {
1522
-            return true;
1523
-        }
1524
-        return false;
1525
-    }
1526
-
1527
-
1528
-
1529
-    /**
1530
-     * Gets all the custom post type models defined
1531
-     *
1532
-     * @return array keys are model "short names" (Eg "Event") and keys are classnames (eg "EEM_Event")
1533
-     */
1534
-    public function cpt_models()
1535
-    {
1536
-        $cpt_models = array();
1537
-        foreach ($this->non_abstract_db_models as $short_name => $classname) {
1538
-            if (is_subclass_of($classname, 'EEM_CPT_Base')) {
1539
-                $cpt_models[$short_name] = $classname;
1540
-            }
1541
-        }
1542
-        return $cpt_models;
1543
-    }
1544
-
1545
-
1546
-
1547
-    /**
1548
-     * @return \EE_Config
1549
-     */
1550
-    public static function CFG()
1551
-    {
1552
-        return self::instance()->CFG;
1553
-    }
25
+	/**
26
+	 * @var EE_Registry $_instance
27
+	 */
28
+	private static $_instance;
29
+
30
+	/**
31
+	 * @var EE_Dependency_Map $_dependency_map
32
+	 */
33
+	protected $_dependency_map;
34
+
35
+	/**
36
+	 * @var array $_class_abbreviations
37
+	 */
38
+	protected $_class_abbreviations = array();
39
+
40
+	/**
41
+	 * @var CommandBusInterface $BUS
42
+	 */
43
+	public $BUS;
44
+
45
+	/**
46
+	 * @var EE_Cart $CART
47
+	 */
48
+	public $CART;
49
+
50
+	/**
51
+	 * @var EE_Config $CFG
52
+	 */
53
+	public $CFG;
54
+
55
+	/**
56
+	 * @var EE_Network_Config $NET_CFG
57
+	 */
58
+	public $NET_CFG;
59
+
60
+	/**
61
+	 * StdClass object for storing library classes in
62
+	 *
63
+	 * @var StdClass $LIB
64
+	 */
65
+	public $LIB;
66
+
67
+	/**
68
+	 * @var EE_Request_Handler $REQ
69
+	 */
70
+	public $REQ;
71
+
72
+	/**
73
+	 * @var EE_Session $SSN
74
+	 */
75
+	public $SSN;
76
+
77
+	/**
78
+	 * @since 4.5.0
79
+	 * @var EE_Capabilities $CAP
80
+	 */
81
+	public $CAP;
82
+
83
+	/**
84
+	 * @since 4.9.0
85
+	 * @var EE_Message_Resource_Manager $MRM
86
+	 */
87
+	public $MRM;
88
+
89
+
90
+	/**
91
+	 * @var Registry $AssetsRegistry
92
+	 */
93
+	public $AssetsRegistry;
94
+
95
+	/**
96
+	 * StdClass object for holding addons which have registered themselves to work with EE core
97
+	 *
98
+	 * @var EE_Addon[] $addons
99
+	 */
100
+	public $addons;
101
+
102
+	/**
103
+	 * keys are 'short names' (eg Event), values are class names (eg 'EEM_Event')
104
+	 *
105
+	 * @var EEM_Base[] $models
106
+	 */
107
+	public $models = array();
108
+
109
+	/**
110
+	 * @var EED_Module[] $modules
111
+	 */
112
+	public $modules;
113
+
114
+	/**
115
+	 * @var EES_Shortcode[] $shortcodes
116
+	 */
117
+	public $shortcodes;
118
+
119
+	/**
120
+	 * @var WP_Widget[] $widgets
121
+	 */
122
+	public $widgets;
123
+
124
+	/**
125
+	 * this is an array of all implemented model names (i.e. not the parent abstract models, or models
126
+	 * which don't actually fetch items from the DB in the normal way (ie, are not children of EEM_Base)).
127
+	 * Keys are model "short names" (eg "Event") as used in model relations, and values are
128
+	 * classnames (eg "EEM_Event")
129
+	 *
130
+	 * @var array $non_abstract_db_models
131
+	 */
132
+	public $non_abstract_db_models = array();
133
+
134
+
135
+	/**
136
+	 * internationalization for JS strings
137
+	 *    usage:   EE_Registry::i18n_js_strings['string_key'] = esc_html__( 'string to translate.', 'event_espresso' );
138
+	 *    in js file:  var translatedString = eei18n.string_key;
139
+	 *
140
+	 * @var array $i18n_js_strings
141
+	 */
142
+	public static $i18n_js_strings = array();
143
+
144
+
145
+	/**
146
+	 * $main_file - path to espresso.php
147
+	 *
148
+	 * @var array $main_file
149
+	 */
150
+	public $main_file;
151
+
152
+	/**
153
+	 * array of ReflectionClass objects where the key is the class name
154
+	 *
155
+	 * @var ReflectionClass[] $_reflectors
156
+	 */
157
+	public $_reflectors;
158
+
159
+	/**
160
+	 * boolean flag to indicate whether or not to load/save dependencies from/to the cache
161
+	 *
162
+	 * @var boolean $_cache_on
163
+	 */
164
+	protected $_cache_on = true;
165
+
166
+
167
+
168
+	/**
169
+	 * @singleton method used to instantiate class object
170
+	 * @param  EE_Dependency_Map $dependency_map
171
+	 * @return EE_Registry instance
172
+	 * @throws InvalidArgumentException
173
+	 * @throws InvalidInterfaceException
174
+	 * @throws InvalidDataTypeException
175
+	 */
176
+	public static function instance(EE_Dependency_Map $dependency_map = null)
177
+	{
178
+		// check if class object is instantiated
179
+		if (! self::$_instance instanceof EE_Registry) {
180
+			self::$_instance = new self($dependency_map);
181
+		}
182
+		return self::$_instance;
183
+	}
184
+
185
+
186
+
187
+	/**
188
+	 * protected constructor to prevent direct creation
189
+	 *
190
+	 * @Constructor
191
+	 * @param  EE_Dependency_Map $dependency_map
192
+	 * @throws InvalidDataTypeException
193
+	 * @throws InvalidInterfaceException
194
+	 * @throws InvalidArgumentException
195
+	 */
196
+	protected function __construct(EE_Dependency_Map $dependency_map)
197
+	{
198
+		$this->_dependency_map = $dependency_map;
199
+		$this->LIB = new stdClass();
200
+		$this->addons = new stdClass();
201
+		$this->modules = new stdClass();
202
+		$this->shortcodes = new stdClass();
203
+		$this->widgets = new stdClass();
204
+		add_action('EE_Load_Espresso_Core__handle_request__initialize_core_loading', array($this, 'initialize'));
205
+	}
206
+
207
+
208
+
209
+	/**
210
+	 * initialize
211
+	 *
212
+	 * @throws EE_Error
213
+	 * @throws ReflectionException
214
+	 */
215
+	public function initialize()
216
+	{
217
+		$this->_class_abbreviations = apply_filters(
218
+			'FHEE__EE_Registry____construct___class_abbreviations',
219
+			array(
220
+				'EE_Config'                                       => 'CFG',
221
+				'EE_Session'                                      => 'SSN',
222
+				'EE_Capabilities'                                 => 'CAP',
223
+				'EE_Cart'                                         => 'CART',
224
+				'EE_Network_Config'                               => 'NET_CFG',
225
+				'EE_Request_Handler'                              => 'REQ',
226
+				'EE_Message_Resource_Manager'                     => 'MRM',
227
+				'EventEspresso\core\services\commands\CommandBus' => 'BUS',
228
+				'EventEspresso\core\services\assets\Registry'     => 'AssetsRegistry',
229
+			)
230
+		);
231
+		$this->load_core('Base', array(), true);
232
+		// add our request and response objects to the cache
233
+		$request_loader = $this->_dependency_map->class_loader('EE_Request');
234
+		$this->_set_cached_class(
235
+			$request_loader(),
236
+			'EE_Request'
237
+		);
238
+		$response_loader = $this->_dependency_map->class_loader('EE_Response');
239
+		$this->_set_cached_class(
240
+			$response_loader(),
241
+			'EE_Response'
242
+		);
243
+		add_action('AHEE__EE_System__set_hooks_for_core', array($this, 'init'));
244
+	}
245
+
246
+
247
+
248
+	/**
249
+	 * @return void
250
+	 */
251
+	public function init()
252
+	{
253
+		// Get current page protocol
254
+		$protocol = isset($_SERVER['HTTPS']) ? 'https://' : 'http://';
255
+		// Output admin-ajax.php URL with same protocol as current page
256
+		self::$i18n_js_strings['ajax_url'] = admin_url('admin-ajax.php', $protocol);
257
+		self::$i18n_js_strings['wp_debug'] = defined('WP_DEBUG') ? WP_DEBUG : false;
258
+	}
259
+
260
+
261
+
262
+	/**
263
+	 * localize_i18n_js_strings
264
+	 *
265
+	 * @return string
266
+	 */
267
+	public static function localize_i18n_js_strings()
268
+	{
269
+		$i18n_js_strings = (array)self::$i18n_js_strings;
270
+		foreach ($i18n_js_strings as $key => $value) {
271
+			if (is_scalar($value)) {
272
+				$i18n_js_strings[$key] = html_entity_decode((string)$value, ENT_QUOTES, 'UTF-8');
273
+			}
274
+		}
275
+		return '/* <![CDATA[ */ var eei18n = ' . wp_json_encode($i18n_js_strings) . '; /* ]]> */';
276
+	}
277
+
278
+
279
+
280
+	/**
281
+	 * @param mixed string | EED_Module $module
282
+	 * @throws EE_Error
283
+	 * @throws ReflectionException
284
+	 */
285
+	public function add_module($module)
286
+	{
287
+		if ($module instanceof EED_Module) {
288
+			$module_class = get_class($module);
289
+			$this->modules->{$module_class} = $module;
290
+		} else {
291
+			if (! class_exists('EE_Module_Request_Router')) {
292
+				$this->load_core('Module_Request_Router');
293
+			}
294
+			EE_Module_Request_Router::module_factory($module);
295
+		}
296
+	}
297
+
298
+
299
+
300
+	/**
301
+	 * @param string $module_name
302
+	 * @return mixed EED_Module | NULL
303
+	 */
304
+	public function get_module($module_name = '')
305
+	{
306
+		return isset($this->modules->{$module_name})
307
+			? $this->modules->{$module_name}
308
+			: null;
309
+	}
310
+
311
+
312
+
313
+	/**
314
+	 * loads core classes - must be singletons
315
+	 *
316
+	 * @param string $class_name - simple class name ie: session
317
+	 * @param mixed  $arguments
318
+	 * @param bool   $load_only
319
+	 * @return mixed
320
+	 * @throws EE_Error
321
+	 * @throws ReflectionException
322
+	 */
323
+	public function load_core($class_name, $arguments = array(), $load_only = false)
324
+	{
325
+		$core_paths = apply_filters(
326
+			'FHEE__EE_Registry__load_core__core_paths',
327
+			array(
328
+				EE_CORE,
329
+				EE_ADMIN,
330
+				EE_CPTS,
331
+				EE_CORE . 'data_migration_scripts' . DS,
332
+				EE_CORE . 'capabilities' . DS,
333
+				EE_CORE . 'request_stack' . DS,
334
+				EE_CORE . 'middleware' . DS,
335
+			)
336
+		);
337
+		// retrieve instantiated class
338
+		return $this->_load(
339
+			$core_paths,
340
+			'EE_',
341
+			$class_name,
342
+			'core',
343
+			$arguments,
344
+			false,
345
+			true,
346
+			$load_only
347
+		);
348
+	}
349
+
350
+
351
+
352
+	/**
353
+	 * loads service classes
354
+	 *
355
+	 * @param string $class_name - simple class name ie: session
356
+	 * @param mixed  $arguments
357
+	 * @param bool   $load_only
358
+	 * @return mixed
359
+	 * @throws EE_Error
360
+	 * @throws ReflectionException
361
+	 */
362
+	public function load_service($class_name, $arguments = array(), $load_only = false)
363
+	{
364
+		$service_paths = apply_filters(
365
+			'FHEE__EE_Registry__load_service__service_paths',
366
+			array(
367
+				EE_CORE . 'services' . DS,
368
+			)
369
+		);
370
+		// retrieve instantiated class
371
+		return $this->_load(
372
+			$service_paths,
373
+			'EE_',
374
+			$class_name,
375
+			'class',
376
+			$arguments,
377
+			false,
378
+			true,
379
+			$load_only
380
+		);
381
+	}
382
+
383
+
384
+
385
+	/**
386
+	 * loads data_migration_scripts
387
+	 *
388
+	 * @param string $class_name - class name for the DMS ie: EE_DMS_Core_4_2_0
389
+	 * @param mixed  $arguments
390
+	 * @return EE_Data_Migration_Script_Base|mixed
391
+	 * @throws EE_Error
392
+	 * @throws ReflectionException
393
+	 */
394
+	public function load_dms($class_name, $arguments = array())
395
+	{
396
+		// retrieve instantiated class
397
+		return $this->_load(
398
+			EE_Data_Migration_Manager::instance()->get_data_migration_script_folders(),
399
+			'EE_DMS_',
400
+			$class_name,
401
+			'dms',
402
+			$arguments,
403
+			false,
404
+			false
405
+		);
406
+	}
407
+
408
+
409
+
410
+	/**
411
+	 * loads object creating classes - must be singletons
412
+	 *
413
+	 * @param string $class_name - simple class name ie: attendee
414
+	 * @param mixed  $arguments  - an array of arguments to pass to the class
415
+	 * @param bool   $from_db    - some classes are instantiated from the db and thus call a different method to
416
+	 *                           instantiate
417
+	 * @param bool   $cache      if you don't want the class to be stored in the internal cache (non-persistent) then
418
+	 *                           set this to FALSE (ie. when instantiating model objects from client in a loop)
419
+	 * @param bool   $load_only  whether or not to just load the file and NOT instantiate, or load AND instantiate
420
+	 *                           (default)
421
+	 * @return EE_Base_Class | bool
422
+	 * @throws EE_Error
423
+	 * @throws ReflectionException
424
+	 */
425
+	public function load_class($class_name, $arguments = array(), $from_db = false, $cache = true, $load_only = false)
426
+	{
427
+		$paths = apply_filters(
428
+			'FHEE__EE_Registry__load_class__paths', array(
429
+			EE_CORE,
430
+			EE_CLASSES,
431
+			EE_BUSINESS,
432
+		)
433
+		);
434
+		// retrieve instantiated class
435
+		return $this->_load(
436
+			$paths,
437
+			'EE_',
438
+			$class_name,
439
+			'class',
440
+			$arguments,
441
+			$from_db,
442
+			$cache,
443
+			$load_only
444
+		);
445
+	}
446
+
447
+
448
+
449
+	/**
450
+	 * loads helper classes - must be singletons
451
+	 *
452
+	 * @param string $class_name - simple class name ie: price
453
+	 * @param mixed  $arguments
454
+	 * @param bool   $load_only
455
+	 * @return EEH_Base | bool
456
+	 * @throws EE_Error
457
+	 * @throws ReflectionException
458
+	 */
459
+	public function load_helper($class_name, $arguments = array(), $load_only = true)
460
+	{
461
+		// todo: add doing_it_wrong() in a few versions after all addons have had calls to this method removed
462
+		$helper_paths = apply_filters('FHEE__EE_Registry__load_helper__helper_paths', array(EE_HELPERS));
463
+		// retrieve instantiated class
464
+		return $this->_load(
465
+			$helper_paths,
466
+			'EEH_',
467
+			$class_name,
468
+			'helper',
469
+			$arguments,
470
+			false,
471
+			true,
472
+			$load_only
473
+		);
474
+	}
475
+
476
+
477
+
478
+	/**
479
+	 * loads core classes - must be singletons
480
+	 *
481
+	 * @param string $class_name - simple class name ie: session
482
+	 * @param mixed  $arguments
483
+	 * @param bool   $load_only
484
+	 * @param bool   $cache      whether to cache the object or not.
485
+	 * @return mixed
486
+	 * @throws EE_Error
487
+	 * @throws ReflectionException
488
+	 */
489
+	public function load_lib($class_name, $arguments = array(), $load_only = false, $cache = true)
490
+	{
491
+		$paths = array(
492
+			EE_LIBRARIES,
493
+			EE_LIBRARIES . 'messages' . DS,
494
+			EE_LIBRARIES . 'shortcodes' . DS,
495
+			EE_LIBRARIES . 'qtips' . DS,
496
+			EE_LIBRARIES . 'payment_methods' . DS,
497
+		);
498
+		// retrieve instantiated class
499
+		return $this->_load(
500
+			$paths,
501
+			'EE_',
502
+			$class_name,
503
+			'lib',
504
+			$arguments,
505
+			false,
506
+			$cache,
507
+			$load_only
508
+		);
509
+	}
510
+
511
+
512
+
513
+	/**
514
+	 * loads model classes - must be singletons
515
+	 *
516
+	 * @param string $class_name - simple class name ie: price
517
+	 * @param mixed  $arguments
518
+	 * @param bool   $load_only
519
+	 * @return EEM_Base | bool
520
+	 * @throws EE_Error
521
+	 * @throws ReflectionException
522
+	 */
523
+	public function load_model($class_name, $arguments = array(), $load_only = false)
524
+	{
525
+		$paths = apply_filters(
526
+			'FHEE__EE_Registry__load_model__paths', array(
527
+			EE_MODELS,
528
+			EE_CORE,
529
+		)
530
+		);
531
+		// retrieve instantiated class
532
+		return $this->_load(
533
+			$paths,
534
+			'EEM_',
535
+			$class_name,
536
+			'model',
537
+			$arguments,
538
+			false,
539
+			true,
540
+			$load_only
541
+		);
542
+	}
543
+
544
+
545
+
546
+	/**
547
+	 * loads model classes - must be singletons
548
+	 *
549
+	 * @param string $class_name - simple class name ie: price
550
+	 * @param mixed  $arguments
551
+	 * @param bool   $load_only
552
+	 * @return mixed | bool
553
+	 * @throws EE_Error
554
+	 * @throws ReflectionException
555
+	 */
556
+	public function load_model_class($class_name, $arguments = array(), $load_only = true)
557
+	{
558
+		$paths = array(
559
+			EE_MODELS . 'fields' . DS,
560
+			EE_MODELS . 'helpers' . DS,
561
+			EE_MODELS . 'relations' . DS,
562
+			EE_MODELS . 'strategies' . DS,
563
+		);
564
+		// retrieve instantiated class
565
+		return $this->_load(
566
+			$paths,
567
+			'EE_',
568
+			$class_name,
569
+			'',
570
+			$arguments,
571
+			false,
572
+			true,
573
+			$load_only
574
+		);
575
+	}
576
+
577
+
578
+
579
+	/**
580
+	 * Determines if $model_name is the name of an actual EE model.
581
+	 *
582
+	 * @param string $model_name like Event, Attendee, Question_Group_Question, etc.
583
+	 * @return boolean
584
+	 */
585
+	public function is_model_name($model_name)
586
+	{
587
+		return isset($this->models[$model_name]);
588
+	}
589
+
590
+
591
+
592
+	/**
593
+	 * generic class loader
594
+	 *
595
+	 * @param string $path_to_file - directory path to file location, not including filename
596
+	 * @param string $file_name    - file name  ie:  my_file.php, including extension
597
+	 * @param string $type         - file type - core? class? helper? model?
598
+	 * @param mixed  $arguments
599
+	 * @param bool   $load_only
600
+	 * @return mixed
601
+	 * @throws EE_Error
602
+	 * @throws ReflectionException
603
+	 */
604
+	public function load_file($path_to_file, $file_name, $type = '', $arguments = array(), $load_only = true)
605
+	{
606
+		// retrieve instantiated class
607
+		return $this->_load(
608
+			$path_to_file,
609
+			'',
610
+			$file_name,
611
+			$type,
612
+			$arguments,
613
+			false,
614
+			true,
615
+			$load_only
616
+		);
617
+	}
618
+
619
+
620
+
621
+	/**
622
+	 * @param string $path_to_file - directory path to file location, not including filename
623
+	 * @param string $class_name   - full class name  ie:  My_Class
624
+	 * @param string $type         - file type - core? class? helper? model?
625
+	 * @param mixed  $arguments
626
+	 * @param bool   $load_only
627
+	 * @return bool|EE_Addon|object
628
+	 * @throws EE_Error
629
+	 * @throws ReflectionException
630
+	 */
631
+	public function load_addon($path_to_file, $class_name, $type = 'class', $arguments = array(), $load_only = false)
632
+	{
633
+		// retrieve instantiated class
634
+		return $this->_load(
635
+			$path_to_file,
636
+			'addon',
637
+			$class_name,
638
+			$type,
639
+			$arguments,
640
+			false,
641
+			true,
642
+			$load_only
643
+		);
644
+	}
645
+
646
+
647
+
648
+	/**
649
+	 * instantiates, caches, and automatically resolves dependencies
650
+	 * for classes that use a Fully Qualified Class Name.
651
+	 * if the class is not capable of being loaded using PSR-4 autoloading,
652
+	 * then you need to use one of the existing load_*() methods
653
+	 * which can resolve the classname and filepath from the passed arguments
654
+	 *
655
+	 * @param bool|string $class_name   Fully Qualified Class Name
656
+	 * @param array       $arguments    an argument, or array of arguments to pass to the class upon instantiation
657
+	 * @param bool        $cache        whether to cache the instantiated object for reuse
658
+	 * @param bool        $from_db      some classes are instantiated from the db
659
+	 *                                  and thus call a different method to instantiate
660
+	 * @param bool        $load_only    if true, will only load the file, but will NOT instantiate an object
661
+	 * @param bool|string $addon        if true, will cache the object in the EE_Registry->$addons array
662
+	 * @return bool|null|mixed          null = failure to load or instantiate class object.
663
+	 *                                  object = class loaded and instantiated successfully.
664
+	 *                                  bool = fail or success when $load_only is true
665
+	 * @throws EE_Error
666
+	 * @throws ReflectionException
667
+	 */
668
+	public function create(
669
+		$class_name = false,
670
+		$arguments = array(),
671
+		$cache = false,
672
+		$from_db = false,
673
+		$load_only = false,
674
+		$addon = false
675
+	) {
676
+		$class_name = ltrim($class_name, '\\');
677
+		$class_name = $this->_dependency_map->get_alias($class_name);
678
+		$class_exists = $this->loadOrVerifyClassExists($class_name, $arguments);
679
+		// if a non-FQCN was passed, then verifyClassExists() might return an object
680
+		// or it could return null if the class just could not be found anywhere
681
+		if ($class_exists instanceof $class_name || $class_exists === null){
682
+			// either way, return the results
683
+			return $class_exists;
684
+		}
685
+		$class_name = $class_exists;
686
+		// if we're only loading the class and it already exists, then let's just return true immediately
687
+		if ($load_only) {
688
+			return true;
689
+		}
690
+		$addon = $addon
691
+			? 'addon'
692
+			: '';
693
+		// $this->_cache_on is toggled during the recursive loading that can occur with dependency injection
694
+		// $cache is controlled by individual calls to separate Registry loader methods like load_class()
695
+		// $load_only is also controlled by individual calls to separate Registry loader methods like load_file()
696
+		if ($this->_cache_on && $cache && ! $load_only) {
697
+			// return object if it's already cached
698
+			$cached_class = $this->_get_cached_class($class_name, $addon);
699
+			if ($cached_class !== null) {
700
+				return $cached_class;
701
+			}
702
+		}
703
+		// obtain the loader method from the dependency map
704
+		$loader = $this->_dependency_map->class_loader($class_name);
705
+		// instantiate the requested object
706
+		if ($loader instanceof Closure) {
707
+			$class_obj = $loader($arguments);
708
+		} else if ($loader && method_exists($this, $loader)) {
709
+			$class_obj = $this->{$loader}($class_name, $arguments);
710
+		} else {
711
+			$class_obj = $this->_create_object($class_name, $arguments, $addon, $from_db);
712
+		}
713
+		if (($this->_cache_on && $cache) || $this->get_class_abbreviation($class_name, '')) {
714
+			// save it for later... kinda like gum  { : $
715
+			$this->_set_cached_class($class_obj, $class_name, $addon, $from_db);
716
+		}
717
+		$this->_cache_on = true;
718
+		return $class_obj;
719
+	}
720
+
721
+
722
+
723
+	/**
724
+	 * Recursively checks that a class exists and potentially attempts to load classes with non-FQCNs
725
+	 *
726
+	 * @param string $class_name
727
+	 * @param array  $arguments
728
+	 * @param int    $attempt
729
+	 * @return mixed
730
+	 */
731
+	private function loadOrVerifyClassExists($class_name, array $arguments, $attempt = 1) {
732
+		if (is_object($class_name) || class_exists($class_name)) {
733
+			return $class_name;
734
+		}
735
+		switch ($attempt) {
736
+			case 1:
737
+				// if it's a FQCN then maybe the class is registered with a preceding \
738
+				$class_name = strpos($class_name, '\\') !== false
739
+					? '\\' . ltrim($class_name, '\\')
740
+					: $class_name;
741
+				break;
742
+			case 2:
743
+				//
744
+				$loader = $this->_dependency_map->class_loader($class_name);
745
+				if ($loader && method_exists($this, $loader)) {
746
+					return $this->{$loader}($class_name, $arguments);
747
+				}
748
+				break;
749
+			case 3:
750
+			default;
751
+				return null;
752
+		}
753
+		$attempt++;
754
+		return $this->loadOrVerifyClassExists($class_name, $arguments, $attempt);
755
+	}
756
+
757
+
758
+
759
+	/**
760
+	 * instantiates, caches, and injects dependencies for classes
761
+	 *
762
+	 * @param array       $file_paths   an array of paths to folders to look in
763
+	 * @param string      $class_prefix EE  or EEM or... ???
764
+	 * @param bool|string $class_name   $class name
765
+	 * @param string      $type         file type - core? class? helper? model?
766
+	 * @param mixed       $arguments    an argument or array of arguments to pass to the class upon instantiation
767
+	 * @param bool        $from_db      some classes are instantiated from the db
768
+	 *                                  and thus call a different method to instantiate
769
+	 * @param bool        $cache        whether to cache the instantiated object for reuse
770
+	 * @param bool        $load_only    if true, will only load the file, but will NOT instantiate an object
771
+	 * @return bool|null|object null = failure to load or instantiate class object.
772
+	 *                                  object = class loaded and instantiated successfully.
773
+	 *                                  bool = fail or success when $load_only is true
774
+	 * @throws EE_Error
775
+	 * @throws ReflectionException
776
+	 */
777
+	protected function _load(
778
+		$file_paths = array(),
779
+		$class_prefix = 'EE_',
780
+		$class_name = false,
781
+		$type = 'class',
782
+		$arguments = array(),
783
+		$from_db = false,
784
+		$cache = true,
785
+		$load_only = false
786
+	) {
787
+		$class_name = ltrim($class_name, '\\');
788
+		// strip php file extension
789
+		$class_name = str_replace('.php', '', trim($class_name));
790
+		// does the class have a prefix ?
791
+		if (! empty($class_prefix) && $class_prefix !== 'addon') {
792
+			// make sure $class_prefix is uppercase
793
+			$class_prefix = strtoupper(trim($class_prefix));
794
+			// add class prefix ONCE!!!
795
+			$class_name = $class_prefix . str_replace($class_prefix, '', $class_name);
796
+		}
797
+		$class_name = $this->_dependency_map->get_alias($class_name);
798
+		$class_exists = class_exists($class_name);
799
+		// if we're only loading the class and it already exists, then let's just return true immediately
800
+		if ($load_only && $class_exists) {
801
+			return true;
802
+		}
803
+		// $this->_cache_on is toggled during the recursive loading that can occur with dependency injection
804
+		// $cache is controlled by individual calls to separate Registry loader methods like load_class()
805
+		// $load_only is also controlled by individual calls to separate Registry loader methods like load_file()
806
+		if ($this->_cache_on && $cache && ! $load_only) {
807
+			// return object if it's already cached
808
+			$cached_class = $this->_get_cached_class($class_name, $class_prefix);
809
+			if ($cached_class !== null) {
810
+				return $cached_class;
811
+			}
812
+		}
813
+		// if the class doesn't already exist.. then we need to try and find the file and load it
814
+		if (! $class_exists) {
815
+			// get full path to file
816
+			$path = $this->_resolve_path($class_name, $type, $file_paths);
817
+			// load the file
818
+			$loaded = $this->_require_file($path, $class_name, $type, $file_paths);
819
+			// if loading failed, or we are only loading a file but NOT instantiating an object
820
+			if (! $loaded || $load_only) {
821
+				// return boolean if only loading, or null if an object was expected
822
+				return $load_only
823
+					? $loaded
824
+					: null;
825
+			}
826
+		}
827
+		// instantiate the requested object
828
+		$class_obj = $this->_create_object($class_name, $arguments, $type, $from_db);
829
+		if ($this->_cache_on && $cache) {
830
+			// save it for later... kinda like gum  { : $
831
+			$this->_set_cached_class($class_obj, $class_name, $class_prefix, $from_db);
832
+		}
833
+		$this->_cache_on = true;
834
+		return $class_obj;
835
+	}
836
+
837
+
838
+
839
+	/**
840
+	 * @param string $class_name
841
+	 * @param string $default have to specify something, but not anything that will conflict
842
+	 * @return mixed|string
843
+	 */
844
+	protected function get_class_abbreviation($class_name, $default = 'FANCY_BATMAN_PANTS')
845
+	{
846
+		return isset($this->_class_abbreviations[$class_name])
847
+			? $this->_class_abbreviations[$class_name]
848
+			: $default;
849
+	}
850
+
851
+	/**
852
+	 * attempts to find a cached version of the requested class
853
+	 * by looking in the following places:
854
+	 *        $this->{$class_abbreviation}            ie:    $this->CART
855
+	 *        $this->{$class_name}                        ie:    $this->Some_Class
856
+	 *        $this->LIB->{$class_name}                ie:    $this->LIB->Some_Class
857
+	 *        $this->addon->{$class_name}    ie:    $this->addon->Some_Addon_Class
858
+	 *
859
+	 * @param string $class_name
860
+	 * @param string $class_prefix
861
+	 * @return mixed
862
+	 */
863
+	protected function _get_cached_class($class_name, $class_prefix = '')
864
+	{
865
+		if ($class_name === 'EE_Registry') {
866
+			return $this;
867
+		}
868
+		$class_abbreviation = $this->get_class_abbreviation($class_name);
869
+		$class_name = str_replace('\\', '_', $class_name);
870
+		// check if class has already been loaded, and return it if it has been
871
+		if (isset($this->{$class_abbreviation})) {
872
+			return $this->{$class_abbreviation};
873
+		}
874
+		if (isset ($this->{$class_name})) {
875
+			return $this->{$class_name};
876
+		}
877
+		if (isset ($this->LIB->{$class_name})) {
878
+			return $this->LIB->{$class_name};
879
+		}
880
+		if ($class_prefix === 'addon' && isset ($this->addons->{$class_name})) {
881
+			return $this->addons->{$class_name};
882
+		}
883
+		return null;
884
+	}
885
+
886
+
887
+
888
+	/**
889
+	 * removes a cached version of the requested class
890
+	 *
891
+	 * @param string  $class_name
892
+	 * @param boolean $addon
893
+	 * @return boolean
894
+	 */
895
+	public function clear_cached_class($class_name, $addon = false)
896
+	{
897
+		$class_abbreviation = $this->get_class_abbreviation($class_name);
898
+		$class_name = str_replace('\\', '_', $class_name);
899
+		// check if class has already been loaded, and return it if it has been
900
+		if (isset($this->{$class_abbreviation})) {
901
+			$this->{$class_abbreviation} = null;
902
+			return true;
903
+		}
904
+		if (isset($this->{$class_name})) {
905
+			$this->{$class_name} = null;
906
+			return true;
907
+		}
908
+		if (isset($this->LIB->{$class_name})) {
909
+			unset($this->LIB->{$class_name});
910
+			return true;
911
+		}
912
+		if ($addon && isset($this->addons->{$class_name})) {
913
+			unset($this->addons->{$class_name});
914
+			return true;
915
+		}
916
+		return false;
917
+	}
918
+
919
+
920
+
921
+	/**
922
+	 * attempts to find a full valid filepath for the requested class.
923
+	 * loops thru each of the base paths in the $file_paths array and appends : "{classname} . {file type} . php"
924
+	 * then returns that path if the target file has been found and is readable
925
+	 *
926
+	 * @param string $class_name
927
+	 * @param string $type
928
+	 * @param array  $file_paths
929
+	 * @return string | bool
930
+	 */
931
+	protected function _resolve_path($class_name, $type = '', $file_paths = array())
932
+	{
933
+		// make sure $file_paths is an array
934
+		$file_paths = is_array($file_paths)
935
+			? $file_paths
936
+			: array($file_paths);
937
+		// cycle thru paths
938
+		foreach ($file_paths as $key => $file_path) {
939
+			// convert all separators to proper DS, if no filepath, then use EE_CLASSES
940
+			$file_path = $file_path
941
+				? str_replace(array('/', '\\'), DS, $file_path)
942
+				: EE_CLASSES;
943
+			// prep file type
944
+			$type = ! empty($type)
945
+				? trim($type, '.') . '.'
946
+				: '';
947
+			// build full file path
948
+			$file_paths[$key] = rtrim($file_path, DS) . DS . $class_name . '.' . $type . 'php';
949
+			//does the file exist and can be read ?
950
+			if (is_readable($file_paths[$key])) {
951
+				return $file_paths[$key];
952
+			}
953
+		}
954
+		return false;
955
+	}
956
+
957
+
958
+
959
+	/**
960
+	 * basically just performs a require_once()
961
+	 * but with some error handling
962
+	 *
963
+	 * @param  string $path
964
+	 * @param  string $class_name
965
+	 * @param  string $type
966
+	 * @param  array  $file_paths
967
+	 * @return bool
968
+	 * @throws EE_Error
969
+	 * @throws ReflectionException
970
+	 */
971
+	protected function _require_file($path, $class_name, $type = '', $file_paths = array())
972
+	{
973
+		// don't give up! you gotta...
974
+		try {
975
+			//does the file exist and can it be read ?
976
+			if (! $path) {
977
+				// so sorry, can't find the file
978
+				throw new EE_Error (
979
+					sprintf(
980
+						esc_html__(
981
+							'The %1$s file %2$s could not be located or is not readable due to file permissions. Please ensure that the following filepath(s) are correct: %3$s',
982
+							'event_espresso'
983
+						),
984
+						trim($type, '.'),
985
+						$class_name,
986
+						'<br />' . implode(',<br />', $file_paths)
987
+					)
988
+				);
989
+			}
990
+			// get the file
991
+			require_once($path);
992
+			// if the class isn't already declared somewhere
993
+			if (class_exists($class_name, false) === false) {
994
+				// so sorry, not a class
995
+				throw new EE_Error(
996
+					sprintf(
997
+						esc_html__('The %s file %s does not appear to contain the %s Class.', 'event_espresso'),
998
+						$type,
999
+						$path,
1000
+						$class_name
1001
+					)
1002
+				);
1003
+			}
1004
+		} catch (EE_Error $e) {
1005
+			$e->get_error();
1006
+			return false;
1007
+		}
1008
+		return true;
1009
+	}
1010
+
1011
+
1012
+
1013
+	/**
1014
+	 * _create_object
1015
+	 * Attempts to instantiate the requested class via any of the
1016
+	 * commonly used instantiation methods employed throughout EE.
1017
+	 * The priority for instantiation is as follows:
1018
+	 *        - abstract classes or any class flagged as "load only" (no instantiation occurs)
1019
+	 *        - model objects via their 'new_instance_from_db' method
1020
+	 *        - model objects via their 'new_instance' method
1021
+	 *        - "singleton" classes" via their 'instance' method
1022
+	 *    - standard instantiable classes via their __constructor
1023
+	 * Prior to instantiation, if the classname exists in the dependency_map,
1024
+	 * then the constructor for the requested class will be examined to determine
1025
+	 * if any dependencies exist, and if they can be injected.
1026
+	 * If so, then those classes will be added to the array of arguments passed to the constructor
1027
+	 *
1028
+	 * @param string $class_name
1029
+	 * @param array  $arguments
1030
+	 * @param string $type
1031
+	 * @param bool   $from_db
1032
+	 * @return null|object
1033
+	 * @throws EE_Error
1034
+	 * @throws ReflectionException
1035
+	 */
1036
+	protected function _create_object($class_name, $arguments = array(), $type = '', $from_db = false)
1037
+	{
1038
+		$class_obj = null;
1039
+		$instantiation_mode = '0) none';
1040
+		// don't give up! you gotta...
1041
+		try {
1042
+			// create reflection
1043
+			$reflector = $this->get_ReflectionClass($class_name);
1044
+			// make sure arguments are an array
1045
+			$arguments = is_array($arguments)
1046
+				? $arguments
1047
+				: array($arguments);
1048
+			// and if arguments array is numerically and sequentially indexed, then we want it to remain as is,
1049
+			// else wrap it in an additional array so that it doesn't get split into multiple parameters
1050
+			$arguments = $this->_array_is_numerically_and_sequentially_indexed($arguments)
1051
+				? $arguments
1052
+				: array($arguments);
1053
+			// attempt to inject dependencies ?
1054
+			if ($this->_dependency_map->has($class_name)) {
1055
+				$arguments = $this->_resolve_dependencies($reflector, $class_name, $arguments);
1056
+			}
1057
+			// instantiate the class if possible
1058
+			if ($reflector->isAbstract()) {
1059
+				// nothing to instantiate, loading file was enough
1060
+				// does not throw an exception so $instantiation_mode is unused
1061
+				// $instantiation_mode = "1) no constructor abstract class";
1062
+				$class_obj = true;
1063
+			} else if (empty($arguments) && $reflector->getConstructor() === null && $reflector->isInstantiable()) {
1064
+				// no constructor = static methods only... nothing to instantiate, loading file was enough
1065
+				$instantiation_mode = '2) no constructor but instantiable';
1066
+				$class_obj = $reflector->newInstance();
1067
+			} else if ($from_db && method_exists($class_name, 'new_instance_from_db')) {
1068
+				$instantiation_mode = '3) new_instance_from_db()';
1069
+				$class_obj = call_user_func_array(array($class_name, 'new_instance_from_db'), $arguments);
1070
+			} else if (method_exists($class_name, 'new_instance')) {
1071
+				$instantiation_mode = '4) new_instance()';
1072
+				$class_obj = call_user_func_array(array($class_name, 'new_instance'), $arguments);
1073
+			} else if (method_exists($class_name, 'instance')) {
1074
+				$instantiation_mode = '5) instance()';
1075
+				$class_obj = call_user_func_array(array($class_name, 'instance'), $arguments);
1076
+			} else if ($reflector->isInstantiable()) {
1077
+				$instantiation_mode = '6) constructor';
1078
+				$class_obj = $reflector->newInstanceArgs($arguments);
1079
+			} else {
1080
+				// heh ? something's not right !
1081
+				throw new EE_Error(
1082
+					sprintf(
1083
+						esc_html__('The %s file %s could not be instantiated.', 'event_espresso'),
1084
+						$type,
1085
+						$class_name
1086
+					)
1087
+				);
1088
+			}
1089
+		} catch (Exception $e) {
1090
+			if (! $e instanceof EE_Error) {
1091
+				$e = new EE_Error(
1092
+					sprintf(
1093
+						esc_html__(
1094
+							'The following error occurred while attempting to instantiate "%1$s": %2$s %3$s %2$s instantiation mode : %4$s',
1095
+							'event_espresso'
1096
+						),
1097
+						$class_name,
1098
+						'<br />',
1099
+						$e->getMessage(),
1100
+						$instantiation_mode
1101
+					)
1102
+				);
1103
+			}
1104
+			$e->get_error();
1105
+		}
1106
+		return $class_obj;
1107
+	}
1108
+
1109
+
1110
+
1111
+	/**
1112
+	 * @see http://stackoverflow.com/questions/173400/how-to-check-if-php-array-is-associative-or-sequential
1113
+	 * @param array $array
1114
+	 * @return bool
1115
+	 */
1116
+	protected function _array_is_numerically_and_sequentially_indexed(array $array)
1117
+	{
1118
+		return ! empty($array)
1119
+			? array_keys($array) === range(0, count($array) - 1)
1120
+			: true;
1121
+	}
1122
+
1123
+
1124
+
1125
+	/**
1126
+	 * getReflectionClass
1127
+	 * checks if a ReflectionClass object has already been generated for a class
1128
+	 * and returns that instead of creating a new one
1129
+	 *
1130
+	 * @param string $class_name
1131
+	 * @return ReflectionClass
1132
+	 * @throws ReflectionException
1133
+	 */
1134
+	public function get_ReflectionClass($class_name)
1135
+	{
1136
+		if (
1137
+			! isset($this->_reflectors[$class_name])
1138
+			|| ! $this->_reflectors[$class_name] instanceof ReflectionClass
1139
+		) {
1140
+			$this->_reflectors[$class_name] = new ReflectionClass($class_name);
1141
+		}
1142
+		return $this->_reflectors[$class_name];
1143
+	}
1144
+
1145
+
1146
+
1147
+	/**
1148
+	 * _resolve_dependencies
1149
+	 * examines the constructor for the requested class to determine
1150
+	 * if any dependencies exist, and if they can be injected.
1151
+	 * If so, then those classes will be added to the array of arguments passed to the constructor
1152
+	 * PLZ NOTE: this is achieved by type hinting the constructor params
1153
+	 * For example:
1154
+	 *        if attempting to load a class "Foo" with the following constructor:
1155
+	 *        __construct( Bar $bar_class, Fighter $grohl_class )
1156
+	 *        then $bar_class and $grohl_class will be added to the $arguments array,
1157
+	 *        but only IF they are NOT already present in the incoming arguments array,
1158
+	 *        and the correct classes can be loaded
1159
+	 *
1160
+	 * @param ReflectionClass $reflector
1161
+	 * @param string          $class_name
1162
+	 * @param array           $arguments
1163
+	 * @return array
1164
+	 * @throws EE_Error
1165
+	 * @throws ReflectionException
1166
+	 */
1167
+	protected function _resolve_dependencies(ReflectionClass $reflector, $class_name, $arguments = array())
1168
+	{
1169
+		// let's examine the constructor
1170
+		$constructor = $reflector->getConstructor();
1171
+		// whu? huh? nothing?
1172
+		if (! $constructor) {
1173
+			return $arguments;
1174
+		}
1175
+		// get constructor parameters
1176
+		$params = $constructor->getParameters();
1177
+		// and the keys for the incoming arguments array so that we can compare existing arguments with what is expected
1178
+		$argument_keys = array_keys($arguments);
1179
+		// now loop thru all of the constructors expected parameters
1180
+		foreach ($params as $index => $param) {
1181
+			// is this a dependency for a specific class ?
1182
+			$param_class = $param->getClass()
1183
+				? $param->getClass()->name
1184
+				: null;
1185
+			// BUT WAIT !!! This class may be an alias for something else (or getting replaced at runtime)
1186
+			$param_class = $this->_dependency_map->has_alias($param_class, $class_name)
1187
+				? $this->_dependency_map->get_alias($param_class, $class_name)
1188
+				: $param_class;
1189
+			if (
1190
+				// param is not even a class
1191
+				$param_class === null
1192
+				// and something already exists in the incoming arguments for this param
1193
+				&& isset($argument_keys[$index], $arguments[$argument_keys[$index]])
1194
+			) {
1195
+				// so let's skip this argument and move on to the next
1196
+				continue;
1197
+			}
1198
+			if (
1199
+				// parameter is type hinted as a class, exists as an incoming argument, AND it's the correct class
1200
+				$param_class !== null
1201
+				&& isset($argument_keys[$index], $arguments[$argument_keys[$index]])
1202
+				&& $arguments[$argument_keys[$index]] instanceof $param_class
1203
+			) {
1204
+				// skip this argument and move on to the next
1205
+				continue;
1206
+			}
1207
+			if (
1208
+				// parameter is type hinted as a class, and should be injected
1209
+				$param_class !== null
1210
+				&& $this->_dependency_map->has_dependency_for_class($class_name, $param_class)
1211
+			) {
1212
+				$arguments = $this->_resolve_dependency(
1213
+					$class_name,
1214
+					$param_class,
1215
+					$arguments,
1216
+					$index,
1217
+					$argument_keys
1218
+				);
1219
+			} else {
1220
+				try {
1221
+					$arguments[$index] = $param->isDefaultValueAvailable()
1222
+						? $param->getDefaultValue()
1223
+						: null;
1224
+				} catch (ReflectionException $e) {
1225
+					throw new ReflectionException(
1226
+						sprintf(
1227
+							esc_html__('%1$s for parameter "$%2$s"', 'event_espresso'),
1228
+							$e->getMessage(),
1229
+							$param->getName()
1230
+						)
1231
+					);
1232
+				}
1233
+			}
1234
+		}
1235
+		return $arguments;
1236
+	}
1237
+
1238
+
1239
+
1240
+	/**
1241
+	 * @param string $class_name
1242
+	 * @param string $param_class
1243
+	 * @param array  $arguments
1244
+	 * @param mixed  $index
1245
+	 * @param array  $argument_keys
1246
+	 * @return array
1247
+	 * @throws EE_Error
1248
+	 * @throws ReflectionException
1249
+	 * @throws InvalidArgumentException
1250
+	 * @throws InvalidInterfaceException
1251
+	 * @throws InvalidDataTypeException
1252
+	 */
1253
+	protected function _resolve_dependency($class_name, $param_class, $arguments, $index, array $argument_keys)
1254
+	{
1255
+		$dependency = null;
1256
+		// should dependency be loaded from cache ?
1257
+		$cache_on = $this->_dependency_map->loading_strategy_for_class_dependency(
1258
+			$class_name,
1259
+			$param_class
1260
+		);
1261
+		$cache_on = $cache_on !== EE_Dependency_Map::load_new_object;
1262
+		// we might have a dependency...
1263
+		// let's MAYBE try and find it in our cache if that's what's been requested
1264
+		$cached_class = $cache_on
1265
+			? $this->_get_cached_class($param_class)
1266
+			: null;
1267
+		// and grab it if it exists
1268
+		if ($cached_class instanceof $param_class) {
1269
+			$dependency = $cached_class;
1270
+		} else if ($param_class !== $class_name) {
1271
+			// obtain the loader method from the dependency map
1272
+			$loader = $this->_dependency_map->class_loader($param_class);
1273
+			// is loader a custom closure ?
1274
+			if ($loader instanceof Closure) {
1275
+				$dependency = $loader($arguments);
1276
+			} else {
1277
+				// set the cache on property for the recursive loading call
1278
+				$this->_cache_on = $cache_on;
1279
+				// if not, then let's try and load it via the registry
1280
+				if ($loader && method_exists($this, $loader)) {
1281
+					$dependency = $this->{$loader}($param_class);
1282
+				} else {
1283
+					$dependency = LoaderFactory::getLoader()->load(
1284
+						$param_class,
1285
+						array(),
1286
+						$cache_on
1287
+					);
1288
+				}
1289
+			}
1290
+		}
1291
+		// did we successfully find the correct dependency ?
1292
+		if ($dependency instanceof $param_class) {
1293
+			// then let's inject it into the incoming array of arguments at the correct location
1294
+			$arguments[$index] = $dependency;
1295
+		}
1296
+		return $arguments;
1297
+	}
1298
+
1299
+
1300
+
1301
+	/**
1302
+	 * _set_cached_class
1303
+	 * attempts to cache the instantiated class locally
1304
+	 * in one of the following places, in the following order:
1305
+	 *        $this->{class_abbreviation}   ie:    $this->CART
1306
+	 *        $this->{$class_name}          ie:    $this->Some_Class
1307
+	 *        $this->addon->{$$class_name}    ie:    $this->addon->Some_Addon_Class
1308
+	 *        $this->LIB->{$class_name}     ie:    $this->LIB->Some_Class
1309
+	 *
1310
+	 * @param object $class_obj
1311
+	 * @param string $class_name
1312
+	 * @param string $class_prefix
1313
+	 * @param bool   $from_db
1314
+	 * @return void
1315
+	 */
1316
+	protected function _set_cached_class($class_obj, $class_name, $class_prefix = '', $from_db = false)
1317
+	{
1318
+		if ($class_name === 'EE_Registry' || empty($class_obj)) {
1319
+			return;
1320
+		}
1321
+		// return newly instantiated class
1322
+		$class_abbreviation = $this->get_class_abbreviation($class_name, '');
1323
+		if ($class_abbreviation) {
1324
+			$this->{$class_abbreviation} = $class_obj;
1325
+			return;
1326
+		}
1327
+		$class_name = str_replace('\\', '_', $class_name);
1328
+		if (property_exists($this, $class_name)) {
1329
+			$this->{$class_name} = $class_obj;
1330
+			return;
1331
+		}
1332
+		if ($class_prefix === 'addon') {
1333
+			$this->addons->{$class_name} = $class_obj;
1334
+			return;
1335
+		}
1336
+		if (! $from_db) {
1337
+			$this->LIB->{$class_name} = $class_obj;
1338
+		}
1339
+	}
1340
+
1341
+
1342
+
1343
+	/**
1344
+	 * call any loader that's been registered in the EE_Dependency_Map::$_class_loaders array
1345
+	 *
1346
+	 * @param string $classname PLEASE NOTE: the class name needs to match what's registered
1347
+	 *                          in the EE_Dependency_Map::$_class_loaders array,
1348
+	 *                          including the class prefix, ie: "EE_", "EEM_", "EEH_", etc
1349
+	 * @param array  $arguments
1350
+	 * @return object
1351
+	 */
1352
+	public static function factory($classname, $arguments = array())
1353
+	{
1354
+		$loader = self::instance()->_dependency_map->class_loader($classname);
1355
+		if ($loader instanceof Closure) {
1356
+			return $loader($arguments);
1357
+		}
1358
+		if (method_exists(self::instance(), $loader)) {
1359
+			return self::instance()->{$loader}($classname, $arguments);
1360
+		}
1361
+		return null;
1362
+	}
1363
+
1364
+
1365
+
1366
+	/**
1367
+	 * Gets the addon by its name/slug (not classname. For that, just
1368
+	 * use the classname as the property name on EE_Config::instance()->addons)
1369
+	 *
1370
+	 * @param string $name
1371
+	 * @return EE_Addon
1372
+	 */
1373
+	public function get_addon_by_name($name)
1374
+	{
1375
+		foreach ($this->addons as $addon) {
1376
+			if ($addon->name() === $name) {
1377
+				return $addon;
1378
+			}
1379
+		}
1380
+		return null;
1381
+	}
1382
+
1383
+
1384
+
1385
+	/**
1386
+	 * Gets an array of all the registered addons, where the keys are their names. (ie, what each returns for their
1387
+	 * name() function) They're already available on EE_Config::instance()->addons as properties, where each property's
1388
+	 * name is the addon's classname. So if you just want to get the addon by classname, use
1389
+	 * EE_Config::instance()->addons->{classname}
1390
+	 *
1391
+	 * @return EE_Addon[] where the KEYS are the addon's name()
1392
+	 */
1393
+	public function get_addons_by_name()
1394
+	{
1395
+		$addons = array();
1396
+		foreach ($this->addons as $addon) {
1397
+			$addons[$addon->name()] = $addon;
1398
+		}
1399
+		return $addons;
1400
+	}
1401
+
1402
+
1403
+
1404
+	/**
1405
+	 * Resets the specified model's instance AND makes sure EE_Registry doesn't keep
1406
+	 * a stale copy of it around
1407
+	 *
1408
+	 * @param string $model_name
1409
+	 * @return \EEM_Base
1410
+	 * @throws \EE_Error
1411
+	 */
1412
+	public function reset_model($model_name)
1413
+	{
1414
+		$model_class_name = strpos($model_name, 'EEM_') !== 0
1415
+			? "EEM_{$model_name}"
1416
+			: $model_name;
1417
+		if (! isset($this->LIB->{$model_class_name}) || ! $this->LIB->{$model_class_name} instanceof EEM_Base) {
1418
+			return null;
1419
+		}
1420
+		//get that model reset it and make sure we nuke the old reference to it
1421
+		if ($this->LIB->{$model_class_name} instanceof $model_class_name
1422
+			&& is_callable(
1423
+				array($model_class_name, 'reset')
1424
+			)) {
1425
+			$this->LIB->{$model_class_name} = $this->LIB->{$model_class_name}->reset();
1426
+		} else {
1427
+			throw new EE_Error(sprintf(esc_html__('Model %s does not have a method "reset"', 'event_espresso'), $model_name));
1428
+		}
1429
+		return $this->LIB->{$model_class_name};
1430
+	}
1431
+
1432
+
1433
+
1434
+	/**
1435
+	 * Resets the registry.
1436
+	 * The criteria for what gets reset is based on what can be shared between sites on the same request when
1437
+	 * switch_to_blog is used in a multisite install.  Here is a list of things that are NOT reset.
1438
+	 * - $_dependency_map
1439
+	 * - $_class_abbreviations
1440
+	 * - $NET_CFG (EE_Network_Config): The config is shared network wide so no need to reset.
1441
+	 * - $REQ:  Still on the same request so no need to change.
1442
+	 * - $CAP: There is no site specific state in the EE_Capability class.
1443
+	 * - $SSN: Although ideally, the session should not be shared between site switches, we can't reset it because only
1444
+	 * one Session can be active in a single request.  Resetting could resolve in "headers already sent" errors.
1445
+	 * - $addons:  In multisite, the state of the addons is something controlled via hooks etc in a normal request.  So
1446
+	 *             for now, we won't reset the addons because it could break calls to an add-ons class/methods in the
1447
+	 *             switch or on the restore.
1448
+	 * - $modules
1449
+	 * - $shortcodes
1450
+	 * - $widgets
1451
+	 *
1452
+	 * @param boolean $hard             [deprecated]
1453
+	 * @param boolean $reinstantiate    whether to create new instances of EE_Registry's singletons too,
1454
+	 *                                  or just reset without re-instantiating (handy to set to FALSE if you're not
1455
+	 *                                  sure if you CAN currently reinstantiate the singletons at the moment)
1456
+	 * @param   bool  $reset_models     Defaults to true.  When false, then the models are not reset.  This is so
1457
+	 *                                  client
1458
+	 *                                  code instead can just change the model context to a different blog id if
1459
+	 *                                  necessary
1460
+	 * @return EE_Registry
1461
+	 * @throws EE_Error
1462
+	 * @throws ReflectionException
1463
+	 */
1464
+	public static function reset($hard = false, $reinstantiate = true, $reset_models = true)
1465
+	{
1466
+		$instance = self::instance();
1467
+		$instance->_cache_on = true;
1468
+		// reset some "special" classes
1469
+		EEH_Activation::reset();
1470
+		$hard = apply_filters( 'FHEE__EE_Registry__reset__hard', $hard);
1471
+		$instance->CFG = EE_Config::reset($hard, $reinstantiate);
1472
+		$instance->CART = null;
1473
+		$instance->MRM = null;
1474
+		$instance->AssetsRegistry = $instance->create('EventEspresso\core\services\assets\Registry');
1475
+		//messages reset
1476
+		EED_Messages::reset();
1477
+		//handle of objects cached on LIB
1478
+		foreach (array('LIB', 'modules') as $cache) {
1479
+			foreach ($instance->{$cache} as $class_name => $class) {
1480
+				if (self::_reset_and_unset_object($class, $reset_models)) {
1481
+					unset($instance->{$cache}->{$class_name});
1482
+				}
1483
+			}
1484
+		}
1485
+		return $instance;
1486
+	}
1487
+
1488
+
1489
+
1490
+	/**
1491
+	 * if passed object implements ResettableInterface, then call it's reset() method
1492
+	 * if passed object implements InterminableInterface, then return false,
1493
+	 * to indicate that it should NOT be cleared from the Registry cache
1494
+	 *
1495
+	 * @param      $object
1496
+	 * @param bool $reset_models
1497
+	 * @return bool returns true if cached object should be unset
1498
+	 */
1499
+	private static function _reset_and_unset_object($object, $reset_models)
1500
+	{
1501
+		if (! is_object($object)) {
1502
+			// don't unset anything that's not an object
1503
+			return false;
1504
+		}
1505
+		if ($object instanceof EED_Module) {
1506
+			$object::reset();
1507
+			// don't unset modules
1508
+			return false;
1509
+		}
1510
+		if ($object instanceof ResettableInterface) {
1511
+			if ($object instanceof EEM_Base) {
1512
+				if ($reset_models) {
1513
+					$object->reset();
1514
+					return true;
1515
+				}
1516
+				return false;
1517
+			}
1518
+			$object->reset();
1519
+			return true;
1520
+		}
1521
+		if (! $object instanceof InterminableInterface) {
1522
+			return true;
1523
+		}
1524
+		return false;
1525
+	}
1526
+
1527
+
1528
+
1529
+	/**
1530
+	 * Gets all the custom post type models defined
1531
+	 *
1532
+	 * @return array keys are model "short names" (Eg "Event") and keys are classnames (eg "EEM_Event")
1533
+	 */
1534
+	public function cpt_models()
1535
+	{
1536
+		$cpt_models = array();
1537
+		foreach ($this->non_abstract_db_models as $short_name => $classname) {
1538
+			if (is_subclass_of($classname, 'EEM_CPT_Base')) {
1539
+				$cpt_models[$short_name] = $classname;
1540
+			}
1541
+		}
1542
+		return $cpt_models;
1543
+	}
1544
+
1545
+
1546
+
1547
+	/**
1548
+	 * @return \EE_Config
1549
+	 */
1550
+	public static function CFG()
1551
+	{
1552
+		return self::instance()->CFG;
1553
+	}
1554 1554
 
1555 1555
 
1556 1556
 }
Please login to merge, or discard this patch.
Spacing   +36 added lines, -36 removed lines patch added patch discarded remove patch
@@ -176,7 +176,7 @@  discard block
 block discarded – undo
176 176
     public static function instance(EE_Dependency_Map $dependency_map = null)
177 177
     {
178 178
         // check if class object is instantiated
179
-        if (! self::$_instance instanceof EE_Registry) {
179
+        if ( ! self::$_instance instanceof EE_Registry) {
180 180
             self::$_instance = new self($dependency_map);
181 181
         }
182 182
         return self::$_instance;
@@ -266,13 +266,13 @@  discard block
 block discarded – undo
266 266
      */
267 267
     public static function localize_i18n_js_strings()
268 268
     {
269
-        $i18n_js_strings = (array)self::$i18n_js_strings;
269
+        $i18n_js_strings = (array) self::$i18n_js_strings;
270 270
         foreach ($i18n_js_strings as $key => $value) {
271 271
             if (is_scalar($value)) {
272
-                $i18n_js_strings[$key] = html_entity_decode((string)$value, ENT_QUOTES, 'UTF-8');
272
+                $i18n_js_strings[$key] = html_entity_decode((string) $value, ENT_QUOTES, 'UTF-8');
273 273
             }
274 274
         }
275
-        return '/* <![CDATA[ */ var eei18n = ' . wp_json_encode($i18n_js_strings) . '; /* ]]> */';
275
+        return '/* <![CDATA[ */ var eei18n = '.wp_json_encode($i18n_js_strings).'; /* ]]> */';
276 276
     }
277 277
 
278 278
 
@@ -288,7 +288,7 @@  discard block
 block discarded – undo
288 288
             $module_class = get_class($module);
289 289
             $this->modules->{$module_class} = $module;
290 290
         } else {
291
-            if (! class_exists('EE_Module_Request_Router')) {
291
+            if ( ! class_exists('EE_Module_Request_Router')) {
292 292
                 $this->load_core('Module_Request_Router');
293 293
             }
294 294
             EE_Module_Request_Router::module_factory($module);
@@ -328,10 +328,10 @@  discard block
 block discarded – undo
328 328
                 EE_CORE,
329 329
                 EE_ADMIN,
330 330
                 EE_CPTS,
331
-                EE_CORE . 'data_migration_scripts' . DS,
332
-                EE_CORE . 'capabilities' . DS,
333
-                EE_CORE . 'request_stack' . DS,
334
-                EE_CORE . 'middleware' . DS,
331
+                EE_CORE.'data_migration_scripts'.DS,
332
+                EE_CORE.'capabilities'.DS,
333
+                EE_CORE.'request_stack'.DS,
334
+                EE_CORE.'middleware'.DS,
335 335
             )
336 336
         );
337 337
         // retrieve instantiated class
@@ -364,7 +364,7 @@  discard block
 block discarded – undo
364 364
         $service_paths = apply_filters(
365 365
             'FHEE__EE_Registry__load_service__service_paths',
366 366
             array(
367
-                EE_CORE . 'services' . DS,
367
+                EE_CORE.'services'.DS,
368 368
             )
369 369
         );
370 370
         // retrieve instantiated class
@@ -490,10 +490,10 @@  discard block
 block discarded – undo
490 490
     {
491 491
         $paths = array(
492 492
             EE_LIBRARIES,
493
-            EE_LIBRARIES . 'messages' . DS,
494
-            EE_LIBRARIES . 'shortcodes' . DS,
495
-            EE_LIBRARIES . 'qtips' . DS,
496
-            EE_LIBRARIES . 'payment_methods' . DS,
493
+            EE_LIBRARIES.'messages'.DS,
494
+            EE_LIBRARIES.'shortcodes'.DS,
495
+            EE_LIBRARIES.'qtips'.DS,
496
+            EE_LIBRARIES.'payment_methods'.DS,
497 497
         );
498 498
         // retrieve instantiated class
499 499
         return $this->_load(
@@ -556,10 +556,10 @@  discard block
 block discarded – undo
556 556
     public function load_model_class($class_name, $arguments = array(), $load_only = true)
557 557
     {
558 558
         $paths = array(
559
-            EE_MODELS . 'fields' . DS,
560
-            EE_MODELS . 'helpers' . DS,
561
-            EE_MODELS . 'relations' . DS,
562
-            EE_MODELS . 'strategies' . DS,
559
+            EE_MODELS.'fields'.DS,
560
+            EE_MODELS.'helpers'.DS,
561
+            EE_MODELS.'relations'.DS,
562
+            EE_MODELS.'strategies'.DS,
563 563
         );
564 564
         // retrieve instantiated class
565 565
         return $this->_load(
@@ -678,7 +678,7 @@  discard block
 block discarded – undo
678 678
         $class_exists = $this->loadOrVerifyClassExists($class_name, $arguments);
679 679
         // if a non-FQCN was passed, then verifyClassExists() might return an object
680 680
         // or it could return null if the class just could not be found anywhere
681
-        if ($class_exists instanceof $class_name || $class_exists === null){
681
+        if ($class_exists instanceof $class_name || $class_exists === null) {
682 682
             // either way, return the results
683 683
             return $class_exists;
684 684
         }
@@ -736,7 +736,7 @@  discard block
 block discarded – undo
736 736
             case 1:
737 737
                 // if it's a FQCN then maybe the class is registered with a preceding \
738 738
                 $class_name = strpos($class_name, '\\') !== false
739
-                    ? '\\' . ltrim($class_name, '\\')
739
+                    ? '\\'.ltrim($class_name, '\\')
740 740
                     : $class_name;
741 741
                 break;
742 742
             case 2:
@@ -788,11 +788,11 @@  discard block
 block discarded – undo
788 788
         // strip php file extension
789 789
         $class_name = str_replace('.php', '', trim($class_name));
790 790
         // does the class have a prefix ?
791
-        if (! empty($class_prefix) && $class_prefix !== 'addon') {
791
+        if ( ! empty($class_prefix) && $class_prefix !== 'addon') {
792 792
             // make sure $class_prefix is uppercase
793 793
             $class_prefix = strtoupper(trim($class_prefix));
794 794
             // add class prefix ONCE!!!
795
-            $class_name = $class_prefix . str_replace($class_prefix, '', $class_name);
795
+            $class_name = $class_prefix.str_replace($class_prefix, '', $class_name);
796 796
         }
797 797
         $class_name = $this->_dependency_map->get_alias($class_name);
798 798
         $class_exists = class_exists($class_name);
@@ -811,13 +811,13 @@  discard block
 block discarded – undo
811 811
             }
812 812
         }
813 813
         // if the class doesn't already exist.. then we need to try and find the file and load it
814
-        if (! $class_exists) {
814
+        if ( ! $class_exists) {
815 815
             // get full path to file
816 816
             $path = $this->_resolve_path($class_name, $type, $file_paths);
817 817
             // load the file
818 818
             $loaded = $this->_require_file($path, $class_name, $type, $file_paths);
819 819
             // if loading failed, or we are only loading a file but NOT instantiating an object
820
-            if (! $loaded || $load_only) {
820
+            if ( ! $loaded || $load_only) {
821 821
                 // return boolean if only loading, or null if an object was expected
822 822
                 return $load_only
823 823
                     ? $loaded
@@ -942,10 +942,10 @@  discard block
 block discarded – undo
942 942
                 : EE_CLASSES;
943 943
             // prep file type
944 944
             $type = ! empty($type)
945
-                ? trim($type, '.') . '.'
945
+                ? trim($type, '.').'.'
946 946
                 : '';
947 947
             // build full file path
948
-            $file_paths[$key] = rtrim($file_path, DS) . DS . $class_name . '.' . $type . 'php';
948
+            $file_paths[$key] = rtrim($file_path, DS).DS.$class_name.'.'.$type.'php';
949 949
             //does the file exist and can be read ?
950 950
             if (is_readable($file_paths[$key])) {
951 951
                 return $file_paths[$key];
@@ -973,9 +973,9 @@  discard block
 block discarded – undo
973 973
         // don't give up! you gotta...
974 974
         try {
975 975
             //does the file exist and can it be read ?
976
-            if (! $path) {
976
+            if ( ! $path) {
977 977
                 // so sorry, can't find the file
978
-                throw new EE_Error (
978
+                throw new EE_Error(
979 979
                     sprintf(
980 980
                         esc_html__(
981 981
                             'The %1$s file %2$s could not be located or is not readable due to file permissions. Please ensure that the following filepath(s) are correct: %3$s',
@@ -983,7 +983,7 @@  discard block
 block discarded – undo
983 983
                         ),
984 984
                         trim($type, '.'),
985 985
                         $class_name,
986
-                        '<br />' . implode(',<br />', $file_paths)
986
+                        '<br />'.implode(',<br />', $file_paths)
987 987
                     )
988 988
                 );
989 989
             }
@@ -1087,7 +1087,7 @@  discard block
 block discarded – undo
1087 1087
                 );
1088 1088
             }
1089 1089
         } catch (Exception $e) {
1090
-            if (! $e instanceof EE_Error) {
1090
+            if ( ! $e instanceof EE_Error) {
1091 1091
                 $e = new EE_Error(
1092 1092
                     sprintf(
1093 1093
                         esc_html__(
@@ -1169,7 +1169,7 @@  discard block
 block discarded – undo
1169 1169
         // let's examine the constructor
1170 1170
         $constructor = $reflector->getConstructor();
1171 1171
         // whu? huh? nothing?
1172
-        if (! $constructor) {
1172
+        if ( ! $constructor) {
1173 1173
             return $arguments;
1174 1174
         }
1175 1175
         // get constructor parameters
@@ -1333,7 +1333,7 @@  discard block
 block discarded – undo
1333 1333
             $this->addons->{$class_name} = $class_obj;
1334 1334
             return;
1335 1335
         }
1336
-        if (! $from_db) {
1336
+        if ( ! $from_db) {
1337 1337
             $this->LIB->{$class_name} = $class_obj;
1338 1338
         }
1339 1339
     }
@@ -1414,7 +1414,7 @@  discard block
 block discarded – undo
1414 1414
         $model_class_name = strpos($model_name, 'EEM_') !== 0
1415 1415
             ? "EEM_{$model_name}"
1416 1416
             : $model_name;
1417
-        if (! isset($this->LIB->{$model_class_name}) || ! $this->LIB->{$model_class_name} instanceof EEM_Base) {
1417
+        if ( ! isset($this->LIB->{$model_class_name}) || ! $this->LIB->{$model_class_name} instanceof EEM_Base) {
1418 1418
             return null;
1419 1419
         }
1420 1420
         //get that model reset it and make sure we nuke the old reference to it
@@ -1467,7 +1467,7 @@  discard block
 block discarded – undo
1467 1467
         $instance->_cache_on = true;
1468 1468
         // reset some "special" classes
1469 1469
         EEH_Activation::reset();
1470
-        $hard = apply_filters( 'FHEE__EE_Registry__reset__hard', $hard);
1470
+        $hard = apply_filters('FHEE__EE_Registry__reset__hard', $hard);
1471 1471
         $instance->CFG = EE_Config::reset($hard, $reinstantiate);
1472 1472
         $instance->CART = null;
1473 1473
         $instance->MRM = null;
@@ -1498,7 +1498,7 @@  discard block
 block discarded – undo
1498 1498
      */
1499 1499
     private static function _reset_and_unset_object($object, $reset_models)
1500 1500
     {
1501
-        if (! is_object($object)) {
1501
+        if ( ! is_object($object)) {
1502 1502
             // don't unset anything that's not an object
1503 1503
             return false;
1504 1504
         }
@@ -1518,7 +1518,7 @@  discard block
 block discarded – undo
1518 1518
             $object->reset();
1519 1519
             return true;
1520 1520
         }
1521
-        if (! $object instanceof InterminableInterface) {
1521
+        if ( ! $object instanceof InterminableInterface) {
1522 1522
             return true;
1523 1523
         }
1524 1524
         return false;
Please login to merge, or discard this patch.
core/EE_Dependency_Map.core.php 1 patch
Indentation   +775 added lines, -775 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,780 +22,780 @@  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\services\orm\ModelFieldFactory'                                                   => array(
626
-                'EventEspresso\core\services\loaders\Loader'              => EE_Dependency_Map::load_from_cache,
627
-            ),
628
-            'LEGACY_MODELS'                                                   => array(
629
-                null,
630
-                'EventEspresso\core\services\orm\ModelFieldFactory' => EE_Dependency_Map::load_from_cache,
631
-            ),
632
-            'EE_Module_Request_Router' => array(
633
-                'EE_Request' => EE_Dependency_Map::load_from_cache,
634
-            ),
635
-        );
636
-    }
637
-
638
-
639
-
640
-    /**
641
-     * Registers how core classes are loaded.
642
-     * This can either be done by simply providing the name of one of the EE_Registry loader methods such as:
643
-     *        'EE_Request_Handler' => 'load_core'
644
-     *        'EE_Messages_Queue'  => 'load_lib'
645
-     *        'EEH_Debug_Tools'    => 'load_helper'
646
-     * or, if greater control is required, by providing a custom closure. For example:
647
-     *        'Some_Class' => function () {
648
-     *            return new Some_Class();
649
-     *        },
650
-     * This is required for instantiating dependencies
651
-     * where an interface has been type hinted in a class constructor. For example:
652
-     *        'Required_Interface' => function () {
653
-     *            return new A_Class_That_Implements_Required_Interface();
654
-     *        },
655
-     *
656
-     * @throws InvalidInterfaceException
657
-     * @throws InvalidDataTypeException
658
-     * @throws InvalidArgumentException
659
-     */
660
-    protected function _register_core_class_loaders()
661
-    {
662
-        //for PHP5.3 compat, we need to register any properties called here in a variable because `$this` cannot
663
-        //be used in a closure.
664
-        $request = &$this->_request;
665
-        $response = &$this->_response;
666
-        $loader = &$this->loader;
667
-        $this->_class_loaders = array(
668
-            //load_core
669
-            'EE_Capabilities'                      => 'load_core',
670
-            'EE_Encryption'                        => 'load_core',
671
-            'EE_Front_Controller'                  => 'load_core',
672
-            'EE_Module_Request_Router'             => 'load_core',
673
-            'EE_Registry'                          => 'load_core',
674
-            'EE_Request'                           => function () use (&$request) {
675
-                return $request;
676
-            },
677
-            'EE_Response'                          => function () use (&$response) {
678
-                return $response;
679
-            },
680
-            'EE_Request_Handler'                   => 'load_core',
681
-            'EE_Session'                           => 'load_core',
682
-            'EE_Cron_Tasks'                        => 'load_core',
683
-            'EE_System'                            => 'load_core',
684
-            'EE_Maintenance_Mode'                  => 'load_core',
685
-            'EE_Register_CPTs'                     => 'load_core',
686
-            'EE_Admin'                             => 'load_core',
687
-            //load_lib
688
-            'EE_Message_Resource_Manager'          => 'load_lib',
689
-            'EE_Message_Type_Collection'           => 'load_lib',
690
-            'EE_Message_Type_Collection_Loader'    => 'load_lib',
691
-            'EE_Messenger_Collection'              => 'load_lib',
692
-            'EE_Messenger_Collection_Loader'       => 'load_lib',
693
-            'EE_Messages_Processor'                => 'load_lib',
694
-            'EE_Message_Repository'                => 'load_lib',
695
-            'EE_Messages_Queue'                    => 'load_lib',
696
-            'EE_Messages_Data_Handler_Collection'  => 'load_lib',
697
-            'EE_Message_Template_Group_Collection' => 'load_lib',
698
-            'EE_Messages_Generator'                => function () {
699
-                return EE_Registry::instance()->load_lib(
700
-                    'Messages_Generator',
701
-                    array(),
702
-                    false,
703
-                    false
704
-                );
705
-            },
706
-            'EE_Messages_Template_Defaults'        => function ($arguments = array()) {
707
-                return EE_Registry::instance()->load_lib(
708
-                    'Messages_Template_Defaults',
709
-                    $arguments,
710
-                    false,
711
-                    false
712
-                );
713
-            },
714
-            //load_model
715
-            // 'EEM_Attendee'                         => 'load_model',
716
-            // 'EEM_Message_Template_Group'           => 'load_model',
717
-            // 'EEM_Message_Template'                 => 'load_model',
718
-            //load_helper
719
-            'EEH_Parse_Shortcodes'                 => function () {
720
-                if (EE_Registry::instance()->load_helper('Parse_Shortcodes')) {
721
-                    return new EEH_Parse_Shortcodes();
722
-                }
723
-                return null;
724
-            },
725
-            'EE_Template_Config'                   => function () {
726
-                return EE_Config::instance()->template_settings;
727
-            },
728
-            'EE_Currency_Config'                   => function () {
729
-                return EE_Config::instance()->currency;
730
-            },
731
-            'EventEspresso\core\services\loaders\Loader' => function () use (&$loader) {
732
-                return $loader;
733
-            },
734
-        );
735
-    }
736
-
737
-
738
-
739
-    /**
740
-     * can be used for supplying alternate names for classes,
741
-     * or for connecting interface names to instantiable classes
742
-     */
743
-    protected function _register_core_aliases()
744
-    {
745
-        $this->_aliases = array(
746
-            'CommandBusInterface'                                                 => 'EventEspresso\core\services\commands\CommandBusInterface',
747
-            'EventEspresso\core\services\commands\CommandBusInterface'            => 'EventEspresso\core\services\commands\CommandBus',
748
-            'CommandHandlerManagerInterface'                                      => 'EventEspresso\core\services\commands\CommandHandlerManagerInterface',
749
-            'EventEspresso\core\services\commands\CommandHandlerManagerInterface' => 'EventEspresso\core\services\commands\CommandHandlerManager',
750
-            'CapChecker'                                                          => 'EventEspresso\core\services\commands\middleware\CapChecker',
751
-            'AddActionHook'                                                       => 'EventEspresso\core\services\commands\middleware\AddActionHook',
752
-            'CapabilitiesChecker'                                                 => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
753
-            'CapabilitiesCheckerInterface'                                        => 'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface',
754
-            'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface' => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
755
-            'CreateRegistrationService'                                           => 'EventEspresso\core\domain\services\registration\CreateRegistrationService',
756
-            'CreateRegCodeCommandHandler'                                         => 'EventEspresso\core\services\commands\registration\CreateRegCodeCommand',
757
-            'CreateRegUrlLinkCommandHandler'                                      => 'EventEspresso\core\services\commands\registration\CreateRegUrlLinkCommand',
758
-            'CreateRegistrationCommandHandler'                                    => 'EventEspresso\core\services\commands\registration\CreateRegistrationCommand',
759
-            'CopyRegistrationDetailsCommandHandler'                               => 'EventEspresso\core\services\commands\registration\CopyRegistrationDetailsCommand',
760
-            'CopyRegistrationPaymentsCommandHandler'                              => 'EventEspresso\core\services\commands\registration\CopyRegistrationPaymentsCommand',
761
-            'CancelRegistrationAndTicketLineItemCommandHandler'                   => 'EventEspresso\core\services\commands\registration\CancelRegistrationAndTicketLineItemCommandHandler',
762
-            'UpdateRegistrationAndTransactionAfterChangeCommandHandler'           => 'EventEspresso\core\services\commands\registration\UpdateRegistrationAndTransactionAfterChangeCommandHandler',
763
-            'CreateTicketLineItemCommandHandler'                                  => 'EventEspresso\core\services\commands\ticket\CreateTicketLineItemCommand',
764
-            'TableManager'                                                        => 'EventEspresso\core\services\database\TableManager',
765
-            'TableAnalysis'                                                       => 'EventEspresso\core\services\database\TableAnalysis',
766
-            'CreateTransactionCommandHandler'                                     => 'EventEspresso\core\services\commands\transaction\CreateTransactionCommandHandler',
767
-            'CreateAttendeeCommandHandler'                                        => 'EventEspresso\core\services\commands\attendee\CreateAttendeeCommandHandler',
768
-            'EspressoShortcode'                                                   => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
769
-            'ShortcodeInterface'                                                  => 'EventEspresso\core\services\shortcodes\ShortcodeInterface',
770
-            'EventEspresso\core\services\shortcodes\ShortcodeInterface'           => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
771
-            'EventEspresso\core\services\cache\CacheStorageInterface'             => 'EventEspresso\core\services\cache\TransientCacheStorage',
772
-            'LoaderInterface'                                                     => 'EventEspresso\core\services\loaders\LoaderInterface',
773
-            'EventEspresso\core\services\loaders\LoaderInterface'                 => 'EventEspresso\core\services\loaders\Loader',
774
-            'CommandFactoryInterface'                                             => 'EventEspresso\core\services\commands\CommandFactoryInterface',
775
-            'EventEspresso\core\services\commands\CommandFactoryInterface'        => 'EventEspresso\core\services\commands\CommandFactory',
776
-            'EventEspresso\core\domain\services\session\SessionIdentifierInterface' => 'EE_Session',
777
-            'NoticeConverterInterface'                                            => 'EventEspresso\core\services\notices\NoticeConverterInterface',
778
-            'EventEspresso\core\services\notices\NoticeConverterInterface'        => 'EventEspresso\core\services\notices\ConvertNoticesToEeErrors',
779
-            'NoticesContainerInterface'                                            => 'EventEspresso\core\services\notices\NoticesContainerInterface',
780
-            'EventEspresso\core\services\notices\NoticesContainerInterface'        => 'EventEspresso\core\services\notices\NoticesContainer',
781
-        );
782
-    }
783
-
784
-
785
-
786
-    /**
787
-     * This is used to reset the internal map and class_loaders to their original default state at the beginning of the
788
-     * request Primarily used by unit tests.
789
-     *
790
-     * @throws InvalidDataTypeException
791
-     * @throws InvalidInterfaceException
792
-     * @throws InvalidArgumentException
793
-     */
794
-    public function reset()
795
-    {
796
-        $this->_register_core_class_loaders();
797
-        $this->_register_core_dependencies();
798
-    }
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\services\orm\ModelFieldFactory'                                                   => array(
626
+				'EventEspresso\core\services\loaders\Loader'              => EE_Dependency_Map::load_from_cache,
627
+			),
628
+			'LEGACY_MODELS'                                                   => array(
629
+				null,
630
+				'EventEspresso\core\services\orm\ModelFieldFactory' => EE_Dependency_Map::load_from_cache,
631
+			),
632
+			'EE_Module_Request_Router' => array(
633
+				'EE_Request' => EE_Dependency_Map::load_from_cache,
634
+			),
635
+		);
636
+	}
637
+
638
+
639
+
640
+	/**
641
+	 * Registers how core classes are loaded.
642
+	 * This can either be done by simply providing the name of one of the EE_Registry loader methods such as:
643
+	 *        'EE_Request_Handler' => 'load_core'
644
+	 *        'EE_Messages_Queue'  => 'load_lib'
645
+	 *        'EEH_Debug_Tools'    => 'load_helper'
646
+	 * or, if greater control is required, by providing a custom closure. For example:
647
+	 *        'Some_Class' => function () {
648
+	 *            return new Some_Class();
649
+	 *        },
650
+	 * This is required for instantiating dependencies
651
+	 * where an interface has been type hinted in a class constructor. For example:
652
+	 *        'Required_Interface' => function () {
653
+	 *            return new A_Class_That_Implements_Required_Interface();
654
+	 *        },
655
+	 *
656
+	 * @throws InvalidInterfaceException
657
+	 * @throws InvalidDataTypeException
658
+	 * @throws InvalidArgumentException
659
+	 */
660
+	protected function _register_core_class_loaders()
661
+	{
662
+		//for PHP5.3 compat, we need to register any properties called here in a variable because `$this` cannot
663
+		//be used in a closure.
664
+		$request = &$this->_request;
665
+		$response = &$this->_response;
666
+		$loader = &$this->loader;
667
+		$this->_class_loaders = array(
668
+			//load_core
669
+			'EE_Capabilities'                      => 'load_core',
670
+			'EE_Encryption'                        => 'load_core',
671
+			'EE_Front_Controller'                  => 'load_core',
672
+			'EE_Module_Request_Router'             => 'load_core',
673
+			'EE_Registry'                          => 'load_core',
674
+			'EE_Request'                           => function () use (&$request) {
675
+				return $request;
676
+			},
677
+			'EE_Response'                          => function () use (&$response) {
678
+				return $response;
679
+			},
680
+			'EE_Request_Handler'                   => 'load_core',
681
+			'EE_Session'                           => 'load_core',
682
+			'EE_Cron_Tasks'                        => 'load_core',
683
+			'EE_System'                            => 'load_core',
684
+			'EE_Maintenance_Mode'                  => 'load_core',
685
+			'EE_Register_CPTs'                     => 'load_core',
686
+			'EE_Admin'                             => 'load_core',
687
+			//load_lib
688
+			'EE_Message_Resource_Manager'          => 'load_lib',
689
+			'EE_Message_Type_Collection'           => 'load_lib',
690
+			'EE_Message_Type_Collection_Loader'    => 'load_lib',
691
+			'EE_Messenger_Collection'              => 'load_lib',
692
+			'EE_Messenger_Collection_Loader'       => 'load_lib',
693
+			'EE_Messages_Processor'                => 'load_lib',
694
+			'EE_Message_Repository'                => 'load_lib',
695
+			'EE_Messages_Queue'                    => 'load_lib',
696
+			'EE_Messages_Data_Handler_Collection'  => 'load_lib',
697
+			'EE_Message_Template_Group_Collection' => 'load_lib',
698
+			'EE_Messages_Generator'                => function () {
699
+				return EE_Registry::instance()->load_lib(
700
+					'Messages_Generator',
701
+					array(),
702
+					false,
703
+					false
704
+				);
705
+			},
706
+			'EE_Messages_Template_Defaults'        => function ($arguments = array()) {
707
+				return EE_Registry::instance()->load_lib(
708
+					'Messages_Template_Defaults',
709
+					$arguments,
710
+					false,
711
+					false
712
+				);
713
+			},
714
+			//load_model
715
+			// 'EEM_Attendee'                         => 'load_model',
716
+			// 'EEM_Message_Template_Group'           => 'load_model',
717
+			// 'EEM_Message_Template'                 => 'load_model',
718
+			//load_helper
719
+			'EEH_Parse_Shortcodes'                 => function () {
720
+				if (EE_Registry::instance()->load_helper('Parse_Shortcodes')) {
721
+					return new EEH_Parse_Shortcodes();
722
+				}
723
+				return null;
724
+			},
725
+			'EE_Template_Config'                   => function () {
726
+				return EE_Config::instance()->template_settings;
727
+			},
728
+			'EE_Currency_Config'                   => function () {
729
+				return EE_Config::instance()->currency;
730
+			},
731
+			'EventEspresso\core\services\loaders\Loader' => function () use (&$loader) {
732
+				return $loader;
733
+			},
734
+		);
735
+	}
736
+
737
+
738
+
739
+	/**
740
+	 * can be used for supplying alternate names for classes,
741
+	 * or for connecting interface names to instantiable classes
742
+	 */
743
+	protected function _register_core_aliases()
744
+	{
745
+		$this->_aliases = array(
746
+			'CommandBusInterface'                                                 => 'EventEspresso\core\services\commands\CommandBusInterface',
747
+			'EventEspresso\core\services\commands\CommandBusInterface'            => 'EventEspresso\core\services\commands\CommandBus',
748
+			'CommandHandlerManagerInterface'                                      => 'EventEspresso\core\services\commands\CommandHandlerManagerInterface',
749
+			'EventEspresso\core\services\commands\CommandHandlerManagerInterface' => 'EventEspresso\core\services\commands\CommandHandlerManager',
750
+			'CapChecker'                                                          => 'EventEspresso\core\services\commands\middleware\CapChecker',
751
+			'AddActionHook'                                                       => 'EventEspresso\core\services\commands\middleware\AddActionHook',
752
+			'CapabilitiesChecker'                                                 => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
753
+			'CapabilitiesCheckerInterface'                                        => 'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface',
754
+			'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface' => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
755
+			'CreateRegistrationService'                                           => 'EventEspresso\core\domain\services\registration\CreateRegistrationService',
756
+			'CreateRegCodeCommandHandler'                                         => 'EventEspresso\core\services\commands\registration\CreateRegCodeCommand',
757
+			'CreateRegUrlLinkCommandHandler'                                      => 'EventEspresso\core\services\commands\registration\CreateRegUrlLinkCommand',
758
+			'CreateRegistrationCommandHandler'                                    => 'EventEspresso\core\services\commands\registration\CreateRegistrationCommand',
759
+			'CopyRegistrationDetailsCommandHandler'                               => 'EventEspresso\core\services\commands\registration\CopyRegistrationDetailsCommand',
760
+			'CopyRegistrationPaymentsCommandHandler'                              => 'EventEspresso\core\services\commands\registration\CopyRegistrationPaymentsCommand',
761
+			'CancelRegistrationAndTicketLineItemCommandHandler'                   => 'EventEspresso\core\services\commands\registration\CancelRegistrationAndTicketLineItemCommandHandler',
762
+			'UpdateRegistrationAndTransactionAfterChangeCommandHandler'           => 'EventEspresso\core\services\commands\registration\UpdateRegistrationAndTransactionAfterChangeCommandHandler',
763
+			'CreateTicketLineItemCommandHandler'                                  => 'EventEspresso\core\services\commands\ticket\CreateTicketLineItemCommand',
764
+			'TableManager'                                                        => 'EventEspresso\core\services\database\TableManager',
765
+			'TableAnalysis'                                                       => 'EventEspresso\core\services\database\TableAnalysis',
766
+			'CreateTransactionCommandHandler'                                     => 'EventEspresso\core\services\commands\transaction\CreateTransactionCommandHandler',
767
+			'CreateAttendeeCommandHandler'                                        => 'EventEspresso\core\services\commands\attendee\CreateAttendeeCommandHandler',
768
+			'EspressoShortcode'                                                   => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
769
+			'ShortcodeInterface'                                                  => 'EventEspresso\core\services\shortcodes\ShortcodeInterface',
770
+			'EventEspresso\core\services\shortcodes\ShortcodeInterface'           => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
771
+			'EventEspresso\core\services\cache\CacheStorageInterface'             => 'EventEspresso\core\services\cache\TransientCacheStorage',
772
+			'LoaderInterface'                                                     => 'EventEspresso\core\services\loaders\LoaderInterface',
773
+			'EventEspresso\core\services\loaders\LoaderInterface'                 => 'EventEspresso\core\services\loaders\Loader',
774
+			'CommandFactoryInterface'                                             => 'EventEspresso\core\services\commands\CommandFactoryInterface',
775
+			'EventEspresso\core\services\commands\CommandFactoryInterface'        => 'EventEspresso\core\services\commands\CommandFactory',
776
+			'EventEspresso\core\domain\services\session\SessionIdentifierInterface' => 'EE_Session',
777
+			'NoticeConverterInterface'                                            => 'EventEspresso\core\services\notices\NoticeConverterInterface',
778
+			'EventEspresso\core\services\notices\NoticeConverterInterface'        => 'EventEspresso\core\services\notices\ConvertNoticesToEeErrors',
779
+			'NoticesContainerInterface'                                            => 'EventEspresso\core\services\notices\NoticesContainerInterface',
780
+			'EventEspresso\core\services\notices\NoticesContainerInterface'        => 'EventEspresso\core\services\notices\NoticesContainer',
781
+		);
782
+	}
783
+
784
+
785
+
786
+	/**
787
+	 * This is used to reset the internal map and class_loaders to their original default state at the beginning of the
788
+	 * request Primarily used by unit tests.
789
+	 *
790
+	 * @throws InvalidDataTypeException
791
+	 * @throws InvalidInterfaceException
792
+	 * @throws InvalidArgumentException
793
+	 */
794
+	public function reset()
795
+	{
796
+		$this->_register_core_class_loaders();
797
+		$this->_register_core_dependencies();
798
+	}
799 799
 
800 800
 
801 801
 }
Please login to merge, or discard this patch.
espresso.php 1 patch
Indentation   +219 added lines, -219 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('ABSPATH')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 /*
5 5
   Plugin Name:		Event Espresso
@@ -40,243 +40,243 @@  discard block
 block discarded – undo
40 40
  * @since            4.0
41 41
  */
42 42
 if (function_exists('espresso_version')) {
43
-    /**
44
-     *    espresso_duplicate_plugin_error
45
-     *    displays if more than one version of EE is activated at the same time
46
-     */
47
-    function espresso_duplicate_plugin_error()
48
-    {
49
-        ?>
43
+	/**
44
+	 *    espresso_duplicate_plugin_error
45
+	 *    displays if more than one version of EE is activated at the same time
46
+	 */
47
+	function espresso_duplicate_plugin_error()
48
+	{
49
+		?>
50 50
         <div class="error">
51 51
             <p>
52 52
                 <?php echo esc_html__(
53
-                        'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
54
-                        'event_espresso'
55
-                ); ?>
53
+						'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
54
+						'event_espresso'
55
+				); ?>
56 56
             </p>
57 57
         </div>
58 58
         <?php
59
-        espresso_deactivate_plugin(plugin_basename(__FILE__));
60
-    }
59
+		espresso_deactivate_plugin(plugin_basename(__FILE__));
60
+	}
61 61
 
62
-    add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
62
+	add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
63 63
 } else {
64
-    define('EE_MIN_PHP_VER_REQUIRED', '5.3.9');
65
-    if ( ! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
66
-        /**
67
-         * espresso_minimum_php_version_error
68
-         *
69
-         * @return void
70
-         */
71
-        function espresso_minimum_php_version_error()
72
-        {
73
-            ?>
64
+	define('EE_MIN_PHP_VER_REQUIRED', '5.3.9');
65
+	if ( ! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
66
+		/**
67
+		 * espresso_minimum_php_version_error
68
+		 *
69
+		 * @return void
70
+		 */
71
+		function espresso_minimum_php_version_error()
72
+		{
73
+			?>
74 74
             <div class="error">
75 75
                 <p>
76 76
                     <?php
77
-                    printf(
78
-                            esc_html__(
79
-                                    'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
80
-                                    'event_espresso'
81
-                            ),
82
-                            EE_MIN_PHP_VER_REQUIRED,
83
-                            PHP_VERSION,
84
-                            '<br/>',
85
-                            '<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
86
-                    );
87
-                    ?>
77
+					printf(
78
+							esc_html__(
79
+									'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
80
+									'event_espresso'
81
+							),
82
+							EE_MIN_PHP_VER_REQUIRED,
83
+							PHP_VERSION,
84
+							'<br/>',
85
+							'<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
86
+					);
87
+					?>
88 88
                 </p>
89 89
             </div>
90 90
             <?php
91
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
92
-        }
91
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
92
+		}
93 93
 
94
-        add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
95
-    } else {
96
-        /**
97
-         * espresso_version
98
-         * Returns the plugin version
99
-         *
100
-         * @return string
101
-         */
102
-        function espresso_version()
103
-        {
104
-            return apply_filters('FHEE__espresso__espresso_version', '4.9.46.rc.042');
105
-        }
94
+		add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
95
+	} else {
96
+		/**
97
+		 * espresso_version
98
+		 * Returns the plugin version
99
+		 *
100
+		 * @return string
101
+		 */
102
+		function espresso_version()
103
+		{
104
+			return apply_filters('FHEE__espresso__espresso_version', '4.9.46.rc.042');
105
+		}
106 106
 
107
-        // define versions
108
-        define('EVENT_ESPRESSO_VERSION', espresso_version());
109
-        define('EE_MIN_WP_VER_REQUIRED', '4.1');
110
-        define('EE_MIN_WP_VER_RECOMMENDED', '4.4.2');
111
-        define('EE_MIN_PHP_VER_RECOMMENDED', '5.4.44');
112
-        define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
113
-        //used to be DIRECTORY_SEPARATOR, but that caused issues on windows
114
-        if ( ! defined('DS')) {
115
-            define('DS', '/');
116
-        }
117
-        if ( ! defined('PS')) {
118
-            define('PS', PATH_SEPARATOR);
119
-        }
120
-        if ( ! defined('SP')) {
121
-            define('SP', ' ');
122
-        }
123
-        if ( ! defined('EENL')) {
124
-            define('EENL', "\n");
125
-        }
126
-        define('EE_SUPPORT_EMAIL', '[email protected]');
127
-        // define the plugin directory and URL
128
-        define('EE_PLUGIN_BASENAME', plugin_basename(EVENT_ESPRESSO_MAIN_FILE));
129
-        define('EE_PLUGIN_DIR_PATH', plugin_dir_path(EVENT_ESPRESSO_MAIN_FILE));
130
-        define('EE_PLUGIN_DIR_URL', plugin_dir_url(EVENT_ESPRESSO_MAIN_FILE));
131
-        // main root folder paths
132
-        define('EE_ADMIN_PAGES', EE_PLUGIN_DIR_PATH . 'admin_pages' . DS);
133
-        define('EE_CORE', EE_PLUGIN_DIR_PATH . 'core' . DS);
134
-        define('EE_MODULES', EE_PLUGIN_DIR_PATH . 'modules' . DS);
135
-        define('EE_PUBLIC', EE_PLUGIN_DIR_PATH . 'public' . DS);
136
-        define('EE_SHORTCODES', EE_PLUGIN_DIR_PATH . 'shortcodes' . DS);
137
-        define('EE_WIDGETS', EE_PLUGIN_DIR_PATH . 'widgets' . DS);
138
-        define('EE_PAYMENT_METHODS', EE_PLUGIN_DIR_PATH . 'payment_methods' . DS);
139
-        define('EE_CAFF_PATH', EE_PLUGIN_DIR_PATH . 'caffeinated' . DS);
140
-        // core system paths
141
-        define('EE_ADMIN', EE_CORE . 'admin' . DS);
142
-        define('EE_CPTS', EE_CORE . 'CPTs' . DS);
143
-        define('EE_CLASSES', EE_CORE . 'db_classes' . DS);
144
-        define('EE_INTERFACES', EE_CORE . 'interfaces' . DS);
145
-        define('EE_BUSINESS', EE_CORE . 'business' . DS);
146
-        define('EE_MODELS', EE_CORE . 'db_models' . DS);
147
-        define('EE_HELPERS', EE_CORE . 'helpers' . DS);
148
-        define('EE_LIBRARIES', EE_CORE . 'libraries' . DS);
149
-        define('EE_TEMPLATES', EE_CORE . 'templates' . DS);
150
-        define('EE_THIRD_PARTY', EE_CORE . 'third_party_libs' . DS);
151
-        define('EE_GLOBAL_ASSETS', EE_TEMPLATES . 'global_assets' . DS);
152
-        define('EE_FORM_SECTIONS', EE_LIBRARIES . 'form_sections' . DS);
153
-        // gateways
154
-        define('EE_GATEWAYS', EE_MODULES . 'gateways' . DS);
155
-        define('EE_GATEWAYS_URL', EE_PLUGIN_DIR_URL . 'modules' . DS . 'gateways' . DS);
156
-        // asset URL paths
157
-        define('EE_TEMPLATES_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'templates' . DS);
158
-        define('EE_GLOBAL_ASSETS_URL', EE_TEMPLATES_URL . 'global_assets' . DS);
159
-        define('EE_IMAGES_URL', EE_GLOBAL_ASSETS_URL . 'images' . DS);
160
-        define('EE_THIRD_PARTY_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'third_party_libs' . DS);
161
-        define('EE_HELPERS_ASSETS', EE_PLUGIN_DIR_URL . 'core/helpers/assets/');
162
-        define('EE_LIBRARIES_URL', EE_PLUGIN_DIR_URL . 'core/libraries/');
163
-        // define upload paths
164
-        $uploads = wp_upload_dir();
165
-        // define the uploads directory and URL
166
-        define('EVENT_ESPRESSO_UPLOAD_DIR', $uploads['basedir'] . DS . 'espresso' . DS);
167
-        define('EVENT_ESPRESSO_UPLOAD_URL', $uploads['baseurl'] . DS . 'espresso' . DS);
168
-        // define the templates directory and URL
169
-        define('EVENT_ESPRESSO_TEMPLATE_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'templates' . DS);
170
-        define('EVENT_ESPRESSO_TEMPLATE_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'templates' . DS);
171
-        // define the gateway directory and URL
172
-        define('EVENT_ESPRESSO_GATEWAY_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'gateways' . DS);
173
-        define('EVENT_ESPRESSO_GATEWAY_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'gateways' . DS);
174
-        // languages folder/path
175
-        define('EE_LANGUAGES_SAFE_LOC', '..' . DS . 'uploads' . DS . 'espresso' . DS . 'languages' . DS);
176
-        define('EE_LANGUAGES_SAFE_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'languages' . DS);
177
-        //check for dompdf fonts in uploads
178
-        if (file_exists(EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS)) {
179
-            define('DOMPDF_FONT_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS);
180
-        }
181
-        //ajax constants
182
-        define(
183
-                'EE_FRONT_AJAX',
184
-                isset($_REQUEST['ee_front_ajax']) || isset($_REQUEST['data']['ee_front_ajax']) ? true : false
185
-        );
186
-        define(
187
-                'EE_ADMIN_AJAX',
188
-                isset($_REQUEST['ee_admin_ajax']) || isset($_REQUEST['data']['ee_admin_ajax']) ? true : false
189
-        );
190
-        //just a handy constant occasionally needed for finding values representing infinity in the DB
191
-        //you're better to use this than its straight value (currently -1) in case you ever
192
-        //want to change its default value! or find when -1 means infinity
193
-        define('EE_INF_IN_DB', -1);
194
-        define('EE_INF', INF > (float)PHP_INT_MAX ? INF : PHP_INT_MAX);
195
-        define('EE_DEBUG', false);
196
-        // for older WP versions
197
-        if ( ! defined('MONTH_IN_SECONDS')) {
198
-            define('MONTH_IN_SECONDS', DAY_IN_SECONDS * 30);
199
-        }
200
-        /**
201
-         *    espresso_plugin_activation
202
-         *    adds a wp-option to indicate that EE has been activated via the WP admin plugins page
203
-         */
204
-        function espresso_plugin_activation()
205
-        {
206
-            update_option('ee_espresso_activation', true);
207
-        }
107
+		// define versions
108
+		define('EVENT_ESPRESSO_VERSION', espresso_version());
109
+		define('EE_MIN_WP_VER_REQUIRED', '4.1');
110
+		define('EE_MIN_WP_VER_RECOMMENDED', '4.4.2');
111
+		define('EE_MIN_PHP_VER_RECOMMENDED', '5.4.44');
112
+		define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
113
+		//used to be DIRECTORY_SEPARATOR, but that caused issues on windows
114
+		if ( ! defined('DS')) {
115
+			define('DS', '/');
116
+		}
117
+		if ( ! defined('PS')) {
118
+			define('PS', PATH_SEPARATOR);
119
+		}
120
+		if ( ! defined('SP')) {
121
+			define('SP', ' ');
122
+		}
123
+		if ( ! defined('EENL')) {
124
+			define('EENL', "\n");
125
+		}
126
+		define('EE_SUPPORT_EMAIL', '[email protected]');
127
+		// define the plugin directory and URL
128
+		define('EE_PLUGIN_BASENAME', plugin_basename(EVENT_ESPRESSO_MAIN_FILE));
129
+		define('EE_PLUGIN_DIR_PATH', plugin_dir_path(EVENT_ESPRESSO_MAIN_FILE));
130
+		define('EE_PLUGIN_DIR_URL', plugin_dir_url(EVENT_ESPRESSO_MAIN_FILE));
131
+		// main root folder paths
132
+		define('EE_ADMIN_PAGES', EE_PLUGIN_DIR_PATH . 'admin_pages' . DS);
133
+		define('EE_CORE', EE_PLUGIN_DIR_PATH . 'core' . DS);
134
+		define('EE_MODULES', EE_PLUGIN_DIR_PATH . 'modules' . DS);
135
+		define('EE_PUBLIC', EE_PLUGIN_DIR_PATH . 'public' . DS);
136
+		define('EE_SHORTCODES', EE_PLUGIN_DIR_PATH . 'shortcodes' . DS);
137
+		define('EE_WIDGETS', EE_PLUGIN_DIR_PATH . 'widgets' . DS);
138
+		define('EE_PAYMENT_METHODS', EE_PLUGIN_DIR_PATH . 'payment_methods' . DS);
139
+		define('EE_CAFF_PATH', EE_PLUGIN_DIR_PATH . 'caffeinated' . DS);
140
+		// core system paths
141
+		define('EE_ADMIN', EE_CORE . 'admin' . DS);
142
+		define('EE_CPTS', EE_CORE . 'CPTs' . DS);
143
+		define('EE_CLASSES', EE_CORE . 'db_classes' . DS);
144
+		define('EE_INTERFACES', EE_CORE . 'interfaces' . DS);
145
+		define('EE_BUSINESS', EE_CORE . 'business' . DS);
146
+		define('EE_MODELS', EE_CORE . 'db_models' . DS);
147
+		define('EE_HELPERS', EE_CORE . 'helpers' . DS);
148
+		define('EE_LIBRARIES', EE_CORE . 'libraries' . DS);
149
+		define('EE_TEMPLATES', EE_CORE . 'templates' . DS);
150
+		define('EE_THIRD_PARTY', EE_CORE . 'third_party_libs' . DS);
151
+		define('EE_GLOBAL_ASSETS', EE_TEMPLATES . 'global_assets' . DS);
152
+		define('EE_FORM_SECTIONS', EE_LIBRARIES . 'form_sections' . DS);
153
+		// gateways
154
+		define('EE_GATEWAYS', EE_MODULES . 'gateways' . DS);
155
+		define('EE_GATEWAYS_URL', EE_PLUGIN_DIR_URL . 'modules' . DS . 'gateways' . DS);
156
+		// asset URL paths
157
+		define('EE_TEMPLATES_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'templates' . DS);
158
+		define('EE_GLOBAL_ASSETS_URL', EE_TEMPLATES_URL . 'global_assets' . DS);
159
+		define('EE_IMAGES_URL', EE_GLOBAL_ASSETS_URL . 'images' . DS);
160
+		define('EE_THIRD_PARTY_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'third_party_libs' . DS);
161
+		define('EE_HELPERS_ASSETS', EE_PLUGIN_DIR_URL . 'core/helpers/assets/');
162
+		define('EE_LIBRARIES_URL', EE_PLUGIN_DIR_URL . 'core/libraries/');
163
+		// define upload paths
164
+		$uploads = wp_upload_dir();
165
+		// define the uploads directory and URL
166
+		define('EVENT_ESPRESSO_UPLOAD_DIR', $uploads['basedir'] . DS . 'espresso' . DS);
167
+		define('EVENT_ESPRESSO_UPLOAD_URL', $uploads['baseurl'] . DS . 'espresso' . DS);
168
+		// define the templates directory and URL
169
+		define('EVENT_ESPRESSO_TEMPLATE_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'templates' . DS);
170
+		define('EVENT_ESPRESSO_TEMPLATE_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'templates' . DS);
171
+		// define the gateway directory and URL
172
+		define('EVENT_ESPRESSO_GATEWAY_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'gateways' . DS);
173
+		define('EVENT_ESPRESSO_GATEWAY_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'gateways' . DS);
174
+		// languages folder/path
175
+		define('EE_LANGUAGES_SAFE_LOC', '..' . DS . 'uploads' . DS . 'espresso' . DS . 'languages' . DS);
176
+		define('EE_LANGUAGES_SAFE_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'languages' . DS);
177
+		//check for dompdf fonts in uploads
178
+		if (file_exists(EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS)) {
179
+			define('DOMPDF_FONT_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS);
180
+		}
181
+		//ajax constants
182
+		define(
183
+				'EE_FRONT_AJAX',
184
+				isset($_REQUEST['ee_front_ajax']) || isset($_REQUEST['data']['ee_front_ajax']) ? true : false
185
+		);
186
+		define(
187
+				'EE_ADMIN_AJAX',
188
+				isset($_REQUEST['ee_admin_ajax']) || isset($_REQUEST['data']['ee_admin_ajax']) ? true : false
189
+		);
190
+		//just a handy constant occasionally needed for finding values representing infinity in the DB
191
+		//you're better to use this than its straight value (currently -1) in case you ever
192
+		//want to change its default value! or find when -1 means infinity
193
+		define('EE_INF_IN_DB', -1);
194
+		define('EE_INF', INF > (float)PHP_INT_MAX ? INF : PHP_INT_MAX);
195
+		define('EE_DEBUG', false);
196
+		// for older WP versions
197
+		if ( ! defined('MONTH_IN_SECONDS')) {
198
+			define('MONTH_IN_SECONDS', DAY_IN_SECONDS * 30);
199
+		}
200
+		/**
201
+		 *    espresso_plugin_activation
202
+		 *    adds a wp-option to indicate that EE has been activated via the WP admin plugins page
203
+		 */
204
+		function espresso_plugin_activation()
205
+		{
206
+			update_option('ee_espresso_activation', true);
207
+		}
208 208
 
209
-        register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
210
-        /**
211
-         *    espresso_load_error_handling
212
-         *    this function loads EE's class for handling exceptions and errors
213
-         */
214
-        function espresso_load_error_handling()
215
-        {
216
-            // load debugging tools
217
-            if (WP_DEBUG === true && is_readable(EE_HELPERS . 'EEH_Debug_Tools.helper.php')) {
218
-                require_once(EE_HELPERS . 'EEH_Debug_Tools.helper.php');
219
-                EEH_Debug_Tools::instance();
220
-            }
221
-            // load error handling
222
-            if (is_readable(EE_CORE . 'EE_Error.core.php')) {
223
-                require_once(EE_CORE . 'EE_Error.core.php');
224
-            } else {
225
-                wp_die(esc_html__('The EE_Error core class could not be loaded.', 'event_espresso'));
226
-            }
227
-        }
209
+		register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
210
+		/**
211
+		 *    espresso_load_error_handling
212
+		 *    this function loads EE's class for handling exceptions and errors
213
+		 */
214
+		function espresso_load_error_handling()
215
+		{
216
+			// load debugging tools
217
+			if (WP_DEBUG === true && is_readable(EE_HELPERS . 'EEH_Debug_Tools.helper.php')) {
218
+				require_once(EE_HELPERS . 'EEH_Debug_Tools.helper.php');
219
+				EEH_Debug_Tools::instance();
220
+			}
221
+			// load error handling
222
+			if (is_readable(EE_CORE . 'EE_Error.core.php')) {
223
+				require_once(EE_CORE . 'EE_Error.core.php');
224
+			} else {
225
+				wp_die(esc_html__('The EE_Error core class could not be loaded.', 'event_espresso'));
226
+			}
227
+		}
228 228
 
229
-        /**
230
-         *    espresso_load_required
231
-         *    given a class name and path, this function will load that file or throw an exception
232
-         *
233
-         * @param    string $classname
234
-         * @param    string $full_path_to_file
235
-         * @throws    EE_Error
236
-         */
237
-        function espresso_load_required($classname, $full_path_to_file)
238
-        {
239
-            static $error_handling_loaded = false;
240
-            if ( ! $error_handling_loaded) {
241
-                espresso_load_error_handling();
242
-                $error_handling_loaded = true;
243
-            }
244
-            if (is_readable($full_path_to_file)) {
245
-                require_once($full_path_to_file);
246
-            } else {
247
-                throw new EE_Error (
248
-                        sprintf(
249
-                                esc_html__(
250
-                                        'The %s class file could not be located or is not readable due to file permissions.',
251
-                                        'event_espresso'
252
-                                ),
253
-                                $classname
254
-                        )
255
-                );
256
-            }
257
-        }
229
+		/**
230
+		 *    espresso_load_required
231
+		 *    given a class name and path, this function will load that file or throw an exception
232
+		 *
233
+		 * @param    string $classname
234
+		 * @param    string $full_path_to_file
235
+		 * @throws    EE_Error
236
+		 */
237
+		function espresso_load_required($classname, $full_path_to_file)
238
+		{
239
+			static $error_handling_loaded = false;
240
+			if ( ! $error_handling_loaded) {
241
+				espresso_load_error_handling();
242
+				$error_handling_loaded = true;
243
+			}
244
+			if (is_readable($full_path_to_file)) {
245
+				require_once($full_path_to_file);
246
+			} else {
247
+				throw new EE_Error (
248
+						sprintf(
249
+								esc_html__(
250
+										'The %s class file could not be located or is not readable due to file permissions.',
251
+										'event_espresso'
252
+								),
253
+								$classname
254
+						)
255
+				);
256
+			}
257
+		}
258 258
 
259
-        espresso_load_required('EEH_Base', EE_CORE . 'helpers' . DS . 'EEH_Base.helper.php');
260
-        espresso_load_required('EEH_File', EE_CORE . 'helpers' . DS . 'EEH_File.helper.php');
261
-        espresso_load_required('EE_Bootstrap', EE_CORE . 'EE_Bootstrap.core.php');
262
-        new EE_Bootstrap();
263
-    }
259
+		espresso_load_required('EEH_Base', EE_CORE . 'helpers' . DS . 'EEH_Base.helper.php');
260
+		espresso_load_required('EEH_File', EE_CORE . 'helpers' . DS . 'EEH_File.helper.php');
261
+		espresso_load_required('EE_Bootstrap', EE_CORE . 'EE_Bootstrap.core.php');
262
+		new EE_Bootstrap();
263
+	}
264 264
 }
265 265
 if ( ! function_exists('espresso_deactivate_plugin')) {
266
-    /**
267
-     *    deactivate_plugin
268
-     * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
269
-     *
270
-     * @access public
271
-     * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
272
-     * @return    void
273
-     */
274
-    function espresso_deactivate_plugin($plugin_basename = '')
275
-    {
276
-        if ( ! function_exists('deactivate_plugins')) {
277
-            require_once(ABSPATH . 'wp-admin/includes/plugin.php');
278
-        }
279
-        unset($_GET['activate'], $_REQUEST['activate']);
280
-        deactivate_plugins($plugin_basename);
281
-    }
266
+	/**
267
+	 *    deactivate_plugin
268
+	 * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
269
+	 *
270
+	 * @access public
271
+	 * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
272
+	 * @return    void
273
+	 */
274
+	function espresso_deactivate_plugin($plugin_basename = '')
275
+	{
276
+		if ( ! function_exists('deactivate_plugins')) {
277
+			require_once(ABSPATH . 'wp-admin/includes/plugin.php');
278
+		}
279
+		unset($_GET['activate'], $_REQUEST['activate']);
280
+		deactivate_plugins($plugin_basename);
281
+	}
282 282
 }
283 283
\ No newline at end of file
Please login to merge, or discard this patch.