Completed
Branch FET/11183/improvements-to-pue-... (232f50)
by
unknown
43:46 queued 26:36
created
modules/core_rest_api/EED_Core_Rest_Api.module.php 2 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -1,7 +1,6 @@
 block discarded – undo
1 1
 <?php
2 2
 
3 3
 use EventEspresso\core\domain\Domain;
4
-use EventEspresso\core\domain\entities\notifications\PersistentAdminNotice;
5 4
 use EventEspresso\core\domain\services\factories\EmailAddressFactory;
6 5
 use EventEspresso\core\domain\services\validation\email\EmailValidationException;
7 6
 use EventEspresso\core\exceptions\InvalidDataTypeException;
Please login to merge, or discard this patch.
Indentation   +1249 added lines, -1249 removed lines patch added patch discarded remove patch
@@ -26,1256 +26,1256 @@
 block discarded – undo
26 26
 class EED_Core_Rest_Api extends \EED_Module
27 27
 {
28 28
 
29
-    const ee_api_namespace           = Domain::API_NAMESPACE;
29
+	const ee_api_namespace           = Domain::API_NAMESPACE;
30 30
 
31
-    const ee_api_namespace_for_regex = 'ee\/v([^/]*)\/';
32
-
33
-    const saved_routes_option_names  = 'ee_core_routes';
34
-
35
-    /**
36
-     * string used in _links response bodies to make them globally unique.
37
-     *
38
-     * @see http://v2.wp-api.org/extending/linking/
39
-     */
40
-    const ee_api_link_namespace = 'https://api.eventespresso.com/';
41
-
42
-    /**
43
-     * @var CalculatedModelFields
44
-     */
45
-    protected static $_field_calculator;
46
-
47
-
48
-
49
-    /**
50
-     * @return EED_Core_Rest_Api|EED_Module
51
-     */
52
-    public static function instance()
53
-    {
54
-        self::$_field_calculator = new CalculatedModelFields();
55
-        return parent::get_instance(__CLASS__);
56
-    }
57
-
58
-
59
-
60
-    /**
61
-     *    set_hooks - for hooking into EE Core, other modules, etc
62
-     *
63
-     * @access    public
64
-     * @return    void
65
-     */
66
-    public static function set_hooks()
67
-    {
68
-        self::set_hooks_both();
69
-    }
70
-
71
-
72
-
73
-    /**
74
-     *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
75
-     *
76
-     * @access    public
77
-     * @return    void
78
-     */
79
-    public static function set_hooks_admin()
80
-    {
81
-        self::set_hooks_both();
82
-    }
83
-
84
-
85
-
86
-    public static function set_hooks_both()
87
-    {
88
-        add_action('rest_api_init', array('EED_Core_Rest_Api', 'register_routes'), 10);
89
-        add_action('rest_api_init', array('EED_Core_Rest_Api', 'set_hooks_rest_api'), 5);
90
-        add_filter('rest_route_data', array('EED_Core_Rest_Api', 'hide_old_endpoints'), 10, 2);
91
-        add_filter('rest_index',
92
-            array('EventEspresso\core\libraries\rest_api\controllers\model\Meta', 'filterEeMetadataIntoIndex'));
93
-        EED_Core_Rest_Api::invalidate_cached_route_data_on_version_change();
94
-    }
95
-
96
-
97
-
98
-    /**
99
-     * sets up hooks which only need to be included as part of REST API requests;
100
-     * other requests like to the frontend or admin etc don't need them
101
-     *
102
-     * @throws \EE_Error
103
-     */
104
-    public static function set_hooks_rest_api()
105
-    {
106
-        //set hooks which account for changes made to the API
107
-        EED_Core_Rest_Api::_set_hooks_for_changes();
108
-    }
109
-
110
-
111
-
112
-    /**
113
-     * public wrapper of _set_hooks_for_changes.
114
-     * Loads all the hooks which make requests to old versions of the API
115
-     * appear the same as they always did
116
-     *
117
-     * @throws EE_Error
118
-     */
119
-    public static function set_hooks_for_changes()
120
-    {
121
-        self::_set_hooks_for_changes();
122
-    }
123
-
124
-
125
-
126
-    /**
127
-     * Loads all the hooks which make requests to old versions of the API
128
-     * appear the same as they always did
129
-     *
130
-     * @throws EE_Error
131
-     */
132
-    protected static function _set_hooks_for_changes()
133
-    {
134
-        $folder_contents = EEH_File::get_contents_of_folders(array(EE_LIBRARIES . 'rest_api' . DS . 'changes'), false);
135
-        foreach ($folder_contents as $classname_in_namespace => $filepath) {
136
-            //ignore the base parent class
137
-            //and legacy named classes
138
-            if ($classname_in_namespace === 'ChangesInBase'
139
-                || strpos($classname_in_namespace, 'Changes_In_') === 0
140
-            ) {
141
-                continue;
142
-            }
143
-            $full_classname = 'EventEspresso\core\libraries\rest_api\changes\\' . $classname_in_namespace;
144
-            if (class_exists($full_classname)) {
145
-                $instance_of_class = new $full_classname;
146
-                if ($instance_of_class instanceof ChangesInBase) {
147
-                    $instance_of_class->setHooks();
148
-                }
149
-            }
150
-        }
151
-    }
152
-
153
-
154
-
155
-    /**
156
-     * Filters the WP routes to add our EE-related ones. This takes a bit of time
157
-     * so we actually prefer to only do it when an EE plugin is activated or upgraded
158
-     *
159
-     * @throws \EE_Error
160
-     */
161
-    public static function register_routes()
162
-    {
163
-        foreach (EED_Core_Rest_Api::get_ee_route_data() as $namespace => $relative_routes) {
164
-            foreach ($relative_routes as $relative_route => $data_for_multiple_endpoints) {
165
-                /**
166
-                 * @var array $data_for_multiple_endpoints numerically indexed array
167
-                 *                                         but can also contain route options like {
168
-                 * @type array    $schema                      {
169
-                 * @type callable $schema_callback
170
-                 * @type array    $callback_args               arguments that will be passed to the callback, after the
171
-                 * WP_REST_Request of course
172
-                 * }
173
-                 * }
174
-                 */
175
-                //when registering routes, register all the endpoints' data at the same time
176
-                $multiple_endpoint_args = array();
177
-                foreach ($data_for_multiple_endpoints as $endpoint_key => $data_for_single_endpoint) {
178
-                    /**
179
-                     * @var array     $data_for_single_endpoint {
180
-                     * @type callable $callback
181
-                     * @type string methods
182
-                     * @type array args
183
-                     * @type array _links
184
-                     * @type array    $callback_args            arguments that will be passed to the callback, after the
185
-                     * WP_REST_Request of course
186
-                     * }
187
-                     */
188
-                    //skip route options
189
-                    if (! is_numeric($endpoint_key)) {
190
-                        continue;
191
-                    }
192
-                    if (! isset($data_for_single_endpoint['callback'], $data_for_single_endpoint['methods'])) {
193
-                        throw new EE_Error(
194
-                            esc_html__(
195
-                                // @codingStandardsIgnoreStart
196
-                                'Endpoint configuration data needs to have entries "callback" (callable) and "methods" (comma-separated list of accepts HTTP methods).',
197
-                                // @codingStandardsIgnoreEnd
198
-                                'event_espresso')
199
-                        );
200
-                    }
201
-                    $callback = $data_for_single_endpoint['callback'];
202
-                    $single_endpoint_args = array(
203
-                        'methods' => $data_for_single_endpoint['methods'],
204
-                        'args'    => isset($data_for_single_endpoint['args']) ? $data_for_single_endpoint['args']
205
-                            : array(),
206
-                    );
207
-                    if (isset($data_for_single_endpoint['_links'])) {
208
-                        $single_endpoint_args['_links'] = $data_for_single_endpoint['_links'];
209
-                    }
210
-                    if (isset($data_for_single_endpoint['callback_args'])) {
211
-                        $callback_args = $data_for_single_endpoint['callback_args'];
212
-                        $single_endpoint_args['callback'] = function (\WP_REST_Request $request) use (
213
-                            $callback,
214
-                            $callback_args
215
-                        ) {
216
-                            array_unshift($callback_args, $request);
217
-                            return call_user_func_array(
218
-                                $callback,
219
-                                $callback_args
220
-                            );
221
-                        };
222
-                    } else {
223
-                        $single_endpoint_args['callback'] = $data_for_single_endpoint['callback'];
224
-                    }
225
-                    $multiple_endpoint_args[] = $single_endpoint_args;
226
-                }
227
-                if (isset($data_for_multiple_endpoints['schema'])) {
228
-                    $schema_route_data = $data_for_multiple_endpoints['schema'];
229
-                    $schema_callback = $schema_route_data['schema_callback'];
230
-                    $callback_args = $schema_route_data['callback_args'];
231
-                    $multiple_endpoint_args['schema'] = function () use ($schema_callback, $callback_args) {
232
-                        return call_user_func_array(
233
-                            $schema_callback,
234
-                            $callback_args
235
-                        );
236
-                    };
237
-                }
238
-                register_rest_route(
239
-                    $namespace,
240
-                    $relative_route,
241
-                    $multiple_endpoint_args
242
-                );
243
-            }
244
-        }
245
-    }
246
-
247
-
248
-
249
-    /**
250
-     * Checks if there was a version change or something that merits invalidating the cached
251
-     * route data. If so, invalidates the cached route data so that it gets refreshed
252
-     * next time the WP API is used
253
-     */
254
-    public static function invalidate_cached_route_data_on_version_change()
255
-    {
256
-        if (EE_System::instance()->detect_req_type() !== EE_System::req_type_normal) {
257
-            EED_Core_Rest_Api::invalidate_cached_route_data();
258
-        }
259
-        foreach (EE_Registry::instance()->addons as $addon) {
260
-            if ($addon instanceof EE_Addon && $addon->detect_req_type() !== EE_System::req_type_normal) {
261
-                EED_Core_Rest_Api::invalidate_cached_route_data();
262
-            }
263
-        }
264
-    }
265
-
266
-
267
-
268
-    /**
269
-     * Removes the cached route data so it will get refreshed next time the WP API is used
270
-     */
271
-    public static function invalidate_cached_route_data()
272
-    {
273
-        //delete the saved EE REST API routes
274
-        foreach (EED_Core_Rest_Api::versions_served() as $version => $hidden) {
275
-            delete_option(EED_Core_Rest_Api::saved_routes_option_names . $version);
276
-        }
277
-    }
278
-
279
-
280
-
281
-    /**
282
-     * Gets the EE route data
283
-     *
284
-     * @return array top-level key is the namespace, next-level key is the route and its value is array{
285
-     * @throws \EE_Error
286
-     * @type string|array $callback
287
-     * @type string       $methods
288
-     * @type boolean      $hidden_endpoint
289
-     * }
290
-     */
291
-    public static function get_ee_route_data()
292
-    {
293
-        $ee_routes = array();
294
-        foreach (self::versions_served() as $version => $hidden_endpoints) {
295
-            $ee_routes[self::ee_api_namespace . $version] = self::_get_ee_route_data_for_version(
296
-                $version,
297
-                $hidden_endpoints
298
-            );
299
-        }
300
-        return $ee_routes;
301
-    }
302
-
303
-
304
-
305
-    /**
306
-     * Gets the EE route data from the wp options if it exists already,
307
-     * otherwise re-generates it and saves it to the option
308
-     *
309
-     * @param string  $version
310
-     * @param boolean $hidden_endpoints
311
-     * @return array
312
-     * @throws \EE_Error
313
-     */
314
-    protected static function _get_ee_route_data_for_version($version, $hidden_endpoints = false)
315
-    {
316
-        $ee_routes = get_option(self::saved_routes_option_names . $version, null);
317
-        if (! $ee_routes || (defined('EE_REST_API_DEBUG_MODE') && EE_REST_API_DEBUG_MODE)) {
318
-            $ee_routes = self::_save_ee_route_data_for_version($version, $hidden_endpoints);
319
-        }
320
-        return $ee_routes;
321
-    }
322
-
323
-
324
-
325
-    /**
326
-     * Saves the EE REST API route data to a wp option and returns it
327
-     *
328
-     * @param string  $version
329
-     * @param boolean $hidden_endpoints
330
-     * @return mixed|null
331
-     * @throws \EE_Error
332
-     */
333
-    protected static function _save_ee_route_data_for_version($version, $hidden_endpoints = false)
334
-    {
335
-        $instance = self::instance();
336
-        $routes = apply_filters(
337
-            'EED_Core_Rest_Api__save_ee_route_data_for_version__routes',
338
-            array_replace_recursive(
339
-                $instance->_get_config_route_data_for_version($version, $hidden_endpoints),
340
-                $instance->_get_meta_route_data_for_version($version, $hidden_endpoints),
341
-                $instance->_get_model_route_data_for_version($version, $hidden_endpoints),
342
-                $instance->_get_rpc_route_data_for_version($version, $hidden_endpoints)
343
-            )
344
-        );
345
-        $option_name = self::saved_routes_option_names . $version;
346
-        if (get_option($option_name)) {
347
-            update_option($option_name, $routes, true);
348
-        } else {
349
-            add_option($option_name, $routes, null, 'no');
350
-        }
351
-        return $routes;
352
-    }
353
-
354
-
355
-
356
-    /**
357
-     * Calculates all the EE routes and saves it to a WordPress option so we don't
358
-     * need to calculate it on every request
359
-     *
360
-     * @deprecated since version 4.9.1
361
-     * @return void
362
-     */
363
-    public static function save_ee_routes()
364
-    {
365
-        if (EE_Maintenance_Mode::instance()->models_can_query()) {
366
-            $instance = self::instance();
367
-            $routes = apply_filters(
368
-                'EED_Core_Rest_Api__save_ee_routes__routes',
369
-                array_replace_recursive(
370
-                    $instance->_register_config_routes(),
371
-                    $instance->_register_meta_routes(),
372
-                    $instance->_register_model_routes(),
373
-                    $instance->_register_rpc_routes()
374
-                )
375
-            );
376
-            update_option(self::saved_routes_option_names, $routes, true);
377
-        }
378
-    }
379
-
380
-
381
-
382
-    /**
383
-     * Gets all the route information relating to EE models
384
-     *
385
-     * @return array @see get_ee_route_data
386
-     * @deprecated since version 4.9.1
387
-     */
388
-    protected function _register_model_routes()
389
-    {
390
-        $model_routes = array();
391
-        foreach (self::versions_served() as $version => $hidden_endpoint) {
392
-            $model_routes[EED_Core_Rest_Api::ee_api_namespace
393
-                          . $version] = $this->_get_config_route_data_for_version($version, $hidden_endpoint);
394
-        }
395
-        return $model_routes;
396
-    }
397
-
398
-
399
-
400
-    /**
401
-     * Decides whether or not to add write endpoints for this model.
402
-     *
403
-     * Currently, this defaults to exclude all global tables and models
404
-     * which would allow inserting WP core data (we don't want to duplicate
405
-     * what WP API does, as it's unnecessary, extra work, and potentially extra bugs)
406
-     * @param EEM_Base $model
407
-     * @return bool
408
-     */
409
-    public static function should_have_write_endpoints(EEM_Base $model)
410
-    {
411
-        if ($model->is_wp_core_model()){
412
-            return false;
413
-        }
414
-        foreach($model->get_tables() as $table){
415
-            if( $table->is_global()){
416
-                return false;
417
-            }
418
-        }
419
-        return true;
420
-    }
421
-
422
-
423
-
424
-    /**
425
-     * Gets the names of all models which should have plural routes (eg `ee/v4.8.36/events`)
426
-     * in this versioned namespace of EE4
427
-     * @param $version
428
-     * @return array keys are model names (eg 'Event') and values ar either classnames (eg 'EEM_Event')
429
-     */
430
-    public static function model_names_with_plural_routes($version){
431
-        $model_version_info = new ModelVersionInfo($version);
432
-        $models_to_register = $model_version_info->modelsForRequestedVersion();
433
-        //let's not bother having endpoints for extra metas
434
-        unset(
435
-            $models_to_register['Extra_Meta'],
436
-            $models_to_register['Extra_Join'],
437
-            $models_to_register['Post_Meta']
438
-        );
439
-        return apply_filters(
440
-            'FHEE__EED_Core_REST_API___register_model_routes',
441
-            $models_to_register
442
-        );
443
-    }
444
-
445
-
446
-
447
-    /**
448
-     * Gets the route data for EE models in the specified version
449
-     *
450
-     * @param string  $version
451
-     * @param boolean $hidden_endpoint
452
-     * @return array
453
-     * @throws EE_Error
454
-     */
455
-    protected function _get_model_route_data_for_version($version, $hidden_endpoint = false)
456
-    {
457
-        $model_routes = array();
458
-        $model_version_info = new ModelVersionInfo($version);
459
-        foreach (EED_Core_Rest_Api::model_names_with_plural_routes($version) as $model_name => $model_classname) {
460
-            $model = \EE_Registry::instance()->load_model($model_name);
461
-            //if this isn't a valid model then let's skip iterate to the next item in the loop.
462
-            if (! $model instanceof EEM_Base) {
463
-                continue;
464
-            }
465
-            //yes we could just register one route for ALL models, but then they wouldn't show up in the index
466
-            $plural_model_route = EED_Core_Rest_Api::get_collection_route($model);
467
-            $singular_model_route = EED_Core_Rest_Api::get_entity_route($model, '(?P<id>[^\/]+)');
468
-            $model_routes[$plural_model_route] = array(
469
-                array(
470
-                    'callback'        => array(
471
-                        'EventEspresso\core\libraries\rest_api\controllers\model\Read',
472
-                        'handleRequestGetAll',
473
-                    ),
474
-                    'callback_args'   => array($version, $model_name),
475
-                    'methods'         => WP_REST_Server::READABLE,
476
-                    'hidden_endpoint' => $hidden_endpoint,
477
-                    'args'            => $this->_get_read_query_params($model, $version),
478
-                    '_links'          => array(
479
-                        'self' => rest_url(EED_Core_Rest_Api::ee_api_namespace . $version . $singular_model_route),
480
-                    ),
481
-                ),
482
-                'schema' => array(
483
-                    'schema_callback' => array(
484
-                        'EventEspresso\core\libraries\rest_api\controllers\model\Read',
485
-                        'handleSchemaRequest',
486
-                    ),
487
-                    'callback_args'   => array($version, $model_name),
488
-                ),
489
-            );
490
-            $model_routes[$singular_model_route] = array(
491
-                array(
492
-                    'callback'        => array(
493
-                        'EventEspresso\core\libraries\rest_api\controllers\model\Read',
494
-                        'handleRequestGetOne',
495
-                    ),
496
-                    'callback_args'   => array($version, $model_name),
497
-                    'methods'         => WP_REST_Server::READABLE,
498
-                    'hidden_endpoint' => $hidden_endpoint,
499
-                    'args'            => $this->_get_response_selection_query_params($model, $version),
500
-                ),
501
-            );
502
-            if( apply_filters(
503
-                'FHEE__EED_Core_Rest_Api___get_model_route_data_for_version__add_write_endpoints',
504
-                EED_Core_Rest_Api::should_have_write_endpoints($model),
505
-                $model
506
-            )){
507
-                $model_routes[$plural_model_route][] = array(
508
-                    'callback'        => array(
509
-                        'EventEspresso\core\libraries\rest_api\controllers\model\Write',
510
-                        'handleRequestInsert',
511
-                    ),
512
-                    'callback_args'   => array($version, $model_name),
513
-                    'methods'         => WP_REST_Server::CREATABLE,
514
-                    'hidden_endpoint' => $hidden_endpoint,
515
-                    'args'            => $this->_get_write_params($model_name, $model_version_info, true),
516
-                );
517
-                $model_routes[$singular_model_route] = array_merge(
518
-                    $model_routes[$singular_model_route],
519
-                    array(
520
-                        array(
521
-                            'callback'        => array(
522
-                                'EventEspresso\core\libraries\rest_api\controllers\model\Write',
523
-                                'handleRequestUpdate',
524
-                            ),
525
-                            'callback_args'   => array($version, $model_name),
526
-                            'methods'         => WP_REST_Server::EDITABLE,
527
-                            'hidden_endpoint' => $hidden_endpoint,
528
-                            'args'            => $this->_get_write_params($model_name, $model_version_info),
529
-                        ),
530
-                        array(
531
-                            'callback'        => array(
532
-                                'EventEspresso\core\libraries\rest_api\controllers\model\Write',
533
-                                'handleRequestDelete',
534
-                            ),
535
-                            'callback_args'   => array($version, $model_name),
536
-                            'methods'         => WP_REST_Server::DELETABLE,
537
-                            'hidden_endpoint' => $hidden_endpoint,
538
-                            'args'            => $this->_get_delete_query_params($model, $version),
539
-                        )
540
-                    )
541
-                );
542
-            }
543
-            foreach ($model->relation_settings() as $relation_name => $relation_obj) {
544
-
545
-                $related_route = EED_Core_Rest_Api::get_relation_route_via(
546
-                    $model,
547
-                    '(?P<id>[^\/]+)',
548
-                    $relation_obj
549
-                );
550
-                $endpoints = array(
551
-                    array(
552
-                        'callback'        => array(
553
-                            'EventEspresso\core\libraries\rest_api\controllers\model\Read',
554
-                            'handleRequestGetRelated',
555
-                        ),
556
-                        'callback_args'   => array($version, $model_name, $relation_name),
557
-                        'methods'         => WP_REST_Server::READABLE,
558
-                        'hidden_endpoint' => $hidden_endpoint,
559
-                        'args'            => $this->_get_read_query_params($relation_obj->get_other_model(), $version),
560
-                    ),
561
-                );
562
-                $model_routes[$related_route] = $endpoints;
563
-            }
564
-        }
565
-        return $model_routes;
566
-    }
567
-
568
-
569
-
570
-    /**
571
-     * Gets the relative URI to a model's REST API plural route, after the EE4 versioned namespace,
572
-     * excluding the preceding slash.
573
-     * Eg you pass get_plural_route_to('Event') = 'events'
574
-     *
575
-     * @param EEM_Base $model
576
-     * @return string
577
-     */
578
-    public static function get_collection_route(EEM_Base $model)
579
-    {
580
-        return EEH_Inflector::pluralize_and_lower($model->get_this_model_name());
581
-    }
582
-
583
-
584
-
585
-    /**
586
-     * Gets the relative URI to a model's REST API singular route, after the EE4 versioned namespace,
587
-     * excluding the preceding slash.
588
-     * Eg you pass get_plural_route_to('Event', 12) = 'events/12'
589
-     *
590
-     * @param EEM_Base $model eg Event or Venue
591
-     * @param string $id
592
-     * @return string
593
-     */
594
-    public static function get_entity_route($model, $id)
595
-    {
596
-        return EED_Core_Rest_Api::get_collection_route($model). '/' . $id;
597
-    }
598
-
599
-
600
-    /**
601
-     * Gets the relative URI to a model's REST API singular route, after the EE4 versioned namespace,
602
-     * excluding the preceding slash.
603
-     * Eg you pass get_plural_route_to('Event', 12) = 'events/12'
604
-     *
605
-     * @param EEM_Base                 $model eg Event or Venue
606
-     * @param string                 $id
607
-     * @param EE_Model_Relation_Base $relation_obj
608
-     * @return string
609
-     */
610
-    public static function get_relation_route_via(EEM_Base $model, $id, EE_Model_Relation_Base $relation_obj)
611
-    {
612
-        $related_model_name_endpoint_part = ModelRead::getRelatedEntityName(
613
-            $relation_obj->get_other_model()->get_this_model_name(),
614
-            $relation_obj
615
-        );
616
-        return EED_Core_Rest_Api::get_entity_route($model, $id) . '/' . $related_model_name_endpoint_part;
617
-    }
618
-
619
-
620
-
621
-    /**
622
-     * Adds onto the $relative_route the EE4 REST API versioned namespace.
623
-     * Eg if given '4.8.36' and 'events', will return 'ee/v4.8.36/events'
624
-     * @param string $relative_route
625
-     * @param string $version
626
-     * @return string
627
-     */
628
-    public static function get_versioned_route_to($relative_route, $version = '4.8.36'){
629
-        return '/' . EED_Core_Rest_Api::ee_api_namespace . $version . '/' . $relative_route;
630
-    }
631
-
632
-
633
-
634
-    /**
635
-     * Adds all the RPC-style routes (remote procedure call-like routes, ie
636
-     * routes that don't conform to the traditional REST CRUD-style).
637
-     *
638
-     * @deprecated since 4.9.1
639
-     */
640
-    protected function _register_rpc_routes()
641
-    {
642
-        $routes = array();
643
-        foreach (self::versions_served() as $version => $hidden_endpoint) {
644
-            $routes[self::ee_api_namespace . $version] = $this->_get_rpc_route_data_for_version(
645
-                $version,
646
-                $hidden_endpoint
647
-            );
648
-        }
649
-        return $routes;
650
-    }
651
-
652
-
653
-
654
-    /**
655
-     * @param string  $version
656
-     * @param boolean $hidden_endpoint
657
-     * @return array
658
-     */
659
-    protected function _get_rpc_route_data_for_version($version, $hidden_endpoint = false)
660
-    {
661
-        $this_versions_routes = array();
662
-        //checkin endpoint
663
-        $this_versions_routes['registrations/(?P<REG_ID>\d+)/toggle_checkin_for_datetime/(?P<DTT_ID>\d+)'] = array(
664
-            array(
665
-                'callback'        => array(
666
-                    'EventEspresso\core\libraries\rest_api\controllers\rpc\Checkin',
667
-                    'handleRequestToggleCheckin',
668
-                ),
669
-                'methods'         => WP_REST_Server::CREATABLE,
670
-                'hidden_endpoint' => $hidden_endpoint,
671
-                'args'            => array(
672
-                    'force' => array(
673
-                        'required'    => false,
674
-                        'default'     => false,
675
-                        'description' => __(
676
-                            // @codingStandardsIgnoreStart
677
-                            'Whether to force toggle checkin, or to verify the registration status and allowed ticket uses',
678
-                            // @codingStandardsIgnoreEnd
679
-                            'event_espresso'
680
-                        ),
681
-                    ),
682
-                ),
683
-                'callback_args'   => array($version),
684
-            ),
685
-        );
686
-        return apply_filters(
687
-            'FHEE__EED_Core_Rest_Api___register_rpc_routes__this_versions_routes',
688
-            $this_versions_routes,
689
-            $version,
690
-            $hidden_endpoint
691
-        );
692
-    }
693
-
694
-
695
-
696
-    /**
697
-     * Gets the query params that can be used when request one or many
698
-     *
699
-     * @param EEM_Base $model
700
-     * @param string   $version
701
-     * @return array
702
-     */
703
-    protected function _get_response_selection_query_params(\EEM_Base $model, $version)
704
-    {
705
-        return apply_filters(
706
-            'FHEE__EED_Core_Rest_Api___get_response_selection_query_params',
707
-            array(
708
-                'include'   => array(
709
-                    'required' => false,
710
-                    'default'  => '*',
711
-                    'type'     => 'string',
712
-                ),
713
-                'calculate' => array(
714
-                    'required'          => false,
715
-                    'default'           => '',
716
-                    'enum'              => self::$_field_calculator->retrieveCalculatedFieldsForModel($model),
717
-                    'type'              => 'string',
718
-                    //because we accept a CSV'd list of the enumerated strings, WP core validation and sanitization
719
-                    //freaks out. We'll just validate this argument while handling the request
720
-                    'validate_callback' => null,
721
-                    'sanitize_callback' => null,
722
-                ),
723
-            ),
724
-            $model,
725
-            $version
726
-        );
727
-    }
728
-
729
-
730
-
731
-    /**
732
-     * Gets the parameters acceptable for delete requests
733
-     *
734
-     * @param \EEM_Base $model
735
-     * @param string    $version
736
-     * @return array
737
-     */
738
-    protected function _get_delete_query_params(\EEM_Base $model, $version)
739
-    {
740
-        $params_for_delete = array(
741
-            'allow_blocking' => array(
742
-                'required' => false,
743
-                'default'  => true,
744
-                'type'     => 'boolean',
745
-            ),
746
-        );
747
-        $params_for_delete['force'] = array(
748
-            'required' => false,
749
-            'default'  => false,
750
-            'type'     => 'boolean',
751
-        );
752
-        return apply_filters(
753
-            'FHEE__EED_Core_Rest_Api___get_delete_query_params',
754
-            $params_for_delete,
755
-            $model,
756
-            $version
757
-        );
758
-    }
759
-
760
-
761
-
762
-    /**
763
-     * Gets info about reading query params that are acceptable
764
-     *
765
-     * @param \EEM_Base $model eg 'Event' or 'Venue'
766
-     * @param  string   $version
767
-     * @return array    describing the args acceptable when querying this model
768
-     * @throws EE_Error
769
-     */
770
-    protected function _get_read_query_params(\EEM_Base $model, $version)
771
-    {
772
-        $default_orderby = array();
773
-        foreach ($model->get_combined_primary_key_fields() as $key_field) {
774
-            $default_orderby[$key_field->get_name()] = 'ASC';
775
-        }
776
-        return array_merge(
777
-            $this->_get_response_selection_query_params($model, $version),
778
-            array(
779
-                'where'    => array(
780
-                    'required' => false,
781
-                    'default'  => array(),
782
-                    'type'     => 'object',
783
-                    //because we accept an almost infinite list of possible where conditions, WP
784
-                    // core validation and sanitization freaks out. We'll just validate this argument
785
-                    // while handling the request
786
-                    'validate_callback' => null,
787
-                    'sanitize_callback' => null,
788
-                ),
789
-                'limit'    => array(
790
-                    'required' => false,
791
-                    'default'  => EED_Core_Rest_Api::get_default_query_limit(),
792
-                    'type'     => array(
793
-                        'array',
794
-                        'string',
795
-                        'integer',
796
-                    ),
797
-                    //because we accept a variety of types, WP core validation and sanitization
798
-                    //freaks out. We'll just validate this argument while handling the request
799
-                    'validate_callback' => null,
800
-                    'sanitize_callback' => null,
801
-                ),
802
-                'order_by' => array(
803
-                    'required' => false,
804
-                    'default'  => $default_orderby,
805
-                    'type'     => array(
806
-                        'object',
807
-                        'string',
808
-                    ),//because we accept a variety of types, WP core validation and sanitization
809
-                    //freaks out. We'll just validate this argument while handling the request
810
-                    'validate_callback' => null,
811
-                    'sanitize_callback' => null,
812
-                ),
813
-                'group_by' => array(
814
-                    'required' => false,
815
-                    'default'  => null,
816
-                    'type'     => array(
817
-                        'object',
818
-                        'string',
819
-                    ),
820
-                    //because we accept  an almost infinite list of possible groupings,
821
-                    // WP core validation and sanitization
822
-                    //freaks out. We'll just validate this argument while handling the request
823
-                    'validate_callback' => null,
824
-                    'sanitize_callback' => null,
825
-                ),
826
-                'having'   => array(
827
-                    'required' => false,
828
-                    'default'  => null,
829
-                    'type'     => 'object',
830
-                    //because we accept an almost infinite list of possible where conditions, WP
831
-                    // core validation and sanitization freaks out. We'll just validate this argument
832
-                    // while handling the request
833
-                    'validate_callback' => null,
834
-                    'sanitize_callback' => null,
835
-                ),
836
-                'caps'     => array(
837
-                    'required' => false,
838
-                    'default'  => EEM_Base::caps_read,
839
-                    'type'     => 'string',
840
-                    'enum'     => array(
841
-                        EEM_Base::caps_read,
842
-                        EEM_Base::caps_read_admin,
843
-                        EEM_Base::caps_edit,
844
-                        EEM_Base::caps_delete
845
-                    )
846
-                ),
847
-            )
848
-        );
849
-    }
850
-
851
-
852
-
853
-    /**
854
-     * Gets parameter information for a model regarding writing data
855
-     *
856
-     * @param string           $model_name
857
-     * @param ModelVersionInfo $model_version_info
858
-     * @param boolean          $create                                       whether this is for request to create (in which case we need
859
-     *                                                                       all required params) or just to update (in which case we don't need those on every request)
860
-     * @return array
861
-     */
862
-    protected function _get_write_params(
863
-        $model_name,
864
-        ModelVersionInfo $model_version_info,
865
-        $create = false
866
-    ) {
867
-        $model = EE_Registry::instance()->load_model($model_name);
868
-        $fields = $model_version_info->fieldsOnModelInThisVersion($model);
869
-        $args_info = array();
870
-        foreach ($fields as $field_name => $field_obj) {
871
-            if ($field_obj->is_auto_increment()) {
872
-                //totally ignore auto increment IDs
873
-                continue;
874
-            }
875
-            $arg_info = $field_obj->getSchema();
876
-            $required = $create && ! $field_obj->is_nullable() && $field_obj->get_default_value() === null;
877
-            $arg_info['required'] = $required;
878
-            //remove the read-only flag. If it were read-only we wouldn't list it as an argument while writing, right?
879
-            unset($arg_info['readonly']);
880
-            $schema_properties = $field_obj->getSchemaProperties();
881
-            if (
882
-                isset($schema_properties['raw'])
883
-                && $field_obj->getSchemaType() === 'object'
884
-            ) {
885
-                //if there's a "raw" form of this argument, use those properties instead
886
-                $arg_info = array_replace(
887
-                    $arg_info,
888
-                    $schema_properties['raw']
889
-                );
890
-            }
891
-            $arg_info['default'] = ModelDataTranslator::prepareFieldValueForJson(
892
-                $field_obj,
893
-                $field_obj->get_default_value(),
894
-                $model_version_info->requestedVersion()
895
-            );
896
-            //we do our own validation and sanitization within the controller
897
-            $arg_info['sanitize_callback'] =
898
-                array(
899
-                    'EED_Core_Rest_Api',
900
-                    'default_sanitize_callback',
901
-                );
902
-            $args_info[$field_name] = $arg_info;
903
-            if ($field_obj instanceof EE_Datetime_Field) {
904
-                $gmt_arg_info = $arg_info;
905
-                $gmt_arg_info['description'] = sprintf(
906
-                    esc_html__(
907
-                        '%1$s - the value for this field in UTC. Ignored if %2$s is provided.',
908
-                        'event_espresso'
909
-                    ),
910
-                    $field_obj->get_nicename(),
911
-                    $field_name
912
-                );
913
-                $args_info[$field_name . '_gmt'] = $gmt_arg_info;
914
-            }
915
-        }
916
-        return $args_info;
917
-    }
918
-
919
-
920
-
921
-    /**
922
-     * Replacement for WP API's 'rest_parse_request_arg'.
923
-     * If the value is blank but not required, don't bother validating it.
924
-     * Also, it uses our email validation instead of WP API's default.
925
-     *
926
-     * @param                 $value
927
-     * @param WP_REST_Request $request
928
-     * @param                 $param
929
-     * @return bool|true|WP_Error
930
-     * @throws InvalidArgumentException
931
-     * @throws InvalidInterfaceException
932
-     * @throws InvalidDataTypeException
933
-     */
934
-    public static function default_sanitize_callback( $value, WP_REST_Request $request, $param)
935
-    {
936
-        $attributes = $request->get_attributes();
937
-        if (! isset($attributes['args'][$param])
938
-            || ! is_array($attributes['args'][$param])) {
939
-            $validation_result = true;
940
-        } else {
941
-            $args = $attributes['args'][$param];
942
-            if ((
943
-                    $value === ''
944
-                    || $value === null
945
-                )
946
-                && (! isset($args['required'])
947
-                    || $args['required'] === false
948
-                )
949
-            ) {
950
-                //not required and not provided? that's cool
951
-                $validation_result = true;
952
-            } elseif (isset($args['format'])
953
-                && $args['format'] === 'email'
954
-            ) {
955
-                $validation_result = true;
956
-                if (! self::_validate_email($value)) {
957
-                    $validation_result = new WP_Error(
958
-                        'rest_invalid_param',
959
-                        esc_html__(
960
-                            'The email address is not valid or does not exist.',
961
-                            'event_espresso'
962
-                        )
963
-                    );
964
-                }
965
-            } else {
966
-                $validation_result = rest_validate_value_from_schema($value, $args, $param);
967
-            }
968
-        }
969
-        if (is_wp_error($validation_result)) {
970
-            return $validation_result;
971
-        }
972
-        return rest_sanitize_request_arg($value, $request, $param);
973
-    }
974
-
975
-
976
-
977
-    /**
978
-     * Returns whether or not this email address is valid. Copied from EE_Email_Validation_Strategy::_validate_email()
979
-     *
980
-     * @param $email
981
-     * @return bool
982
-     * @throws InvalidArgumentException
983
-     * @throws InvalidInterfaceException
984
-     * @throws InvalidDataTypeException
985
-     */
986
-    protected static function _validate_email($email){
987
-        try {
988
-            EmailAddressFactory::create($email);
989
-            return true;
990
-        } catch (EmailValidationException $e) {
991
-            return false;
992
-        }
993
-    }
994
-
995
-
996
-
997
-    /**
998
-     * Gets routes for the config
999
-     *
1000
-     * @return array @see _register_model_routes
1001
-     * @deprecated since version 4.9.1
1002
-     */
1003
-    protected function _register_config_routes()
1004
-    {
1005
-        $config_routes = array();
1006
-        foreach (self::versions_served() as $version => $hidden_endpoint) {
1007
-            $config_routes[self::ee_api_namespace . $version] = $this->_get_config_route_data_for_version(
1008
-                $version,
1009
-                $hidden_endpoint
1010
-            );
1011
-        }
1012
-        return $config_routes;
1013
-    }
1014
-
1015
-
1016
-
1017
-    /**
1018
-     * Gets routes for the config for the specified version
1019
-     *
1020
-     * @param string  $version
1021
-     * @param boolean $hidden_endpoint
1022
-     * @return array
1023
-     */
1024
-    protected function _get_config_route_data_for_version($version, $hidden_endpoint)
1025
-    {
1026
-        return array(
1027
-            'config'    => array(
1028
-                array(
1029
-                    'callback'        => array(
1030
-                        'EventEspresso\core\libraries\rest_api\controllers\config\Read',
1031
-                        'handleRequest',
1032
-                    ),
1033
-                    'methods'         => WP_REST_Server::READABLE,
1034
-                    'hidden_endpoint' => $hidden_endpoint,
1035
-                    'callback_args'   => array($version),
1036
-                ),
1037
-            ),
1038
-            'site_info' => array(
1039
-                array(
1040
-                    'callback'        => array(
1041
-                        'EventEspresso\core\libraries\rest_api\controllers\config\Read',
1042
-                        'handleRequestSiteInfo',
1043
-                    ),
1044
-                    'methods'         => WP_REST_Server::READABLE,
1045
-                    'hidden_endpoint' => $hidden_endpoint,
1046
-                    'callback_args'   => array($version),
1047
-                ),
1048
-            ),
1049
-        );
1050
-    }
1051
-
1052
-
1053
-
1054
-    /**
1055
-     * Gets the meta info routes
1056
-     *
1057
-     * @return array @see _register_model_routes
1058
-     * @deprecated since version 4.9.1
1059
-     */
1060
-    protected function _register_meta_routes()
1061
-    {
1062
-        $meta_routes = array();
1063
-        foreach (self::versions_served() as $version => $hidden_endpoint) {
1064
-            $meta_routes[self::ee_api_namespace . $version] = $this->_get_meta_route_data_for_version(
1065
-                $version,
1066
-                $hidden_endpoint
1067
-            );
1068
-        }
1069
-        return $meta_routes;
1070
-    }
1071
-
1072
-
1073
-
1074
-    /**
1075
-     * @param string  $version
1076
-     * @param boolean $hidden_endpoint
1077
-     * @return array
1078
-     */
1079
-    protected function _get_meta_route_data_for_version($version, $hidden_endpoint = false)
1080
-    {
1081
-        return array(
1082
-            'resources' => array(
1083
-                array(
1084
-                    'callback'        => array(
1085
-                        'EventEspresso\core\libraries\rest_api\controllers\model\Meta',
1086
-                        'handleRequestModelsMeta',
1087
-                    ),
1088
-                    'methods'         => WP_REST_Server::READABLE,
1089
-                    'hidden_endpoint' => $hidden_endpoint,
1090
-                    'callback_args'   => array($version),
1091
-                ),
1092
-            ),
1093
-        );
1094
-    }
1095
-
1096
-
1097
-
1098
-    /**
1099
-     * Tries to hide old 4.6 endpoints from the
1100
-     *
1101
-     * @param array $route_data
1102
-     * @return array
1103
-     * @throws \EE_Error
1104
-     */
1105
-    public static function hide_old_endpoints($route_data)
1106
-    {
1107
-        //allow API clients to override which endpoints get hidden, in case
1108
-        //they want to discover particular endpoints
1109
-        //also, we don't have access to the request so we have to just grab it from the superglobal
1110
-        $force_show_ee_namespace = ltrim(
1111
-            EEH_Array::is_set($_REQUEST, 'force_show_ee_namespace', ''),
1112
-            '/'
1113
-        );
1114
-        foreach (EED_Core_Rest_Api::get_ee_route_data() as $namespace => $relative_urls) {
1115
-            foreach ($relative_urls as $resource_name => $endpoints) {
1116
-                foreach ($endpoints as $key => $endpoint) {
1117
-                    //skip schema and other route options
1118
-                    if (! is_numeric($key)) {
1119
-                        continue;
1120
-                    }
1121
-                    //by default, hide "hidden_endpoint"s, unless the request indicates
1122
-                    //to $force_show_ee_namespace, in which case only show that one
1123
-                    //namespace's endpoints (and hide all others)
1124
-                    if (
1125
-                        ($force_show_ee_namespace !== '' && $force_show_ee_namespace !== $namespace)
1126
-                        || ($endpoint['hidden_endpoint'] && $force_show_ee_namespace === '')
1127
-                    ) {
1128
-                        $full_route = '/' . ltrim($namespace, '/');
1129
-                        $full_route .= '/' . ltrim($resource_name, '/');
1130
-                        unset($route_data[$full_route]);
1131
-                    }
1132
-                }
1133
-            }
1134
-        }
1135
-        return $route_data;
1136
-    }
1137
-
1138
-
1139
-
1140
-    /**
1141
-     * Returns an array describing which versions of core support serving requests for.
1142
-     * Keys are core versions' major and minor version, and values are the
1143
-     * LOWEST requested version they can serve. Eg, 4.7 can serve requests for 4.6-like
1144
-     * data by just removing a few models and fields from the responses. However, 4.15 might remove
1145
-     * the answers table entirely, in which case it would be very difficult for
1146
-     * it to serve 4.6-style responses.
1147
-     * Versions of core that are missing from this array are unknowns.
1148
-     * previous ver
1149
-     *
1150
-     * @return array
1151
-     */
1152
-    public static function version_compatibilities()
1153
-    {
1154
-        return apply_filters(
1155
-            'FHEE__EED_Core_REST_API__version_compatibilities',
1156
-            array(
1157
-                '4.8.29' => '4.8.29',
1158
-                '4.8.33' => '4.8.29',
1159
-                '4.8.34' => '4.8.29',
1160
-                '4.8.36' => '4.8.29',
1161
-            )
1162
-        );
1163
-    }
1164
-
1165
-
1166
-
1167
-    /**
1168
-     * Gets the latest API version served. Eg if there
1169
-     * are two versions served of the API, 4.8.29 and 4.8.32, and
1170
-     * we are on core version 4.8.34, it will return the string "4.8.32"
1171
-     *
1172
-     * @return string
1173
-     */
1174
-    public static function latest_rest_api_version()
1175
-    {
1176
-        $versions_served = \EED_Core_Rest_Api::versions_served();
1177
-        $versions_served_keys = array_keys($versions_served);
1178
-        return end($versions_served_keys);
1179
-    }
1180
-
1181
-
1182
-
1183
-    /**
1184
-     * Using EED_Core_Rest_Api::version_compatibilities(), determines what version of
1185
-     * EE the API can serve requests for. Eg, if we are on 4.15 of core, and
1186
-     * we can serve requests from 4.12 or later, this will return array( '4.12', '4.13', '4.14', '4.15' ).
1187
-     * We also indicate whether or not this version should be put in the index or not
1188
-     *
1189
-     * @return array keys are API version numbers (just major and minor numbers), and values
1190
-     * are whether or not they should be hidden
1191
-     */
1192
-    public static function versions_served()
1193
-    {
1194
-        $versions_served = array();
1195
-        $possibly_served_versions = EED_Core_Rest_Api::version_compatibilities();
1196
-        $lowest_compatible_version = end($possibly_served_versions);
1197
-        reset($possibly_served_versions);
1198
-        $versions_served_historically = array_keys($possibly_served_versions);
1199
-        $latest_version = end($versions_served_historically);
1200
-        reset($versions_served_historically);
1201
-        //for each version of core we have ever served:
1202
-        foreach ($versions_served_historically as $key_versioned_endpoint) {
1203
-            //if it's not above the current core version, and it's compatible with the current version of core
1204
-            if ($key_versioned_endpoint === $latest_version) {
1205
-                //don't hide the latest version in the index
1206
-                $versions_served[$key_versioned_endpoint] = false;
1207
-            } elseif (
1208
-                $key_versioned_endpoint >= $lowest_compatible_version
1209
-                && $key_versioned_endpoint < EED_Core_Rest_Api::core_version()
1210
-            ) {
1211
-                //include, but hide, previous versions which are still supported
1212
-                $versions_served[$key_versioned_endpoint] = true;
1213
-            } elseif (apply_filters(
1214
-                'FHEE__EED_Core_Rest_Api__versions_served__include_incompatible_versions',
1215
-                false,
1216
-                $possibly_served_versions
1217
-            )) {
1218
-                //if a version is no longer supported, don't include it in index or list of versions served
1219
-                $versions_served[$key_versioned_endpoint] = true;
1220
-            }
1221
-        }
1222
-        return $versions_served;
1223
-    }
1224
-
1225
-
1226
-
1227
-    /**
1228
-     * Gets the major and minor version of EE core's version string
1229
-     *
1230
-     * @return string
1231
-     */
1232
-    public static function core_version()
1233
-    {
1234
-        return apply_filters(
1235
-            'FHEE__EED_Core_REST_API__core_version',
1236
-            implode(
1237
-                '.',
1238
-                array_slice(
1239
-                    explode(
1240
-                        '.',
1241
-                        espresso_version()
1242
-                    ),
1243
-                0,
1244
-                3
1245
-                )
1246
-            )
1247
-        );
1248
-    }
1249
-
1250
-
1251
-
1252
-    /**
1253
-     * Gets the default limit that should be used when querying for resources
1254
-     *
1255
-     * @return int
1256
-     */
1257
-    public static function get_default_query_limit()
1258
-    {
1259
-        //we actually don't use a const because we want folks to always use
1260
-        //this method, not the const directly
1261
-        return apply_filters(
1262
-            'FHEE__EED_Core_Rest_Api__get_default_query_limit',
1263
-            50
1264
-        );
1265
-    }
1266
-
1267
-
1268
-
1269
-    /**
1270
-     *    run - initial module setup
1271
-     *
1272
-     * @access    public
1273
-     * @param  WP $WP
1274
-     * @return    void
1275
-     */
1276
-    public function run($WP)
1277
-    {
1278
-    }
31
+	const ee_api_namespace_for_regex = 'ee\/v([^/]*)\/';
32
+
33
+	const saved_routes_option_names  = 'ee_core_routes';
34
+
35
+	/**
36
+	 * string used in _links response bodies to make them globally unique.
37
+	 *
38
+	 * @see http://v2.wp-api.org/extending/linking/
39
+	 */
40
+	const ee_api_link_namespace = 'https://api.eventespresso.com/';
41
+
42
+	/**
43
+	 * @var CalculatedModelFields
44
+	 */
45
+	protected static $_field_calculator;
46
+
47
+
48
+
49
+	/**
50
+	 * @return EED_Core_Rest_Api|EED_Module
51
+	 */
52
+	public static function instance()
53
+	{
54
+		self::$_field_calculator = new CalculatedModelFields();
55
+		return parent::get_instance(__CLASS__);
56
+	}
57
+
58
+
59
+
60
+	/**
61
+	 *    set_hooks - for hooking into EE Core, other modules, etc
62
+	 *
63
+	 * @access    public
64
+	 * @return    void
65
+	 */
66
+	public static function set_hooks()
67
+	{
68
+		self::set_hooks_both();
69
+	}
70
+
71
+
72
+
73
+	/**
74
+	 *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
75
+	 *
76
+	 * @access    public
77
+	 * @return    void
78
+	 */
79
+	public static function set_hooks_admin()
80
+	{
81
+		self::set_hooks_both();
82
+	}
83
+
84
+
85
+
86
+	public static function set_hooks_both()
87
+	{
88
+		add_action('rest_api_init', array('EED_Core_Rest_Api', 'register_routes'), 10);
89
+		add_action('rest_api_init', array('EED_Core_Rest_Api', 'set_hooks_rest_api'), 5);
90
+		add_filter('rest_route_data', array('EED_Core_Rest_Api', 'hide_old_endpoints'), 10, 2);
91
+		add_filter('rest_index',
92
+			array('EventEspresso\core\libraries\rest_api\controllers\model\Meta', 'filterEeMetadataIntoIndex'));
93
+		EED_Core_Rest_Api::invalidate_cached_route_data_on_version_change();
94
+	}
95
+
96
+
97
+
98
+	/**
99
+	 * sets up hooks which only need to be included as part of REST API requests;
100
+	 * other requests like to the frontend or admin etc don't need them
101
+	 *
102
+	 * @throws \EE_Error
103
+	 */
104
+	public static function set_hooks_rest_api()
105
+	{
106
+		//set hooks which account for changes made to the API
107
+		EED_Core_Rest_Api::_set_hooks_for_changes();
108
+	}
109
+
110
+
111
+
112
+	/**
113
+	 * public wrapper of _set_hooks_for_changes.
114
+	 * Loads all the hooks which make requests to old versions of the API
115
+	 * appear the same as they always did
116
+	 *
117
+	 * @throws EE_Error
118
+	 */
119
+	public static function set_hooks_for_changes()
120
+	{
121
+		self::_set_hooks_for_changes();
122
+	}
123
+
124
+
125
+
126
+	/**
127
+	 * Loads all the hooks which make requests to old versions of the API
128
+	 * appear the same as they always did
129
+	 *
130
+	 * @throws EE_Error
131
+	 */
132
+	protected static function _set_hooks_for_changes()
133
+	{
134
+		$folder_contents = EEH_File::get_contents_of_folders(array(EE_LIBRARIES . 'rest_api' . DS . 'changes'), false);
135
+		foreach ($folder_contents as $classname_in_namespace => $filepath) {
136
+			//ignore the base parent class
137
+			//and legacy named classes
138
+			if ($classname_in_namespace === 'ChangesInBase'
139
+				|| strpos($classname_in_namespace, 'Changes_In_') === 0
140
+			) {
141
+				continue;
142
+			}
143
+			$full_classname = 'EventEspresso\core\libraries\rest_api\changes\\' . $classname_in_namespace;
144
+			if (class_exists($full_classname)) {
145
+				$instance_of_class = new $full_classname;
146
+				if ($instance_of_class instanceof ChangesInBase) {
147
+					$instance_of_class->setHooks();
148
+				}
149
+			}
150
+		}
151
+	}
152
+
153
+
154
+
155
+	/**
156
+	 * Filters the WP routes to add our EE-related ones. This takes a bit of time
157
+	 * so we actually prefer to only do it when an EE plugin is activated or upgraded
158
+	 *
159
+	 * @throws \EE_Error
160
+	 */
161
+	public static function register_routes()
162
+	{
163
+		foreach (EED_Core_Rest_Api::get_ee_route_data() as $namespace => $relative_routes) {
164
+			foreach ($relative_routes as $relative_route => $data_for_multiple_endpoints) {
165
+				/**
166
+				 * @var array $data_for_multiple_endpoints numerically indexed array
167
+				 *                                         but can also contain route options like {
168
+				 * @type array    $schema                      {
169
+				 * @type callable $schema_callback
170
+				 * @type array    $callback_args               arguments that will be passed to the callback, after the
171
+				 * WP_REST_Request of course
172
+				 * }
173
+				 * }
174
+				 */
175
+				//when registering routes, register all the endpoints' data at the same time
176
+				$multiple_endpoint_args = array();
177
+				foreach ($data_for_multiple_endpoints as $endpoint_key => $data_for_single_endpoint) {
178
+					/**
179
+					 * @var array     $data_for_single_endpoint {
180
+					 * @type callable $callback
181
+					 * @type string methods
182
+					 * @type array args
183
+					 * @type array _links
184
+					 * @type array    $callback_args            arguments that will be passed to the callback, after the
185
+					 * WP_REST_Request of course
186
+					 * }
187
+					 */
188
+					//skip route options
189
+					if (! is_numeric($endpoint_key)) {
190
+						continue;
191
+					}
192
+					if (! isset($data_for_single_endpoint['callback'], $data_for_single_endpoint['methods'])) {
193
+						throw new EE_Error(
194
+							esc_html__(
195
+								// @codingStandardsIgnoreStart
196
+								'Endpoint configuration data needs to have entries "callback" (callable) and "methods" (comma-separated list of accepts HTTP methods).',
197
+								// @codingStandardsIgnoreEnd
198
+								'event_espresso')
199
+						);
200
+					}
201
+					$callback = $data_for_single_endpoint['callback'];
202
+					$single_endpoint_args = array(
203
+						'methods' => $data_for_single_endpoint['methods'],
204
+						'args'    => isset($data_for_single_endpoint['args']) ? $data_for_single_endpoint['args']
205
+							: array(),
206
+					);
207
+					if (isset($data_for_single_endpoint['_links'])) {
208
+						$single_endpoint_args['_links'] = $data_for_single_endpoint['_links'];
209
+					}
210
+					if (isset($data_for_single_endpoint['callback_args'])) {
211
+						$callback_args = $data_for_single_endpoint['callback_args'];
212
+						$single_endpoint_args['callback'] = function (\WP_REST_Request $request) use (
213
+							$callback,
214
+							$callback_args
215
+						) {
216
+							array_unshift($callback_args, $request);
217
+							return call_user_func_array(
218
+								$callback,
219
+								$callback_args
220
+							);
221
+						};
222
+					} else {
223
+						$single_endpoint_args['callback'] = $data_for_single_endpoint['callback'];
224
+					}
225
+					$multiple_endpoint_args[] = $single_endpoint_args;
226
+				}
227
+				if (isset($data_for_multiple_endpoints['schema'])) {
228
+					$schema_route_data = $data_for_multiple_endpoints['schema'];
229
+					$schema_callback = $schema_route_data['schema_callback'];
230
+					$callback_args = $schema_route_data['callback_args'];
231
+					$multiple_endpoint_args['schema'] = function () use ($schema_callback, $callback_args) {
232
+						return call_user_func_array(
233
+							$schema_callback,
234
+							$callback_args
235
+						);
236
+					};
237
+				}
238
+				register_rest_route(
239
+					$namespace,
240
+					$relative_route,
241
+					$multiple_endpoint_args
242
+				);
243
+			}
244
+		}
245
+	}
246
+
247
+
248
+
249
+	/**
250
+	 * Checks if there was a version change or something that merits invalidating the cached
251
+	 * route data. If so, invalidates the cached route data so that it gets refreshed
252
+	 * next time the WP API is used
253
+	 */
254
+	public static function invalidate_cached_route_data_on_version_change()
255
+	{
256
+		if (EE_System::instance()->detect_req_type() !== EE_System::req_type_normal) {
257
+			EED_Core_Rest_Api::invalidate_cached_route_data();
258
+		}
259
+		foreach (EE_Registry::instance()->addons as $addon) {
260
+			if ($addon instanceof EE_Addon && $addon->detect_req_type() !== EE_System::req_type_normal) {
261
+				EED_Core_Rest_Api::invalidate_cached_route_data();
262
+			}
263
+		}
264
+	}
265
+
266
+
267
+
268
+	/**
269
+	 * Removes the cached route data so it will get refreshed next time the WP API is used
270
+	 */
271
+	public static function invalidate_cached_route_data()
272
+	{
273
+		//delete the saved EE REST API routes
274
+		foreach (EED_Core_Rest_Api::versions_served() as $version => $hidden) {
275
+			delete_option(EED_Core_Rest_Api::saved_routes_option_names . $version);
276
+		}
277
+	}
278
+
279
+
280
+
281
+	/**
282
+	 * Gets the EE route data
283
+	 *
284
+	 * @return array top-level key is the namespace, next-level key is the route and its value is array{
285
+	 * @throws \EE_Error
286
+	 * @type string|array $callback
287
+	 * @type string       $methods
288
+	 * @type boolean      $hidden_endpoint
289
+	 * }
290
+	 */
291
+	public static function get_ee_route_data()
292
+	{
293
+		$ee_routes = array();
294
+		foreach (self::versions_served() as $version => $hidden_endpoints) {
295
+			$ee_routes[self::ee_api_namespace . $version] = self::_get_ee_route_data_for_version(
296
+				$version,
297
+				$hidden_endpoints
298
+			);
299
+		}
300
+		return $ee_routes;
301
+	}
302
+
303
+
304
+
305
+	/**
306
+	 * Gets the EE route data from the wp options if it exists already,
307
+	 * otherwise re-generates it and saves it to the option
308
+	 *
309
+	 * @param string  $version
310
+	 * @param boolean $hidden_endpoints
311
+	 * @return array
312
+	 * @throws \EE_Error
313
+	 */
314
+	protected static function _get_ee_route_data_for_version($version, $hidden_endpoints = false)
315
+	{
316
+		$ee_routes = get_option(self::saved_routes_option_names . $version, null);
317
+		if (! $ee_routes || (defined('EE_REST_API_DEBUG_MODE') && EE_REST_API_DEBUG_MODE)) {
318
+			$ee_routes = self::_save_ee_route_data_for_version($version, $hidden_endpoints);
319
+		}
320
+		return $ee_routes;
321
+	}
322
+
323
+
324
+
325
+	/**
326
+	 * Saves the EE REST API route data to a wp option and returns it
327
+	 *
328
+	 * @param string  $version
329
+	 * @param boolean $hidden_endpoints
330
+	 * @return mixed|null
331
+	 * @throws \EE_Error
332
+	 */
333
+	protected static function _save_ee_route_data_for_version($version, $hidden_endpoints = false)
334
+	{
335
+		$instance = self::instance();
336
+		$routes = apply_filters(
337
+			'EED_Core_Rest_Api__save_ee_route_data_for_version__routes',
338
+			array_replace_recursive(
339
+				$instance->_get_config_route_data_for_version($version, $hidden_endpoints),
340
+				$instance->_get_meta_route_data_for_version($version, $hidden_endpoints),
341
+				$instance->_get_model_route_data_for_version($version, $hidden_endpoints),
342
+				$instance->_get_rpc_route_data_for_version($version, $hidden_endpoints)
343
+			)
344
+		);
345
+		$option_name = self::saved_routes_option_names . $version;
346
+		if (get_option($option_name)) {
347
+			update_option($option_name, $routes, true);
348
+		} else {
349
+			add_option($option_name, $routes, null, 'no');
350
+		}
351
+		return $routes;
352
+	}
353
+
354
+
355
+
356
+	/**
357
+	 * Calculates all the EE routes and saves it to a WordPress option so we don't
358
+	 * need to calculate it on every request
359
+	 *
360
+	 * @deprecated since version 4.9.1
361
+	 * @return void
362
+	 */
363
+	public static function save_ee_routes()
364
+	{
365
+		if (EE_Maintenance_Mode::instance()->models_can_query()) {
366
+			$instance = self::instance();
367
+			$routes = apply_filters(
368
+				'EED_Core_Rest_Api__save_ee_routes__routes',
369
+				array_replace_recursive(
370
+					$instance->_register_config_routes(),
371
+					$instance->_register_meta_routes(),
372
+					$instance->_register_model_routes(),
373
+					$instance->_register_rpc_routes()
374
+				)
375
+			);
376
+			update_option(self::saved_routes_option_names, $routes, true);
377
+		}
378
+	}
379
+
380
+
381
+
382
+	/**
383
+	 * Gets all the route information relating to EE models
384
+	 *
385
+	 * @return array @see get_ee_route_data
386
+	 * @deprecated since version 4.9.1
387
+	 */
388
+	protected function _register_model_routes()
389
+	{
390
+		$model_routes = array();
391
+		foreach (self::versions_served() as $version => $hidden_endpoint) {
392
+			$model_routes[EED_Core_Rest_Api::ee_api_namespace
393
+						  . $version] = $this->_get_config_route_data_for_version($version, $hidden_endpoint);
394
+		}
395
+		return $model_routes;
396
+	}
397
+
398
+
399
+
400
+	/**
401
+	 * Decides whether or not to add write endpoints for this model.
402
+	 *
403
+	 * Currently, this defaults to exclude all global tables and models
404
+	 * which would allow inserting WP core data (we don't want to duplicate
405
+	 * what WP API does, as it's unnecessary, extra work, and potentially extra bugs)
406
+	 * @param EEM_Base $model
407
+	 * @return bool
408
+	 */
409
+	public static function should_have_write_endpoints(EEM_Base $model)
410
+	{
411
+		if ($model->is_wp_core_model()){
412
+			return false;
413
+		}
414
+		foreach($model->get_tables() as $table){
415
+			if( $table->is_global()){
416
+				return false;
417
+			}
418
+		}
419
+		return true;
420
+	}
421
+
422
+
423
+
424
+	/**
425
+	 * Gets the names of all models which should have plural routes (eg `ee/v4.8.36/events`)
426
+	 * in this versioned namespace of EE4
427
+	 * @param $version
428
+	 * @return array keys are model names (eg 'Event') and values ar either classnames (eg 'EEM_Event')
429
+	 */
430
+	public static function model_names_with_plural_routes($version){
431
+		$model_version_info = new ModelVersionInfo($version);
432
+		$models_to_register = $model_version_info->modelsForRequestedVersion();
433
+		//let's not bother having endpoints for extra metas
434
+		unset(
435
+			$models_to_register['Extra_Meta'],
436
+			$models_to_register['Extra_Join'],
437
+			$models_to_register['Post_Meta']
438
+		);
439
+		return apply_filters(
440
+			'FHEE__EED_Core_REST_API___register_model_routes',
441
+			$models_to_register
442
+		);
443
+	}
444
+
445
+
446
+
447
+	/**
448
+	 * Gets the route data for EE models in the specified version
449
+	 *
450
+	 * @param string  $version
451
+	 * @param boolean $hidden_endpoint
452
+	 * @return array
453
+	 * @throws EE_Error
454
+	 */
455
+	protected function _get_model_route_data_for_version($version, $hidden_endpoint = false)
456
+	{
457
+		$model_routes = array();
458
+		$model_version_info = new ModelVersionInfo($version);
459
+		foreach (EED_Core_Rest_Api::model_names_with_plural_routes($version) as $model_name => $model_classname) {
460
+			$model = \EE_Registry::instance()->load_model($model_name);
461
+			//if this isn't a valid model then let's skip iterate to the next item in the loop.
462
+			if (! $model instanceof EEM_Base) {
463
+				continue;
464
+			}
465
+			//yes we could just register one route for ALL models, but then they wouldn't show up in the index
466
+			$plural_model_route = EED_Core_Rest_Api::get_collection_route($model);
467
+			$singular_model_route = EED_Core_Rest_Api::get_entity_route($model, '(?P<id>[^\/]+)');
468
+			$model_routes[$plural_model_route] = array(
469
+				array(
470
+					'callback'        => array(
471
+						'EventEspresso\core\libraries\rest_api\controllers\model\Read',
472
+						'handleRequestGetAll',
473
+					),
474
+					'callback_args'   => array($version, $model_name),
475
+					'methods'         => WP_REST_Server::READABLE,
476
+					'hidden_endpoint' => $hidden_endpoint,
477
+					'args'            => $this->_get_read_query_params($model, $version),
478
+					'_links'          => array(
479
+						'self' => rest_url(EED_Core_Rest_Api::ee_api_namespace . $version . $singular_model_route),
480
+					),
481
+				),
482
+				'schema' => array(
483
+					'schema_callback' => array(
484
+						'EventEspresso\core\libraries\rest_api\controllers\model\Read',
485
+						'handleSchemaRequest',
486
+					),
487
+					'callback_args'   => array($version, $model_name),
488
+				),
489
+			);
490
+			$model_routes[$singular_model_route] = array(
491
+				array(
492
+					'callback'        => array(
493
+						'EventEspresso\core\libraries\rest_api\controllers\model\Read',
494
+						'handleRequestGetOne',
495
+					),
496
+					'callback_args'   => array($version, $model_name),
497
+					'methods'         => WP_REST_Server::READABLE,
498
+					'hidden_endpoint' => $hidden_endpoint,
499
+					'args'            => $this->_get_response_selection_query_params($model, $version),
500
+				),
501
+			);
502
+			if( apply_filters(
503
+				'FHEE__EED_Core_Rest_Api___get_model_route_data_for_version__add_write_endpoints',
504
+				EED_Core_Rest_Api::should_have_write_endpoints($model),
505
+				$model
506
+			)){
507
+				$model_routes[$plural_model_route][] = array(
508
+					'callback'        => array(
509
+						'EventEspresso\core\libraries\rest_api\controllers\model\Write',
510
+						'handleRequestInsert',
511
+					),
512
+					'callback_args'   => array($version, $model_name),
513
+					'methods'         => WP_REST_Server::CREATABLE,
514
+					'hidden_endpoint' => $hidden_endpoint,
515
+					'args'            => $this->_get_write_params($model_name, $model_version_info, true),
516
+				);
517
+				$model_routes[$singular_model_route] = array_merge(
518
+					$model_routes[$singular_model_route],
519
+					array(
520
+						array(
521
+							'callback'        => array(
522
+								'EventEspresso\core\libraries\rest_api\controllers\model\Write',
523
+								'handleRequestUpdate',
524
+							),
525
+							'callback_args'   => array($version, $model_name),
526
+							'methods'         => WP_REST_Server::EDITABLE,
527
+							'hidden_endpoint' => $hidden_endpoint,
528
+							'args'            => $this->_get_write_params($model_name, $model_version_info),
529
+						),
530
+						array(
531
+							'callback'        => array(
532
+								'EventEspresso\core\libraries\rest_api\controllers\model\Write',
533
+								'handleRequestDelete',
534
+							),
535
+							'callback_args'   => array($version, $model_name),
536
+							'methods'         => WP_REST_Server::DELETABLE,
537
+							'hidden_endpoint' => $hidden_endpoint,
538
+							'args'            => $this->_get_delete_query_params($model, $version),
539
+						)
540
+					)
541
+				);
542
+			}
543
+			foreach ($model->relation_settings() as $relation_name => $relation_obj) {
544
+
545
+				$related_route = EED_Core_Rest_Api::get_relation_route_via(
546
+					$model,
547
+					'(?P<id>[^\/]+)',
548
+					$relation_obj
549
+				);
550
+				$endpoints = array(
551
+					array(
552
+						'callback'        => array(
553
+							'EventEspresso\core\libraries\rest_api\controllers\model\Read',
554
+							'handleRequestGetRelated',
555
+						),
556
+						'callback_args'   => array($version, $model_name, $relation_name),
557
+						'methods'         => WP_REST_Server::READABLE,
558
+						'hidden_endpoint' => $hidden_endpoint,
559
+						'args'            => $this->_get_read_query_params($relation_obj->get_other_model(), $version),
560
+					),
561
+				);
562
+				$model_routes[$related_route] = $endpoints;
563
+			}
564
+		}
565
+		return $model_routes;
566
+	}
567
+
568
+
569
+
570
+	/**
571
+	 * Gets the relative URI to a model's REST API plural route, after the EE4 versioned namespace,
572
+	 * excluding the preceding slash.
573
+	 * Eg you pass get_plural_route_to('Event') = 'events'
574
+	 *
575
+	 * @param EEM_Base $model
576
+	 * @return string
577
+	 */
578
+	public static function get_collection_route(EEM_Base $model)
579
+	{
580
+		return EEH_Inflector::pluralize_and_lower($model->get_this_model_name());
581
+	}
582
+
583
+
584
+
585
+	/**
586
+	 * Gets the relative URI to a model's REST API singular route, after the EE4 versioned namespace,
587
+	 * excluding the preceding slash.
588
+	 * Eg you pass get_plural_route_to('Event', 12) = 'events/12'
589
+	 *
590
+	 * @param EEM_Base $model eg Event or Venue
591
+	 * @param string $id
592
+	 * @return string
593
+	 */
594
+	public static function get_entity_route($model, $id)
595
+	{
596
+		return EED_Core_Rest_Api::get_collection_route($model). '/' . $id;
597
+	}
598
+
599
+
600
+	/**
601
+	 * Gets the relative URI to a model's REST API singular route, after the EE4 versioned namespace,
602
+	 * excluding the preceding slash.
603
+	 * Eg you pass get_plural_route_to('Event', 12) = 'events/12'
604
+	 *
605
+	 * @param EEM_Base                 $model eg Event or Venue
606
+	 * @param string                 $id
607
+	 * @param EE_Model_Relation_Base $relation_obj
608
+	 * @return string
609
+	 */
610
+	public static function get_relation_route_via(EEM_Base $model, $id, EE_Model_Relation_Base $relation_obj)
611
+	{
612
+		$related_model_name_endpoint_part = ModelRead::getRelatedEntityName(
613
+			$relation_obj->get_other_model()->get_this_model_name(),
614
+			$relation_obj
615
+		);
616
+		return EED_Core_Rest_Api::get_entity_route($model, $id) . '/' . $related_model_name_endpoint_part;
617
+	}
618
+
619
+
620
+
621
+	/**
622
+	 * Adds onto the $relative_route the EE4 REST API versioned namespace.
623
+	 * Eg if given '4.8.36' and 'events', will return 'ee/v4.8.36/events'
624
+	 * @param string $relative_route
625
+	 * @param string $version
626
+	 * @return string
627
+	 */
628
+	public static function get_versioned_route_to($relative_route, $version = '4.8.36'){
629
+		return '/' . EED_Core_Rest_Api::ee_api_namespace . $version . '/' . $relative_route;
630
+	}
631
+
632
+
633
+
634
+	/**
635
+	 * Adds all the RPC-style routes (remote procedure call-like routes, ie
636
+	 * routes that don't conform to the traditional REST CRUD-style).
637
+	 *
638
+	 * @deprecated since 4.9.1
639
+	 */
640
+	protected function _register_rpc_routes()
641
+	{
642
+		$routes = array();
643
+		foreach (self::versions_served() as $version => $hidden_endpoint) {
644
+			$routes[self::ee_api_namespace . $version] = $this->_get_rpc_route_data_for_version(
645
+				$version,
646
+				$hidden_endpoint
647
+			);
648
+		}
649
+		return $routes;
650
+	}
651
+
652
+
653
+
654
+	/**
655
+	 * @param string  $version
656
+	 * @param boolean $hidden_endpoint
657
+	 * @return array
658
+	 */
659
+	protected function _get_rpc_route_data_for_version($version, $hidden_endpoint = false)
660
+	{
661
+		$this_versions_routes = array();
662
+		//checkin endpoint
663
+		$this_versions_routes['registrations/(?P<REG_ID>\d+)/toggle_checkin_for_datetime/(?P<DTT_ID>\d+)'] = array(
664
+			array(
665
+				'callback'        => array(
666
+					'EventEspresso\core\libraries\rest_api\controllers\rpc\Checkin',
667
+					'handleRequestToggleCheckin',
668
+				),
669
+				'methods'         => WP_REST_Server::CREATABLE,
670
+				'hidden_endpoint' => $hidden_endpoint,
671
+				'args'            => array(
672
+					'force' => array(
673
+						'required'    => false,
674
+						'default'     => false,
675
+						'description' => __(
676
+							// @codingStandardsIgnoreStart
677
+							'Whether to force toggle checkin, or to verify the registration status and allowed ticket uses',
678
+							// @codingStandardsIgnoreEnd
679
+							'event_espresso'
680
+						),
681
+					),
682
+				),
683
+				'callback_args'   => array($version),
684
+			),
685
+		);
686
+		return apply_filters(
687
+			'FHEE__EED_Core_Rest_Api___register_rpc_routes__this_versions_routes',
688
+			$this_versions_routes,
689
+			$version,
690
+			$hidden_endpoint
691
+		);
692
+	}
693
+
694
+
695
+
696
+	/**
697
+	 * Gets the query params that can be used when request one or many
698
+	 *
699
+	 * @param EEM_Base $model
700
+	 * @param string   $version
701
+	 * @return array
702
+	 */
703
+	protected function _get_response_selection_query_params(\EEM_Base $model, $version)
704
+	{
705
+		return apply_filters(
706
+			'FHEE__EED_Core_Rest_Api___get_response_selection_query_params',
707
+			array(
708
+				'include'   => array(
709
+					'required' => false,
710
+					'default'  => '*',
711
+					'type'     => 'string',
712
+				),
713
+				'calculate' => array(
714
+					'required'          => false,
715
+					'default'           => '',
716
+					'enum'              => self::$_field_calculator->retrieveCalculatedFieldsForModel($model),
717
+					'type'              => 'string',
718
+					//because we accept a CSV'd list of the enumerated strings, WP core validation and sanitization
719
+					//freaks out. We'll just validate this argument while handling the request
720
+					'validate_callback' => null,
721
+					'sanitize_callback' => null,
722
+				),
723
+			),
724
+			$model,
725
+			$version
726
+		);
727
+	}
728
+
729
+
730
+
731
+	/**
732
+	 * Gets the parameters acceptable for delete requests
733
+	 *
734
+	 * @param \EEM_Base $model
735
+	 * @param string    $version
736
+	 * @return array
737
+	 */
738
+	protected function _get_delete_query_params(\EEM_Base $model, $version)
739
+	{
740
+		$params_for_delete = array(
741
+			'allow_blocking' => array(
742
+				'required' => false,
743
+				'default'  => true,
744
+				'type'     => 'boolean',
745
+			),
746
+		);
747
+		$params_for_delete['force'] = array(
748
+			'required' => false,
749
+			'default'  => false,
750
+			'type'     => 'boolean',
751
+		);
752
+		return apply_filters(
753
+			'FHEE__EED_Core_Rest_Api___get_delete_query_params',
754
+			$params_for_delete,
755
+			$model,
756
+			$version
757
+		);
758
+	}
759
+
760
+
761
+
762
+	/**
763
+	 * Gets info about reading query params that are acceptable
764
+	 *
765
+	 * @param \EEM_Base $model eg 'Event' or 'Venue'
766
+	 * @param  string   $version
767
+	 * @return array    describing the args acceptable when querying this model
768
+	 * @throws EE_Error
769
+	 */
770
+	protected function _get_read_query_params(\EEM_Base $model, $version)
771
+	{
772
+		$default_orderby = array();
773
+		foreach ($model->get_combined_primary_key_fields() as $key_field) {
774
+			$default_orderby[$key_field->get_name()] = 'ASC';
775
+		}
776
+		return array_merge(
777
+			$this->_get_response_selection_query_params($model, $version),
778
+			array(
779
+				'where'    => array(
780
+					'required' => false,
781
+					'default'  => array(),
782
+					'type'     => 'object',
783
+					//because we accept an almost infinite list of possible where conditions, WP
784
+					// core validation and sanitization freaks out. We'll just validate this argument
785
+					// while handling the request
786
+					'validate_callback' => null,
787
+					'sanitize_callback' => null,
788
+				),
789
+				'limit'    => array(
790
+					'required' => false,
791
+					'default'  => EED_Core_Rest_Api::get_default_query_limit(),
792
+					'type'     => array(
793
+						'array',
794
+						'string',
795
+						'integer',
796
+					),
797
+					//because we accept a variety of types, WP core validation and sanitization
798
+					//freaks out. We'll just validate this argument while handling the request
799
+					'validate_callback' => null,
800
+					'sanitize_callback' => null,
801
+				),
802
+				'order_by' => array(
803
+					'required' => false,
804
+					'default'  => $default_orderby,
805
+					'type'     => array(
806
+						'object',
807
+						'string',
808
+					),//because we accept a variety of types, WP core validation and sanitization
809
+					//freaks out. We'll just validate this argument while handling the request
810
+					'validate_callback' => null,
811
+					'sanitize_callback' => null,
812
+				),
813
+				'group_by' => array(
814
+					'required' => false,
815
+					'default'  => null,
816
+					'type'     => array(
817
+						'object',
818
+						'string',
819
+					),
820
+					//because we accept  an almost infinite list of possible groupings,
821
+					// WP core validation and sanitization
822
+					//freaks out. We'll just validate this argument while handling the request
823
+					'validate_callback' => null,
824
+					'sanitize_callback' => null,
825
+				),
826
+				'having'   => array(
827
+					'required' => false,
828
+					'default'  => null,
829
+					'type'     => 'object',
830
+					//because we accept an almost infinite list of possible where conditions, WP
831
+					// core validation and sanitization freaks out. We'll just validate this argument
832
+					// while handling the request
833
+					'validate_callback' => null,
834
+					'sanitize_callback' => null,
835
+				),
836
+				'caps'     => array(
837
+					'required' => false,
838
+					'default'  => EEM_Base::caps_read,
839
+					'type'     => 'string',
840
+					'enum'     => array(
841
+						EEM_Base::caps_read,
842
+						EEM_Base::caps_read_admin,
843
+						EEM_Base::caps_edit,
844
+						EEM_Base::caps_delete
845
+					)
846
+				),
847
+			)
848
+		);
849
+	}
850
+
851
+
852
+
853
+	/**
854
+	 * Gets parameter information for a model regarding writing data
855
+	 *
856
+	 * @param string           $model_name
857
+	 * @param ModelVersionInfo $model_version_info
858
+	 * @param boolean          $create                                       whether this is for request to create (in which case we need
859
+	 *                                                                       all required params) or just to update (in which case we don't need those on every request)
860
+	 * @return array
861
+	 */
862
+	protected function _get_write_params(
863
+		$model_name,
864
+		ModelVersionInfo $model_version_info,
865
+		$create = false
866
+	) {
867
+		$model = EE_Registry::instance()->load_model($model_name);
868
+		$fields = $model_version_info->fieldsOnModelInThisVersion($model);
869
+		$args_info = array();
870
+		foreach ($fields as $field_name => $field_obj) {
871
+			if ($field_obj->is_auto_increment()) {
872
+				//totally ignore auto increment IDs
873
+				continue;
874
+			}
875
+			$arg_info = $field_obj->getSchema();
876
+			$required = $create && ! $field_obj->is_nullable() && $field_obj->get_default_value() === null;
877
+			$arg_info['required'] = $required;
878
+			//remove the read-only flag. If it were read-only we wouldn't list it as an argument while writing, right?
879
+			unset($arg_info['readonly']);
880
+			$schema_properties = $field_obj->getSchemaProperties();
881
+			if (
882
+				isset($schema_properties['raw'])
883
+				&& $field_obj->getSchemaType() === 'object'
884
+			) {
885
+				//if there's a "raw" form of this argument, use those properties instead
886
+				$arg_info = array_replace(
887
+					$arg_info,
888
+					$schema_properties['raw']
889
+				);
890
+			}
891
+			$arg_info['default'] = ModelDataTranslator::prepareFieldValueForJson(
892
+				$field_obj,
893
+				$field_obj->get_default_value(),
894
+				$model_version_info->requestedVersion()
895
+			);
896
+			//we do our own validation and sanitization within the controller
897
+			$arg_info['sanitize_callback'] =
898
+				array(
899
+					'EED_Core_Rest_Api',
900
+					'default_sanitize_callback',
901
+				);
902
+			$args_info[$field_name] = $arg_info;
903
+			if ($field_obj instanceof EE_Datetime_Field) {
904
+				$gmt_arg_info = $arg_info;
905
+				$gmt_arg_info['description'] = sprintf(
906
+					esc_html__(
907
+						'%1$s - the value for this field in UTC. Ignored if %2$s is provided.',
908
+						'event_espresso'
909
+					),
910
+					$field_obj->get_nicename(),
911
+					$field_name
912
+				);
913
+				$args_info[$field_name . '_gmt'] = $gmt_arg_info;
914
+			}
915
+		}
916
+		return $args_info;
917
+	}
918
+
919
+
920
+
921
+	/**
922
+	 * Replacement for WP API's 'rest_parse_request_arg'.
923
+	 * If the value is blank but not required, don't bother validating it.
924
+	 * Also, it uses our email validation instead of WP API's default.
925
+	 *
926
+	 * @param                 $value
927
+	 * @param WP_REST_Request $request
928
+	 * @param                 $param
929
+	 * @return bool|true|WP_Error
930
+	 * @throws InvalidArgumentException
931
+	 * @throws InvalidInterfaceException
932
+	 * @throws InvalidDataTypeException
933
+	 */
934
+	public static function default_sanitize_callback( $value, WP_REST_Request $request, $param)
935
+	{
936
+		$attributes = $request->get_attributes();
937
+		if (! isset($attributes['args'][$param])
938
+			|| ! is_array($attributes['args'][$param])) {
939
+			$validation_result = true;
940
+		} else {
941
+			$args = $attributes['args'][$param];
942
+			if ((
943
+					$value === ''
944
+					|| $value === null
945
+				)
946
+				&& (! isset($args['required'])
947
+					|| $args['required'] === false
948
+				)
949
+			) {
950
+				//not required and not provided? that's cool
951
+				$validation_result = true;
952
+			} elseif (isset($args['format'])
953
+				&& $args['format'] === 'email'
954
+			) {
955
+				$validation_result = true;
956
+				if (! self::_validate_email($value)) {
957
+					$validation_result = new WP_Error(
958
+						'rest_invalid_param',
959
+						esc_html__(
960
+							'The email address is not valid or does not exist.',
961
+							'event_espresso'
962
+						)
963
+					);
964
+				}
965
+			} else {
966
+				$validation_result = rest_validate_value_from_schema($value, $args, $param);
967
+			}
968
+		}
969
+		if (is_wp_error($validation_result)) {
970
+			return $validation_result;
971
+		}
972
+		return rest_sanitize_request_arg($value, $request, $param);
973
+	}
974
+
975
+
976
+
977
+	/**
978
+	 * Returns whether or not this email address is valid. Copied from EE_Email_Validation_Strategy::_validate_email()
979
+	 *
980
+	 * @param $email
981
+	 * @return bool
982
+	 * @throws InvalidArgumentException
983
+	 * @throws InvalidInterfaceException
984
+	 * @throws InvalidDataTypeException
985
+	 */
986
+	protected static function _validate_email($email){
987
+		try {
988
+			EmailAddressFactory::create($email);
989
+			return true;
990
+		} catch (EmailValidationException $e) {
991
+			return false;
992
+		}
993
+	}
994
+
995
+
996
+
997
+	/**
998
+	 * Gets routes for the config
999
+	 *
1000
+	 * @return array @see _register_model_routes
1001
+	 * @deprecated since version 4.9.1
1002
+	 */
1003
+	protected function _register_config_routes()
1004
+	{
1005
+		$config_routes = array();
1006
+		foreach (self::versions_served() as $version => $hidden_endpoint) {
1007
+			$config_routes[self::ee_api_namespace . $version] = $this->_get_config_route_data_for_version(
1008
+				$version,
1009
+				$hidden_endpoint
1010
+			);
1011
+		}
1012
+		return $config_routes;
1013
+	}
1014
+
1015
+
1016
+
1017
+	/**
1018
+	 * Gets routes for the config for the specified version
1019
+	 *
1020
+	 * @param string  $version
1021
+	 * @param boolean $hidden_endpoint
1022
+	 * @return array
1023
+	 */
1024
+	protected function _get_config_route_data_for_version($version, $hidden_endpoint)
1025
+	{
1026
+		return array(
1027
+			'config'    => array(
1028
+				array(
1029
+					'callback'        => array(
1030
+						'EventEspresso\core\libraries\rest_api\controllers\config\Read',
1031
+						'handleRequest',
1032
+					),
1033
+					'methods'         => WP_REST_Server::READABLE,
1034
+					'hidden_endpoint' => $hidden_endpoint,
1035
+					'callback_args'   => array($version),
1036
+				),
1037
+			),
1038
+			'site_info' => array(
1039
+				array(
1040
+					'callback'        => array(
1041
+						'EventEspresso\core\libraries\rest_api\controllers\config\Read',
1042
+						'handleRequestSiteInfo',
1043
+					),
1044
+					'methods'         => WP_REST_Server::READABLE,
1045
+					'hidden_endpoint' => $hidden_endpoint,
1046
+					'callback_args'   => array($version),
1047
+				),
1048
+			),
1049
+		);
1050
+	}
1051
+
1052
+
1053
+
1054
+	/**
1055
+	 * Gets the meta info routes
1056
+	 *
1057
+	 * @return array @see _register_model_routes
1058
+	 * @deprecated since version 4.9.1
1059
+	 */
1060
+	protected function _register_meta_routes()
1061
+	{
1062
+		$meta_routes = array();
1063
+		foreach (self::versions_served() as $version => $hidden_endpoint) {
1064
+			$meta_routes[self::ee_api_namespace . $version] = $this->_get_meta_route_data_for_version(
1065
+				$version,
1066
+				$hidden_endpoint
1067
+			);
1068
+		}
1069
+		return $meta_routes;
1070
+	}
1071
+
1072
+
1073
+
1074
+	/**
1075
+	 * @param string  $version
1076
+	 * @param boolean $hidden_endpoint
1077
+	 * @return array
1078
+	 */
1079
+	protected function _get_meta_route_data_for_version($version, $hidden_endpoint = false)
1080
+	{
1081
+		return array(
1082
+			'resources' => array(
1083
+				array(
1084
+					'callback'        => array(
1085
+						'EventEspresso\core\libraries\rest_api\controllers\model\Meta',
1086
+						'handleRequestModelsMeta',
1087
+					),
1088
+					'methods'         => WP_REST_Server::READABLE,
1089
+					'hidden_endpoint' => $hidden_endpoint,
1090
+					'callback_args'   => array($version),
1091
+				),
1092
+			),
1093
+		);
1094
+	}
1095
+
1096
+
1097
+
1098
+	/**
1099
+	 * Tries to hide old 4.6 endpoints from the
1100
+	 *
1101
+	 * @param array $route_data
1102
+	 * @return array
1103
+	 * @throws \EE_Error
1104
+	 */
1105
+	public static function hide_old_endpoints($route_data)
1106
+	{
1107
+		//allow API clients to override which endpoints get hidden, in case
1108
+		//they want to discover particular endpoints
1109
+		//also, we don't have access to the request so we have to just grab it from the superglobal
1110
+		$force_show_ee_namespace = ltrim(
1111
+			EEH_Array::is_set($_REQUEST, 'force_show_ee_namespace', ''),
1112
+			'/'
1113
+		);
1114
+		foreach (EED_Core_Rest_Api::get_ee_route_data() as $namespace => $relative_urls) {
1115
+			foreach ($relative_urls as $resource_name => $endpoints) {
1116
+				foreach ($endpoints as $key => $endpoint) {
1117
+					//skip schema and other route options
1118
+					if (! is_numeric($key)) {
1119
+						continue;
1120
+					}
1121
+					//by default, hide "hidden_endpoint"s, unless the request indicates
1122
+					//to $force_show_ee_namespace, in which case only show that one
1123
+					//namespace's endpoints (and hide all others)
1124
+					if (
1125
+						($force_show_ee_namespace !== '' && $force_show_ee_namespace !== $namespace)
1126
+						|| ($endpoint['hidden_endpoint'] && $force_show_ee_namespace === '')
1127
+					) {
1128
+						$full_route = '/' . ltrim($namespace, '/');
1129
+						$full_route .= '/' . ltrim($resource_name, '/');
1130
+						unset($route_data[$full_route]);
1131
+					}
1132
+				}
1133
+			}
1134
+		}
1135
+		return $route_data;
1136
+	}
1137
+
1138
+
1139
+
1140
+	/**
1141
+	 * Returns an array describing which versions of core support serving requests for.
1142
+	 * Keys are core versions' major and minor version, and values are the
1143
+	 * LOWEST requested version they can serve. Eg, 4.7 can serve requests for 4.6-like
1144
+	 * data by just removing a few models and fields from the responses. However, 4.15 might remove
1145
+	 * the answers table entirely, in which case it would be very difficult for
1146
+	 * it to serve 4.6-style responses.
1147
+	 * Versions of core that are missing from this array are unknowns.
1148
+	 * previous ver
1149
+	 *
1150
+	 * @return array
1151
+	 */
1152
+	public static function version_compatibilities()
1153
+	{
1154
+		return apply_filters(
1155
+			'FHEE__EED_Core_REST_API__version_compatibilities',
1156
+			array(
1157
+				'4.8.29' => '4.8.29',
1158
+				'4.8.33' => '4.8.29',
1159
+				'4.8.34' => '4.8.29',
1160
+				'4.8.36' => '4.8.29',
1161
+			)
1162
+		);
1163
+	}
1164
+
1165
+
1166
+
1167
+	/**
1168
+	 * Gets the latest API version served. Eg if there
1169
+	 * are two versions served of the API, 4.8.29 and 4.8.32, and
1170
+	 * we are on core version 4.8.34, it will return the string "4.8.32"
1171
+	 *
1172
+	 * @return string
1173
+	 */
1174
+	public static function latest_rest_api_version()
1175
+	{
1176
+		$versions_served = \EED_Core_Rest_Api::versions_served();
1177
+		$versions_served_keys = array_keys($versions_served);
1178
+		return end($versions_served_keys);
1179
+	}
1180
+
1181
+
1182
+
1183
+	/**
1184
+	 * Using EED_Core_Rest_Api::version_compatibilities(), determines what version of
1185
+	 * EE the API can serve requests for. Eg, if we are on 4.15 of core, and
1186
+	 * we can serve requests from 4.12 or later, this will return array( '4.12', '4.13', '4.14', '4.15' ).
1187
+	 * We also indicate whether or not this version should be put in the index or not
1188
+	 *
1189
+	 * @return array keys are API version numbers (just major and minor numbers), and values
1190
+	 * are whether or not they should be hidden
1191
+	 */
1192
+	public static function versions_served()
1193
+	{
1194
+		$versions_served = array();
1195
+		$possibly_served_versions = EED_Core_Rest_Api::version_compatibilities();
1196
+		$lowest_compatible_version = end($possibly_served_versions);
1197
+		reset($possibly_served_versions);
1198
+		$versions_served_historically = array_keys($possibly_served_versions);
1199
+		$latest_version = end($versions_served_historically);
1200
+		reset($versions_served_historically);
1201
+		//for each version of core we have ever served:
1202
+		foreach ($versions_served_historically as $key_versioned_endpoint) {
1203
+			//if it's not above the current core version, and it's compatible with the current version of core
1204
+			if ($key_versioned_endpoint === $latest_version) {
1205
+				//don't hide the latest version in the index
1206
+				$versions_served[$key_versioned_endpoint] = false;
1207
+			} elseif (
1208
+				$key_versioned_endpoint >= $lowest_compatible_version
1209
+				&& $key_versioned_endpoint < EED_Core_Rest_Api::core_version()
1210
+			) {
1211
+				//include, but hide, previous versions which are still supported
1212
+				$versions_served[$key_versioned_endpoint] = true;
1213
+			} elseif (apply_filters(
1214
+				'FHEE__EED_Core_Rest_Api__versions_served__include_incompatible_versions',
1215
+				false,
1216
+				$possibly_served_versions
1217
+			)) {
1218
+				//if a version is no longer supported, don't include it in index or list of versions served
1219
+				$versions_served[$key_versioned_endpoint] = true;
1220
+			}
1221
+		}
1222
+		return $versions_served;
1223
+	}
1224
+
1225
+
1226
+
1227
+	/**
1228
+	 * Gets the major and minor version of EE core's version string
1229
+	 *
1230
+	 * @return string
1231
+	 */
1232
+	public static function core_version()
1233
+	{
1234
+		return apply_filters(
1235
+			'FHEE__EED_Core_REST_API__core_version',
1236
+			implode(
1237
+				'.',
1238
+				array_slice(
1239
+					explode(
1240
+						'.',
1241
+						espresso_version()
1242
+					),
1243
+				0,
1244
+				3
1245
+				)
1246
+			)
1247
+		);
1248
+	}
1249
+
1250
+
1251
+
1252
+	/**
1253
+	 * Gets the default limit that should be used when querying for resources
1254
+	 *
1255
+	 * @return int
1256
+	 */
1257
+	public static function get_default_query_limit()
1258
+	{
1259
+		//we actually don't use a const because we want folks to always use
1260
+		//this method, not the const directly
1261
+		return apply_filters(
1262
+			'FHEE__EED_Core_Rest_Api__get_default_query_limit',
1263
+			50
1264
+		);
1265
+	}
1266
+
1267
+
1268
+
1269
+	/**
1270
+	 *    run - initial module setup
1271
+	 *
1272
+	 * @access    public
1273
+	 * @param  WP $WP
1274
+	 * @return    void
1275
+	 */
1276
+	public function run($WP)
1277
+	{
1278
+	}
1279 1279
 }
1280 1280
 
1281 1281
 // End of file EED_Core_Rest_Api.module.php
Please login to merge, or discard this patch.
core/services/bootstrap/BootstrapCore.php 2 patches
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -169,7 +169,7 @@  discard block
 block discarded – undo
169 169
         // load interfaces
170 170
         espresso_load_required(
171 171
             'EEH_Autoloader',
172
-            EE_CORE . 'helpers' . DS . 'EEH_Autoloader.helper.php'
172
+            EE_CORE.'helpers'.DS.'EEH_Autoloader.helper.php'
173 173
         );
174 174
         EEH_Autoloader::instance();
175 175
     }
@@ -184,13 +184,13 @@  discard block
 block discarded – undo
184 184
     protected function setAutoloadersForRequiredFiles()
185 185
     {
186 186
         // load interfaces
187
-        EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_CORE . 'interfaces', true);
187
+        EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_CORE.'interfaces', true);
188 188
         // load helpers
189 189
         EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_HELPERS);
190 190
         // load request stack
191
-        EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_CORE . 'request_stack' . DS);
191
+        EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_CORE.'request_stack'.DS);
192 192
         // load middleware
193
-        EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_CORE . 'middleware' . DS);
193
+        EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_CORE.'middleware'.DS);
194 194
     }
195 195
 
196 196
 
@@ -208,7 +208,7 @@  discard block
 block discarded – undo
208 208
          * so items at the beginning of the final middleware stack will run last.
209 209
          * First parameter is the middleware classname, second is an array of arguments
210 210
          */
211
-        $stack_apps            = apply_filters(
211
+        $stack_apps = apply_filters(
212 212
             'FHEE__EventEspresso_core_services_bootstrap_BootstrapCore__buildRequestStack__stack_apps',
213 213
             array(
214 214
                 // first in last out
@@ -220,7 +220,7 @@  discard block
 block discarded – undo
220 220
             )
221 221
         );
222 222
         // legacy filter for backwards compatibility
223
-        $stack_apps            = apply_filters(
223
+        $stack_apps = apply_filters(
224 224
             'FHEE__EE_Bootstrap__build_request_stack__stack_apps',
225 225
             $stack_apps
226 226
         );
Please login to merge, or discard this patch.
Indentation   +228 added lines, -228 removed lines patch added patch discarded remove patch
@@ -52,234 +52,234 @@
 block discarded – undo
52 52
 class BootstrapCore
53 53
 {
54 54
 
55
-    /**
56
-     * @type LoaderInterface $loader
57
-     */
58
-    private $loader;
59
-
60
-    /**
61
-     * @var RequestInterface $request
62
-     */
63
-    protected $request;
64
-
65
-    /**
66
-     * @var ResponseInterface $response
67
-     */
68
-    protected $response;
69
-
70
-    /**
71
-     * @var RequestStackBuilder $request_stack_builder
72
-     */
73
-    protected $request_stack_builder;
74
-
75
-    /**
76
-     * @var RequestStack $request_stack
77
-     */
78
-    protected $request_stack;
79
-
80
-
81
-    /**
82
-     * BootstrapCore constructor.
83
-     */
84
-    public function __construct()
85
-    {
86
-        // construct request stack and run middleware apps as soon as all WP plugins are loaded
87
-        add_action('plugins_loaded', array($this, 'initialize'), 0);
88
-    }
89
-
90
-
91
-    /**
92
-     * @throws InvalidRequestStackMiddlewareException
93
-     * @throws InvalidClassException
94
-     * @throws DomainException
95
-     * @throws EE_Error
96
-     * @throws InvalidArgumentException
97
-     * @throws InvalidDataTypeException
98
-     * @throws InvalidInterfaceException
99
-     * @throws ReflectionException
100
-     */
101
-    public function initialize()
102
-    {
103
-        $this->bootstrapDependencyInjectionContainer();
104
-        $this->bootstrapDomain();
105
-        $bootstrap_request = $this->bootstrapRequestResponseObjects();
106
-        add_action(
107
-            'EE_Load_Espresso_Core__handle_request__initialize_core_loading',
108
-            array($bootstrap_request, 'setupLegacyRequest')
109
-        );
110
-        $this->runRequestStack();
111
-    }
112
-
113
-
114
-    /**
115
-     * @throws ReflectionException
116
-     * @throws EE_Error
117
-     * @throws InvalidArgumentException
118
-     * @throws InvalidDataTypeException
119
-     * @throws InvalidInterfaceException
120
-     */
121
-    private function bootstrapDependencyInjectionContainer()
122
-    {
123
-        $bootstrap_di = new BootstrapDependencyInjectionContainer();
124
-        $bootstrap_di->buildLegacyDependencyInjectionContainer();
125
-        $bootstrap_di->buildLoader();
126
-        $registry = $bootstrap_di->getRegistry();
127
-        $dependency_map = $bootstrap_di->getDependencyMap();
128
-        $dependency_map->initialize();
129
-        $registry->initialize();
130
-        $this->loader = $bootstrap_di->getLoader();
131
-    }
132
-
133
-
134
-    /**
135
-     * configures the Domain object for core
136
-     *
137
-     * @return void
138
-     * @throws DomainException
139
-     * @throws InvalidArgumentException
140
-     * @throws InvalidDataTypeException
141
-     * @throws InvalidClassException
142
-     * @throws InvalidFilePathException
143
-     * @throws InvalidInterfaceException
144
-     */
145
-    private function bootstrapDomain()
146
-    {
147
-        DomainFactory::getShared(
148
-            new FullyQualifiedName(
149
-                'EventEspresso\core\domain\Domain'
150
-            ),
151
-            array(
152
-                new FilePath(EVENT_ESPRESSO_MAIN_FILE),
153
-                Version::fromString(espresso_version())
154
-            )
155
-        );
156
-    }
157
-
158
-
159
-    /**
160
-     * sets up the request and response objects
161
-     *
162
-     * @return BootstrapRequestResponseObjects
163
-     * @throws InvalidArgumentException
164
-     */
165
-    private function bootstrapRequestResponseObjects()
166
-    {
167
-        /** @var BootstrapRequestResponseObjects $bootstrap_request */
168
-        $bootstrap_request = $this->loader->getShared(
169
-            'EventEspresso\core\services\bootstrap\BootstrapRequestResponseObjects',
170
-            array($this->loader)
171
-        );
172
-        $bootstrap_request->buildRequestResponse();
173
-        $bootstrap_request->shareRequestResponse();
174
-        $this->request  = $this->loader->getShared('EventEspresso\core\services\request\Request');
175
-        $this->response = $this->loader->getShared('EventEspresso\core\services\request\Response');
176
-        return $bootstrap_request;
177
-    }
178
-
179
-
180
-    /**
181
-     * run_request_stack
182
-     * construct request stack and run middleware apps
183
-     *
184
-     * @throws InvalidRequestStackMiddlewareException
185
-     * @throws InvalidInterfaceException
186
-     * @throws InvalidDataTypeException
187
-     * @throws EE_Error
188
-     */
189
-    public function runRequestStack()
190
-    {
191
-        $this->loadAutoloader();
192
-        $this->setAutoloadersForRequiredFiles();
193
-        $this->request_stack_builder = $this->buildRequestStack();
194
-        $this->request_stack         = $this->request_stack_builder->resolve(
195
-            new RequestStackCoreApp()
196
-        );
197
-        $this->request_stack->handleRequest($this->request, $this->response);
198
-        $this->request_stack->handleResponse();
199
-    }
200
-
201
-
202
-    /**
203
-     * load_autoloader
204
-     *
205
-     * @throws EE_Error
206
-     */
207
-    protected function loadAutoloader()
208
-    {
209
-        // load interfaces
210
-        espresso_load_required(
211
-            'EEH_Autoloader',
212
-            EE_CORE . 'helpers' . DS . 'EEH_Autoloader.helper.php'
213
-        );
214
-        EEH_Autoloader::instance();
215
-    }
216
-
217
-
218
-
219
-    /**
220
-     * load_required_files
221
-     *
222
-     * @throws EE_Error
223
-     */
224
-    protected function setAutoloadersForRequiredFiles()
225
-    {
226
-        // load interfaces
227
-        EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_CORE . 'interfaces', true);
228
-        // load helpers
229
-        EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_HELPERS);
230
-        // load request stack
231
-        EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_CORE . 'request_stack' . DS);
232
-        // load middleware
233
-        EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_CORE . 'middleware' . DS);
234
-    }
235
-
236
-
237
-
238
-    /**
239
-     * build_request_stack
240
-     *
241
-     * @return RequestStackBuilder
242
-     */
243
-    public function buildRequestStack()
244
-    {
245
-        $request_stack_builder = new RequestStackBuilder($this->loader);
246
-        /**
247
-         * ! IMPORTANT ! The middleware stack operates FILO : FIRST IN LAST OUT
248
-         * so items at the beginning of the final middleware stack will run last.
249
-         * First parameter is the middleware classname, second is an array of arguments
250
-         */
251
-        $stack_apps            = apply_filters(
252
-            'FHEE__EventEspresso_core_services_bootstrap_BootstrapCore__buildRequestStack__stack_apps',
253
-            array(
254
-                // first in last out
255
-                'EventEspresso\core\services\request\middleware\BotDetector' => array(),
256
-                'EventEspresso\core\services\request\middleware\DetectFileEditorRequest' => array(),
257
-                'EventEspresso\core\services\request\middleware\PreProductionVersionWarning' => array(),
258
-                'EventEspresso\core\services\request\middleware\RecommendedVersions' => array(),
259
-                // last in first out
260
-                'EventEspresso\core\services\request\middleware\DetectLogin' => array(),
261
-            )
262
-        );
263
-        // legacy filter for backwards compatibility
264
-        $stack_apps            = apply_filters(
265
-            'FHEE__EE_Bootstrap__build_request_stack__stack_apps',
266
-            $stack_apps
267
-        );
268
-        // load middleware onto stack : FILO (First In Last Out)
269
-        // items at the beginning of the $stack_apps array will run last
270
-        foreach ((array) $stack_apps as $stack_app => $stack_app_args) {
271
-            $request_stack_builder->push(array($stack_app, $stack_app_args));
272
-        }
273
-        // finally, we'll add this on its own because we need it to always be part of the stack
274
-        // and we also need it to always run first because the rest of the system relies on it
275
-        $request_stack_builder->push(
276
-            array('EventEspresso\core\services\request\middleware\SetRequestTypeContextChecker', array())
277
-        );
278
-        return apply_filters(
279
-            'FHEE__EE_Bootstrap__build_request_stack__request_stack_builder',
280
-            $request_stack_builder
281
-        );
282
-    }
55
+	/**
56
+	 * @type LoaderInterface $loader
57
+	 */
58
+	private $loader;
59
+
60
+	/**
61
+	 * @var RequestInterface $request
62
+	 */
63
+	protected $request;
64
+
65
+	/**
66
+	 * @var ResponseInterface $response
67
+	 */
68
+	protected $response;
69
+
70
+	/**
71
+	 * @var RequestStackBuilder $request_stack_builder
72
+	 */
73
+	protected $request_stack_builder;
74
+
75
+	/**
76
+	 * @var RequestStack $request_stack
77
+	 */
78
+	protected $request_stack;
79
+
80
+
81
+	/**
82
+	 * BootstrapCore constructor.
83
+	 */
84
+	public function __construct()
85
+	{
86
+		// construct request stack and run middleware apps as soon as all WP plugins are loaded
87
+		add_action('plugins_loaded', array($this, 'initialize'), 0);
88
+	}
89
+
90
+
91
+	/**
92
+	 * @throws InvalidRequestStackMiddlewareException
93
+	 * @throws InvalidClassException
94
+	 * @throws DomainException
95
+	 * @throws EE_Error
96
+	 * @throws InvalidArgumentException
97
+	 * @throws InvalidDataTypeException
98
+	 * @throws InvalidInterfaceException
99
+	 * @throws ReflectionException
100
+	 */
101
+	public function initialize()
102
+	{
103
+		$this->bootstrapDependencyInjectionContainer();
104
+		$this->bootstrapDomain();
105
+		$bootstrap_request = $this->bootstrapRequestResponseObjects();
106
+		add_action(
107
+			'EE_Load_Espresso_Core__handle_request__initialize_core_loading',
108
+			array($bootstrap_request, 'setupLegacyRequest')
109
+		);
110
+		$this->runRequestStack();
111
+	}
112
+
113
+
114
+	/**
115
+	 * @throws ReflectionException
116
+	 * @throws EE_Error
117
+	 * @throws InvalidArgumentException
118
+	 * @throws InvalidDataTypeException
119
+	 * @throws InvalidInterfaceException
120
+	 */
121
+	private function bootstrapDependencyInjectionContainer()
122
+	{
123
+		$bootstrap_di = new BootstrapDependencyInjectionContainer();
124
+		$bootstrap_di->buildLegacyDependencyInjectionContainer();
125
+		$bootstrap_di->buildLoader();
126
+		$registry = $bootstrap_di->getRegistry();
127
+		$dependency_map = $bootstrap_di->getDependencyMap();
128
+		$dependency_map->initialize();
129
+		$registry->initialize();
130
+		$this->loader = $bootstrap_di->getLoader();
131
+	}
132
+
133
+
134
+	/**
135
+	 * configures the Domain object for core
136
+	 *
137
+	 * @return void
138
+	 * @throws DomainException
139
+	 * @throws InvalidArgumentException
140
+	 * @throws InvalidDataTypeException
141
+	 * @throws InvalidClassException
142
+	 * @throws InvalidFilePathException
143
+	 * @throws InvalidInterfaceException
144
+	 */
145
+	private function bootstrapDomain()
146
+	{
147
+		DomainFactory::getShared(
148
+			new FullyQualifiedName(
149
+				'EventEspresso\core\domain\Domain'
150
+			),
151
+			array(
152
+				new FilePath(EVENT_ESPRESSO_MAIN_FILE),
153
+				Version::fromString(espresso_version())
154
+			)
155
+		);
156
+	}
157
+
158
+
159
+	/**
160
+	 * sets up the request and response objects
161
+	 *
162
+	 * @return BootstrapRequestResponseObjects
163
+	 * @throws InvalidArgumentException
164
+	 */
165
+	private function bootstrapRequestResponseObjects()
166
+	{
167
+		/** @var BootstrapRequestResponseObjects $bootstrap_request */
168
+		$bootstrap_request = $this->loader->getShared(
169
+			'EventEspresso\core\services\bootstrap\BootstrapRequestResponseObjects',
170
+			array($this->loader)
171
+		);
172
+		$bootstrap_request->buildRequestResponse();
173
+		$bootstrap_request->shareRequestResponse();
174
+		$this->request  = $this->loader->getShared('EventEspresso\core\services\request\Request');
175
+		$this->response = $this->loader->getShared('EventEspresso\core\services\request\Response');
176
+		return $bootstrap_request;
177
+	}
178
+
179
+
180
+	/**
181
+	 * run_request_stack
182
+	 * construct request stack and run middleware apps
183
+	 *
184
+	 * @throws InvalidRequestStackMiddlewareException
185
+	 * @throws InvalidInterfaceException
186
+	 * @throws InvalidDataTypeException
187
+	 * @throws EE_Error
188
+	 */
189
+	public function runRequestStack()
190
+	{
191
+		$this->loadAutoloader();
192
+		$this->setAutoloadersForRequiredFiles();
193
+		$this->request_stack_builder = $this->buildRequestStack();
194
+		$this->request_stack         = $this->request_stack_builder->resolve(
195
+			new RequestStackCoreApp()
196
+		);
197
+		$this->request_stack->handleRequest($this->request, $this->response);
198
+		$this->request_stack->handleResponse();
199
+	}
200
+
201
+
202
+	/**
203
+	 * load_autoloader
204
+	 *
205
+	 * @throws EE_Error
206
+	 */
207
+	protected function loadAutoloader()
208
+	{
209
+		// load interfaces
210
+		espresso_load_required(
211
+			'EEH_Autoloader',
212
+			EE_CORE . 'helpers' . DS . 'EEH_Autoloader.helper.php'
213
+		);
214
+		EEH_Autoloader::instance();
215
+	}
216
+
217
+
218
+
219
+	/**
220
+	 * load_required_files
221
+	 *
222
+	 * @throws EE_Error
223
+	 */
224
+	protected function setAutoloadersForRequiredFiles()
225
+	{
226
+		// load interfaces
227
+		EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_CORE . 'interfaces', true);
228
+		// load helpers
229
+		EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_HELPERS);
230
+		// load request stack
231
+		EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_CORE . 'request_stack' . DS);
232
+		// load middleware
233
+		EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_CORE . 'middleware' . DS);
234
+	}
235
+
236
+
237
+
238
+	/**
239
+	 * build_request_stack
240
+	 *
241
+	 * @return RequestStackBuilder
242
+	 */
243
+	public function buildRequestStack()
244
+	{
245
+		$request_stack_builder = new RequestStackBuilder($this->loader);
246
+		/**
247
+		 * ! IMPORTANT ! The middleware stack operates FILO : FIRST IN LAST OUT
248
+		 * so items at the beginning of the final middleware stack will run last.
249
+		 * First parameter is the middleware classname, second is an array of arguments
250
+		 */
251
+		$stack_apps            = apply_filters(
252
+			'FHEE__EventEspresso_core_services_bootstrap_BootstrapCore__buildRequestStack__stack_apps',
253
+			array(
254
+				// first in last out
255
+				'EventEspresso\core\services\request\middleware\BotDetector' => array(),
256
+				'EventEspresso\core\services\request\middleware\DetectFileEditorRequest' => array(),
257
+				'EventEspresso\core\services\request\middleware\PreProductionVersionWarning' => array(),
258
+				'EventEspresso\core\services\request\middleware\RecommendedVersions' => array(),
259
+				// last in first out
260
+				'EventEspresso\core\services\request\middleware\DetectLogin' => array(),
261
+			)
262
+		);
263
+		// legacy filter for backwards compatibility
264
+		$stack_apps            = apply_filters(
265
+			'FHEE__EE_Bootstrap__build_request_stack__stack_apps',
266
+			$stack_apps
267
+		);
268
+		// load middleware onto stack : FILO (First In Last Out)
269
+		// items at the beginning of the $stack_apps array will run last
270
+		foreach ((array) $stack_apps as $stack_app => $stack_app_args) {
271
+			$request_stack_builder->push(array($stack_app, $stack_app_args));
272
+		}
273
+		// finally, we'll add this on its own because we need it to always be part of the stack
274
+		// and we also need it to always run first because the rest of the system relies on it
275
+		$request_stack_builder->push(
276
+			array('EventEspresso\core\services\request\middleware\SetRequestTypeContextChecker', array())
277
+		);
278
+		return apply_filters(
279
+			'FHEE__EE_Bootstrap__build_request_stack__request_stack_builder',
280
+			$request_stack_builder
281
+		);
282
+	}
283 283
 
284 284
 
285 285
 }
Please login to merge, or discard this patch.
core/services/loaders/Loader.php 1 patch
Indentation   +108 added lines, -108 removed lines patch added patch discarded remove patch
@@ -22,114 +22,114 @@
 block discarded – undo
22 22
 {
23 23
 
24 24
 
25
-    /**
26
-     * @var LoaderDecoratorInterface $new_loader
27
-     */
28
-    private $new_loader;
29
-
30
-
31
-    /**
32
-     * @var LoaderDecoratorInterface $shared_loader
33
-     */
34
-    private $shared_loader;
35
-
36
-
37
-
38
-    /**
39
-     * Loader constructor.
40
-     *
41
-     * @param LoaderDecoratorInterface $new_loader
42
-     * @param CachingLoaderDecoratorInterface $shared_loader
43
-     * @throws InvalidInterfaceException
44
-     * @throws InvalidArgumentException
45
-     * @throws InvalidDataTypeException
46
-     */
47
-    public function __construct(LoaderDecoratorInterface $new_loader, CachingLoaderDecoratorInterface $shared_loader)
48
-    {
49
-        $this->new_loader = $new_loader;
50
-        $this->shared_loader = $shared_loader;
51
-    }
52
-
53
-
54
-
55
-    /**
56
-     * @return LoaderDecoratorInterface
57
-     */
58
-    public function getNewLoader()
59
-    {
60
-        return $this->new_loader;
61
-    }
62
-
63
-
64
-
65
-    /**
66
-     * @return CachingLoaderDecoratorInterface
67
-     */
68
-    public function getSharedLoader()
69
-    {
70
-        return $this->shared_loader;
71
-    }
72
-
73
-
74
-
75
-    /**
76
-     * @param string $fqcn
77
-     * @param array  $arguments
78
-     * @param bool   $shared
79
-     * @return mixed
80
-     */
81
-    public function load($fqcn, $arguments = array(), $shared = true)
82
-    {
83
-        return $shared
84
-            ? $this->getSharedLoader()->load($fqcn, $arguments, $shared)
85
-            : $this->getNewLoader()->load($fqcn, $arguments, $shared);
86
-    }
87
-
88
-
89
-
90
-    /**
91
-     * @param string $fqcn
92
-     * @param array  $arguments
93
-     * @return mixed
94
-     */
95
-    public function getNew($fqcn, $arguments = array())
96
-    {
97
-        return $this->getNewLoader()->load($fqcn, $arguments, false);
98
-    }
99
-
100
-
101
-
102
-    /**
103
-     * @param string $fqcn
104
-     * @param array  $arguments
105
-     * @return mixed
106
-     */
107
-    public function getShared($fqcn, $arguments = array())
108
-    {
109
-        return $this->getSharedLoader()->load($fqcn, $arguments);
110
-    }
111
-
112
-
113
-    /**
114
-     * @param string $fqcn
115
-     * @param mixed  $object
116
-     * @return bool
117
-     * @throws InvalidArgumentException
118
-     */
119
-    public function share($fqcn, $object)
120
-    {
121
-        return $this->getSharedLoader()->share($fqcn, $object);
122
-    }
123
-
124
-
125
-
126
-    /**
127
-     * calls reset() on loaders if that method exists
128
-     */
129
-    public function reset()
130
-    {
131
-        $this->shared_loader->reset();
132
-    }
25
+	/**
26
+	 * @var LoaderDecoratorInterface $new_loader
27
+	 */
28
+	private $new_loader;
29
+
30
+
31
+	/**
32
+	 * @var LoaderDecoratorInterface $shared_loader
33
+	 */
34
+	private $shared_loader;
35
+
36
+
37
+
38
+	/**
39
+	 * Loader constructor.
40
+	 *
41
+	 * @param LoaderDecoratorInterface $new_loader
42
+	 * @param CachingLoaderDecoratorInterface $shared_loader
43
+	 * @throws InvalidInterfaceException
44
+	 * @throws InvalidArgumentException
45
+	 * @throws InvalidDataTypeException
46
+	 */
47
+	public function __construct(LoaderDecoratorInterface $new_loader, CachingLoaderDecoratorInterface $shared_loader)
48
+	{
49
+		$this->new_loader = $new_loader;
50
+		$this->shared_loader = $shared_loader;
51
+	}
52
+
53
+
54
+
55
+	/**
56
+	 * @return LoaderDecoratorInterface
57
+	 */
58
+	public function getNewLoader()
59
+	{
60
+		return $this->new_loader;
61
+	}
62
+
63
+
64
+
65
+	/**
66
+	 * @return CachingLoaderDecoratorInterface
67
+	 */
68
+	public function getSharedLoader()
69
+	{
70
+		return $this->shared_loader;
71
+	}
72
+
73
+
74
+
75
+	/**
76
+	 * @param string $fqcn
77
+	 * @param array  $arguments
78
+	 * @param bool   $shared
79
+	 * @return mixed
80
+	 */
81
+	public function load($fqcn, $arguments = array(), $shared = true)
82
+	{
83
+		return $shared
84
+			? $this->getSharedLoader()->load($fqcn, $arguments, $shared)
85
+			: $this->getNewLoader()->load($fqcn, $arguments, $shared);
86
+	}
87
+
88
+
89
+
90
+	/**
91
+	 * @param string $fqcn
92
+	 * @param array  $arguments
93
+	 * @return mixed
94
+	 */
95
+	public function getNew($fqcn, $arguments = array())
96
+	{
97
+		return $this->getNewLoader()->load($fqcn, $arguments, false);
98
+	}
99
+
100
+
101
+
102
+	/**
103
+	 * @param string $fqcn
104
+	 * @param array  $arguments
105
+	 * @return mixed
106
+	 */
107
+	public function getShared($fqcn, $arguments = array())
108
+	{
109
+		return $this->getSharedLoader()->load($fqcn, $arguments);
110
+	}
111
+
112
+
113
+	/**
114
+	 * @param string $fqcn
115
+	 * @param mixed  $object
116
+	 * @return bool
117
+	 * @throws InvalidArgumentException
118
+	 */
119
+	public function share($fqcn, $object)
120
+	{
121
+		return $this->getSharedLoader()->share($fqcn, $object);
122
+	}
123
+
124
+
125
+
126
+	/**
127
+	 * calls reset() on loaders if that method exists
128
+	 */
129
+	public function reset()
130
+	{
131
+		$this->shared_loader->reset();
132
+	}
133 133
 
134 134
 }
135 135
 // End of file Loader.php
Please login to merge, or discard this patch.
core/EE_Load_Espresso_Core.core.php 2 patches
Unused Use Statements   -5 removed lines patch added patch discarded remove patch
@@ -1,12 +1,7 @@
 block discarded – undo
1 1
 <?php
2 2
 
3
-use EventEspresso\core\domain\DomainFactory;
4
-use EventEspresso\core\domain\values\FilePath;
5
-use EventEspresso\core\domain\values\FullyQualifiedName;
6
-use EventEspresso\core\domain\values\Version;
7 3
 use EventEspresso\core\exceptions\InvalidDataTypeException;
8 4
 use EventEspresso\core\exceptions\InvalidInterfaceException;
9
-use EventEspresso\core\services\loaders\LoaderFactory;
10 5
 use EventEspresso\core\services\request\RequestDecoratorInterface;
11 6
 use EventEspresso\core\services\request\RequestInterface;
12 7
 use EventEspresso\core\services\request\RequestStackCoreAppInterface;
Please login to merge, or discard this patch.
Indentation   +116 added lines, -116 removed lines patch added patch discarded remove patch
@@ -31,123 +31,123 @@
 block discarded – undo
31 31
 class EE_Load_Espresso_Core implements RequestDecoratorInterface, RequestStackCoreAppInterface
32 32
 {
33 33
 
34
-    /**
35
-     * @var RequestInterface $request
36
-     */
37
-    protected $request;
38
-
39
-    /**
40
-     * @var ResponseInterface $response
41
-     */
42
-    protected $response;
43
-
44
-    /**
45
-     * @var EE_Dependency_Map $dependency_map
46
-     */
47
-    protected $dependency_map;
48
-
49
-    /**
50
-     * @var EE_Registry $registry
51
-     */
52
-    protected $registry;
53
-
54
-
55
-    /**
56
-     * EE_Load_Espresso_Core constructor
57
-     *
58
-     * @param EE_Registry       $registry
59
-     * @param EE_Dependency_Map $dependency_map
60
-     * @throws EE_Error
61
-     */
34
+	/**
35
+	 * @var RequestInterface $request
36
+	 */
37
+	protected $request;
38
+
39
+	/**
40
+	 * @var ResponseInterface $response
41
+	 */
42
+	protected $response;
43
+
44
+	/**
45
+	 * @var EE_Dependency_Map $dependency_map
46
+	 */
47
+	protected $dependency_map;
48
+
49
+	/**
50
+	 * @var EE_Registry $registry
51
+	 */
52
+	protected $registry;
53
+
54
+
55
+	/**
56
+	 * EE_Load_Espresso_Core constructor
57
+	 *
58
+	 * @param EE_Registry       $registry
59
+	 * @param EE_Dependency_Map $dependency_map
60
+	 * @throws EE_Error
61
+	 */
62 62
 	public function __construct(EE_Registry $registry, EE_Dependency_Map $dependency_map) {
63
-        EE_Error::doing_it_wrong(
64
-            __METHOD__,
65
-            sprintf(
66
-                esc_html__(
67
-                    'This class is deprecated. Please use %1$s instead. All Event Espresso request stack classes have been moved to %2$s and are now under the %3$s namespace',
68
-                    'event_espresso'
69
-                ),
70
-                'EventEspresso\core\services\request\RequestStackCoreApp',
71
-                '\core\services\request',
72
-                'EventEspresso\core\services\request'
73
-            ),
74
-            '4.9.53'
75
-        );
76
-    }
77
-
78
-
79
-    /**
80
-     * handle
81
-     * sets hooks for running rest of system
82
-     * provides "AHEE__EE_System__construct__complete" hook for EE Addons to use as their starting point
83
-     * starting EE Addons from any other point may lead to problems
84
-     *
85
-     * @param RequestInterface $request
86
-     * @param ResponseInterface      $response
87
-     * @return ResponseInterface
88
-     * @throws EE_Error
89
-     * @throws InvalidDataTypeException
90
-     * @throws InvalidInterfaceException
91
-     * @throws InvalidArgumentException
92
-     * @throws DomainException
93
-     */
94
-    public function handleRequest(RequestInterface $request, ResponseInterface $response)
95
-    {
96
-    }
97
-
98
-
99
-
100
-    /**
101
-     * @return RequestInterface
102
-     */
103
-    public function request()
104
-    {
105
-    }
106
-
107
-
108
-
109
-    /**
110
-     * @return ResponseInterface
111
-     */
112
-    public function response()
113
-    {
114
-    }
115
-
116
-
117
-
118
-    /**
119
-     * @return EE_Dependency_Map
120
-     * @throws EE_Error
121
-     */
122
-    public function dependency_map()
123
-    {
124
-    }
125
-
126
-
127
-
128
-    /**
129
-     * @return EE_Registry
130
-     * @throws EE_Error
131
-     */
132
-    public function registry()
133
-    {
134
-    }
135
-
136
-
137
-
138
-
139
-
140
-
141
-    /**
142
-     * called after the request stack has been fully processed
143
-     * if any of the middleware apps has requested the plugin be deactivated, then we do that now
144
-     *
145
-     * @param RequestInterface $request
146
-     * @param ResponseInterface $response
147
-     */
148
-    public function handleResponse(RequestInterface $request, ResponseInterface $response)
149
-    {
150
-    }
63
+		EE_Error::doing_it_wrong(
64
+			__METHOD__,
65
+			sprintf(
66
+				esc_html__(
67
+					'This class is deprecated. Please use %1$s instead. All Event Espresso request stack classes have been moved to %2$s and are now under the %3$s namespace',
68
+					'event_espresso'
69
+				),
70
+				'EventEspresso\core\services\request\RequestStackCoreApp',
71
+				'\core\services\request',
72
+				'EventEspresso\core\services\request'
73
+			),
74
+			'4.9.53'
75
+		);
76
+	}
77
+
78
+
79
+	/**
80
+	 * handle
81
+	 * sets hooks for running rest of system
82
+	 * provides "AHEE__EE_System__construct__complete" hook for EE Addons to use as their starting point
83
+	 * starting EE Addons from any other point may lead to problems
84
+	 *
85
+	 * @param RequestInterface $request
86
+	 * @param ResponseInterface      $response
87
+	 * @return ResponseInterface
88
+	 * @throws EE_Error
89
+	 * @throws InvalidDataTypeException
90
+	 * @throws InvalidInterfaceException
91
+	 * @throws InvalidArgumentException
92
+	 * @throws DomainException
93
+	 */
94
+	public function handleRequest(RequestInterface $request, ResponseInterface $response)
95
+	{
96
+	}
97
+
98
+
99
+
100
+	/**
101
+	 * @return RequestInterface
102
+	 */
103
+	public function request()
104
+	{
105
+	}
106
+
107
+
108
+
109
+	/**
110
+	 * @return ResponseInterface
111
+	 */
112
+	public function response()
113
+	{
114
+	}
115
+
116
+
117
+
118
+	/**
119
+	 * @return EE_Dependency_Map
120
+	 * @throws EE_Error
121
+	 */
122
+	public function dependency_map()
123
+	{
124
+	}
125
+
126
+
127
+
128
+	/**
129
+	 * @return EE_Registry
130
+	 * @throws EE_Error
131
+	 */
132
+	public function registry()
133
+	{
134
+	}
135
+
136
+
137
+
138
+
139
+
140
+
141
+	/**
142
+	 * called after the request stack has been fully processed
143
+	 * if any of the middleware apps has requested the plugin be deactivated, then we do that now
144
+	 *
145
+	 * @param RequestInterface $request
146
+	 * @param ResponseInterface $response
147
+	 */
148
+	public function handleResponse(RequestInterface $request, ResponseInterface $response)
149
+	{
150
+	}
151 151
 
152 152
 
153 153
 
Please login to merge, or discard this patch.
core/services/loaders/CoreLoader.php 1 patch
Indentation   +109 added lines, -109 removed lines patch added patch discarded remove patch
@@ -33,115 +33,115 @@
 block discarded – undo
33 33
 class CoreLoader implements LoaderDecoratorInterface
34 34
 {
35 35
 
36
-    /**
37
-     * @var EE_Registry|CoffeeShop $generator
38
-     */
39
-    private $generator;
40
-
41
-
42
-
43
-    /**
44
-     * CoreLoader constructor.
45
-     *
46
-     * @param EE_Registry|CoffeeShop $generator
47
-     * @throws InvalidArgumentException
48
-     */
49
-    public function __construct($generator)
50
-    {
51
-        if(!($generator instanceof EE_Registry || $generator instanceof CoffeeShop)) {
52
-            throw new InvalidArgumentException(
53
-                esc_html__(
54
-                    'The CoreLoader class must receive an instance of EE_Registry or the CoffeeShop DI container.',
55
-                    'event_espresso'
56
-                )
57
-            );
58
-        }
59
-        $this->generator = $generator;
60
-    }
61
-
62
-
63
-
64
-    /**
65
-     * Calls the appropriate loading method from the installed generator;
66
-     * If EE_Registry is being used, then the additional parameters for the EE_Registry::create() method
67
-     * can be added to the $arguments array and they will be extracted and passed to EE_Registry::create(),
68
-     * but NOT to the class being instantiated.
69
-     * This is done by adding the parameters to the $arguments array as follows:
70
-     *  array(
71
-     *      'EE_Registry::create(from_db)'   => true, // boolean value, default = false
72
-     *      'EE_Registry::create(load_only)' => true, // boolean value, default = false
73
-     *      'EE_Registry::create(addon)'     => true, // boolean value, default = false
74
-     *  )
75
-     *
76
-     * @param string $fqcn
77
-     * @param array  $arguments
78
-     * @param bool   $shared
79
-     * @return mixed
80
-     * @throws OutOfBoundsException
81
-     * @throws ServiceExistsException
82
-     * @throws InstantiationException
83
-     * @throws InvalidIdentifierException
84
-     * @throws InvalidDataTypeException
85
-     * @throws InvalidClassException
86
-     * @throws EE_Error
87
-     * @throws ServiceNotFoundException
88
-     * @throws ReflectionException
89
-     */
90
-    public function load($fqcn, $arguments = array(), $shared = true)
91
-    {
92
-        $shared = filter_var($shared, FILTER_VALIDATE_BOOLEAN);
93
-        if($this->generator instanceof EE_Registry) {
94
-            // check if additional EE_Registry::create() arguments have been passed
95
-            // from_db
96
-            $from_db = isset($arguments['EE_Registry::create(from_db)'])
97
-                ? filter_var($arguments['EE_Registry::create(from_db)'], FILTER_VALIDATE_BOOLEAN)
98
-                : false;
99
-            // load_only
100
-            $load_only = isset($arguments['EE_Registry::create(load_only)'])
101
-                ? filter_var($arguments['EE_Registry::create(load_only)'], FILTER_VALIDATE_BOOLEAN)
102
-                : false;
103
-            // addon
104
-            $addon = isset($arguments['EE_Registry::create(addon)'])
105
-                ? filter_var($arguments['EE_Registry::create(addon)'], FILTER_VALIDATE_BOOLEAN)
106
-                : false;
107
-            unset(
108
-                $arguments['EE_Registry::create(from_db)'],
109
-                $arguments['EE_Registry::create(load_only)'],
110
-                $arguments['EE_Registry::create(addon)']
111
-            );
112
-            // addons need to be cached on EE_Registry
113
-            $shared = $addon ? true : $shared;
114
-            return $this->generator->create(
115
-                $fqcn,
116
-                $arguments,
117
-                $shared,
118
-                $from_db,
119
-                $load_only,
120
-                $addon
121
-            );
122
-        }
123
-        return $this->generator->brew(
124
-            $fqcn,
125
-            $arguments,
126
-            $shared ? CoffeeMaker::BREW_SHARED : CoffeeMaker::BREW_NEW
127
-        );
128
-
129
-    }
130
-
131
-
132
-
133
-    /**
134
-     * calls reset() on generator if method exists
135
-     *
136
-     * @throws EE_Error
137
-     * @throws ReflectionException
138
-     */
139
-    public function reset()
140
-    {
141
-        if ($this->generator instanceof ResettableInterface) {
142
-            $this->generator->reset();
143
-        }
144
-    }
36
+	/**
37
+	 * @var EE_Registry|CoffeeShop $generator
38
+	 */
39
+	private $generator;
40
+
41
+
42
+
43
+	/**
44
+	 * CoreLoader constructor.
45
+	 *
46
+	 * @param EE_Registry|CoffeeShop $generator
47
+	 * @throws InvalidArgumentException
48
+	 */
49
+	public function __construct($generator)
50
+	{
51
+		if(!($generator instanceof EE_Registry || $generator instanceof CoffeeShop)) {
52
+			throw new InvalidArgumentException(
53
+				esc_html__(
54
+					'The CoreLoader class must receive an instance of EE_Registry or the CoffeeShop DI container.',
55
+					'event_espresso'
56
+				)
57
+			);
58
+		}
59
+		$this->generator = $generator;
60
+	}
61
+
62
+
63
+
64
+	/**
65
+	 * Calls the appropriate loading method from the installed generator;
66
+	 * If EE_Registry is being used, then the additional parameters for the EE_Registry::create() method
67
+	 * can be added to the $arguments array and they will be extracted and passed to EE_Registry::create(),
68
+	 * but NOT to the class being instantiated.
69
+	 * This is done by adding the parameters to the $arguments array as follows:
70
+	 *  array(
71
+	 *      'EE_Registry::create(from_db)'   => true, // boolean value, default = false
72
+	 *      'EE_Registry::create(load_only)' => true, // boolean value, default = false
73
+	 *      'EE_Registry::create(addon)'     => true, // boolean value, default = false
74
+	 *  )
75
+	 *
76
+	 * @param string $fqcn
77
+	 * @param array  $arguments
78
+	 * @param bool   $shared
79
+	 * @return mixed
80
+	 * @throws OutOfBoundsException
81
+	 * @throws ServiceExistsException
82
+	 * @throws InstantiationException
83
+	 * @throws InvalidIdentifierException
84
+	 * @throws InvalidDataTypeException
85
+	 * @throws InvalidClassException
86
+	 * @throws EE_Error
87
+	 * @throws ServiceNotFoundException
88
+	 * @throws ReflectionException
89
+	 */
90
+	public function load($fqcn, $arguments = array(), $shared = true)
91
+	{
92
+		$shared = filter_var($shared, FILTER_VALIDATE_BOOLEAN);
93
+		if($this->generator instanceof EE_Registry) {
94
+			// check if additional EE_Registry::create() arguments have been passed
95
+			// from_db
96
+			$from_db = isset($arguments['EE_Registry::create(from_db)'])
97
+				? filter_var($arguments['EE_Registry::create(from_db)'], FILTER_VALIDATE_BOOLEAN)
98
+				: false;
99
+			// load_only
100
+			$load_only = isset($arguments['EE_Registry::create(load_only)'])
101
+				? filter_var($arguments['EE_Registry::create(load_only)'], FILTER_VALIDATE_BOOLEAN)
102
+				: false;
103
+			// addon
104
+			$addon = isset($arguments['EE_Registry::create(addon)'])
105
+				? filter_var($arguments['EE_Registry::create(addon)'], FILTER_VALIDATE_BOOLEAN)
106
+				: false;
107
+			unset(
108
+				$arguments['EE_Registry::create(from_db)'],
109
+				$arguments['EE_Registry::create(load_only)'],
110
+				$arguments['EE_Registry::create(addon)']
111
+			);
112
+			// addons need to be cached on EE_Registry
113
+			$shared = $addon ? true : $shared;
114
+			return $this->generator->create(
115
+				$fqcn,
116
+				$arguments,
117
+				$shared,
118
+				$from_db,
119
+				$load_only,
120
+				$addon
121
+			);
122
+		}
123
+		return $this->generator->brew(
124
+			$fqcn,
125
+			$arguments,
126
+			$shared ? CoffeeMaker::BREW_SHARED : CoffeeMaker::BREW_NEW
127
+		);
128
+
129
+	}
130
+
131
+
132
+
133
+	/**
134
+	 * calls reset() on generator if method exists
135
+	 *
136
+	 * @throws EE_Error
137
+	 * @throws ReflectionException
138
+	 */
139
+	public function reset()
140
+	{
141
+		if ($this->generator instanceof ResettableInterface) {
142
+			$this->generator->reset();
143
+		}
144
+	}
145 145
 
146 146
 }
147 147
 // End of file CoreLoader.php
Please login to merge, or discard this patch.
core/services/loaders/CachingLoader.php 2 patches
Indentation   +165 added lines, -165 removed lines patch added patch discarded remove patch
@@ -22,171 +22,171 @@
 block discarded – undo
22 22
 class CachingLoader extends CachingLoaderDecorator
23 23
 {
24 24
 
25
-    /**
26
-     * @var CollectionInterface $cache
27
-     */
28
-    protected $cache;
29
-
30
-    /**
31
-     * @var string $identifier
32
-     */
33
-    protected $identifier;
34
-
35
-
36
-
37
-    /**
38
-     * CachingLoader constructor.
39
-     *
40
-     * @param LoaderDecoratorInterface $loader
41
-     * @param CollectionInterface      $cache
42
-     * @param string                   $identifier
43
-     * @throws InvalidDataTypeException
44
-     */
45
-    public function __construct(
46
-        LoaderDecoratorInterface $loader,
47
-        CollectionInterface $cache,
48
-        $identifier = ''
49
-    ) {
50
-        parent::__construct($loader);
51
-        $this->cache = $cache;
52
-        $this->setIdentifier($identifier);
53
-        if ($this->identifier !== '') {
54
-            // to only clear this cache, and assuming an identifier has been set, simply do the following:
55
-            // do_action('AHEE__EventEspresso_core_services_loaders_CachingLoader__resetCache__IDENTIFIER');
56
-            // where "IDENTIFIER" = the string that was set during construction
57
-            add_action(
58
-                "AHEE__EventEspresso_core_services_loaders_CachingLoader__resetCache__{$identifier}",
59
-                array($this, 'reset')
60
-            );
61
-        }
62
-        // to clear ALL caches, simply do the following:
63
-        // do_action('AHEE__EventEspresso_core_services_loaders_CachingLoader__resetCache');
64
-        add_action(
65
-            'AHEE__EventEspresso_core_services_loaders_CachingLoader__resetCache',
66
-            array($this, 'reset')
67
-        );
68
-    }
69
-
70
-
71
-
72
-    /**
73
-     * @return string
74
-     */
75
-    public function identifier()
76
-    {
77
-        return $this->identifier;
78
-    }
79
-
80
-
81
-
82
-    /**
83
-     * @param string $identifier
84
-     * @throws InvalidDataTypeException
85
-     */
86
-    private function setIdentifier($identifier)
87
-    {
88
-        if (! is_string($identifier)) {
89
-            throw new InvalidDataTypeException('$identifier', $identifier, 'string');
90
-        }
91
-        $this->identifier = $identifier;
92
-    }
93
-
94
-
95
-    /**
96
-     * @param string $fqcn
97
-     * @param mixed  $object
98
-     * @return bool
99
-     * @throws InvalidArgumentException
100
-     */
101
-    public function share($fqcn, $object)
102
-    {
103
-        if ($object instanceof $fqcn) {
104
-            return $this->cache->add($object, md5($fqcn));
105
-        }
106
-        throw new InvalidArgumentException(
107
-            sprintf(
108
-                esc_html__(
109
-                    'The supplied class name "%1$s" must match the class of the supplied object.',
110
-                    'event_espresso'
111
-                ),
112
-                $fqcn
113
-            )
114
-        );
115
-    }
116
-
117
-
118
-    /**
119
-     * @param string $fqcn
120
-     * @param array  $arguments
121
-     * @param bool   $shared
122
-     * @return mixed
123
-     */
124
-    public function load($fqcn, $arguments = array(), $shared = true)
125
-    {
126
-        $fqcn = ltrim($fqcn, '\\');
127
-        // caching can be turned off via the following code:
128
-        // add_filter('FHEE__EventEspresso_core_services_loaders_CachingLoader__load__bypass_cache', '__return_true');
129
-        if(
130
-            apply_filters(
131
-                'FHEE__EventEspresso_core_services_loaders_CachingLoader__load__bypass_cache',
132
-                false,
133
-                $this
134
-            )
135
-        ){
136
-            // even though $shared might be true, caching could be bypassed for whatever reason,
137
-            // so we don't want the core loader to cache anything, therefore caching is turned off
138
-            return $this->loader->load($fqcn, $arguments, false);
139
-        }
140
-        $identifier = md5($fqcn . $this->getIdentifierForArgument($arguments));
141
-        if ($this->cache->has($identifier)) {
142
-            return $this->cache->get($identifier);
143
-        }
144
-        $object = $this->loader->load($fqcn, $arguments, $shared);
145
-        if ($object instanceof $fqcn) {
146
-            $this->cache->add($object, $identifier);
147
-        }
148
-        return $object;
149
-    }
150
-
151
-
152
-
153
-    /**
154
-     * empties cache and calls reset() on loader if method exists
155
-     */
156
-    public function reset()
157
-    {
158
-        $this->cache->trashAndDetachAll();
159
-        $this->loader->reset();
160
-    }
161
-
162
-
163
-
164
-    /**
165
-     * build a string representation of a class' arguments
166
-     * (mostly because Closures can't be serialized)
167
-     *
168
-     * @param array $arguments
169
-     * @return string
170
-     */
171
-    private function getIdentifierForArgument(array $arguments)
172
-    {
173
-        $identifier = '';
174
-        foreach ($arguments as $argument) {
175
-            switch (true) {
176
-                case is_object($argument) :
177
-                case $argument instanceof Closure :
178
-                    $identifier .= spl_object_hash($argument);
179
-                    break;
180
-                case is_array($argument) :
181
-                    $identifier .= $this->getIdentifierForArgument($argument);
182
-                    break;
183
-                default :
184
-                    $identifier .= $argument;
185
-                    break;
186
-            }
187
-        }
188
-        return $identifier;
189
-    }
25
+	/**
26
+	 * @var CollectionInterface $cache
27
+	 */
28
+	protected $cache;
29
+
30
+	/**
31
+	 * @var string $identifier
32
+	 */
33
+	protected $identifier;
34
+
35
+
36
+
37
+	/**
38
+	 * CachingLoader constructor.
39
+	 *
40
+	 * @param LoaderDecoratorInterface $loader
41
+	 * @param CollectionInterface      $cache
42
+	 * @param string                   $identifier
43
+	 * @throws InvalidDataTypeException
44
+	 */
45
+	public function __construct(
46
+		LoaderDecoratorInterface $loader,
47
+		CollectionInterface $cache,
48
+		$identifier = ''
49
+	) {
50
+		parent::__construct($loader);
51
+		$this->cache = $cache;
52
+		$this->setIdentifier($identifier);
53
+		if ($this->identifier !== '') {
54
+			// to only clear this cache, and assuming an identifier has been set, simply do the following:
55
+			// do_action('AHEE__EventEspresso_core_services_loaders_CachingLoader__resetCache__IDENTIFIER');
56
+			// where "IDENTIFIER" = the string that was set during construction
57
+			add_action(
58
+				"AHEE__EventEspresso_core_services_loaders_CachingLoader__resetCache__{$identifier}",
59
+				array($this, 'reset')
60
+			);
61
+		}
62
+		// to clear ALL caches, simply do the following:
63
+		// do_action('AHEE__EventEspresso_core_services_loaders_CachingLoader__resetCache');
64
+		add_action(
65
+			'AHEE__EventEspresso_core_services_loaders_CachingLoader__resetCache',
66
+			array($this, 'reset')
67
+		);
68
+	}
69
+
70
+
71
+
72
+	/**
73
+	 * @return string
74
+	 */
75
+	public function identifier()
76
+	{
77
+		return $this->identifier;
78
+	}
79
+
80
+
81
+
82
+	/**
83
+	 * @param string $identifier
84
+	 * @throws InvalidDataTypeException
85
+	 */
86
+	private function setIdentifier($identifier)
87
+	{
88
+		if (! is_string($identifier)) {
89
+			throw new InvalidDataTypeException('$identifier', $identifier, 'string');
90
+		}
91
+		$this->identifier = $identifier;
92
+	}
93
+
94
+
95
+	/**
96
+	 * @param string $fqcn
97
+	 * @param mixed  $object
98
+	 * @return bool
99
+	 * @throws InvalidArgumentException
100
+	 */
101
+	public function share($fqcn, $object)
102
+	{
103
+		if ($object instanceof $fqcn) {
104
+			return $this->cache->add($object, md5($fqcn));
105
+		}
106
+		throw new InvalidArgumentException(
107
+			sprintf(
108
+				esc_html__(
109
+					'The supplied class name "%1$s" must match the class of the supplied object.',
110
+					'event_espresso'
111
+				),
112
+				$fqcn
113
+			)
114
+		);
115
+	}
116
+
117
+
118
+	/**
119
+	 * @param string $fqcn
120
+	 * @param array  $arguments
121
+	 * @param bool   $shared
122
+	 * @return mixed
123
+	 */
124
+	public function load($fqcn, $arguments = array(), $shared = true)
125
+	{
126
+		$fqcn = ltrim($fqcn, '\\');
127
+		// caching can be turned off via the following code:
128
+		// add_filter('FHEE__EventEspresso_core_services_loaders_CachingLoader__load__bypass_cache', '__return_true');
129
+		if(
130
+			apply_filters(
131
+				'FHEE__EventEspresso_core_services_loaders_CachingLoader__load__bypass_cache',
132
+				false,
133
+				$this
134
+			)
135
+		){
136
+			// even though $shared might be true, caching could be bypassed for whatever reason,
137
+			// so we don't want the core loader to cache anything, therefore caching is turned off
138
+			return $this->loader->load($fqcn, $arguments, false);
139
+		}
140
+		$identifier = md5($fqcn . $this->getIdentifierForArgument($arguments));
141
+		if ($this->cache->has($identifier)) {
142
+			return $this->cache->get($identifier);
143
+		}
144
+		$object = $this->loader->load($fqcn, $arguments, $shared);
145
+		if ($object instanceof $fqcn) {
146
+			$this->cache->add($object, $identifier);
147
+		}
148
+		return $object;
149
+	}
150
+
151
+
152
+
153
+	/**
154
+	 * empties cache and calls reset() on loader if method exists
155
+	 */
156
+	public function reset()
157
+	{
158
+		$this->cache->trashAndDetachAll();
159
+		$this->loader->reset();
160
+	}
161
+
162
+
163
+
164
+	/**
165
+	 * build a string representation of a class' arguments
166
+	 * (mostly because Closures can't be serialized)
167
+	 *
168
+	 * @param array $arguments
169
+	 * @return string
170
+	 */
171
+	private function getIdentifierForArgument(array $arguments)
172
+	{
173
+		$identifier = '';
174
+		foreach ($arguments as $argument) {
175
+			switch (true) {
176
+				case is_object($argument) :
177
+				case $argument instanceof Closure :
178
+					$identifier .= spl_object_hash($argument);
179
+					break;
180
+				case is_array($argument) :
181
+					$identifier .= $this->getIdentifierForArgument($argument);
182
+					break;
183
+				default :
184
+					$identifier .= $argument;
185
+					break;
186
+			}
187
+		}
188
+		return $identifier;
189
+	}
190 190
 
191 191
 
192 192
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -85,7 +85,7 @@  discard block
 block discarded – undo
85 85
      */
86 86
     private function setIdentifier($identifier)
87 87
     {
88
-        if (! is_string($identifier)) {
88
+        if ( ! is_string($identifier)) {
89 89
             throw new InvalidDataTypeException('$identifier', $identifier, 'string');
90 90
         }
91 91
         $this->identifier = $identifier;
@@ -126,18 +126,18 @@  discard block
 block discarded – undo
126 126
         $fqcn = ltrim($fqcn, '\\');
127 127
         // caching can be turned off via the following code:
128 128
         // add_filter('FHEE__EventEspresso_core_services_loaders_CachingLoader__load__bypass_cache', '__return_true');
129
-        if(
129
+        if (
130 130
             apply_filters(
131 131
                 'FHEE__EventEspresso_core_services_loaders_CachingLoader__load__bypass_cache',
132 132
                 false,
133 133
                 $this
134 134
             )
135
-        ){
135
+        ) {
136 136
             // even though $shared might be true, caching could be bypassed for whatever reason,
137 137
             // so we don't want the core loader to cache anything, therefore caching is turned off
138 138
             return $this->loader->load($fqcn, $arguments, false);
139 139
         }
140
-        $identifier = md5($fqcn . $this->getIdentifierForArgument($arguments));
140
+        $identifier = md5($fqcn.$this->getIdentifierForArgument($arguments));
141 141
         if ($this->cache->has($identifier)) {
142 142
             return $this->cache->get($identifier);
143 143
         }
Please login to merge, or discard this patch.
core/EE_System.core.php 2 patches
Spacing   +30 added lines, -30 removed lines patch added patch discarded remove patch
@@ -140,7 +140,7 @@  discard block
 block discarded – undo
140 140
         EE_Maintenance_Mode $maintenance_mode = null
141 141
     ) {
142 142
         // check if class object is instantiated
143
-        if (! self::$_instance instanceof EE_System) {
143
+        if ( ! self::$_instance instanceof EE_System) {
144 144
             self::$_instance = new self($registry, $loader, $request, $maintenance_mode);
145 145
         }
146 146
         return self::$_instance;
@@ -259,7 +259,7 @@  discard block
 block discarded – undo
259 259
         $this->capabilities = $this->loader->getShared('EE_Capabilities');
260 260
         add_action(
261 261
             'AHEE__EE_Capabilities__init_caps__before_initialization',
262
-            function ()
262
+            function()
263 263
             {
264 264
                 LoaderFactory::getLoader()->getShared('EE_Payment_Method_Manager');
265 265
             }
@@ -303,7 +303,7 @@  discard block
 block discarded – undo
303 303
     {
304 304
         // set autoloaders for all of the classes implementing EEI_Plugin_API
305 305
         // which provide helpers for EE plugin authors to more easily register certain components with EE.
306
-        EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'plugin_api');
306
+        EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_LIBRARIES.'plugin_api');
307 307
         $this->loader->getShared('EE_Request_Handler');
308 308
     }
309 309
 
@@ -323,14 +323,14 @@  discard block
 block discarded – undo
323 323
         $load_callback,
324 324
         $plugin_file_constant
325 325
     ) {
326
-        if (! defined($version_constant)) {
326
+        if ( ! defined($version_constant)) {
327 327
             return;
328 328
         }
329 329
         $addon_version = constant($version_constant);
330 330
         if ($addon_version && version_compare($addon_version, $min_version_required, '<')) {
331 331
             remove_action('AHEE__EE_System__load_espresso_addons', $load_callback);
332
-            if (! function_exists('deactivate_plugins')) {
333
-                require_once ABSPATH . 'wp-admin/includes/plugin.php';
332
+            if ( ! function_exists('deactivate_plugins')) {
333
+                require_once ABSPATH.'wp-admin/includes/plugin.php';
334 334
             }
335 335
             deactivate_plugins(plugin_basename(constant($plugin_file_constant)));
336 336
             unset($_GET['activate'], $_REQUEST['activate'], $_GET['activate-multi'], $_REQUEST['activate-multi']);
@@ -343,7 +343,7 @@  discard block
 block discarded – undo
343 343
                     $addon_name,
344 344
                     $min_version_required
345 345
                 ),
346
-                __FILE__, __FUNCTION__ . "({$addon_name})", __LINE__
346
+                __FILE__, __FUNCTION__."({$addon_name})", __LINE__
347 347
             );
348 348
             EE_Error::get_notices(false, true);
349 349
         }
@@ -393,7 +393,7 @@  discard block
 block discarded – undo
393 393
                 true
394 394
             )
395 395
         ) {
396
-            include_once EE_THIRD_PARTY . 'wp-api-basic-auth' . DS . 'basic-auth.php';
396
+            include_once EE_THIRD_PARTY.'wp-api-basic-auth'.DS.'basic-auth.php';
397 397
         }
398 398
         do_action('AHEE__EE_System__load_espresso_addons__complete');
399 399
     }
@@ -500,11 +500,11 @@  discard block
 block discarded – undo
500 500
     private function fix_espresso_db_upgrade_option($espresso_db_update = null)
501 501
     {
502 502
         do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__begin', $espresso_db_update);
503
-        if (! $espresso_db_update) {
503
+        if ( ! $espresso_db_update) {
504 504
             $espresso_db_update = get_option('espresso_db_update');
505 505
         }
506 506
         // check that option is an array
507
-        if (! is_array($espresso_db_update)) {
507
+        if ( ! is_array($espresso_db_update)) {
508 508
             // if option is FALSE, then it never existed
509 509
             if ($espresso_db_update === false) {
510 510
                 // make $espresso_db_update an array and save option with autoload OFF
@@ -524,10 +524,10 @@  discard block
 block discarded – undo
524 524
                     //so it must be numerically-indexed, where values are versions installed...
525 525
                     //fix it!
526 526
                     $version_string                         = $should_be_array;
527
-                    $corrected_db_update[ $version_string ] = array('unknown-date');
527
+                    $corrected_db_update[$version_string] = array('unknown-date');
528 528
                 } else {
529 529
                     //ok it checks out
530
-                    $corrected_db_update[ $should_be_version_string ] = $should_be_array;
530
+                    $corrected_db_update[$should_be_version_string] = $should_be_array;
531 531
                 }
532 532
             }
533 533
             $espresso_db_update = $corrected_db_update;
@@ -609,13 +609,13 @@  discard block
 block discarded – undo
609 609
      */
610 610
     public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null)
611 611
     {
612
-        if (! $version_history) {
612
+        if ( ! $version_history) {
613 613
             $version_history = $this->fix_espresso_db_upgrade_option($version_history);
614 614
         }
615 615
         if ($current_version_to_add === null) {
616 616
             $current_version_to_add = espresso_version();
617 617
         }
618
-        $version_history[ $current_version_to_add ][] = date('Y-m-d H:i:s', time());
618
+        $version_history[$current_version_to_add][] = date('Y-m-d H:i:s', time());
619 619
         // re-save
620 620
         return update_option('espresso_db_update', $version_history);
621 621
     }
@@ -708,7 +708,7 @@  discard block
 block discarded – undo
708 708
         if ($activation_history_for_addon) {
709 709
             //it exists, so this isn't a completely new install
710 710
             //check if this version already in that list of previously installed versions
711
-            if (! isset($activation_history_for_addon[ $version_to_upgrade_to ])) {
711
+            if ( ! isset($activation_history_for_addon[$version_to_upgrade_to])) {
712 712
                 //it a version we haven't seen before
713 713
                 if ($version_is_higher === 1) {
714 714
                     $req_type = EE_System::req_type_upgrade;
@@ -788,7 +788,7 @@  discard block
 block discarded – undo
788 788
             foreach ($activation_history as $version => $times_activated) {
789 789
                 //check there is a record of when this version was activated. Otherwise,
790 790
                 //mark it as unknown
791
-                if (! $times_activated) {
791
+                if ( ! $times_activated) {
792 792
                     $times_activated = array('unknown-date');
793 793
                 }
794 794
                 if (is_string($times_activated)) {
@@ -889,7 +889,7 @@  discard block
 block discarded – undo
889 889
     private function _parse_model_names()
890 890
     {
891 891
         //get all the files in the EE_MODELS folder that end in .model.php
892
-        $models                 = glob(EE_MODELS . '*.model.php');
892
+        $models                 = glob(EE_MODELS.'*.model.php');
893 893
         $model_names            = array();
894 894
         $non_abstract_db_models = array();
895 895
         foreach ($models as $model) {
@@ -898,9 +898,9 @@  discard block
 block discarded – undo
898 898
             $short_name      = str_replace('EEM_', '', $classname);
899 899
             $reflectionClass = new ReflectionClass($classname);
900 900
             if ($reflectionClass->isSubclassOf('EEM_Base') && ! $reflectionClass->isAbstract()) {
901
-                $non_abstract_db_models[ $short_name ] = $classname;
901
+                $non_abstract_db_models[$short_name] = $classname;
902 902
             }
903
-            $model_names[ $short_name ] = $classname;
903
+            $model_names[$short_name] = $classname;
904 904
         }
905 905
         $this->registry->models                 = apply_filters('FHEE__EE_System__parse_model_names', $model_names);
906 906
         $this->registry->non_abstract_db_models = apply_filters(
@@ -919,8 +919,8 @@  discard block
 block discarded – undo
919 919
      */
920 920
     private function _maybe_brew_regular()
921 921
     {
922
-        if ((! defined('EE_DECAF') || EE_DECAF !== true) && is_readable(EE_CAFF_PATH . 'brewing_regular.php')) {
923
-            require_once EE_CAFF_PATH . 'brewing_regular.php';
922
+        if (( ! defined('EE_DECAF') || EE_DECAF !== true) && is_readable(EE_CAFF_PATH.'brewing_regular.php')) {
923
+            require_once EE_CAFF_PATH.'brewing_regular.php';
924 924
         }
925 925
     }
926 926
 
@@ -973,17 +973,17 @@  discard block
 block discarded – undo
973 973
         $class_names = EEH_Class_Tools::get_class_names_for_all_callbacks_on_hook(
974 974
             'AHEE__EE_System__register_shortcodes_modules_and_addons'
975 975
         );
976
-        if (! empty($class_names)) {
976
+        if ( ! empty($class_names)) {
977 977
             $msg = __(
978 978
                 'The following plugins, addons, or modules appear to be incompatible with this version of Event Espresso and were automatically deactivated to avoid fatal errors:',
979 979
                 'event_espresso'
980 980
             );
981 981
             $msg .= '<ul>';
982 982
             foreach ($class_names as $class_name) {
983
-                $msg .= '<li><b>Event Espresso - ' . str_replace(
983
+                $msg .= '<li><b>Event Espresso - '.str_replace(
984 984
                         array('EE_', 'EEM_', 'EED_', 'EES_', 'EEW_'), '',
985 985
                         $class_name
986
-                    ) . '</b></li>';
986
+                    ).'</b></li>';
987 987
             }
988 988
             $msg .= '</ul>';
989 989
             $msg .= __(
@@ -1054,7 +1054,7 @@  discard block
 block discarded – undo
1054 1054
     private function _deactivate_incompatible_addons()
1055 1055
     {
1056 1056
         $incompatible_addons = get_option('ee_incompatible_addons', array());
1057
-        if (! empty($incompatible_addons)) {
1057
+        if ( ! empty($incompatible_addons)) {
1058 1058
             $active_plugins = get_option('active_plugins', array());
1059 1059
             foreach ($active_plugins as $active_plugin) {
1060 1060
                 foreach ($incompatible_addons as $incompatible_addon) {
@@ -1149,10 +1149,10 @@  discard block
 block discarded – undo
1149 1149
         do_action('AHEE__EE_System__core_loaded_and_ready');
1150 1150
         // load_espresso_template_tags
1151 1151
         if (
1152
-            is_readable(EE_PUBLIC . 'template_tags.php')
1152
+            is_readable(EE_PUBLIC.'template_tags.php')
1153 1153
             && ($this->request->isFrontend() || $this->request->isIframe() || $this->request->isFeed())
1154 1154
         ) {
1155
-            require_once EE_PUBLIC . 'template_tags.php';
1155
+            require_once EE_PUBLIC.'template_tags.php';
1156 1156
         }
1157 1157
         do_action('AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons');
1158 1158
         if ($this->request->isAdmin() || $this->request->isFrontend() || $this->request->isIframe()) {
@@ -1216,13 +1216,13 @@  discard block
 block discarded – undo
1216 1216
     public static function do_not_cache()
1217 1217
     {
1218 1218
         // set no cache constants
1219
-        if (! defined('DONOTCACHEPAGE')) {
1219
+        if ( ! defined('DONOTCACHEPAGE')) {
1220 1220
             define('DONOTCACHEPAGE', true);
1221 1221
         }
1222
-        if (! defined('DONOTCACHCEOBJECT')) {
1222
+        if ( ! defined('DONOTCACHCEOBJECT')) {
1223 1223
             define('DONOTCACHCEOBJECT', true);
1224 1224
         }
1225
-        if (! defined('DONOTCACHEDB')) {
1225
+        if ( ! defined('DONOTCACHEDB')) {
1226 1226
             define('DONOTCACHEDB', true);
1227 1227
         }
1228 1228
         // add no cache headers
Please login to merge, or discard this patch.
Indentation   +1250 added lines, -1250 removed lines patch added patch discarded remove patch
@@ -24,1256 +24,1256 @@
 block discarded – undo
24 24
 {
25 25
 
26 26
 
27
-    /**
28
-     * indicates this is a 'normal' request. Ie, not activation, nor upgrade, nor activation.
29
-     * So examples of this would be a normal GET request on the frontend or backend, or a POST, etc
30
-     */
31
-    const req_type_normal = 0;
32
-
33
-    /**
34
-     * Indicates this is a brand new installation of EE so we should install
35
-     * tables and default data etc
36
-     */
37
-    const req_type_new_activation = 1;
38
-
39
-    /**
40
-     * we've detected that EE has been reactivated (or EE was activated during maintenance mode,
41
-     * and we just exited maintenance mode). We MUST check the database is setup properly
42
-     * and that default data is setup too
43
-     */
44
-    const req_type_reactivation = 2;
45
-
46
-    /**
47
-     * indicates that EE has been upgraded since its previous request.
48
-     * We may have data migration scripts to call and will want to trigger maintenance mode
49
-     */
50
-    const req_type_upgrade = 3;
51
-
52
-    /**
53
-     * TODO  will detect that EE has been DOWNGRADED. We probably don't want to run in this case...
54
-     */
55
-    const req_type_downgrade = 4;
56
-
57
-    /**
58
-     * @deprecated since version 4.6.0.dev.006
59
-     * Now whenever a new_activation is detected the request type is still just
60
-     * new_activation (same for reactivation, upgrade, downgrade etc), but if we'r ein maintenance mode
61
-     * EE_System::initialize_db_if_no_migrations_required and EE_Addon::initialize_db_if_no_migrations_required
62
-     * will instead enqueue that EE plugin's db initialization for when we're taken out of maintenance mode.
63
-     * (Specifically, when the migration manager indicates migrations are finished
64
-     * EE_Data_Migration_Manager::initialize_db_for_enqueued_ee_plugins() will be called)
65
-     */
66
-    const req_type_activation_but_not_installed = 5;
67
-
68
-    /**
69
-     * option prefix for recording the activation history (like core's "espresso_db_update") of addons
70
-     */
71
-    const addon_activation_history_option_prefix = 'ee_addon_activation_history_';
72
-
73
-
74
-    /**
75
-     * @var EE_System $_instance
76
-     */
77
-    private static $_instance;
78
-
79
-    /**
80
-     * @var EE_Registry $registry
81
-     */
82
-    private $registry;
83
-
84
-    /**
85
-     * @var LoaderInterface $loader
86
-     */
87
-    private $loader;
88
-
89
-    /**
90
-     * @var EE_Capabilities $capabilities
91
-     */
92
-    private $capabilities;
93
-
94
-    /**
95
-     * @var RequestInterface $request
96
-     */
97
-    private $request;
98
-
99
-    /**
100
-     * @var EE_Maintenance_Mode $maintenance_mode
101
-     */
102
-    private $maintenance_mode;
103
-
104
-    /**
105
-     * Stores which type of request this is, options being one of the constants on EE_System starting with req_type_*.
106
-     * It can be a brand-new activation, a reactivation, an upgrade, a downgrade, or a normal request.
107
-     *
108
-     * @var int $_req_type
109
-     */
110
-    private $_req_type;
111
-
112
-    /**
113
-     * Whether or not there was a non-micro version change in EE core version during this request
114
-     *
115
-     * @var boolean $_major_version_change
116
-     */
117
-    private $_major_version_change = false;
118
-
119
-    /**
120
-     * A Context DTO dedicated solely to identifying the current request type.
121
-     *
122
-     * @var RequestTypeContextCheckerInterface $request_type
123
-     */
124
-    private $request_type;
125
-
126
-
127
-
128
-    /**
129
-     * @singleton method used to instantiate class object
130
-     * @param EE_Registry|null         $registry
131
-     * @param LoaderInterface|null     $loader
132
-     * @param RequestInterface|null          $request
133
-     * @param EE_Maintenance_Mode|null $maintenance_mode
134
-     * @return EE_System
135
-     */
136
-    public static function instance(
137
-        EE_Registry $registry = null,
138
-        LoaderInterface $loader = null,
139
-        RequestInterface $request = null,
140
-        EE_Maintenance_Mode $maintenance_mode = null
141
-    ) {
142
-        // check if class object is instantiated
143
-        if (! self::$_instance instanceof EE_System) {
144
-            self::$_instance = new self($registry, $loader, $request, $maintenance_mode);
145
-        }
146
-        return self::$_instance;
147
-    }
148
-
149
-
150
-
151
-    /**
152
-     * resets the instance and returns it
153
-     *
154
-     * @return EE_System
155
-     */
156
-    public static function reset()
157
-    {
158
-        self::$_instance->_req_type = null;
159
-        //make sure none of the old hooks are left hanging around
160
-        remove_all_actions('AHEE__EE_System__perform_activations_upgrades_and_migrations');
161
-        //we need to reset the migration manager in order for it to detect DMSs properly
162
-        EE_Data_Migration_Manager::reset();
163
-        self::instance()->detect_activations_or_upgrades();
164
-        self::instance()->perform_activations_upgrades_and_migrations();
165
-        return self::instance();
166
-    }
167
-
168
-
169
-
170
-    /**
171
-     * sets hooks for running rest of system
172
-     * provides "AHEE__EE_System__construct__complete" hook for EE Addons to use as their starting point
173
-     * starting EE Addons from any other point may lead to problems
174
-     *
175
-     * @param EE_Registry         $registry
176
-     * @param LoaderInterface     $loader
177
-     * @param RequestInterface          $request
178
-     * @param EE_Maintenance_Mode $maintenance_mode
179
-     */
180
-    private function __construct(
181
-        EE_Registry $registry,
182
-        LoaderInterface $loader,
183
-        RequestInterface $request,
184
-        EE_Maintenance_Mode $maintenance_mode
185
-    ) {
186
-        $this->registry         = $registry;
187
-        $this->loader           = $loader;
188
-        $this->request          = $request;
189
-        $this->maintenance_mode = $maintenance_mode;
190
-        do_action('AHEE__EE_System__construct__begin', $this);
191
-        add_action(
192
-            'AHEE__EE_Bootstrap__load_espresso_addons',
193
-            array($this, 'loadCapabilities'),
194
-            5
195
-        );
196
-        add_action(
197
-            'AHEE__EE_Bootstrap__load_espresso_addons',
198
-            array($this, 'loadCommandBus'),
199
-            7
200
-        );
201
-        add_action(
202
-            'AHEE__EE_Bootstrap__load_espresso_addons',
203
-            array($this, 'loadPluginApi'),
204
-            9
205
-        );
206
-        // allow addons to load first so that they can register autoloaders, set hooks for running DMS's, etc
207
-        add_action(
208
-            'AHEE__EE_Bootstrap__load_espresso_addons',
209
-            array($this, 'load_espresso_addons')
210
-        );
211
-        // when an ee addon is activated, we want to call the core hook(s) again
212
-        // because the newly-activated addon didn't get a chance to run at all
213
-        add_action('activate_plugin', array($this, 'load_espresso_addons'), 1);
214
-        // detect whether install or upgrade
215
-        add_action(
216
-            'AHEE__EE_Bootstrap__detect_activations_or_upgrades',
217
-            array($this, 'detect_activations_or_upgrades'),
218
-            3
219
-        );
220
-        // load EE_Config, EE_Textdomain, etc
221
-        add_action(
222
-            'AHEE__EE_Bootstrap__load_core_configuration',
223
-            array($this, 'load_core_configuration'),
224
-            5
225
-        );
226
-        // load EE_Config, EE_Textdomain, etc
227
-        add_action(
228
-            'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets',
229
-            array($this, 'register_shortcodes_modules_and_widgets'),
230
-            7
231
-        );
232
-        // you wanna get going? I wanna get going... let's get going!
233
-        add_action(
234
-            'AHEE__EE_Bootstrap__brew_espresso',
235
-            array($this, 'brew_espresso'),
236
-            9
237
-        );
238
-        //other housekeeping
239
-        //exclude EE critical pages from wp_list_pages
240
-        add_filter(
241
-            'wp_list_pages_excludes',
242
-            array($this, 'remove_pages_from_wp_list_pages'),
243
-            10
244
-        );
245
-        // ALL EE Addons should use the following hook point to attach their initial setup too
246
-        // it's extremely important for EE Addons to register any class autoloaders so that they can be available when the EE_Config loads
247
-        do_action('AHEE__EE_System__construct__complete', $this);
248
-    }
249
-
250
-
251
-    /**
252
-     * load and setup EE_Capabilities
253
-     *
254
-     * @return void
255
-     * @throws EE_Error
256
-     */
257
-    public function loadCapabilities()
258
-    {
259
-        $this->capabilities = $this->loader->getShared('EE_Capabilities');
260
-        add_action(
261
-            'AHEE__EE_Capabilities__init_caps__before_initialization',
262
-            function ()
263
-            {
264
-                LoaderFactory::getLoader()->getShared('EE_Payment_Method_Manager');
265
-            }
266
-        );
267
-    }
268
-
269
-
270
-
271
-    /**
272
-     * create and cache the CommandBus, and also add middleware
273
-     * The CapChecker middleware requires the use of EE_Capabilities
274
-     * which is why we need to load the CommandBus after Caps are set up
275
-     *
276
-     * @return void
277
-     * @throws EE_Error
278
-     */
279
-    public function loadCommandBus()
280
-    {
281
-        $this->loader->getShared(
282
-            'CommandBusInterface',
283
-            array(
284
-                null,
285
-                apply_filters(
286
-                    'FHEE__EE_Load_Espresso_Core__handle_request__CommandBus_middleware',
287
-                    array(
288
-                        $this->loader->getShared('EventEspresso\core\services\commands\middleware\CapChecker'),
289
-                        $this->loader->getShared('EventEspresso\core\services\commands\middleware\AddActionHook'),
290
-                    )
291
-                ),
292
-            )
293
-        );
294
-    }
295
-
296
-
297
-
298
-    /**
299
-     * @return void
300
-     * @throws EE_Error
301
-     */
302
-    public function loadPluginApi()
303
-    {
304
-        // set autoloaders for all of the classes implementing EEI_Plugin_API
305
-        // which provide helpers for EE plugin authors to more easily register certain components with EE.
306
-        EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'plugin_api');
307
-        $this->loader->getShared('EE_Request_Handler');
308
-    }
309
-
310
-
311
-    /**
312
-     * @param string $addon_name
313
-     * @param string $version_constant
314
-     * @param string $min_version_required
315
-     * @param string $load_callback
316
-     * @param string $plugin_file_constant
317
-     * @return void
318
-     */
319
-    private function deactivateIncompatibleAddon(
320
-        $addon_name,
321
-        $version_constant,
322
-        $min_version_required,
323
-        $load_callback,
324
-        $plugin_file_constant
325
-    ) {
326
-        if (! defined($version_constant)) {
327
-            return;
328
-        }
329
-        $addon_version = constant($version_constant);
330
-        if ($addon_version && version_compare($addon_version, $min_version_required, '<')) {
331
-            remove_action('AHEE__EE_System__load_espresso_addons', $load_callback);
332
-            if (! function_exists('deactivate_plugins')) {
333
-                require_once ABSPATH . 'wp-admin/includes/plugin.php';
334
-            }
335
-            deactivate_plugins(plugin_basename(constant($plugin_file_constant)));
336
-            unset($_GET['activate'], $_REQUEST['activate'], $_GET['activate-multi'], $_REQUEST['activate-multi']);
337
-            EE_Error::add_error(
338
-                sprintf(
339
-                    esc_html__(
340
-                        'We\'re sorry, but the Event Espresso %1$s addon was deactivated because version %2$s or higher is required with this version of Event Espresso core.',
341
-                        'event_espresso'
342
-                    ),
343
-                    $addon_name,
344
-                    $min_version_required
345
-                ),
346
-                __FILE__, __FUNCTION__ . "({$addon_name})", __LINE__
347
-            );
348
-            EE_Error::get_notices(false, true);
349
-        }
350
-    }
351
-
352
-
353
-    /**
354
-     * load_espresso_addons
355
-     * allow addons to load first so that they can set hooks for running DMS's, etc
356
-     * this is hooked into both:
357
-     *    'AHEE__EE_Bootstrap__load_core_configuration'
358
-     *        which runs during the WP 'plugins_loaded' action at priority 5
359
-     *    and the WP 'activate_plugin' hook point
360
-     *
361
-     * @access public
362
-     * @return void
363
-     */
364
-    public function load_espresso_addons()
365
-    {
366
-        $this->deactivateIncompatibleAddon(
367
-            'Wait Lists',
368
-            'EE_WAIT_LISTS_VERSION',
369
-            '1.0.0.beta.074',
370
-            'load_espresso_wait_lists',
371
-            'EE_WAIT_LISTS_PLUGIN_FILE'
372
-        );
373
-        $this->deactivateIncompatibleAddon(
374
-            'Automated Upcoming Event Notifications',
375
-            'EE_AUTOMATED_UPCOMING_EVENT_NOTIFICATION_VERSION',
376
-            '1.0.0.beta.091',
377
-            'load_espresso_automated_upcoming_event_notification',
378
-            'EE_AUTOMATED_UPCOMING_EVENT_NOTIFICATION_PLUGIN_FILE'
379
-        );
380
-        do_action('AHEE__EE_System__load_espresso_addons');
381
-        //if the WP API basic auth plugin isn't already loaded, load it now.
382
-        //We want it for mobile apps. Just include the entire plugin
383
-        //also, don't load the basic auth when a plugin is getting activated, because
384
-        //it could be the basic auth plugin, and it doesn't check if its methods are already defined
385
-        //and causes a fatal error
386
-        if (
387
-            $this->request->getRequestParam('activate') !== 'true'
388
-            && ! function_exists('json_basic_auth_handler')
389
-            && ! function_exists('json_basic_auth_error')
390
-            && ! in_array(
391
-                $this->request->getRequestParam('action'),
392
-                array('activate', 'activate-selected'),
393
-                true
394
-            )
395
-        ) {
396
-            include_once EE_THIRD_PARTY . 'wp-api-basic-auth' . DS . 'basic-auth.php';
397
-        }
398
-        do_action('AHEE__EE_System__load_espresso_addons__complete');
399
-    }
400
-
401
-
402
-
403
-    /**
404
-     * detect_activations_or_upgrades
405
-     * Checks for activation or upgrade of core first;
406
-     * then also checks if any registered addons have been activated or upgraded
407
-     * This is hooked into 'AHEE__EE_Bootstrap__detect_activations_or_upgrades'
408
-     * which runs during the WP 'plugins_loaded' action at priority 3
409
-     *
410
-     * @access public
411
-     * @return void
412
-     */
413
-    public function detect_activations_or_upgrades()
414
-    {
415
-        //first off: let's make sure to handle core
416
-        $this->detect_if_activation_or_upgrade();
417
-        foreach ($this->registry->addons as $addon) {
418
-            if ($addon instanceof EE_Addon) {
419
-                //detect teh request type for that addon
420
-                $addon->detect_activation_or_upgrade();
421
-            }
422
-        }
423
-    }
424
-
425
-
426
-
427
-    /**
428
-     * detect_if_activation_or_upgrade
429
-     * Takes care of detecting whether this is a brand new install or code upgrade,
430
-     * and either setting up the DB or setting up maintenance mode etc.
431
-     *
432
-     * @access public
433
-     * @return void
434
-     */
435
-    public function detect_if_activation_or_upgrade()
436
-    {
437
-        do_action('AHEE__EE_System___detect_if_activation_or_upgrade__begin');
438
-        // check if db has been updated, or if its a brand-new installation
439
-        $espresso_db_update = $this->fix_espresso_db_upgrade_option();
440
-        $request_type       = $this->detect_req_type($espresso_db_update);
441
-        //EEH_Debug_Tools::printr( $request_type, '$request_type', __FILE__, __LINE__ );
442
-        switch ($request_type) {
443
-            case EE_System::req_type_new_activation:
444
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__new_activation');
445
-                $this->_handle_core_version_change($espresso_db_update);
446
-                break;
447
-            case EE_System::req_type_reactivation:
448
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__reactivation');
449
-                $this->_handle_core_version_change($espresso_db_update);
450
-                break;
451
-            case EE_System::req_type_upgrade:
452
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__upgrade');
453
-                //migrations may be required now that we've upgraded
454
-                $this->maintenance_mode->set_maintenance_mode_if_db_old();
455
-                $this->_handle_core_version_change($espresso_db_update);
456
-                //				echo "done upgrade";die;
457
-                break;
458
-            case EE_System::req_type_downgrade:
459
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__downgrade');
460
-                //its possible migrations are no longer required
461
-                $this->maintenance_mode->set_maintenance_mode_if_db_old();
462
-                $this->_handle_core_version_change($espresso_db_update);
463
-                break;
464
-            case EE_System::req_type_normal:
465
-            default:
466
-                break;
467
-        }
468
-        do_action('AHEE__EE_System__detect_if_activation_or_upgrade__complete');
469
-    }
470
-
471
-
472
-
473
-    /**
474
-     * Updates the list of installed versions and sets hooks for
475
-     * initializing the database later during the request
476
-     *
477
-     * @param array $espresso_db_update
478
-     */
479
-    private function _handle_core_version_change($espresso_db_update)
480
-    {
481
-        $this->update_list_of_installed_versions($espresso_db_update);
482
-        //get ready to verify the DB is ok (provided we aren't in maintenance mode, of course)
483
-        add_action(
484
-            'AHEE__EE_System__perform_activations_upgrades_and_migrations',
485
-            array($this, 'initialize_db_if_no_migrations_required')
486
-        );
487
-    }
488
-
489
-
490
-
491
-    /**
492
-     * standardizes the wp option 'espresso_db_upgrade' which actually stores
493
-     * information about what versions of EE have been installed and activated,
494
-     * NOT necessarily the state of the database
495
-     *
496
-     * @param mixed $espresso_db_update           the value of the WordPress option.
497
-     *                                            If not supplied, fetches it from the options table
498
-     * @return array the correct value of 'espresso_db_upgrade', after saving it, if it needed correction
499
-     */
500
-    private function fix_espresso_db_upgrade_option($espresso_db_update = null)
501
-    {
502
-        do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__begin', $espresso_db_update);
503
-        if (! $espresso_db_update) {
504
-            $espresso_db_update = get_option('espresso_db_update');
505
-        }
506
-        // check that option is an array
507
-        if (! is_array($espresso_db_update)) {
508
-            // if option is FALSE, then it never existed
509
-            if ($espresso_db_update === false) {
510
-                // make $espresso_db_update an array and save option with autoload OFF
511
-                $espresso_db_update = array();
512
-                add_option('espresso_db_update', $espresso_db_update, '', 'no');
513
-            } else {
514
-                // option is NOT FALSE but also is NOT an array, so make it an array and save it
515
-                $espresso_db_update = array($espresso_db_update => array());
516
-                update_option('espresso_db_update', $espresso_db_update);
517
-            }
518
-        } else {
519
-            $corrected_db_update = array();
520
-            //if IS an array, but is it an array where KEYS are version numbers, and values are arrays?
521
-            foreach ($espresso_db_update as $should_be_version_string => $should_be_array) {
522
-                if (is_int($should_be_version_string) && ! is_array($should_be_array)) {
523
-                    //the key is an int, and the value IS NOT an array
524
-                    //so it must be numerically-indexed, where values are versions installed...
525
-                    //fix it!
526
-                    $version_string                         = $should_be_array;
527
-                    $corrected_db_update[ $version_string ] = array('unknown-date');
528
-                } else {
529
-                    //ok it checks out
530
-                    $corrected_db_update[ $should_be_version_string ] = $should_be_array;
531
-                }
532
-            }
533
-            $espresso_db_update = $corrected_db_update;
534
-            update_option('espresso_db_update', $espresso_db_update);
535
-        }
536
-        do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__complete', $espresso_db_update);
537
-        return $espresso_db_update;
538
-    }
539
-
540
-
541
-
542
-    /**
543
-     * Does the traditional work of setting up the plugin's database and adding default data.
544
-     * If migration script/process did not exist, this is what would happen on every activation/reactivation/upgrade.
545
-     * NOTE: if we're in maintenance mode (which would be the case if we detect there are data
546
-     * migration scripts that need to be run and a version change happens), enqueues core for database initialization,
547
-     * so that it will be done when migrations are finished
548
-     *
549
-     * @param boolean $initialize_addons_too if true, we double-check addons' database tables etc too;
550
-     * @param boolean $verify_schema         if true will re-check the database tables have the correct schema.
551
-     *                                       This is a resource-intensive job
552
-     *                                       so we prefer to only do it when necessary
553
-     * @return void
554
-     * @throws EE_Error
555
-     */
556
-    public function initialize_db_if_no_migrations_required($initialize_addons_too = false, $verify_schema = true)
557
-    {
558
-        $request_type = $this->detect_req_type();
559
-        //only initialize system if we're not in maintenance mode.
560
-        if ($this->maintenance_mode->level() !== EE_Maintenance_Mode::level_2_complete_maintenance) {
561
-            update_option('ee_flush_rewrite_rules', true);
562
-            if ($verify_schema) {
563
-                EEH_Activation::initialize_db_and_folders();
564
-            }
565
-            EEH_Activation::initialize_db_content();
566
-            EEH_Activation::system_initialization();
567
-            if ($initialize_addons_too) {
568
-                $this->initialize_addons();
569
-            }
570
-        } else {
571
-            EE_Data_Migration_Manager::instance()->enqueue_db_initialization_for('Core');
572
-        }
573
-        if ($request_type === EE_System::req_type_new_activation
574
-            || $request_type === EE_System::req_type_reactivation
575
-            || (
576
-                $request_type === EE_System::req_type_upgrade
577
-                && $this->is_major_version_change()
578
-            )
579
-        ) {
580
-            add_action('AHEE__EE_System__initialize_last', array($this, 'redirect_to_about_ee'), 9);
581
-        }
582
-    }
583
-
584
-
585
-
586
-    /**
587
-     * Initializes the db for all registered addons
588
-     *
589
-     * @throws EE_Error
590
-     */
591
-    public function initialize_addons()
592
-    {
593
-        //foreach registered addon, make sure its db is up-to-date too
594
-        foreach ($this->registry->addons as $addon) {
595
-            if ($addon instanceof EE_Addon) {
596
-                $addon->initialize_db_if_no_migrations_required();
597
-            }
598
-        }
599
-    }
600
-
601
-
602
-
603
-    /**
604
-     * Adds the current code version to the saved wp option which stores a list of all ee versions ever installed.
605
-     *
606
-     * @param    array  $version_history
607
-     * @param    string $current_version_to_add version to be added to the version history
608
-     * @return    boolean success as to whether or not this option was changed
609
-     */
610
-    public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null)
611
-    {
612
-        if (! $version_history) {
613
-            $version_history = $this->fix_espresso_db_upgrade_option($version_history);
614
-        }
615
-        if ($current_version_to_add === null) {
616
-            $current_version_to_add = espresso_version();
617
-        }
618
-        $version_history[ $current_version_to_add ][] = date('Y-m-d H:i:s', time());
619
-        // re-save
620
-        return update_option('espresso_db_update', $version_history);
621
-    }
622
-
623
-
624
-
625
-    /**
626
-     * Detects if the current version indicated in the has existed in the list of
627
-     * previously-installed versions of EE (espresso_db_update). Does NOT modify it (ie, no side-effect)
628
-     *
629
-     * @param array $espresso_db_update array from the wp option stored under the name 'espresso_db_update'.
630
-     *                                  If not supplied, fetches it from the options table.
631
-     *                                  Also, caches its result so later parts of the code can also know whether
632
-     *                                  there's been an update or not. This way we can add the current version to
633
-     *                                  espresso_db_update, but still know if this is a new install or not
634
-     * @return int one of the constants on EE_System::req_type_
635
-     */
636
-    public function detect_req_type($espresso_db_update = null)
637
-    {
638
-        if ($this->_req_type === null) {
639
-            $espresso_db_update          = ! empty($espresso_db_update)
640
-                ? $espresso_db_update
641
-                : $this->fix_espresso_db_upgrade_option();
642
-            $this->_req_type             = EE_System::detect_req_type_given_activation_history(
643
-                $espresso_db_update,
644
-                'ee_espresso_activation', espresso_version()
645
-            );
646
-            $this->_major_version_change = $this->_detect_major_version_change($espresso_db_update);
647
-            $this->request->setIsActivation($this->_req_type !== EE_System::req_type_normal);
648
-        }
649
-        return $this->_req_type;
650
-    }
651
-
652
-
653
-
654
-    /**
655
-     * Returns whether or not there was a non-micro version change (ie, change in either
656
-     * the first or second number in the version. Eg 4.9.0.rc.001 to 4.10.0.rc.000,
657
-     * but not 4.9.0.rc.0001 to 4.9.1.rc.0001
658
-     *
659
-     * @param $activation_history
660
-     * @return bool
661
-     */
662
-    private function _detect_major_version_change($activation_history)
663
-    {
664
-        $previous_version       = EE_System::_get_most_recently_active_version_from_activation_history($activation_history);
665
-        $previous_version_parts = explode('.', $previous_version);
666
-        $current_version_parts  = explode('.', espresso_version());
667
-        return isset($previous_version_parts[0], $previous_version_parts[1], $current_version_parts[0], $current_version_parts[1])
668
-               && ($previous_version_parts[0] !== $current_version_parts[0]
669
-                   || $previous_version_parts[1] !== $current_version_parts[1]
670
-               );
671
-    }
672
-
673
-
674
-
675
-    /**
676
-     * Returns true if either the major or minor version of EE changed during this request.
677
-     * 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
678
-     *
679
-     * @return bool
680
-     */
681
-    public function is_major_version_change()
682
-    {
683
-        return $this->_major_version_change;
684
-    }
685
-
686
-
687
-
688
-    /**
689
-     * Determines the request type for any ee addon, given three piece of info: the current array of activation
690
-     * histories (for core that' 'espresso_db_update' wp option); the name of the WordPress option which is temporarily
691
-     * set upon activation of the plugin (for core it's 'ee_espresso_activation'); and the version that this plugin was
692
-     * just activated to (for core that will always be espresso_version())
693
-     *
694
-     * @param array  $activation_history_for_addon     the option's value which stores the activation history for this
695
-     *                                                 ee plugin. for core that's 'espresso_db_update'
696
-     * @param string $activation_indicator_option_name the name of the WordPress option that is temporarily set to
697
-     *                                                 indicate that this plugin was just activated
698
-     * @param string $version_to_upgrade_to            the version that was just upgraded to (for core that will be
699
-     *                                                 espresso_version())
700
-     * @return int one of the constants on EE_System::req_type_*
701
-     */
702
-    public static function detect_req_type_given_activation_history(
703
-        $activation_history_for_addon,
704
-        $activation_indicator_option_name,
705
-        $version_to_upgrade_to
706
-    ) {
707
-        $version_is_higher = self::_new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to);
708
-        if ($activation_history_for_addon) {
709
-            //it exists, so this isn't a completely new install
710
-            //check if this version already in that list of previously installed versions
711
-            if (! isset($activation_history_for_addon[ $version_to_upgrade_to ])) {
712
-                //it a version we haven't seen before
713
-                if ($version_is_higher === 1) {
714
-                    $req_type = EE_System::req_type_upgrade;
715
-                } else {
716
-                    $req_type = EE_System::req_type_downgrade;
717
-                }
718
-                delete_option($activation_indicator_option_name);
719
-            } else {
720
-                // its not an update. maybe a reactivation?
721
-                if (get_option($activation_indicator_option_name, false)) {
722
-                    if ($version_is_higher === -1) {
723
-                        $req_type = EE_System::req_type_downgrade;
724
-                    } elseif ($version_is_higher === 0) {
725
-                        //we've seen this version before, but it's an activation. must be a reactivation
726
-                        $req_type = EE_System::req_type_reactivation;
727
-                    } else {//$version_is_higher === 1
728
-                        $req_type = EE_System::req_type_upgrade;
729
-                    }
730
-                    delete_option($activation_indicator_option_name);
731
-                } else {
732
-                    //we've seen this version before and the activation indicate doesn't show it was just activated
733
-                    if ($version_is_higher === -1) {
734
-                        $req_type = EE_System::req_type_downgrade;
735
-                    } elseif ($version_is_higher === 0) {
736
-                        //we've seen this version before and it's not an activation. its normal request
737
-                        $req_type = EE_System::req_type_normal;
738
-                    } else {//$version_is_higher === 1
739
-                        $req_type = EE_System::req_type_upgrade;
740
-                    }
741
-                }
742
-            }
743
-        } else {
744
-            //brand new install
745
-            $req_type = EE_System::req_type_new_activation;
746
-            delete_option($activation_indicator_option_name);
747
-        }
748
-        return $req_type;
749
-    }
750
-
751
-
752
-
753
-    /**
754
-     * Detects if the $version_to_upgrade_to is higher than the most recent version in
755
-     * the $activation_history_for_addon
756
-     *
757
-     * @param array  $activation_history_for_addon (keys are versions, values are arrays of times activated,
758
-     *                                             sometimes containing 'unknown-date'
759
-     * @param string $version_to_upgrade_to        (current version)
760
-     * @return int results of version_compare( $version_to_upgrade_to, $most_recently_active_version ).
761
-     *                                             ie, -1 if $version_to_upgrade_to is LOWER (downgrade);
762
-     *                                             0 if $version_to_upgrade_to MATCHES (reactivation or normal request);
763
-     *                                             1 if $version_to_upgrade_to is HIGHER (upgrade) ;
764
-     */
765
-    private static function _new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to)
766
-    {
767
-        //find the most recently-activated version
768
-        $most_recently_active_version =
769
-            EE_System::_get_most_recently_active_version_from_activation_history($activation_history_for_addon);
770
-        return version_compare($version_to_upgrade_to, $most_recently_active_version);
771
-    }
772
-
773
-
774
-
775
-    /**
776
-     * Gets the most recently active version listed in the activation history,
777
-     * and if none are found (ie, it's a brand new install) returns '0.0.0.dev.000'.
778
-     *
779
-     * @param array $activation_history  (keys are versions, values are arrays of times activated,
780
-     *                                   sometimes containing 'unknown-date'
781
-     * @return string
782
-     */
783
-    private static function _get_most_recently_active_version_from_activation_history($activation_history)
784
-    {
785
-        $most_recently_active_version_activation = '1970-01-01 00:00:00';
786
-        $most_recently_active_version            = '0.0.0.dev.000';
787
-        if (is_array($activation_history)) {
788
-            foreach ($activation_history as $version => $times_activated) {
789
-                //check there is a record of when this version was activated. Otherwise,
790
-                //mark it as unknown
791
-                if (! $times_activated) {
792
-                    $times_activated = array('unknown-date');
793
-                }
794
-                if (is_string($times_activated)) {
795
-                    $times_activated = array($times_activated);
796
-                }
797
-                foreach ($times_activated as $an_activation) {
798
-                    if ($an_activation !== 'unknown-date'
799
-                        && $an_activation
800
-                           > $most_recently_active_version_activation) {
801
-                        $most_recently_active_version            = $version;
802
-                        $most_recently_active_version_activation = $an_activation === 'unknown-date'
803
-                            ? '1970-01-01 00:00:00'
804
-                            : $an_activation;
805
-                    }
806
-                }
807
-            }
808
-        }
809
-        return $most_recently_active_version;
810
-    }
811
-
812
-
813
-
814
-    /**
815
-     * This redirects to the about EE page after activation
816
-     *
817
-     * @return void
818
-     */
819
-    public function redirect_to_about_ee()
820
-    {
821
-        $notices = EE_Error::get_notices(false);
822
-        //if current user is an admin and it's not an ajax or rest request
823
-        if (
824
-            ! isset($notices['errors'])
825
-            && $this->request->isAdmin()
826
-            && apply_filters(
827
-                'FHEE__EE_System__redirect_to_about_ee__do_redirect',
828
-                $this->capabilities->current_user_can('manage_options', 'espresso_about_default')
829
-            )
830
-        ) {
831
-            $query_params = array('page' => 'espresso_about');
832
-            if (EE_System::instance()->detect_req_type() === EE_System::req_type_new_activation) {
833
-                $query_params['new_activation'] = true;
834
-            }
835
-            if (EE_System::instance()->detect_req_type() === EE_System::req_type_reactivation) {
836
-                $query_params['reactivation'] = true;
837
-            }
838
-            $url = add_query_arg($query_params, admin_url('admin.php'));
839
-            wp_safe_redirect($url);
840
-            exit();
841
-        }
842
-    }
843
-
844
-
845
-
846
-    /**
847
-     * load_core_configuration
848
-     * this is hooked into 'AHEE__EE_Bootstrap__load_core_configuration'
849
-     * which runs during the WP 'plugins_loaded' action at priority 5
850
-     *
851
-     * @return void
852
-     * @throws ReflectionException
853
-     */
854
-    public function load_core_configuration()
855
-    {
856
-        do_action('AHEE__EE_System__load_core_configuration__begin', $this);
857
-        $this->loader->getShared('EE_Load_Textdomain');
858
-        //load textdomain
859
-        EE_Load_Textdomain::load_textdomain();
860
-        // load and setup EE_Config and EE_Network_Config
861
-        $config = $this->loader->getShared('EE_Config');
862
-        $this->loader->getShared('EE_Network_Config');
863
-        // setup autoloaders
864
-        // enable logging?
865
-        if ($config->admin->use_full_logging) {
866
-            $this->loader->getShared('EE_Log');
867
-        }
868
-        // check for activation errors
869
-        $activation_errors = get_option('ee_plugin_activation_errors', false);
870
-        if ($activation_errors) {
871
-            EE_Error::add_error($activation_errors, __FILE__, __FUNCTION__, __LINE__);
872
-            update_option('ee_plugin_activation_errors', false);
873
-        }
874
-        // get model names
875
-        $this->_parse_model_names();
876
-        //load caf stuff a chance to play during the activation process too.
877
-        $this->_maybe_brew_regular();
878
-        do_action('AHEE__EE_System__load_core_configuration__complete', $this);
879
-    }
880
-
881
-
882
-
883
-    /**
884
-     * cycles through all of the models/*.model.php files, and assembles an array of model names
885
-     *
886
-     * @return void
887
-     * @throws ReflectionException
888
-     */
889
-    private function _parse_model_names()
890
-    {
891
-        //get all the files in the EE_MODELS folder that end in .model.php
892
-        $models                 = glob(EE_MODELS . '*.model.php');
893
-        $model_names            = array();
894
-        $non_abstract_db_models = array();
895
-        foreach ($models as $model) {
896
-            // get model classname
897
-            $classname       = EEH_File::get_classname_from_filepath_with_standard_filename($model);
898
-            $short_name      = str_replace('EEM_', '', $classname);
899
-            $reflectionClass = new ReflectionClass($classname);
900
-            if ($reflectionClass->isSubclassOf('EEM_Base') && ! $reflectionClass->isAbstract()) {
901
-                $non_abstract_db_models[ $short_name ] = $classname;
902
-            }
903
-            $model_names[ $short_name ] = $classname;
904
-        }
905
-        $this->registry->models                 = apply_filters('FHEE__EE_System__parse_model_names', $model_names);
906
-        $this->registry->non_abstract_db_models = apply_filters(
907
-            'FHEE__EE_System__parse_implemented_model_names',
908
-            $non_abstract_db_models
909
-        );
910
-    }
911
-
912
-
913
-
914
-    /**
915
-     * The purpose of this method is to simply check for a file named "caffeinated/brewing_regular.php" for any hooks
916
-     * that need to be setup before our EE_System launches.
917
-     *
918
-     * @return void
919
-     */
920
-    private function _maybe_brew_regular()
921
-    {
922
-        if ((! defined('EE_DECAF') || EE_DECAF !== true) && is_readable(EE_CAFF_PATH . 'brewing_regular.php')) {
923
-            require_once EE_CAFF_PATH . 'brewing_regular.php';
924
-        }
925
-    }
926
-
927
-
928
-
929
-    /**
930
-     * register_shortcodes_modules_and_widgets
931
-     * generate lists of shortcodes and modules, then verify paths and classes
932
-     * This is hooked into 'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets'
933
-     * which runs during the WP 'plugins_loaded' action at priority 7
934
-     *
935
-     * @access public
936
-     * @return void
937
-     * @throws Exception
938
-     */
939
-    public function register_shortcodes_modules_and_widgets()
940
-    {
941
-        if ($this->request->isFrontend() || $this->request->isIframe()) {
942
-            try {
943
-                // load, register, and add shortcodes the new way
944
-                $this->loader->getShared(
945
-                    'EventEspresso\core\services\shortcodes\ShortcodesManager',
946
-                    array(
947
-                        // and the old way, but we'll put it under control of the new system
948
-                        EE_Config::getLegacyShortcodesManager(),
949
-                    )
950
-                );
951
-            } catch (Exception $exception) {
952
-                new ExceptionStackTraceDisplay($exception);
953
-            }
954
-        }
955
-        do_action('AHEE__EE_System__register_shortcodes_modules_and_widgets');
956
-        // check for addons using old hook point
957
-        if (has_action('AHEE__EE_System__register_shortcodes_modules_and_addons')) {
958
-            $this->_incompatible_addon_error();
959
-        }
960
-    }
961
-
962
-
963
-
964
-    /**
965
-     * _incompatible_addon_error
966
-     *
967
-     * @access public
968
-     * @return void
969
-     */
970
-    private function _incompatible_addon_error()
971
-    {
972
-        // get array of classes hooking into here
973
-        $class_names = EEH_Class_Tools::get_class_names_for_all_callbacks_on_hook(
974
-            'AHEE__EE_System__register_shortcodes_modules_and_addons'
975
-        );
976
-        if (! empty($class_names)) {
977
-            $msg = __(
978
-                'The following plugins, addons, or modules appear to be incompatible with this version of Event Espresso and were automatically deactivated to avoid fatal errors:',
979
-                'event_espresso'
980
-            );
981
-            $msg .= '<ul>';
982
-            foreach ($class_names as $class_name) {
983
-                $msg .= '<li><b>Event Espresso - ' . str_replace(
984
-                        array('EE_', 'EEM_', 'EED_', 'EES_', 'EEW_'), '',
985
-                        $class_name
986
-                    ) . '</b></li>';
987
-            }
988
-            $msg .= '</ul>';
989
-            $msg .= __(
990
-                'Compatibility issues can be avoided and/or resolved by keeping addons and plugins updated to the latest version.',
991
-                'event_espresso'
992
-            );
993
-            // save list of incompatible addons to wp-options for later use
994
-            add_option('ee_incompatible_addons', $class_names, '', 'no');
995
-            if (is_admin()) {
996
-                EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
997
-            }
998
-        }
999
-    }
1000
-
1001
-
1002
-
1003
-    /**
1004
-     * brew_espresso
1005
-     * begins the process of setting hooks for initializing EE in the correct order
1006
-     * This is happening on the 'AHEE__EE_Bootstrap__brew_espresso' hook point
1007
-     * which runs during the WP 'plugins_loaded' action at priority 9
1008
-     *
1009
-     * @return void
1010
-     */
1011
-    public function brew_espresso()
1012
-    {
1013
-        do_action('AHEE__EE_System__brew_espresso__begin', $this);
1014
-        // load some final core systems
1015
-        add_action('init', array($this, 'set_hooks_for_core'), 1);
1016
-        add_action('init', array($this, 'perform_activations_upgrades_and_migrations'), 3);
1017
-        add_action('init', array($this, 'load_CPTs_and_session'), 5);
1018
-        add_action('init', array($this, 'load_controllers'), 7);
1019
-        add_action('init', array($this, 'core_loaded_and_ready'), 9);
1020
-        add_action('init', array($this, 'initialize'), 10);
1021
-        add_action('init', array($this, 'initialize_last'), 100);
1022
-        if (is_admin() && apply_filters('FHEE__EE_System__brew_espresso__load_pue', true)) {
1023
-            // pew pew pew
1024
-            $this->loader->getShared('EventEspresso\core\services\licensing\LicenseService');
1025
-            do_action('AHEE__EE_System__brew_espresso__after_pue_init');
1026
-        }
1027
-        do_action('AHEE__EE_System__brew_espresso__complete', $this);
1028
-    }
1029
-
1030
-
1031
-
1032
-    /**
1033
-     *    set_hooks_for_core
1034
-     *
1035
-     * @access public
1036
-     * @return    void
1037
-     * @throws EE_Error
1038
-     */
1039
-    public function set_hooks_for_core()
1040
-    {
1041
-        $this->_deactivate_incompatible_addons();
1042
-        do_action('AHEE__EE_System__set_hooks_for_core');
1043
-        $this->loader->getShared('EventEspresso\core\domain\values\session\SessionLifespan');
1044
-        //caps need to be initialized on every request so that capability maps are set.
1045
-        //@see https://events.codebasehq.com/projects/event-espresso/tickets/8674
1046
-        $this->registry->CAP->init_caps();
1047
-    }
1048
-
1049
-
1050
-
1051
-    /**
1052
-     * Using the information gathered in EE_System::_incompatible_addon_error,
1053
-     * deactivates any addons considered incompatible with the current version of EE
1054
-     */
1055
-    private function _deactivate_incompatible_addons()
1056
-    {
1057
-        $incompatible_addons = get_option('ee_incompatible_addons', array());
1058
-        if (! empty($incompatible_addons)) {
1059
-            $active_plugins = get_option('active_plugins', array());
1060
-            foreach ($active_plugins as $active_plugin) {
1061
-                foreach ($incompatible_addons as $incompatible_addon) {
1062
-                    if (strpos($active_plugin, $incompatible_addon) !== false) {
1063
-                        unset($_GET['activate']);
1064
-                        espresso_deactivate_plugin($active_plugin);
1065
-                    }
1066
-                }
1067
-            }
1068
-        }
1069
-    }
1070
-
1071
-
1072
-
1073
-    /**
1074
-     *    perform_activations_upgrades_and_migrations
1075
-     *
1076
-     * @access public
1077
-     * @return    void
1078
-     */
1079
-    public function perform_activations_upgrades_and_migrations()
1080
-    {
1081
-        do_action('AHEE__EE_System__perform_activations_upgrades_and_migrations');
1082
-    }
1083
-
1084
-
1085
-
1086
-    /**
1087
-     *    load_CPTs_and_session
1088
-     *
1089
-     * @access public
1090
-     * @return    void
1091
-     */
1092
-    public function load_CPTs_and_session()
1093
-    {
1094
-        do_action('AHEE__EE_System__load_CPTs_and_session__start');
1095
-        // register Custom Post Types
1096
-        $this->loader->getShared('EE_Register_CPTs');
1097
-        do_action('AHEE__EE_System__load_CPTs_and_session__complete');
1098
-    }
1099
-
1100
-
1101
-
1102
-    /**
1103
-     * load_controllers
1104
-     * this is the best place to load any additional controllers that needs access to EE core.
1105
-     * it is expected that all basic core EE systems, that are not dependant on the current request are loaded at this
1106
-     * time
1107
-     *
1108
-     * @access public
1109
-     * @return void
1110
-     */
1111
-    public function load_controllers()
1112
-    {
1113
-        do_action('AHEE__EE_System__load_controllers__start');
1114
-        // let's get it started
1115
-        if (
1116
-            ! $this->maintenance_mode->level()
1117
-            && ($this->request->isFrontend() || $this->request->isFrontAjax())
1118
-        ) {
1119
-            do_action('AHEE__EE_System__load_controllers__load_front_controllers');
1120
-            $this->loader->getShared('EE_Front_Controller');
1121
-        } elseif ($this->request->isAdmin() || $this->request->isAdminAjax()) {
1122
-            do_action('AHEE__EE_System__load_controllers__load_admin_controllers');
1123
-            $this->loader->getShared('EE_Admin');
1124
-        }
1125
-        do_action('AHEE__EE_System__load_controllers__complete');
1126
-    }
1127
-
1128
-
1129
-
1130
-    /**
1131
-     * core_loaded_and_ready
1132
-     * all of the basic EE core should be loaded at this point and available regardless of M-Mode
1133
-     *
1134
-     * @access public
1135
-     * @return void
1136
-     */
1137
-    public function core_loaded_and_ready()
1138
-    {
1139
-        if (
1140
-            $this->request->isAdmin()
1141
-            || $this->request->isEeAjax()
1142
-            || $this->request->isFrontend()
1143
-        ) {
1144
-            $this->loader->getShared('EE_Session');
1145
-        }
1146
-        do_action('AHEE__EE_System__core_loaded_and_ready');
1147
-        // load_espresso_template_tags
1148
-        if (
1149
-            is_readable(EE_PUBLIC . 'template_tags.php')
1150
-            && ($this->request->isFrontend() || $this->request->isIframe() || $this->request->isFeed())
1151
-        ) {
1152
-            require_once EE_PUBLIC . 'template_tags.php';
1153
-        }
1154
-        do_action('AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons');
1155
-        if ($this->request->isAdmin() || $this->request->isFrontend() || $this->request->isIframe()) {
1156
-            $this->loader->getShared('EventEspresso\core\services\assets\Registry');
1157
-        }
1158
-    }
1159
-
1160
-
1161
-
1162
-    /**
1163
-     * initialize
1164
-     * this is the best place to begin initializing client code
1165
-     *
1166
-     * @access public
1167
-     * @return void
1168
-     */
1169
-    public function initialize()
1170
-    {
1171
-        do_action('AHEE__EE_System__initialize');
1172
-    }
1173
-
1174
-
1175
-
1176
-    /**
1177
-     * initialize_last
1178
-     * this is run really late during the WP init hook point, and ensures that mostly everything else that needs to
1179
-     * initialize has done so
1180
-     *
1181
-     * @access public
1182
-     * @return void
1183
-     */
1184
-    public function initialize_last()
1185
-    {
1186
-        do_action('AHEE__EE_System__initialize_last');
1187
-        add_action('admin_bar_init', array($this, 'addEspressoToolbar'));
1188
-    }
1189
-
1190
-
1191
-
1192
-    /**
1193
-     * @return void
1194
-     * @throws EE_Error
1195
-     */
1196
-    public function addEspressoToolbar()
1197
-    {
1198
-        $this->loader->getShared(
1199
-            'EventEspresso\core\domain\services\admin\AdminToolBar',
1200
-            array($this->registry->CAP)
1201
-        );
1202
-    }
1203
-
1204
-
1205
-
1206
-    /**
1207
-     * do_not_cache
1208
-     * sets no cache headers and defines no cache constants for WP plugins
1209
-     *
1210
-     * @access public
1211
-     * @return void
1212
-     */
1213
-    public static function do_not_cache()
1214
-    {
1215
-        // set no cache constants
1216
-        if (! defined('DONOTCACHEPAGE')) {
1217
-            define('DONOTCACHEPAGE', true);
1218
-        }
1219
-        if (! defined('DONOTCACHCEOBJECT')) {
1220
-            define('DONOTCACHCEOBJECT', true);
1221
-        }
1222
-        if (! defined('DONOTCACHEDB')) {
1223
-            define('DONOTCACHEDB', true);
1224
-        }
1225
-        // add no cache headers
1226
-        add_action('send_headers', array('EE_System', 'nocache_headers'), 10);
1227
-        // plus a little extra for nginx and Google Chrome
1228
-        add_filter('nocache_headers', array('EE_System', 'extra_nocache_headers'), 10, 1);
1229
-        // prevent browsers from prefetching of the rel='next' link, because it may contain content that interferes with the registration process
1230
-        remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');
1231
-    }
1232
-
1233
-
1234
-
1235
-    /**
1236
-     *    extra_nocache_headers
1237
-     *
1238
-     * @access    public
1239
-     * @param $headers
1240
-     * @return    array
1241
-     */
1242
-    public static function extra_nocache_headers($headers)
1243
-    {
1244
-        // for NGINX
1245
-        $headers['X-Accel-Expires'] = 0;
1246
-        // plus extra for Google Chrome since it doesn't seem to respect "no-cache", but WILL respect "no-store"
1247
-        $headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0';
1248
-        return $headers;
1249
-    }
1250
-
1251
-
1252
-
1253
-    /**
1254
-     *    nocache_headers
1255
-     *
1256
-     * @access    public
1257
-     * @return    void
1258
-     */
1259
-    public static function nocache_headers()
1260
-    {
1261
-        nocache_headers();
1262
-    }
1263
-
1264
-
1265
-
1266
-    /**
1267
-     * simply hooks into "wp_list_pages_exclude" filter (for wp_list_pages method) and makes sure EE critical pages are
1268
-     * never returned with the function.
1269
-     *
1270
-     * @param  array $exclude_array any existing pages being excluded are in this array.
1271
-     * @return array
1272
-     */
1273
-    public function remove_pages_from_wp_list_pages($exclude_array)
1274
-    {
1275
-        return array_merge($exclude_array, $this->registry->CFG->core->get_critical_pages_array());
1276
-    }
27
+	/**
28
+	 * indicates this is a 'normal' request. Ie, not activation, nor upgrade, nor activation.
29
+	 * So examples of this would be a normal GET request on the frontend or backend, or a POST, etc
30
+	 */
31
+	const req_type_normal = 0;
32
+
33
+	/**
34
+	 * Indicates this is a brand new installation of EE so we should install
35
+	 * tables and default data etc
36
+	 */
37
+	const req_type_new_activation = 1;
38
+
39
+	/**
40
+	 * we've detected that EE has been reactivated (or EE was activated during maintenance mode,
41
+	 * and we just exited maintenance mode). We MUST check the database is setup properly
42
+	 * and that default data is setup too
43
+	 */
44
+	const req_type_reactivation = 2;
45
+
46
+	/**
47
+	 * indicates that EE has been upgraded since its previous request.
48
+	 * We may have data migration scripts to call and will want to trigger maintenance mode
49
+	 */
50
+	const req_type_upgrade = 3;
51
+
52
+	/**
53
+	 * TODO  will detect that EE has been DOWNGRADED. We probably don't want to run in this case...
54
+	 */
55
+	const req_type_downgrade = 4;
56
+
57
+	/**
58
+	 * @deprecated since version 4.6.0.dev.006
59
+	 * Now whenever a new_activation is detected the request type is still just
60
+	 * new_activation (same for reactivation, upgrade, downgrade etc), but if we'r ein maintenance mode
61
+	 * EE_System::initialize_db_if_no_migrations_required and EE_Addon::initialize_db_if_no_migrations_required
62
+	 * will instead enqueue that EE plugin's db initialization for when we're taken out of maintenance mode.
63
+	 * (Specifically, when the migration manager indicates migrations are finished
64
+	 * EE_Data_Migration_Manager::initialize_db_for_enqueued_ee_plugins() will be called)
65
+	 */
66
+	const req_type_activation_but_not_installed = 5;
67
+
68
+	/**
69
+	 * option prefix for recording the activation history (like core's "espresso_db_update") of addons
70
+	 */
71
+	const addon_activation_history_option_prefix = 'ee_addon_activation_history_';
72
+
73
+
74
+	/**
75
+	 * @var EE_System $_instance
76
+	 */
77
+	private static $_instance;
78
+
79
+	/**
80
+	 * @var EE_Registry $registry
81
+	 */
82
+	private $registry;
83
+
84
+	/**
85
+	 * @var LoaderInterface $loader
86
+	 */
87
+	private $loader;
88
+
89
+	/**
90
+	 * @var EE_Capabilities $capabilities
91
+	 */
92
+	private $capabilities;
93
+
94
+	/**
95
+	 * @var RequestInterface $request
96
+	 */
97
+	private $request;
98
+
99
+	/**
100
+	 * @var EE_Maintenance_Mode $maintenance_mode
101
+	 */
102
+	private $maintenance_mode;
103
+
104
+	/**
105
+	 * Stores which type of request this is, options being one of the constants on EE_System starting with req_type_*.
106
+	 * It can be a brand-new activation, a reactivation, an upgrade, a downgrade, or a normal request.
107
+	 *
108
+	 * @var int $_req_type
109
+	 */
110
+	private $_req_type;
111
+
112
+	/**
113
+	 * Whether or not there was a non-micro version change in EE core version during this request
114
+	 *
115
+	 * @var boolean $_major_version_change
116
+	 */
117
+	private $_major_version_change = false;
118
+
119
+	/**
120
+	 * A Context DTO dedicated solely to identifying the current request type.
121
+	 *
122
+	 * @var RequestTypeContextCheckerInterface $request_type
123
+	 */
124
+	private $request_type;
125
+
126
+
127
+
128
+	/**
129
+	 * @singleton method used to instantiate class object
130
+	 * @param EE_Registry|null         $registry
131
+	 * @param LoaderInterface|null     $loader
132
+	 * @param RequestInterface|null          $request
133
+	 * @param EE_Maintenance_Mode|null $maintenance_mode
134
+	 * @return EE_System
135
+	 */
136
+	public static function instance(
137
+		EE_Registry $registry = null,
138
+		LoaderInterface $loader = null,
139
+		RequestInterface $request = null,
140
+		EE_Maintenance_Mode $maintenance_mode = null
141
+	) {
142
+		// check if class object is instantiated
143
+		if (! self::$_instance instanceof EE_System) {
144
+			self::$_instance = new self($registry, $loader, $request, $maintenance_mode);
145
+		}
146
+		return self::$_instance;
147
+	}
148
+
149
+
150
+
151
+	/**
152
+	 * resets the instance and returns it
153
+	 *
154
+	 * @return EE_System
155
+	 */
156
+	public static function reset()
157
+	{
158
+		self::$_instance->_req_type = null;
159
+		//make sure none of the old hooks are left hanging around
160
+		remove_all_actions('AHEE__EE_System__perform_activations_upgrades_and_migrations');
161
+		//we need to reset the migration manager in order for it to detect DMSs properly
162
+		EE_Data_Migration_Manager::reset();
163
+		self::instance()->detect_activations_or_upgrades();
164
+		self::instance()->perform_activations_upgrades_and_migrations();
165
+		return self::instance();
166
+	}
167
+
168
+
169
+
170
+	/**
171
+	 * sets hooks for running rest of system
172
+	 * provides "AHEE__EE_System__construct__complete" hook for EE Addons to use as their starting point
173
+	 * starting EE Addons from any other point may lead to problems
174
+	 *
175
+	 * @param EE_Registry         $registry
176
+	 * @param LoaderInterface     $loader
177
+	 * @param RequestInterface          $request
178
+	 * @param EE_Maintenance_Mode $maintenance_mode
179
+	 */
180
+	private function __construct(
181
+		EE_Registry $registry,
182
+		LoaderInterface $loader,
183
+		RequestInterface $request,
184
+		EE_Maintenance_Mode $maintenance_mode
185
+	) {
186
+		$this->registry         = $registry;
187
+		$this->loader           = $loader;
188
+		$this->request          = $request;
189
+		$this->maintenance_mode = $maintenance_mode;
190
+		do_action('AHEE__EE_System__construct__begin', $this);
191
+		add_action(
192
+			'AHEE__EE_Bootstrap__load_espresso_addons',
193
+			array($this, 'loadCapabilities'),
194
+			5
195
+		);
196
+		add_action(
197
+			'AHEE__EE_Bootstrap__load_espresso_addons',
198
+			array($this, 'loadCommandBus'),
199
+			7
200
+		);
201
+		add_action(
202
+			'AHEE__EE_Bootstrap__load_espresso_addons',
203
+			array($this, 'loadPluginApi'),
204
+			9
205
+		);
206
+		// allow addons to load first so that they can register autoloaders, set hooks for running DMS's, etc
207
+		add_action(
208
+			'AHEE__EE_Bootstrap__load_espresso_addons',
209
+			array($this, 'load_espresso_addons')
210
+		);
211
+		// when an ee addon is activated, we want to call the core hook(s) again
212
+		// because the newly-activated addon didn't get a chance to run at all
213
+		add_action('activate_plugin', array($this, 'load_espresso_addons'), 1);
214
+		// detect whether install or upgrade
215
+		add_action(
216
+			'AHEE__EE_Bootstrap__detect_activations_or_upgrades',
217
+			array($this, 'detect_activations_or_upgrades'),
218
+			3
219
+		);
220
+		// load EE_Config, EE_Textdomain, etc
221
+		add_action(
222
+			'AHEE__EE_Bootstrap__load_core_configuration',
223
+			array($this, 'load_core_configuration'),
224
+			5
225
+		);
226
+		// load EE_Config, EE_Textdomain, etc
227
+		add_action(
228
+			'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets',
229
+			array($this, 'register_shortcodes_modules_and_widgets'),
230
+			7
231
+		);
232
+		// you wanna get going? I wanna get going... let's get going!
233
+		add_action(
234
+			'AHEE__EE_Bootstrap__brew_espresso',
235
+			array($this, 'brew_espresso'),
236
+			9
237
+		);
238
+		//other housekeeping
239
+		//exclude EE critical pages from wp_list_pages
240
+		add_filter(
241
+			'wp_list_pages_excludes',
242
+			array($this, 'remove_pages_from_wp_list_pages'),
243
+			10
244
+		);
245
+		// ALL EE Addons should use the following hook point to attach their initial setup too
246
+		// it's extremely important for EE Addons to register any class autoloaders so that they can be available when the EE_Config loads
247
+		do_action('AHEE__EE_System__construct__complete', $this);
248
+	}
249
+
250
+
251
+	/**
252
+	 * load and setup EE_Capabilities
253
+	 *
254
+	 * @return void
255
+	 * @throws EE_Error
256
+	 */
257
+	public function loadCapabilities()
258
+	{
259
+		$this->capabilities = $this->loader->getShared('EE_Capabilities');
260
+		add_action(
261
+			'AHEE__EE_Capabilities__init_caps__before_initialization',
262
+			function ()
263
+			{
264
+				LoaderFactory::getLoader()->getShared('EE_Payment_Method_Manager');
265
+			}
266
+		);
267
+	}
268
+
269
+
270
+
271
+	/**
272
+	 * create and cache the CommandBus, and also add middleware
273
+	 * The CapChecker middleware requires the use of EE_Capabilities
274
+	 * which is why we need to load the CommandBus after Caps are set up
275
+	 *
276
+	 * @return void
277
+	 * @throws EE_Error
278
+	 */
279
+	public function loadCommandBus()
280
+	{
281
+		$this->loader->getShared(
282
+			'CommandBusInterface',
283
+			array(
284
+				null,
285
+				apply_filters(
286
+					'FHEE__EE_Load_Espresso_Core__handle_request__CommandBus_middleware',
287
+					array(
288
+						$this->loader->getShared('EventEspresso\core\services\commands\middleware\CapChecker'),
289
+						$this->loader->getShared('EventEspresso\core\services\commands\middleware\AddActionHook'),
290
+					)
291
+				),
292
+			)
293
+		);
294
+	}
295
+
296
+
297
+
298
+	/**
299
+	 * @return void
300
+	 * @throws EE_Error
301
+	 */
302
+	public function loadPluginApi()
303
+	{
304
+		// set autoloaders for all of the classes implementing EEI_Plugin_API
305
+		// which provide helpers for EE plugin authors to more easily register certain components with EE.
306
+		EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'plugin_api');
307
+		$this->loader->getShared('EE_Request_Handler');
308
+	}
309
+
310
+
311
+	/**
312
+	 * @param string $addon_name
313
+	 * @param string $version_constant
314
+	 * @param string $min_version_required
315
+	 * @param string $load_callback
316
+	 * @param string $plugin_file_constant
317
+	 * @return void
318
+	 */
319
+	private function deactivateIncompatibleAddon(
320
+		$addon_name,
321
+		$version_constant,
322
+		$min_version_required,
323
+		$load_callback,
324
+		$plugin_file_constant
325
+	) {
326
+		if (! defined($version_constant)) {
327
+			return;
328
+		}
329
+		$addon_version = constant($version_constant);
330
+		if ($addon_version && version_compare($addon_version, $min_version_required, '<')) {
331
+			remove_action('AHEE__EE_System__load_espresso_addons', $load_callback);
332
+			if (! function_exists('deactivate_plugins')) {
333
+				require_once ABSPATH . 'wp-admin/includes/plugin.php';
334
+			}
335
+			deactivate_plugins(plugin_basename(constant($plugin_file_constant)));
336
+			unset($_GET['activate'], $_REQUEST['activate'], $_GET['activate-multi'], $_REQUEST['activate-multi']);
337
+			EE_Error::add_error(
338
+				sprintf(
339
+					esc_html__(
340
+						'We\'re sorry, but the Event Espresso %1$s addon was deactivated because version %2$s or higher is required with this version of Event Espresso core.',
341
+						'event_espresso'
342
+					),
343
+					$addon_name,
344
+					$min_version_required
345
+				),
346
+				__FILE__, __FUNCTION__ . "({$addon_name})", __LINE__
347
+			);
348
+			EE_Error::get_notices(false, true);
349
+		}
350
+	}
351
+
352
+
353
+	/**
354
+	 * load_espresso_addons
355
+	 * allow addons to load first so that they can set hooks for running DMS's, etc
356
+	 * this is hooked into both:
357
+	 *    'AHEE__EE_Bootstrap__load_core_configuration'
358
+	 *        which runs during the WP 'plugins_loaded' action at priority 5
359
+	 *    and the WP 'activate_plugin' hook point
360
+	 *
361
+	 * @access public
362
+	 * @return void
363
+	 */
364
+	public function load_espresso_addons()
365
+	{
366
+		$this->deactivateIncompatibleAddon(
367
+			'Wait Lists',
368
+			'EE_WAIT_LISTS_VERSION',
369
+			'1.0.0.beta.074',
370
+			'load_espresso_wait_lists',
371
+			'EE_WAIT_LISTS_PLUGIN_FILE'
372
+		);
373
+		$this->deactivateIncompatibleAddon(
374
+			'Automated Upcoming Event Notifications',
375
+			'EE_AUTOMATED_UPCOMING_EVENT_NOTIFICATION_VERSION',
376
+			'1.0.0.beta.091',
377
+			'load_espresso_automated_upcoming_event_notification',
378
+			'EE_AUTOMATED_UPCOMING_EVENT_NOTIFICATION_PLUGIN_FILE'
379
+		);
380
+		do_action('AHEE__EE_System__load_espresso_addons');
381
+		//if the WP API basic auth plugin isn't already loaded, load it now.
382
+		//We want it for mobile apps. Just include the entire plugin
383
+		//also, don't load the basic auth when a plugin is getting activated, because
384
+		//it could be the basic auth plugin, and it doesn't check if its methods are already defined
385
+		//and causes a fatal error
386
+		if (
387
+			$this->request->getRequestParam('activate') !== 'true'
388
+			&& ! function_exists('json_basic_auth_handler')
389
+			&& ! function_exists('json_basic_auth_error')
390
+			&& ! in_array(
391
+				$this->request->getRequestParam('action'),
392
+				array('activate', 'activate-selected'),
393
+				true
394
+			)
395
+		) {
396
+			include_once EE_THIRD_PARTY . 'wp-api-basic-auth' . DS . 'basic-auth.php';
397
+		}
398
+		do_action('AHEE__EE_System__load_espresso_addons__complete');
399
+	}
400
+
401
+
402
+
403
+	/**
404
+	 * detect_activations_or_upgrades
405
+	 * Checks for activation or upgrade of core first;
406
+	 * then also checks if any registered addons have been activated or upgraded
407
+	 * This is hooked into 'AHEE__EE_Bootstrap__detect_activations_or_upgrades'
408
+	 * which runs during the WP 'plugins_loaded' action at priority 3
409
+	 *
410
+	 * @access public
411
+	 * @return void
412
+	 */
413
+	public function detect_activations_or_upgrades()
414
+	{
415
+		//first off: let's make sure to handle core
416
+		$this->detect_if_activation_or_upgrade();
417
+		foreach ($this->registry->addons as $addon) {
418
+			if ($addon instanceof EE_Addon) {
419
+				//detect teh request type for that addon
420
+				$addon->detect_activation_or_upgrade();
421
+			}
422
+		}
423
+	}
424
+
425
+
426
+
427
+	/**
428
+	 * detect_if_activation_or_upgrade
429
+	 * Takes care of detecting whether this is a brand new install or code upgrade,
430
+	 * and either setting up the DB or setting up maintenance mode etc.
431
+	 *
432
+	 * @access public
433
+	 * @return void
434
+	 */
435
+	public function detect_if_activation_or_upgrade()
436
+	{
437
+		do_action('AHEE__EE_System___detect_if_activation_or_upgrade__begin');
438
+		// check if db has been updated, or if its a brand-new installation
439
+		$espresso_db_update = $this->fix_espresso_db_upgrade_option();
440
+		$request_type       = $this->detect_req_type($espresso_db_update);
441
+		//EEH_Debug_Tools::printr( $request_type, '$request_type', __FILE__, __LINE__ );
442
+		switch ($request_type) {
443
+			case EE_System::req_type_new_activation:
444
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__new_activation');
445
+				$this->_handle_core_version_change($espresso_db_update);
446
+				break;
447
+			case EE_System::req_type_reactivation:
448
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__reactivation');
449
+				$this->_handle_core_version_change($espresso_db_update);
450
+				break;
451
+			case EE_System::req_type_upgrade:
452
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__upgrade');
453
+				//migrations may be required now that we've upgraded
454
+				$this->maintenance_mode->set_maintenance_mode_if_db_old();
455
+				$this->_handle_core_version_change($espresso_db_update);
456
+				//				echo "done upgrade";die;
457
+				break;
458
+			case EE_System::req_type_downgrade:
459
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__downgrade');
460
+				//its possible migrations are no longer required
461
+				$this->maintenance_mode->set_maintenance_mode_if_db_old();
462
+				$this->_handle_core_version_change($espresso_db_update);
463
+				break;
464
+			case EE_System::req_type_normal:
465
+			default:
466
+				break;
467
+		}
468
+		do_action('AHEE__EE_System__detect_if_activation_or_upgrade__complete');
469
+	}
470
+
471
+
472
+
473
+	/**
474
+	 * Updates the list of installed versions and sets hooks for
475
+	 * initializing the database later during the request
476
+	 *
477
+	 * @param array $espresso_db_update
478
+	 */
479
+	private function _handle_core_version_change($espresso_db_update)
480
+	{
481
+		$this->update_list_of_installed_versions($espresso_db_update);
482
+		//get ready to verify the DB is ok (provided we aren't in maintenance mode, of course)
483
+		add_action(
484
+			'AHEE__EE_System__perform_activations_upgrades_and_migrations',
485
+			array($this, 'initialize_db_if_no_migrations_required')
486
+		);
487
+	}
488
+
489
+
490
+
491
+	/**
492
+	 * standardizes the wp option 'espresso_db_upgrade' which actually stores
493
+	 * information about what versions of EE have been installed and activated,
494
+	 * NOT necessarily the state of the database
495
+	 *
496
+	 * @param mixed $espresso_db_update           the value of the WordPress option.
497
+	 *                                            If not supplied, fetches it from the options table
498
+	 * @return array the correct value of 'espresso_db_upgrade', after saving it, if it needed correction
499
+	 */
500
+	private function fix_espresso_db_upgrade_option($espresso_db_update = null)
501
+	{
502
+		do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__begin', $espresso_db_update);
503
+		if (! $espresso_db_update) {
504
+			$espresso_db_update = get_option('espresso_db_update');
505
+		}
506
+		// check that option is an array
507
+		if (! is_array($espresso_db_update)) {
508
+			// if option is FALSE, then it never existed
509
+			if ($espresso_db_update === false) {
510
+				// make $espresso_db_update an array and save option with autoload OFF
511
+				$espresso_db_update = array();
512
+				add_option('espresso_db_update', $espresso_db_update, '', 'no');
513
+			} else {
514
+				// option is NOT FALSE but also is NOT an array, so make it an array and save it
515
+				$espresso_db_update = array($espresso_db_update => array());
516
+				update_option('espresso_db_update', $espresso_db_update);
517
+			}
518
+		} else {
519
+			$corrected_db_update = array();
520
+			//if IS an array, but is it an array where KEYS are version numbers, and values are arrays?
521
+			foreach ($espresso_db_update as $should_be_version_string => $should_be_array) {
522
+				if (is_int($should_be_version_string) && ! is_array($should_be_array)) {
523
+					//the key is an int, and the value IS NOT an array
524
+					//so it must be numerically-indexed, where values are versions installed...
525
+					//fix it!
526
+					$version_string                         = $should_be_array;
527
+					$corrected_db_update[ $version_string ] = array('unknown-date');
528
+				} else {
529
+					//ok it checks out
530
+					$corrected_db_update[ $should_be_version_string ] = $should_be_array;
531
+				}
532
+			}
533
+			$espresso_db_update = $corrected_db_update;
534
+			update_option('espresso_db_update', $espresso_db_update);
535
+		}
536
+		do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__complete', $espresso_db_update);
537
+		return $espresso_db_update;
538
+	}
539
+
540
+
541
+
542
+	/**
543
+	 * Does the traditional work of setting up the plugin's database and adding default data.
544
+	 * If migration script/process did not exist, this is what would happen on every activation/reactivation/upgrade.
545
+	 * NOTE: if we're in maintenance mode (which would be the case if we detect there are data
546
+	 * migration scripts that need to be run and a version change happens), enqueues core for database initialization,
547
+	 * so that it will be done when migrations are finished
548
+	 *
549
+	 * @param boolean $initialize_addons_too if true, we double-check addons' database tables etc too;
550
+	 * @param boolean $verify_schema         if true will re-check the database tables have the correct schema.
551
+	 *                                       This is a resource-intensive job
552
+	 *                                       so we prefer to only do it when necessary
553
+	 * @return void
554
+	 * @throws EE_Error
555
+	 */
556
+	public function initialize_db_if_no_migrations_required($initialize_addons_too = false, $verify_schema = true)
557
+	{
558
+		$request_type = $this->detect_req_type();
559
+		//only initialize system if we're not in maintenance mode.
560
+		if ($this->maintenance_mode->level() !== EE_Maintenance_Mode::level_2_complete_maintenance) {
561
+			update_option('ee_flush_rewrite_rules', true);
562
+			if ($verify_schema) {
563
+				EEH_Activation::initialize_db_and_folders();
564
+			}
565
+			EEH_Activation::initialize_db_content();
566
+			EEH_Activation::system_initialization();
567
+			if ($initialize_addons_too) {
568
+				$this->initialize_addons();
569
+			}
570
+		} else {
571
+			EE_Data_Migration_Manager::instance()->enqueue_db_initialization_for('Core');
572
+		}
573
+		if ($request_type === EE_System::req_type_new_activation
574
+			|| $request_type === EE_System::req_type_reactivation
575
+			|| (
576
+				$request_type === EE_System::req_type_upgrade
577
+				&& $this->is_major_version_change()
578
+			)
579
+		) {
580
+			add_action('AHEE__EE_System__initialize_last', array($this, 'redirect_to_about_ee'), 9);
581
+		}
582
+	}
583
+
584
+
585
+
586
+	/**
587
+	 * Initializes the db for all registered addons
588
+	 *
589
+	 * @throws EE_Error
590
+	 */
591
+	public function initialize_addons()
592
+	{
593
+		//foreach registered addon, make sure its db is up-to-date too
594
+		foreach ($this->registry->addons as $addon) {
595
+			if ($addon instanceof EE_Addon) {
596
+				$addon->initialize_db_if_no_migrations_required();
597
+			}
598
+		}
599
+	}
600
+
601
+
602
+
603
+	/**
604
+	 * Adds the current code version to the saved wp option which stores a list of all ee versions ever installed.
605
+	 *
606
+	 * @param    array  $version_history
607
+	 * @param    string $current_version_to_add version to be added to the version history
608
+	 * @return    boolean success as to whether or not this option was changed
609
+	 */
610
+	public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null)
611
+	{
612
+		if (! $version_history) {
613
+			$version_history = $this->fix_espresso_db_upgrade_option($version_history);
614
+		}
615
+		if ($current_version_to_add === null) {
616
+			$current_version_to_add = espresso_version();
617
+		}
618
+		$version_history[ $current_version_to_add ][] = date('Y-m-d H:i:s', time());
619
+		// re-save
620
+		return update_option('espresso_db_update', $version_history);
621
+	}
622
+
623
+
624
+
625
+	/**
626
+	 * Detects if the current version indicated in the has existed in the list of
627
+	 * previously-installed versions of EE (espresso_db_update). Does NOT modify it (ie, no side-effect)
628
+	 *
629
+	 * @param array $espresso_db_update array from the wp option stored under the name 'espresso_db_update'.
630
+	 *                                  If not supplied, fetches it from the options table.
631
+	 *                                  Also, caches its result so later parts of the code can also know whether
632
+	 *                                  there's been an update or not. This way we can add the current version to
633
+	 *                                  espresso_db_update, but still know if this is a new install or not
634
+	 * @return int one of the constants on EE_System::req_type_
635
+	 */
636
+	public function detect_req_type($espresso_db_update = null)
637
+	{
638
+		if ($this->_req_type === null) {
639
+			$espresso_db_update          = ! empty($espresso_db_update)
640
+				? $espresso_db_update
641
+				: $this->fix_espresso_db_upgrade_option();
642
+			$this->_req_type             = EE_System::detect_req_type_given_activation_history(
643
+				$espresso_db_update,
644
+				'ee_espresso_activation', espresso_version()
645
+			);
646
+			$this->_major_version_change = $this->_detect_major_version_change($espresso_db_update);
647
+			$this->request->setIsActivation($this->_req_type !== EE_System::req_type_normal);
648
+		}
649
+		return $this->_req_type;
650
+	}
651
+
652
+
653
+
654
+	/**
655
+	 * Returns whether or not there was a non-micro version change (ie, change in either
656
+	 * the first or second number in the version. Eg 4.9.0.rc.001 to 4.10.0.rc.000,
657
+	 * but not 4.9.0.rc.0001 to 4.9.1.rc.0001
658
+	 *
659
+	 * @param $activation_history
660
+	 * @return bool
661
+	 */
662
+	private function _detect_major_version_change($activation_history)
663
+	{
664
+		$previous_version       = EE_System::_get_most_recently_active_version_from_activation_history($activation_history);
665
+		$previous_version_parts = explode('.', $previous_version);
666
+		$current_version_parts  = explode('.', espresso_version());
667
+		return isset($previous_version_parts[0], $previous_version_parts[1], $current_version_parts[0], $current_version_parts[1])
668
+			   && ($previous_version_parts[0] !== $current_version_parts[0]
669
+				   || $previous_version_parts[1] !== $current_version_parts[1]
670
+			   );
671
+	}
672
+
673
+
674
+
675
+	/**
676
+	 * Returns true if either the major or minor version of EE changed during this request.
677
+	 * 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
678
+	 *
679
+	 * @return bool
680
+	 */
681
+	public function is_major_version_change()
682
+	{
683
+		return $this->_major_version_change;
684
+	}
685
+
686
+
687
+
688
+	/**
689
+	 * Determines the request type for any ee addon, given three piece of info: the current array of activation
690
+	 * histories (for core that' 'espresso_db_update' wp option); the name of the WordPress option which is temporarily
691
+	 * set upon activation of the plugin (for core it's 'ee_espresso_activation'); and the version that this plugin was
692
+	 * just activated to (for core that will always be espresso_version())
693
+	 *
694
+	 * @param array  $activation_history_for_addon     the option's value which stores the activation history for this
695
+	 *                                                 ee plugin. for core that's 'espresso_db_update'
696
+	 * @param string $activation_indicator_option_name the name of the WordPress option that is temporarily set to
697
+	 *                                                 indicate that this plugin was just activated
698
+	 * @param string $version_to_upgrade_to            the version that was just upgraded to (for core that will be
699
+	 *                                                 espresso_version())
700
+	 * @return int one of the constants on EE_System::req_type_*
701
+	 */
702
+	public static function detect_req_type_given_activation_history(
703
+		$activation_history_for_addon,
704
+		$activation_indicator_option_name,
705
+		$version_to_upgrade_to
706
+	) {
707
+		$version_is_higher = self::_new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to);
708
+		if ($activation_history_for_addon) {
709
+			//it exists, so this isn't a completely new install
710
+			//check if this version already in that list of previously installed versions
711
+			if (! isset($activation_history_for_addon[ $version_to_upgrade_to ])) {
712
+				//it a version we haven't seen before
713
+				if ($version_is_higher === 1) {
714
+					$req_type = EE_System::req_type_upgrade;
715
+				} else {
716
+					$req_type = EE_System::req_type_downgrade;
717
+				}
718
+				delete_option($activation_indicator_option_name);
719
+			} else {
720
+				// its not an update. maybe a reactivation?
721
+				if (get_option($activation_indicator_option_name, false)) {
722
+					if ($version_is_higher === -1) {
723
+						$req_type = EE_System::req_type_downgrade;
724
+					} elseif ($version_is_higher === 0) {
725
+						//we've seen this version before, but it's an activation. must be a reactivation
726
+						$req_type = EE_System::req_type_reactivation;
727
+					} else {//$version_is_higher === 1
728
+						$req_type = EE_System::req_type_upgrade;
729
+					}
730
+					delete_option($activation_indicator_option_name);
731
+				} else {
732
+					//we've seen this version before and the activation indicate doesn't show it was just activated
733
+					if ($version_is_higher === -1) {
734
+						$req_type = EE_System::req_type_downgrade;
735
+					} elseif ($version_is_higher === 0) {
736
+						//we've seen this version before and it's not an activation. its normal request
737
+						$req_type = EE_System::req_type_normal;
738
+					} else {//$version_is_higher === 1
739
+						$req_type = EE_System::req_type_upgrade;
740
+					}
741
+				}
742
+			}
743
+		} else {
744
+			//brand new install
745
+			$req_type = EE_System::req_type_new_activation;
746
+			delete_option($activation_indicator_option_name);
747
+		}
748
+		return $req_type;
749
+	}
750
+
751
+
752
+
753
+	/**
754
+	 * Detects if the $version_to_upgrade_to is higher than the most recent version in
755
+	 * the $activation_history_for_addon
756
+	 *
757
+	 * @param array  $activation_history_for_addon (keys are versions, values are arrays of times activated,
758
+	 *                                             sometimes containing 'unknown-date'
759
+	 * @param string $version_to_upgrade_to        (current version)
760
+	 * @return int results of version_compare( $version_to_upgrade_to, $most_recently_active_version ).
761
+	 *                                             ie, -1 if $version_to_upgrade_to is LOWER (downgrade);
762
+	 *                                             0 if $version_to_upgrade_to MATCHES (reactivation or normal request);
763
+	 *                                             1 if $version_to_upgrade_to is HIGHER (upgrade) ;
764
+	 */
765
+	private static function _new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to)
766
+	{
767
+		//find the most recently-activated version
768
+		$most_recently_active_version =
769
+			EE_System::_get_most_recently_active_version_from_activation_history($activation_history_for_addon);
770
+		return version_compare($version_to_upgrade_to, $most_recently_active_version);
771
+	}
772
+
773
+
774
+
775
+	/**
776
+	 * Gets the most recently active version listed in the activation history,
777
+	 * and if none are found (ie, it's a brand new install) returns '0.0.0.dev.000'.
778
+	 *
779
+	 * @param array $activation_history  (keys are versions, values are arrays of times activated,
780
+	 *                                   sometimes containing 'unknown-date'
781
+	 * @return string
782
+	 */
783
+	private static function _get_most_recently_active_version_from_activation_history($activation_history)
784
+	{
785
+		$most_recently_active_version_activation = '1970-01-01 00:00:00';
786
+		$most_recently_active_version            = '0.0.0.dev.000';
787
+		if (is_array($activation_history)) {
788
+			foreach ($activation_history as $version => $times_activated) {
789
+				//check there is a record of when this version was activated. Otherwise,
790
+				//mark it as unknown
791
+				if (! $times_activated) {
792
+					$times_activated = array('unknown-date');
793
+				}
794
+				if (is_string($times_activated)) {
795
+					$times_activated = array($times_activated);
796
+				}
797
+				foreach ($times_activated as $an_activation) {
798
+					if ($an_activation !== 'unknown-date'
799
+						&& $an_activation
800
+						   > $most_recently_active_version_activation) {
801
+						$most_recently_active_version            = $version;
802
+						$most_recently_active_version_activation = $an_activation === 'unknown-date'
803
+							? '1970-01-01 00:00:00'
804
+							: $an_activation;
805
+					}
806
+				}
807
+			}
808
+		}
809
+		return $most_recently_active_version;
810
+	}
811
+
812
+
813
+
814
+	/**
815
+	 * This redirects to the about EE page after activation
816
+	 *
817
+	 * @return void
818
+	 */
819
+	public function redirect_to_about_ee()
820
+	{
821
+		$notices = EE_Error::get_notices(false);
822
+		//if current user is an admin and it's not an ajax or rest request
823
+		if (
824
+			! isset($notices['errors'])
825
+			&& $this->request->isAdmin()
826
+			&& apply_filters(
827
+				'FHEE__EE_System__redirect_to_about_ee__do_redirect',
828
+				$this->capabilities->current_user_can('manage_options', 'espresso_about_default')
829
+			)
830
+		) {
831
+			$query_params = array('page' => 'espresso_about');
832
+			if (EE_System::instance()->detect_req_type() === EE_System::req_type_new_activation) {
833
+				$query_params['new_activation'] = true;
834
+			}
835
+			if (EE_System::instance()->detect_req_type() === EE_System::req_type_reactivation) {
836
+				$query_params['reactivation'] = true;
837
+			}
838
+			$url = add_query_arg($query_params, admin_url('admin.php'));
839
+			wp_safe_redirect($url);
840
+			exit();
841
+		}
842
+	}
843
+
844
+
845
+
846
+	/**
847
+	 * load_core_configuration
848
+	 * this is hooked into 'AHEE__EE_Bootstrap__load_core_configuration'
849
+	 * which runs during the WP 'plugins_loaded' action at priority 5
850
+	 *
851
+	 * @return void
852
+	 * @throws ReflectionException
853
+	 */
854
+	public function load_core_configuration()
855
+	{
856
+		do_action('AHEE__EE_System__load_core_configuration__begin', $this);
857
+		$this->loader->getShared('EE_Load_Textdomain');
858
+		//load textdomain
859
+		EE_Load_Textdomain::load_textdomain();
860
+		// load and setup EE_Config and EE_Network_Config
861
+		$config = $this->loader->getShared('EE_Config');
862
+		$this->loader->getShared('EE_Network_Config');
863
+		// setup autoloaders
864
+		// enable logging?
865
+		if ($config->admin->use_full_logging) {
866
+			$this->loader->getShared('EE_Log');
867
+		}
868
+		// check for activation errors
869
+		$activation_errors = get_option('ee_plugin_activation_errors', false);
870
+		if ($activation_errors) {
871
+			EE_Error::add_error($activation_errors, __FILE__, __FUNCTION__, __LINE__);
872
+			update_option('ee_plugin_activation_errors', false);
873
+		}
874
+		// get model names
875
+		$this->_parse_model_names();
876
+		//load caf stuff a chance to play during the activation process too.
877
+		$this->_maybe_brew_regular();
878
+		do_action('AHEE__EE_System__load_core_configuration__complete', $this);
879
+	}
880
+
881
+
882
+
883
+	/**
884
+	 * cycles through all of the models/*.model.php files, and assembles an array of model names
885
+	 *
886
+	 * @return void
887
+	 * @throws ReflectionException
888
+	 */
889
+	private function _parse_model_names()
890
+	{
891
+		//get all the files in the EE_MODELS folder that end in .model.php
892
+		$models                 = glob(EE_MODELS . '*.model.php');
893
+		$model_names            = array();
894
+		$non_abstract_db_models = array();
895
+		foreach ($models as $model) {
896
+			// get model classname
897
+			$classname       = EEH_File::get_classname_from_filepath_with_standard_filename($model);
898
+			$short_name      = str_replace('EEM_', '', $classname);
899
+			$reflectionClass = new ReflectionClass($classname);
900
+			if ($reflectionClass->isSubclassOf('EEM_Base') && ! $reflectionClass->isAbstract()) {
901
+				$non_abstract_db_models[ $short_name ] = $classname;
902
+			}
903
+			$model_names[ $short_name ] = $classname;
904
+		}
905
+		$this->registry->models                 = apply_filters('FHEE__EE_System__parse_model_names', $model_names);
906
+		$this->registry->non_abstract_db_models = apply_filters(
907
+			'FHEE__EE_System__parse_implemented_model_names',
908
+			$non_abstract_db_models
909
+		);
910
+	}
911
+
912
+
913
+
914
+	/**
915
+	 * The purpose of this method is to simply check for a file named "caffeinated/brewing_regular.php" for any hooks
916
+	 * that need to be setup before our EE_System launches.
917
+	 *
918
+	 * @return void
919
+	 */
920
+	private function _maybe_brew_regular()
921
+	{
922
+		if ((! defined('EE_DECAF') || EE_DECAF !== true) && is_readable(EE_CAFF_PATH . 'brewing_regular.php')) {
923
+			require_once EE_CAFF_PATH . 'brewing_regular.php';
924
+		}
925
+	}
926
+
927
+
928
+
929
+	/**
930
+	 * register_shortcodes_modules_and_widgets
931
+	 * generate lists of shortcodes and modules, then verify paths and classes
932
+	 * This is hooked into 'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets'
933
+	 * which runs during the WP 'plugins_loaded' action at priority 7
934
+	 *
935
+	 * @access public
936
+	 * @return void
937
+	 * @throws Exception
938
+	 */
939
+	public function register_shortcodes_modules_and_widgets()
940
+	{
941
+		if ($this->request->isFrontend() || $this->request->isIframe()) {
942
+			try {
943
+				// load, register, and add shortcodes the new way
944
+				$this->loader->getShared(
945
+					'EventEspresso\core\services\shortcodes\ShortcodesManager',
946
+					array(
947
+						// and the old way, but we'll put it under control of the new system
948
+						EE_Config::getLegacyShortcodesManager(),
949
+					)
950
+				);
951
+			} catch (Exception $exception) {
952
+				new ExceptionStackTraceDisplay($exception);
953
+			}
954
+		}
955
+		do_action('AHEE__EE_System__register_shortcodes_modules_and_widgets');
956
+		// check for addons using old hook point
957
+		if (has_action('AHEE__EE_System__register_shortcodes_modules_and_addons')) {
958
+			$this->_incompatible_addon_error();
959
+		}
960
+	}
961
+
962
+
963
+
964
+	/**
965
+	 * _incompatible_addon_error
966
+	 *
967
+	 * @access public
968
+	 * @return void
969
+	 */
970
+	private function _incompatible_addon_error()
971
+	{
972
+		// get array of classes hooking into here
973
+		$class_names = EEH_Class_Tools::get_class_names_for_all_callbacks_on_hook(
974
+			'AHEE__EE_System__register_shortcodes_modules_and_addons'
975
+		);
976
+		if (! empty($class_names)) {
977
+			$msg = __(
978
+				'The following plugins, addons, or modules appear to be incompatible with this version of Event Espresso and were automatically deactivated to avoid fatal errors:',
979
+				'event_espresso'
980
+			);
981
+			$msg .= '<ul>';
982
+			foreach ($class_names as $class_name) {
983
+				$msg .= '<li><b>Event Espresso - ' . str_replace(
984
+						array('EE_', 'EEM_', 'EED_', 'EES_', 'EEW_'), '',
985
+						$class_name
986
+					) . '</b></li>';
987
+			}
988
+			$msg .= '</ul>';
989
+			$msg .= __(
990
+				'Compatibility issues can be avoided and/or resolved by keeping addons and plugins updated to the latest version.',
991
+				'event_espresso'
992
+			);
993
+			// save list of incompatible addons to wp-options for later use
994
+			add_option('ee_incompatible_addons', $class_names, '', 'no');
995
+			if (is_admin()) {
996
+				EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
997
+			}
998
+		}
999
+	}
1000
+
1001
+
1002
+
1003
+	/**
1004
+	 * brew_espresso
1005
+	 * begins the process of setting hooks for initializing EE in the correct order
1006
+	 * This is happening on the 'AHEE__EE_Bootstrap__brew_espresso' hook point
1007
+	 * which runs during the WP 'plugins_loaded' action at priority 9
1008
+	 *
1009
+	 * @return void
1010
+	 */
1011
+	public function brew_espresso()
1012
+	{
1013
+		do_action('AHEE__EE_System__brew_espresso__begin', $this);
1014
+		// load some final core systems
1015
+		add_action('init', array($this, 'set_hooks_for_core'), 1);
1016
+		add_action('init', array($this, 'perform_activations_upgrades_and_migrations'), 3);
1017
+		add_action('init', array($this, 'load_CPTs_and_session'), 5);
1018
+		add_action('init', array($this, 'load_controllers'), 7);
1019
+		add_action('init', array($this, 'core_loaded_and_ready'), 9);
1020
+		add_action('init', array($this, 'initialize'), 10);
1021
+		add_action('init', array($this, 'initialize_last'), 100);
1022
+		if (is_admin() && apply_filters('FHEE__EE_System__brew_espresso__load_pue', true)) {
1023
+			// pew pew pew
1024
+			$this->loader->getShared('EventEspresso\core\services\licensing\LicenseService');
1025
+			do_action('AHEE__EE_System__brew_espresso__after_pue_init');
1026
+		}
1027
+		do_action('AHEE__EE_System__brew_espresso__complete', $this);
1028
+	}
1029
+
1030
+
1031
+
1032
+	/**
1033
+	 *    set_hooks_for_core
1034
+	 *
1035
+	 * @access public
1036
+	 * @return    void
1037
+	 * @throws EE_Error
1038
+	 */
1039
+	public function set_hooks_for_core()
1040
+	{
1041
+		$this->_deactivate_incompatible_addons();
1042
+		do_action('AHEE__EE_System__set_hooks_for_core');
1043
+		$this->loader->getShared('EventEspresso\core\domain\values\session\SessionLifespan');
1044
+		//caps need to be initialized on every request so that capability maps are set.
1045
+		//@see https://events.codebasehq.com/projects/event-espresso/tickets/8674
1046
+		$this->registry->CAP->init_caps();
1047
+	}
1048
+
1049
+
1050
+
1051
+	/**
1052
+	 * Using the information gathered in EE_System::_incompatible_addon_error,
1053
+	 * deactivates any addons considered incompatible with the current version of EE
1054
+	 */
1055
+	private function _deactivate_incompatible_addons()
1056
+	{
1057
+		$incompatible_addons = get_option('ee_incompatible_addons', array());
1058
+		if (! empty($incompatible_addons)) {
1059
+			$active_plugins = get_option('active_plugins', array());
1060
+			foreach ($active_plugins as $active_plugin) {
1061
+				foreach ($incompatible_addons as $incompatible_addon) {
1062
+					if (strpos($active_plugin, $incompatible_addon) !== false) {
1063
+						unset($_GET['activate']);
1064
+						espresso_deactivate_plugin($active_plugin);
1065
+					}
1066
+				}
1067
+			}
1068
+		}
1069
+	}
1070
+
1071
+
1072
+
1073
+	/**
1074
+	 *    perform_activations_upgrades_and_migrations
1075
+	 *
1076
+	 * @access public
1077
+	 * @return    void
1078
+	 */
1079
+	public function perform_activations_upgrades_and_migrations()
1080
+	{
1081
+		do_action('AHEE__EE_System__perform_activations_upgrades_and_migrations');
1082
+	}
1083
+
1084
+
1085
+
1086
+	/**
1087
+	 *    load_CPTs_and_session
1088
+	 *
1089
+	 * @access public
1090
+	 * @return    void
1091
+	 */
1092
+	public function load_CPTs_and_session()
1093
+	{
1094
+		do_action('AHEE__EE_System__load_CPTs_and_session__start');
1095
+		// register Custom Post Types
1096
+		$this->loader->getShared('EE_Register_CPTs');
1097
+		do_action('AHEE__EE_System__load_CPTs_and_session__complete');
1098
+	}
1099
+
1100
+
1101
+
1102
+	/**
1103
+	 * load_controllers
1104
+	 * this is the best place to load any additional controllers that needs access to EE core.
1105
+	 * it is expected that all basic core EE systems, that are not dependant on the current request are loaded at this
1106
+	 * time
1107
+	 *
1108
+	 * @access public
1109
+	 * @return void
1110
+	 */
1111
+	public function load_controllers()
1112
+	{
1113
+		do_action('AHEE__EE_System__load_controllers__start');
1114
+		// let's get it started
1115
+		if (
1116
+			! $this->maintenance_mode->level()
1117
+			&& ($this->request->isFrontend() || $this->request->isFrontAjax())
1118
+		) {
1119
+			do_action('AHEE__EE_System__load_controllers__load_front_controllers');
1120
+			$this->loader->getShared('EE_Front_Controller');
1121
+		} elseif ($this->request->isAdmin() || $this->request->isAdminAjax()) {
1122
+			do_action('AHEE__EE_System__load_controllers__load_admin_controllers');
1123
+			$this->loader->getShared('EE_Admin');
1124
+		}
1125
+		do_action('AHEE__EE_System__load_controllers__complete');
1126
+	}
1127
+
1128
+
1129
+
1130
+	/**
1131
+	 * core_loaded_and_ready
1132
+	 * all of the basic EE core should be loaded at this point and available regardless of M-Mode
1133
+	 *
1134
+	 * @access public
1135
+	 * @return void
1136
+	 */
1137
+	public function core_loaded_and_ready()
1138
+	{
1139
+		if (
1140
+			$this->request->isAdmin()
1141
+			|| $this->request->isEeAjax()
1142
+			|| $this->request->isFrontend()
1143
+		) {
1144
+			$this->loader->getShared('EE_Session');
1145
+		}
1146
+		do_action('AHEE__EE_System__core_loaded_and_ready');
1147
+		// load_espresso_template_tags
1148
+		if (
1149
+			is_readable(EE_PUBLIC . 'template_tags.php')
1150
+			&& ($this->request->isFrontend() || $this->request->isIframe() || $this->request->isFeed())
1151
+		) {
1152
+			require_once EE_PUBLIC . 'template_tags.php';
1153
+		}
1154
+		do_action('AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons');
1155
+		if ($this->request->isAdmin() || $this->request->isFrontend() || $this->request->isIframe()) {
1156
+			$this->loader->getShared('EventEspresso\core\services\assets\Registry');
1157
+		}
1158
+	}
1159
+
1160
+
1161
+
1162
+	/**
1163
+	 * initialize
1164
+	 * this is the best place to begin initializing client code
1165
+	 *
1166
+	 * @access public
1167
+	 * @return void
1168
+	 */
1169
+	public function initialize()
1170
+	{
1171
+		do_action('AHEE__EE_System__initialize');
1172
+	}
1173
+
1174
+
1175
+
1176
+	/**
1177
+	 * initialize_last
1178
+	 * this is run really late during the WP init hook point, and ensures that mostly everything else that needs to
1179
+	 * initialize has done so
1180
+	 *
1181
+	 * @access public
1182
+	 * @return void
1183
+	 */
1184
+	public function initialize_last()
1185
+	{
1186
+		do_action('AHEE__EE_System__initialize_last');
1187
+		add_action('admin_bar_init', array($this, 'addEspressoToolbar'));
1188
+	}
1189
+
1190
+
1191
+
1192
+	/**
1193
+	 * @return void
1194
+	 * @throws EE_Error
1195
+	 */
1196
+	public function addEspressoToolbar()
1197
+	{
1198
+		$this->loader->getShared(
1199
+			'EventEspresso\core\domain\services\admin\AdminToolBar',
1200
+			array($this->registry->CAP)
1201
+		);
1202
+	}
1203
+
1204
+
1205
+
1206
+	/**
1207
+	 * do_not_cache
1208
+	 * sets no cache headers and defines no cache constants for WP plugins
1209
+	 *
1210
+	 * @access public
1211
+	 * @return void
1212
+	 */
1213
+	public static function do_not_cache()
1214
+	{
1215
+		// set no cache constants
1216
+		if (! defined('DONOTCACHEPAGE')) {
1217
+			define('DONOTCACHEPAGE', true);
1218
+		}
1219
+		if (! defined('DONOTCACHCEOBJECT')) {
1220
+			define('DONOTCACHCEOBJECT', true);
1221
+		}
1222
+		if (! defined('DONOTCACHEDB')) {
1223
+			define('DONOTCACHEDB', true);
1224
+		}
1225
+		// add no cache headers
1226
+		add_action('send_headers', array('EE_System', 'nocache_headers'), 10);
1227
+		// plus a little extra for nginx and Google Chrome
1228
+		add_filter('nocache_headers', array('EE_System', 'extra_nocache_headers'), 10, 1);
1229
+		// prevent browsers from prefetching of the rel='next' link, because it may contain content that interferes with the registration process
1230
+		remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');
1231
+	}
1232
+
1233
+
1234
+
1235
+	/**
1236
+	 *    extra_nocache_headers
1237
+	 *
1238
+	 * @access    public
1239
+	 * @param $headers
1240
+	 * @return    array
1241
+	 */
1242
+	public static function extra_nocache_headers($headers)
1243
+	{
1244
+		// for NGINX
1245
+		$headers['X-Accel-Expires'] = 0;
1246
+		// plus extra for Google Chrome since it doesn't seem to respect "no-cache", but WILL respect "no-store"
1247
+		$headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0';
1248
+		return $headers;
1249
+	}
1250
+
1251
+
1252
+
1253
+	/**
1254
+	 *    nocache_headers
1255
+	 *
1256
+	 * @access    public
1257
+	 * @return    void
1258
+	 */
1259
+	public static function nocache_headers()
1260
+	{
1261
+		nocache_headers();
1262
+	}
1263
+
1264
+
1265
+
1266
+	/**
1267
+	 * simply hooks into "wp_list_pages_exclude" filter (for wp_list_pages method) and makes sure EE critical pages are
1268
+	 * never returned with the function.
1269
+	 *
1270
+	 * @param  array $exclude_array any existing pages being excluded are in this array.
1271
+	 * @return array
1272
+	 */
1273
+	public function remove_pages_from_wp_list_pages($exclude_array)
1274
+	{
1275
+		return array_merge($exclude_array, $this->registry->CFG->core->get_critical_pages_array());
1276
+	}
1277 1277
 
1278 1278
 
1279 1279
 
Please login to merge, or discard this patch.
core/helpers/EEH_Line_Item.helper.php 2 patches
Indentation   +1698 added lines, -1698 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if (!defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 
5 5
 /**
@@ -23,1703 +23,1703 @@  discard block
 block discarded – undo
23 23
 class EEH_Line_Item
24 24
 {
25 25
 
26
-    //other functions: cancel ticket purchase
27
-    //delete ticket purchase
28
-    //add promotion
29
-
30
-
31
-    /**
32
-     * Adds a simple item (unrelated to any other model object) to the provided PARENT line item.
33
-     * Does NOT automatically re-calculate the line item totals or update the related transaction.
34
-     * You should call recalculate_total_including_taxes() on the grant total line item after this
35
-     * to update the subtotals, and EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
36
-     * to keep the registration final prices in-sync with the transaction's total.
37
-     *
38
-     * @param EE_Line_Item $parent_line_item
39
-     * @param string $name
40
-     * @param float $unit_price
41
-     * @param string $description
42
-     * @param int $quantity
43
-     * @param boolean $taxable
44
-     * @param boolean $code if set to a value, ensures there is only one line item with that code
45
-     * @return boolean success
46
-     * @throws \EE_Error
47
-     */
48
-    public static function add_unrelated_item(EE_Line_Item $parent_line_item, $name, $unit_price, $description = '', $quantity = 1, $taxable = FALSE, $code = NULL)
49
-    {
50
-        $items_subtotal = self::get_pre_tax_subtotal($parent_line_item);
51
-        $line_item = EE_Line_Item::new_instance(array(
52
-            'LIN_name' => $name,
53
-            'LIN_desc' => $description,
54
-            'LIN_unit_price' => $unit_price,
55
-            'LIN_quantity' => $quantity,
56
-            'LIN_percent' => null,
57
-            'LIN_is_taxable' => $taxable,
58
-            'LIN_order' => $items_subtotal instanceof EE_Line_Item ? count($items_subtotal->children()) : 0,
59
-            'LIN_total' => (float)$unit_price * (int)$quantity,
60
-            'LIN_type' => EEM_Line_Item::type_line_item,
61
-            'LIN_code' => $code,
62
-        ));
63
-        $line_item = apply_filters(
64
-            'FHEE__EEH_Line_Item__add_unrelated_item__line_item',
65
-            $line_item,
66
-            $parent_line_item
67
-        );
68
-        return self::add_item($parent_line_item, $line_item);
69
-    }
70
-
71
-
72
-    /**
73
-     * Adds a simple item ( unrelated to any other model object) to the total line item,
74
-     * in the correct spot in the line item tree. Automatically
75
-     * re-calculates the line item totals and updates the related transaction. But
76
-     * DOES NOT automatically upgrade the transaction's registrations' final prices (which
77
-     * should probably change because of this).
78
-     * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
79
-     * after using this, to keep the registration final prices in-sync with the transaction's total.
80
-     *
81
-     * @param EE_Line_Item $parent_line_item
82
-     * @param string $name
83
-     * @param float $percentage_amount
84
-     * @param string $description
85
-     * @param boolean $taxable
86
-     * @return boolean success
87
-     * @throws \EE_Error
88
-     */
89
-    public static function add_percentage_based_item(EE_Line_Item $parent_line_item, $name, $percentage_amount, $description = '', $taxable = FALSE)
90
-    {
91
-        $line_item = EE_Line_Item::new_instance(array(
92
-            'LIN_name' => $name,
93
-            'LIN_desc' => $description,
94
-            'LIN_unit_price' => 0,
95
-            'LIN_percent' => $percentage_amount,
96
-            'LIN_quantity' => 1,
97
-            'LIN_is_taxable' => $taxable,
98
-            'LIN_total' => (float)($percentage_amount * ($parent_line_item->total() / 100)),
99
-            'LIN_type' => EEM_Line_Item::type_line_item,
100
-            'LIN_parent' => $parent_line_item->ID()
101
-        ));
102
-        $line_item = apply_filters(
103
-            'FHEE__EEH_Line_Item__add_percentage_based_item__line_item',
104
-            $line_item
105
-        );
106
-        return $parent_line_item->add_child_line_item($line_item, false);
107
-    }
108
-
109
-
110
-    /**
111
-     * Returns the new line item created by adding a purchase of the ticket
112
-     * ensures that ticket line item is saved, and that cart total has been recalculated.
113
-     * If this ticket has already been purchased, just increments its count.
114
-     * Automatically re-calculates the line item totals and updates the related transaction. But
115
-     * DOES NOT automatically upgrade the transaction's registrations' final prices (which
116
-     * should probably change because of this).
117
-     * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
118
-     * after using this, to keep the registration final prices in-sync with the transaction's total.
119
-     *
120
-     * @param EE_Line_Item $total_line_item grand total line item of type EEM_Line_Item::type_total
121
-     * @param EE_Ticket $ticket
122
-     * @param int $qty
123
-     * @return \EE_Line_Item
124
-     * @throws \EE_Error
125
-     */
126
-    public static function add_ticket_purchase(EE_Line_Item $total_line_item, EE_Ticket $ticket, $qty = 1)
127
-    {
128
-        if (!$total_line_item instanceof EE_Line_Item || !$total_line_item->is_total()) {
129
-            throw new EE_Error(sprintf(__('A valid line item total is required in order to add tickets. A line item of type "%s" was passed.', 'event_espresso'), $ticket->ID(), $total_line_item->ID()));
130
-        }
131
-        // either increment the qty for an existing ticket
132
-        $line_item = self::increment_ticket_qty_if_already_in_cart($total_line_item, $ticket, $qty);
133
-        // or add a new one
134
-        if (!$line_item instanceof EE_Line_Item) {
135
-            $line_item = self::create_ticket_line_item($total_line_item, $ticket, $qty);
136
-        }
137
-        $total_line_item->recalculate_total_including_taxes();
138
-        return $line_item;
139
-    }
140
-
141
-
142
-    /**
143
-     * Returns the new line item created by adding a purchase of the ticket
144
-     * @param \EE_Line_Item $total_line_item
145
-     * @param EE_Ticket $ticket
146
-     * @param int $qty
147
-     * @return \EE_Line_Item
148
-     * @throws \EE_Error
149
-     */
150
-    public static function increment_ticket_qty_if_already_in_cart(EE_Line_Item $total_line_item, EE_Ticket $ticket, $qty = 1)
151
-    {
152
-        $line_item = null;
153
-        if ($total_line_item instanceof EE_Line_Item && $total_line_item->is_total()) {
154
-            $ticket_line_items = EEH_Line_Item::get_ticket_line_items($total_line_item);
155
-            foreach ((array)$ticket_line_items as $ticket_line_item) {
156
-                if (
157
-                    $ticket_line_item instanceof EE_Line_Item
158
-                    && (int)$ticket_line_item->OBJ_ID() === (int)$ticket->ID()
159
-                ) {
160
-                    $line_item = $ticket_line_item;
161
-                    break;
162
-                }
163
-            }
164
-        }
165
-        if ($line_item instanceof EE_Line_Item) {
166
-            EEH_Line_Item::increment_quantity($line_item, $qty);
167
-            return $line_item;
168
-        }
169
-        return null;
170
-    }
171
-
172
-
173
-    /**
174
-     * Increments the line item and all its children's quantity by $qty (but percent line items are unaffected).
175
-     * Does NOT save or recalculate other line items totals
176
-     *
177
-     * @param EE_Line_Item $line_item
178
-     * @param int $qty
179
-     * @return void
180
-     * @throws \EE_Error
181
-     */
182
-    public static function increment_quantity(EE_Line_Item $line_item, $qty = 1)
183
-    {
184
-        if (!$line_item->is_percent()) {
185
-            $qty += $line_item->quantity();
186
-            $line_item->set_quantity($qty);
187
-            $line_item->set_total($line_item->unit_price() * $qty);
188
-            $line_item->save();
189
-        }
190
-        foreach ($line_item->children() as $child) {
191
-            if ($child->is_sub_line_item()) {
192
-                EEH_Line_Item::update_quantity($child, $qty);
193
-            }
194
-        }
195
-    }
196
-
197
-
198
-    /**
199
-     * Decrements the line item and all its children's quantity by $qty (but percent line items are unaffected).
200
-     * Does NOT save or recalculate other line items totals
201
-     *
202
-     * @param EE_Line_Item $line_item
203
-     * @param int $qty
204
-     * @return void
205
-     * @throws \EE_Error
206
-     */
207
-    public static function decrement_quantity(EE_Line_Item $line_item, $qty = 1)
208
-    {
209
-        if (!$line_item->is_percent()) {
210
-            $qty = $line_item->quantity() - $qty;
211
-            $qty = max($qty, 0);
212
-            $line_item->set_quantity($qty);
213
-            $line_item->set_total($line_item->unit_price() * $qty);
214
-            $line_item->save();
215
-        }
216
-        foreach ($line_item->children() as $child) {
217
-            if ($child->is_sub_line_item()) {
218
-                EEH_Line_Item::update_quantity($child, $qty);
219
-            }
220
-        }
221
-    }
222
-
223
-
224
-    /**
225
-     * Updates the line item and its children's quantities to the specified number.
226
-     * Does NOT save them or recalculate totals.
227
-     *
228
-     * @param EE_Line_Item $line_item
229
-     * @param int $new_quantity
230
-     * @throws \EE_Error
231
-     */
232
-    public static function update_quantity(EE_Line_Item $line_item, $new_quantity)
233
-    {
234
-        if (!$line_item->is_percent()) {
235
-            $line_item->set_quantity($new_quantity);
236
-            $line_item->set_total($line_item->unit_price() * $new_quantity);
237
-            $line_item->save();
238
-        }
239
-        foreach ($line_item->children() as $child) {
240
-            if ($child->is_sub_line_item()) {
241
-                EEH_Line_Item::update_quantity($child, $new_quantity);
242
-            }
243
-        }
244
-    }
245
-
246
-
247
-    /**
248
-     * Returns the new line item created by adding a purchase of the ticket
249
-     * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
250
-     * @param EE_Ticket $ticket
251
-     * @param int $qty
252
-     * @return \EE_Line_Item
253
-     * @throws \EE_Error
254
-     */
255
-    public static function create_ticket_line_item(EE_Line_Item $total_line_item, EE_Ticket $ticket, $qty = 1)
256
-    {
257
-        $datetimes = $ticket->datetimes();
258
-        $first_datetime = reset($datetimes);
259
-        if ($first_datetime instanceof EE_Datetime && $first_datetime->event() instanceof EE_Event) {
260
-            $first_datetime_name = $first_datetime->event()->name();
261
-        } else {
262
-            $first_datetime_name = __('Event', 'event_espresso');
263
-        }
264
-        $event = sprintf(_x('(For %1$s)', '(For Event Name)', 'event_espresso'), $first_datetime_name);
265
-        // get event subtotal line
266
-        $events_sub_total = self::get_event_line_item_for_ticket($total_line_item, $ticket);
267
-        // add $ticket to cart
268
-        $line_item = EE_Line_Item::new_instance(array(
269
-            'LIN_name' => $ticket->name(),
270
-            'LIN_desc' => $ticket->description() !== '' ? $ticket->description() . ' ' . $event : $event,
271
-            'LIN_unit_price' => $ticket->price(),
272
-            'LIN_quantity' => $qty,
273
-            'LIN_is_taxable' => $ticket->taxable(),
274
-            'LIN_order' => count($events_sub_total->children()),
275
-            'LIN_total' => $ticket->price() * $qty,
276
-            'LIN_type' => EEM_Line_Item::type_line_item,
277
-            'OBJ_ID' => $ticket->ID(),
278
-            'OBJ_type' => 'Ticket'
279
-        ));
280
-        $line_item = apply_filters(
281
-            'FHEE__EEH_Line_Item__create_ticket_line_item__line_item',
282
-            $line_item
283
-        );
284
-        $events_sub_total->add_child_line_item($line_item);
285
-        //now add the sub-line items
286
-        $running_total_for_ticket = 0;
287
-        foreach ($ticket->prices(array('order_by' => array('PRC_order' => 'ASC'))) as $price) {
288
-            $sign = $price->is_discount() ? -1 : 1;
289
-            $price_total = $price->is_percent()
290
-                ? $running_total_for_ticket * $price->amount() / 100
291
-                : $price->amount() * $qty;
292
-            $sub_line_item = EE_Line_Item::new_instance(array(
293
-                'LIN_name' => $price->name(),
294
-                'LIN_desc' => $price->desc(),
295
-                'LIN_quantity' => $price->is_percent() ? null : $qty,
296
-                'LIN_is_taxable' => false,
297
-                'LIN_order' => $price->order(),
298
-                'LIN_total' => $sign * $price_total,
299
-                'LIN_type' => EEM_Line_Item::type_sub_line_item,
300
-                'OBJ_ID' => $price->ID(),
301
-                'OBJ_type' => 'Price'
302
-            ));
303
-            $sub_line_item = apply_filters(
304
-                'FHEE__EEH_Line_Item__create_ticket_line_item__sub_line_item',
305
-                $sub_line_item
306
-            );
307
-            if ($price->is_percent()) {
308
-                $sub_line_item->set_percent($sign * $price->amount());
309
-            } else {
310
-                $sub_line_item->set_unit_price($sign * $price->amount());
311
-            }
312
-            $running_total_for_ticket += $price_total;
313
-            $line_item->add_child_line_item($sub_line_item);
314
-        }
315
-        return $line_item;
316
-    }
317
-
318
-
319
-    /**
320
-     * Adds the specified item under the pre-tax-sub-total line item. Automatically
321
-     * re-calculates the line item totals and updates the related transaction. But
322
-     * DOES NOT automatically upgrade the transaction's registrations' final prices (which
323
-     * should probably change because of this).
324
-     * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
325
-     * after using this, to keep the registration final prices in-sync with the transaction's total.
326
-     *
327
-     * @param EE_Line_Item $total_line_item
328
-     * @param EE_Line_Item $item to be added
329
-     * @return boolean
330
-     * @throws \EE_Error
331
-     */
332
-    public static function add_item(EE_Line_Item $total_line_item, EE_Line_Item $item)
333
-    {
334
-        $pre_tax_subtotal = self::get_pre_tax_subtotal($total_line_item);
335
-        if ($pre_tax_subtotal instanceof EE_Line_Item) {
336
-            $success = $pre_tax_subtotal->add_child_line_item($item);
337
-        } else {
338
-            return FALSE;
339
-        }
340
-        $total_line_item->recalculate_total_including_taxes();
341
-        return $success;
342
-    }
343
-
344
-
345
-    /**
346
-     * cancels an existing ticket line item,
347
-     * by decrementing it's quantity by 1 and adding a new "type_cancellation" sub-line-item.
348
-     * ALL totals and subtotals will NEED TO BE UPDATED after performing this action
349
-     *
350
-     * @param EE_Line_Item $ticket_line_item
351
-     * @param int $qty
352
-     * @return bool success
353
-     * @throws \EE_Error
354
-     */
355
-    public static function cancel_ticket_line_item(EE_Line_Item $ticket_line_item, $qty = 1)
356
-    {
357
-        // validate incoming line_item
358
-        if ($ticket_line_item->OBJ_type() !== 'Ticket') {
359
-            throw new EE_Error(
360
-                sprintf(
361
-                    __('The supplied line item must have an Object Type of "Ticket", not %1$s.', 'event_espresso'),
362
-                    $ticket_line_item->type()
363
-                )
364
-            );
365
-        }
366
-        if ($ticket_line_item->quantity() < $qty) {
367
-            throw new EE_Error(
368
-                sprintf(
369
-                    __('Can not cancel %1$d ticket(s) because the supplied line item has a quantity of %2$d.', 'event_espresso'),
370
-                    $qty,
371
-                    $ticket_line_item->quantity()
372
-                )
373
-            );
374
-        }
375
-        // decrement ticket quantity; don't rely on auto-fixing when recalculating totals to do this
376
-        $ticket_line_item->set_quantity($ticket_line_item->quantity() - $qty);
377
-        foreach ($ticket_line_item->children() as $child_line_item) {
378
-            if (
379
-                $child_line_item->is_sub_line_item()
380
-                && !$child_line_item->is_percent()
381
-                && !$child_line_item->is_cancellation()
382
-            ) {
383
-                $child_line_item->set_quantity($child_line_item->quantity() - $qty);
384
-            }
385
-        }
386
-        // get cancellation sub line item
387
-        $cancellation_line_item = EEH_Line_Item::get_descendants_of_type(
388
-            $ticket_line_item,
389
-            EEM_Line_Item::type_cancellation
390
-        );
391
-        $cancellation_line_item = reset($cancellation_line_item);
392
-        // verify that this ticket was indeed previously cancelled
393
-        if ($cancellation_line_item instanceof EE_Line_Item) {
394
-            // increment cancelled quantity
395
-            $cancellation_line_item->set_quantity($cancellation_line_item->quantity() + $qty);
396
-        } else {
397
-            // create cancellation sub line item
398
-            $cancellation_line_item = EE_Line_Item::new_instance(array(
399
-                'LIN_name' => __('Cancellation', 'event_espresso'),
400
-                'LIN_desc' => sprintf(
401
-                    _x('Cancelled %1$s : %2$s', 'Cancelled Ticket Name : 2015-01-01 11:11', 'event_espresso'),
402
-                    $ticket_line_item->name(),
403
-                    current_time(get_option('date_format') . ' ' . get_option('time_format'))
404
-                ),
405
-                'LIN_unit_price' => 0, // $ticket_line_item->unit_price()
406
-                'LIN_quantity' => $qty,
407
-                'LIN_is_taxable' => $ticket_line_item->is_taxable(),
408
-                'LIN_order' => count($ticket_line_item->children()),
409
-                'LIN_total' => 0, // $ticket_line_item->unit_price()
410
-                'LIN_type' => EEM_Line_Item::type_cancellation,
411
-            ));
412
-            $ticket_line_item->add_child_line_item($cancellation_line_item);
413
-        }
414
-        if ($ticket_line_item->save_this_and_descendants() > 0) {
415
-            // decrement parent line item quantity
416
-            $event_line_item = $ticket_line_item->parent();
417
-            if ($event_line_item instanceof EE_Line_Item && $event_line_item->OBJ_type() === 'Event') {
418
-                $event_line_item->set_quantity($event_line_item->quantity() - $qty);
419
-                $event_line_item->save();
420
-            }
421
-            EEH_Line_Item::get_grand_total_and_recalculate_everything($ticket_line_item);
422
-            return true;
423
-        }
424
-        return false;
425
-    }
426
-
427
-
428
-    /**
429
-     * reinstates (un-cancels?) a previously canceled ticket line item,
430
-     * by incrementing it's quantity by 1, and decrementing it's "type_cancellation" sub-line-item.
431
-     * ALL totals and subtotals will NEED TO BE UPDATED after performing this action
432
-     *
433
-     * @param EE_Line_Item $ticket_line_item
434
-     * @param int $qty
435
-     * @return bool success
436
-     * @throws \EE_Error
437
-     */
438
-    public static function reinstate_canceled_ticket_line_item(EE_Line_Item $ticket_line_item, $qty = 1)
439
-    {
440
-        // validate incoming line_item
441
-        if ($ticket_line_item->OBJ_type() !== 'Ticket') {
442
-            throw new EE_Error(
443
-                sprintf(
444
-                    __('The supplied line item must have an Object Type of "Ticket", not %1$s.', 'event_espresso'),
445
-                    $ticket_line_item->type()
446
-                )
447
-            );
448
-        }
449
-        // get cancellation sub line item
450
-        $cancellation_line_item = EEH_Line_Item::get_descendants_of_type(
451
-            $ticket_line_item,
452
-            EEM_Line_Item::type_cancellation
453
-        );
454
-        $cancellation_line_item = reset($cancellation_line_item);
455
-        // verify that this ticket was indeed previously cancelled
456
-        if (!$cancellation_line_item instanceof EE_Line_Item) {
457
-            return false;
458
-        }
459
-        if ($cancellation_line_item->quantity() > $qty) {
460
-            // decrement cancelled quantity
461
-            $cancellation_line_item->set_quantity($cancellation_line_item->quantity() - $qty);
462
-        } else if ($cancellation_line_item->quantity() == $qty) {
463
-            // decrement cancelled quantity in case anyone still has the object kicking around
464
-            $cancellation_line_item->set_quantity($cancellation_line_item->quantity() - $qty);
465
-            // delete because quantity will end up as 0
466
-            $cancellation_line_item->delete();
467
-            // and attempt to destroy the object,
468
-            // even though PHP won't actually destroy it until it needs the memory
469
-            unset($cancellation_line_item);
470
-        } else {
471
-            // what ?!?! negative quantity ?!?!
472
-            throw new EE_Error(
473
-                sprintf(
474
-                    __('Can not reinstate %1$d cancelled ticket(s) because the cancelled ticket quantity is only %2$d.',
475
-                        'event_espresso'),
476
-                    $qty,
477
-                    $cancellation_line_item->quantity()
478
-                )
479
-            );
480
-        }
481
-        // increment ticket quantity
482
-        $ticket_line_item->set_quantity($ticket_line_item->quantity() + $qty);
483
-        if ($ticket_line_item->save_this_and_descendants() > 0) {
484
-            // increment parent line item quantity
485
-            $event_line_item = $ticket_line_item->parent();
486
-            if ($event_line_item instanceof EE_Line_Item && $event_line_item->OBJ_type() === 'Event') {
487
-                $event_line_item->set_quantity($event_line_item->quantity() + $qty);
488
-            }
489
-            EEH_Line_Item::get_grand_total_and_recalculate_everything($ticket_line_item);
490
-            return true;
491
-        }
492
-        return false;
493
-    }
494
-
495
-
496
-    /**
497
-     * calls EEH_Line_Item::find_transaction_grand_total_for_line_item()
498
-     * then EE_Line_Item::recalculate_total_including_taxes() on the result
499
-     *
500
-     * @param EE_Line_Item $line_item
501
-     * @return \EE_Line_Item
502
-     */
503
-    public static function get_grand_total_and_recalculate_everything(EE_Line_Item $line_item)
504
-    {
505
-        $grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($line_item);
506
-        return $grand_total_line_item->recalculate_total_including_taxes();
507
-    }
508
-
509
-
510
-    /**
511
-     * Gets the line item which contains the subtotal of all the items
512
-     *
513
-     * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
514
-     * @return \EE_Line_Item
515
-     * @throws \EE_Error
516
-     */
517
-    public static function get_pre_tax_subtotal(EE_Line_Item $total_line_item)
518
-    {
519
-        $pre_tax_subtotal = $total_line_item->get_child_line_item('pre-tax-subtotal');
520
-        return $pre_tax_subtotal instanceof EE_Line_Item
521
-            ? $pre_tax_subtotal
522
-            : self::create_pre_tax_subtotal($total_line_item);
523
-    }
524
-
525
-
526
-    /**
527
-     * Gets the line item for the taxes subtotal
528
-     *
529
-     * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
530
-     * @return \EE_Line_Item
531
-     * @throws \EE_Error
532
-     */
533
-    public static function get_taxes_subtotal(EE_Line_Item $total_line_item)
534
-    {
535
-        $taxes = $total_line_item->get_child_line_item('taxes');
536
-        return $taxes ? $taxes : self::create_taxes_subtotal($total_line_item);
537
-    }
538
-
539
-
540
-    /**
541
-     * sets the TXN ID on an EE_Line_Item if passed a valid EE_Transaction object
542
-     *
543
-     * @param EE_Line_Item $line_item
544
-     * @param EE_Transaction $transaction
545
-     * @return void
546
-     * @throws \EE_Error
547
-     */
548
-    public static function set_TXN_ID(EE_Line_Item $line_item, $transaction = NULL)
549
-    {
550
-        if ($transaction) {
551
-            /** @type EEM_Transaction $EEM_Transaction */
552
-            $EEM_Transaction = EE_Registry::instance()->load_model('Transaction');
553
-            $TXN_ID = $EEM_Transaction->ensure_is_ID($transaction);
554
-            $line_item->set_TXN_ID($TXN_ID);
555
-        }
556
-    }
557
-
558
-
559
-    /**
560
-     * Creates a new default total line item for the transaction,
561
-     * and its tickets subtotal and taxes subtotal line items (and adds the
562
-     * existing taxes as children of the taxes subtotal line item)
563
-     *
564
-     * @param EE_Transaction $transaction
565
-     * @return \EE_Line_Item of type total
566
-     * @throws \EE_Error
567
-     */
568
-    public static function create_total_line_item($transaction = NULL)
569
-    {
570
-        $total_line_item = EE_Line_Item::new_instance(array(
571
-            'LIN_code' => 'total',
572
-            'LIN_name' => __('Grand Total', 'event_espresso'),
573
-            'LIN_type' => EEM_Line_Item::type_total,
574
-            'OBJ_type' => 'Transaction'
575
-        ));
576
-        $total_line_item = apply_filters(
577
-            'FHEE__EEH_Line_Item__create_total_line_item__total_line_item',
578
-            $total_line_item
579
-        );
580
-        self::set_TXN_ID($total_line_item, $transaction);
581
-        self::create_pre_tax_subtotal($total_line_item, $transaction);
582
-        self::create_taxes_subtotal($total_line_item, $transaction);
583
-        return $total_line_item;
584
-    }
585
-
586
-
587
-    /**
588
-     * Creates a default items subtotal line item
589
-     *
590
-     * @param EE_Line_Item $total_line_item
591
-     * @param EE_Transaction $transaction
592
-     * @return EE_Line_Item
593
-     * @throws \EE_Error
594
-     */
595
-    protected static function create_pre_tax_subtotal(EE_Line_Item $total_line_item, $transaction = NULL)
596
-    {
597
-        $pre_tax_line_item = EE_Line_Item::new_instance(array(
598
-            'LIN_code' => 'pre-tax-subtotal',
599
-            'LIN_name' => __('Pre-Tax Subtotal', 'event_espresso'),
600
-            'LIN_type' => EEM_Line_Item::type_sub_total
601
-        ));
602
-        $pre_tax_line_item = apply_filters(
603
-            'FHEE__EEH_Line_Item__create_pre_tax_subtotal__pre_tax_line_item',
604
-            $pre_tax_line_item
605
-        );
606
-        self::set_TXN_ID($pre_tax_line_item, $transaction);
607
-        $total_line_item->add_child_line_item($pre_tax_line_item);
608
-        self::create_event_subtotal($pre_tax_line_item, $transaction);
609
-        return $pre_tax_line_item;
610
-    }
611
-
612
-
613
-    /**
614
-     * Creates a line item for the taxes subtotal and finds all the tax prices
615
-     * and applies taxes to it
616
-     *
617
-     * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
618
-     * @param EE_Transaction $transaction
619
-     * @return EE_Line_Item
620
-     * @throws \EE_Error
621
-     */
622
-    protected static function create_taxes_subtotal(EE_Line_Item $total_line_item, $transaction = NULL)
623
-    {
624
-        $tax_line_item = EE_Line_Item::new_instance(array(
625
-            'LIN_code' => 'taxes',
626
-            'LIN_name' => __('Taxes', 'event_espresso'),
627
-            'LIN_type' => EEM_Line_Item::type_tax_sub_total,
628
-            'LIN_order' => 1000,//this should always come last
629
-        ));
630
-        $tax_line_item = apply_filters(
631
-            'FHEE__EEH_Line_Item__create_taxes_subtotal__tax_line_item',
632
-            $tax_line_item
633
-        );
634
-        self::set_TXN_ID($tax_line_item, $transaction);
635
-        $total_line_item->add_child_line_item($tax_line_item);
636
-        //and lastly, add the actual taxes
637
-        self::apply_taxes($total_line_item);
638
-        return $tax_line_item;
639
-    }
640
-
641
-
642
-    /**
643
-     * Creates a default items subtotal line item
644
-     *
645
-     * @param EE_Line_Item $pre_tax_line_item
646
-     * @param EE_Transaction $transaction
647
-     * @param EE_Event $event
648
-     * @return EE_Line_Item
649
-     * @throws \EE_Error
650
-     */
651
-    public static function create_event_subtotal(EE_Line_Item $pre_tax_line_item, $transaction = NULL, $event = NULL)
652
-    {
653
-        $event_line_item = EE_Line_Item::new_instance(array(
654
-            'LIN_code' => self::get_event_code($event),
655
-            'LIN_name' => self::get_event_name($event),
656
-            'LIN_desc' => self::get_event_desc($event),
657
-            'LIN_type' => EEM_Line_Item::type_sub_total,
658
-            'OBJ_type' => 'Event',
659
-            'OBJ_ID' => $event instanceof EE_Event ? $event->ID() : 0
660
-        ));
661
-        $event_line_item = apply_filters(
662
-            'FHEE__EEH_Line_Item__create_event_subtotal__event_line_item',
663
-            $event_line_item
664
-        );
665
-        self::set_TXN_ID($event_line_item, $transaction);
666
-        $pre_tax_line_item->add_child_line_item($event_line_item);
667
-        return $event_line_item;
668
-    }
669
-
670
-
671
-    /**
672
-     * Gets what the event ticket's code SHOULD be
673
-     *
674
-     * @param EE_Event $event
675
-     * @return string
676
-     * @throws \EE_Error
677
-     */
678
-    public static function get_event_code($event)
679
-    {
680
-        return 'event-' . ($event instanceof EE_Event ? $event->ID() : '0');
681
-    }
682
-
683
-    /**
684
-     * Gets the event name
685
-     * @param EE_Event $event
686
-     * @return string
687
-     */
688
-    public static function get_event_name($event)
689
-    {
690
-        return $event instanceof EE_Event ? $event->name() : __('Event', 'event_espresso');
691
-    }
692
-
693
-    /**
694
-     * Gets the event excerpt
695
-     * @param EE_Event $event
696
-     * @return string
697
-     */
698
-    public static function get_event_desc($event)
699
-    {
700
-        return $event instanceof EE_Event ? $event->short_description() : '';
701
-    }
702
-
703
-    /**
704
-     * Given the grand total line item and a ticket, finds the event sub-total
705
-     * line item the ticket's purchase should be added onto
706
-     *
707
-     * @access public
708
-     * @param EE_Line_Item $grand_total the grand total line item
709
-     * @param EE_Ticket $ticket
710
-     * @throws \EE_Error
711
-     * @return EE_Line_Item
712
-     */
713
-    public static function get_event_line_item_for_ticket(EE_Line_Item $grand_total, EE_Ticket $ticket)
714
-    {
715
-        $first_datetime = $ticket->first_datetime();
716
-        if (!$first_datetime instanceof EE_Datetime) {
717
-            throw new EE_Error(
718
-                sprintf(__('The supplied ticket (ID %d) has no datetimes', 'event_espresso'), $ticket->ID())
719
-            );
720
-        }
721
-        $event = $first_datetime->event();
722
-        if (!$event instanceof EE_Event) {
723
-            throw new EE_Error(
724
-                sprintf(
725
-                    __('The supplied ticket (ID %d) has no event data associated with it.', 'event_espresso'),
726
-                    $ticket->ID()
727
-                )
728
-            );
729
-        }
730
-        $events_sub_total = EEH_Line_Item::get_event_line_item($grand_total, $event);
731
-        if (!$events_sub_total instanceof EE_Line_Item) {
732
-            throw new EE_Error(
733
-                sprintf(
734
-                    __('There is no events sub-total for ticket %s on total line item %d', 'event_espresso'),
735
-                    $ticket->ID(),
736
-                    $grand_total->ID()
737
-                )
738
-            );
739
-        }
740
-        return $events_sub_total;
741
-    }
742
-
743
-
744
-    /**
745
-     * Gets the event line item
746
-     *
747
-     * @param EE_Line_Item $grand_total
748
-     * @param EE_Event $event
749
-     * @return EE_Line_Item for the event subtotal which is a child of $grand_total
750
-     * @throws \EE_Error
751
-     */
752
-    public static function get_event_line_item(EE_Line_Item $grand_total, $event)
753
-    {
754
-        /** @type EE_Event $event */
755
-        $event = EEM_Event::instance()->ensure_is_obj($event, true);
756
-        $event_line_item = NULL;
757
-        $found = false;
758
-        foreach (EEH_Line_Item::get_event_subtotals($grand_total) as $event_line_item) {
759
-            // default event subtotal, we should only ever find this the first time this method is called
760
-            if (!$event_line_item->OBJ_ID()) {
761
-                // let's use this! but first... set the event details
762
-                EEH_Line_Item::set_event_subtotal_details($event_line_item, $event);
763
-                $found = true;
764
-                break;
765
-            } else if ($event_line_item->OBJ_ID() === $event->ID()) {
766
-                // found existing line item for this event in the cart, so break out of loop and use this one
767
-                $found = true;
768
-                break;
769
-            }
770
-        }
771
-        if (!$found) {
772
-            //there is no event sub-total yet, so add it
773
-            $pre_tax_subtotal = EEH_Line_Item::get_pre_tax_subtotal($grand_total);
774
-            // create a new "event" subtotal below that
775
-            $event_line_item = EEH_Line_Item::create_event_subtotal($pre_tax_subtotal, null, $event);
776
-            // and set the event details
777
-            EEH_Line_Item::set_event_subtotal_details($event_line_item, $event);
778
-        }
779
-        return $event_line_item;
780
-    }
781
-
782
-
783
-    /**
784
-     * Creates a default items subtotal line item
785
-     *
786
-     * @param EE_Line_Item $event_line_item
787
-     * @param EE_Event $event
788
-     * @param EE_Transaction $transaction
789
-     * @return EE_Line_Item
790
-     * @throws \EE_Error
791
-     */
792
-    public static function set_event_subtotal_details(
793
-        EE_Line_Item $event_line_item,
794
-        EE_Event $event,
795
-        $transaction = null
796
-    )
797
-    {
798
-        if ($event instanceof EE_Event) {
799
-            $event_line_item->set_code(self::get_event_code($event));
800
-            $event_line_item->set_name(self::get_event_name($event));
801
-            $event_line_item->set_desc(self::get_event_desc($event));
802
-            $event_line_item->set_OBJ_ID($event->ID());
803
-        }
804
-        self::set_TXN_ID($event_line_item, $transaction);
805
-    }
806
-
807
-
808
-    /**
809
-     * Finds what taxes should apply, adds them as tax line items under the taxes sub-total,
810
-     * and recalculates the taxes sub-total and the grand total. Resets the taxes, so
811
-     * any old taxes are removed
812
-     *
813
-     * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
814
-     * @throws \EE_Error
815
-     */
816
-    public static function apply_taxes(EE_Line_Item $total_line_item)
817
-    {
818
-        /** @type EEM_Price $EEM_Price */
819
-        $EEM_Price = EE_Registry::instance()->load_model('Price');
820
-        // get array of taxes via Price Model
821
-        $ordered_taxes = $EEM_Price->get_all_prices_that_are_taxes();
822
-        ksort($ordered_taxes);
823
-        $taxes_line_item = self::get_taxes_subtotal($total_line_item);
824
-        //just to be safe, remove its old tax line items
825
-        $taxes_line_item->delete_children_line_items();
826
-        //loop thru taxes
827
-        foreach ($ordered_taxes as $order => $taxes) {
828
-            foreach ($taxes as $tax) {
829
-                if ($tax instanceof EE_Price) {
830
-                    $tax_line_item = EE_Line_Item::new_instance(
831
-                        array(
832
-                            'LIN_name' => $tax->name(),
833
-                            'LIN_desc' => $tax->desc(),
834
-                            'LIN_percent' => $tax->amount(),
835
-                            'LIN_is_taxable' => false,
836
-                            'LIN_order' => $order,
837
-                            'LIN_total' => 0,
838
-                            'LIN_type' => EEM_Line_Item::type_tax,
839
-                            'OBJ_type' => 'Price',
840
-                            'OBJ_ID' => $tax->ID()
841
-                        )
842
-                    );
843
-                    $tax_line_item = apply_filters(
844
-                        'FHEE__EEH_Line_Item__apply_taxes__tax_line_item',
845
-                        $tax_line_item
846
-                    );
847
-                    $taxes_line_item->add_child_line_item($tax_line_item);
848
-                }
849
-            }
850
-        }
851
-        $total_line_item->recalculate_total_including_taxes();
852
-    }
853
-
854
-
855
-    /**
856
-     * Ensures that taxes have been applied to the order, if not applies them.
857
-     * Returns the total amount of tax
858
-     *
859
-     * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
860
-     * @return float
861
-     * @throws \EE_Error
862
-     */
863
-    public static function ensure_taxes_applied($total_line_item)
864
-    {
865
-        $taxes_subtotal = self::get_taxes_subtotal($total_line_item);
866
-        if (!$taxes_subtotal->children()) {
867
-            self::apply_taxes($total_line_item);
868
-        }
869
-        return $taxes_subtotal->total();
870
-    }
871
-
872
-
873
-    /**
874
-     * Deletes ALL children of the passed line item
875
-     *
876
-     * @param EE_Line_Item $parent_line_item
877
-     * @return bool
878
-     * @throws \EE_Error
879
-     */
880
-    public static function delete_all_child_items(EE_Line_Item $parent_line_item)
881
-    {
882
-        $deleted = 0;
883
-        foreach ($parent_line_item->children() as $child_line_item) {
884
-            if ($child_line_item instanceof EE_Line_Item) {
885
-                $deleted += EEH_Line_Item::delete_all_child_items($child_line_item);
886
-                if ($child_line_item->ID()) {
887
-                    $child_line_item->delete();
888
-                    unset($child_line_item);
889
-                } else {
890
-                    $parent_line_item->delete_child_line_item($child_line_item->code());
891
-                }
892
-                $deleted++;
893
-            }
894
-        }
895
-        return $deleted;
896
-    }
897
-
898
-
899
-    /**
900
-     * Deletes the line items as indicated by the line item code(s) provided,
901
-     * regardless of where they're found in the line item tree. Automatically
902
-     * re-calculates the line item totals and updates the related transaction. But
903
-     * DOES NOT automatically upgrade the transaction's registrations' final prices (which
904
-     * should probably change because of this).
905
-     * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
906
-     * after using this, to keep the registration final prices in-sync with the transaction's total.
907
-     * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
908
-     * @param array|bool|string $line_item_codes
909
-     * @return int number of items successfully removed
910
-     */
911
-    public static function delete_items(EE_Line_Item $total_line_item, $line_item_codes = FALSE)
912
-    {
913
-
914
-        if ($total_line_item->type() !== EEM_Line_Item::type_total) {
915
-            EE_Error::doing_it_wrong(
916
-                'EEH_Line_Item::delete_items',
917
-                __(
918
-                    'This static method should only be called with a TOTAL line item, otherwise we won\'t recalculate the totals correctly',
919
-                    'event_espresso'
920
-                ),
921
-                '4.6.18'
922
-            );
923
-        }
924
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
925
-
926
-        // check if only a single line_item_id was passed
927
-        if (!empty($line_item_codes) && !is_array($line_item_codes)) {
928
-            // place single line_item_id in an array to appear as multiple line_item_ids
929
-            $line_item_codes = array($line_item_codes);
930
-        }
931
-        $removals = 0;
932
-        // cycle thru line_item_ids
933
-        foreach ($line_item_codes as $line_item_id) {
934
-            $removals += $total_line_item->delete_child_line_item($line_item_id);
935
-        }
936
-
937
-        if ($removals > 0) {
938
-            $total_line_item->recalculate_taxes_and_tax_total();
939
-            return $removals;
940
-        } else {
941
-            return FALSE;
942
-        }
943
-    }
944
-
945
-
946
-    /**
947
-     * Overwrites the previous tax by clearing out the old taxes, and creates a new
948
-     * tax and updates the total line item accordingly
949
-     *
950
-     * @param EE_Line_Item $total_line_item
951
-     * @param float $amount
952
-     * @param string $name
953
-     * @param string $description
954
-     * @param string $code
955
-     * @param boolean $add_to_existing_line_item
956
-     *                          if true, and a duplicate line item with the same code is found,
957
-     *                          $amount will be added onto it; otherwise will simply set the taxes to match $amount
958
-     * @return EE_Line_Item the new tax line item created
959
-     * @throws \EE_Error
960
-     */
961
-    public static function set_total_tax_to(
962
-        EE_Line_Item $total_line_item,
963
-        $amount,
964
-        $name = null,
965
-        $description = null,
966
-        $code = null,
967
-        $add_to_existing_line_item = false
968
-    )
969
-    {
970
-        $tax_subtotal = self::get_taxes_subtotal($total_line_item);
971
-        $taxable_total = $total_line_item->taxable_total();
972
-
973
-        if ($add_to_existing_line_item) {
974
-            $new_tax = $tax_subtotal->get_child_line_item($code);
975
-            EEM_Line_Item::instance()->delete(
976
-                array(array('LIN_code' => array('!=', $code), 'LIN_parent' => $tax_subtotal->ID()))
977
-            );
978
-        } else {
979
-            $new_tax = null;
980
-            $tax_subtotal->delete_children_line_items();
981
-        }
982
-        if ($new_tax) {
983
-            $new_tax->set_total($new_tax->total() + $amount);
984
-            $new_tax->set_percent($taxable_total ? $new_tax->total() / $taxable_total * 100 : 0);
985
-        } else {
986
-            //no existing tax item. Create it
987
-            $new_tax = EE_Line_Item::new_instance(array(
988
-                'TXN_ID' => $total_line_item->TXN_ID(),
989
-                'LIN_name' => $name ? $name : __('Tax', 'event_espresso'),
990
-                'LIN_desc' => $description ? $description : '',
991
-                'LIN_percent' => $taxable_total ? ($amount / $taxable_total * 100) : 0,
992
-                'LIN_total' => $amount,
993
-                'LIN_parent' => $tax_subtotal->ID(),
994
-                'LIN_type' => EEM_Line_Item::type_tax,
995
-                'LIN_code' => $code
996
-            ));
997
-        }
998
-
999
-        $new_tax = apply_filters(
1000
-            'FHEE__EEH_Line_Item__set_total_tax_to__new_tax_subtotal',
1001
-            $new_tax,
1002
-            $total_line_item
1003
-        );
1004
-        $new_tax->save();
1005
-        $tax_subtotal->set_total($new_tax->total());
1006
-        $tax_subtotal->save();
1007
-        $total_line_item->recalculate_total_including_taxes();
1008
-        return $new_tax;
1009
-    }
1010
-
1011
-
1012
-    /**
1013
-     * Makes all the line items which are children of $line_item taxable (or not).
1014
-     * Does NOT save the line items
1015
-     * @param EE_Line_Item $line_item
1016
-     * @param string $code_substring_for_whitelist if this string is part of the line item's code
1017
-     *  it will be whitelisted (ie, except from becoming taxable)
1018
-     * @param boolean $taxable
1019
-     */
1020
-    public static function set_line_items_taxable(
1021
-        EE_Line_Item $line_item,
1022
-        $taxable = true,
1023
-        $code_substring_for_whitelist = null
1024
-    )
1025
-    {
1026
-        $whitelisted = false;
1027
-        if ($code_substring_for_whitelist !== null) {
1028
-            $whitelisted = strpos($line_item->code(), $code_substring_for_whitelist) !== false ? true : false;
1029
-        }
1030
-        if (!$whitelisted && $line_item->is_line_item()) {
1031
-            $line_item->set_is_taxable($taxable);
1032
-        }
1033
-        foreach ($line_item->children() as $child_line_item) {
1034
-            EEH_Line_Item::set_line_items_taxable($child_line_item, $taxable, $code_substring_for_whitelist);
1035
-        }
1036
-    }
1037
-
1038
-
1039
-    /**
1040
-     * Gets all descendants that are event subtotals
1041
-     *
1042
-     * @uses  EEH_Line_Item::get_subtotals_of_object_type()
1043
-     * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1044
-     * @return EE_Line_Item[]
1045
-     */
1046
-    public static function get_event_subtotals(EE_Line_Item $parent_line_item)
1047
-    {
1048
-        return self::get_subtotals_of_object_type($parent_line_item, 'Event');
1049
-    }
1050
-
1051
-
1052
-    /**
1053
-     * Gets all descendants subtotals that match the supplied object type
1054
-     *
1055
-     * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1056
-     * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1057
-     * @param string $obj_type
1058
-     * @return EE_Line_Item[]
1059
-     */
1060
-    public static function get_subtotals_of_object_type(EE_Line_Item $parent_line_item, $obj_type = '')
1061
-    {
1062
-        return self::_get_descendants_by_type_and_object_type(
1063
-            $parent_line_item,
1064
-            EEM_Line_Item::type_sub_total,
1065
-            $obj_type
1066
-        );
1067
-    }
1068
-
1069
-
1070
-    /**
1071
-     * Gets all descendants that are tickets
1072
-     *
1073
-     * @uses  EEH_Line_Item::get_line_items_of_object_type()
1074
-     * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1075
-     * @return EE_Line_Item[]
1076
-     */
1077
-    public static function get_ticket_line_items(EE_Line_Item $parent_line_item)
1078
-    {
1079
-        return self::get_line_items_of_object_type($parent_line_item, 'Ticket');
1080
-    }
1081
-
1082
-
1083
-    /**
1084
-     * Gets all descendants subtotals that match the supplied object type
1085
-     *
1086
-     * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1087
-     * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1088
-     * @param string $obj_type
1089
-     * @return EE_Line_Item[]
1090
-     */
1091
-    public static function get_line_items_of_object_type(EE_Line_Item $parent_line_item, $obj_type = '')
1092
-    {
1093
-        return self::_get_descendants_by_type_and_object_type($parent_line_item, EEM_Line_Item::type_line_item, $obj_type);
1094
-    }
1095
-
1096
-
1097
-    /**
1098
-     * Gets all the descendants (ie, children or children of children etc) that are of the type 'tax'
1099
-     * @uses  EEH_Line_Item::get_descendants_of_type()
1100
-     * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1101
-     * @return EE_Line_Item[]
1102
-     */
1103
-    public static function get_tax_descendants(EE_Line_Item $parent_line_item)
1104
-    {
1105
-        return EEH_Line_Item::get_descendants_of_type($parent_line_item, EEM_Line_Item::type_tax);
1106
-    }
1107
-
1108
-
1109
-    /**
1110
-     * Gets all the real items purchased which are children of this item
1111
-     * @uses  EEH_Line_Item::get_descendants_of_type()
1112
-     * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1113
-     * @return EE_Line_Item[]
1114
-     */
1115
-    public static function get_line_item_descendants(EE_Line_Item $parent_line_item)
1116
-    {
1117
-        return EEH_Line_Item::get_descendants_of_type($parent_line_item, EEM_Line_Item::type_line_item);
1118
-    }
1119
-
1120
-
1121
-    /**
1122
-     * Gets all descendants of supplied line item that match the supplied line item type
1123
-     *
1124
-     * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1125
-     * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1126
-     * @param string $line_item_type one of the EEM_Line_Item constants
1127
-     * @return EE_Line_Item[]
1128
-     */
1129
-    public static function get_descendants_of_type(EE_Line_Item $parent_line_item, $line_item_type)
1130
-    {
1131
-        return self::_get_descendants_by_type_and_object_type($parent_line_item, $line_item_type, NULL);
1132
-    }
1133
-
1134
-
1135
-    /**
1136
-     * Gets all descendants of supplied line item that match the supplied line item type and possibly the object type as well
1137
-     *
1138
-     * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1139
-     * @param string $line_item_type one of the EEM_Line_Item constants
1140
-     * @param string | NULL $obj_type object model class name (minus prefix) or NULL to ignore object type when searching
1141
-     * @return EE_Line_Item[]
1142
-     */
1143
-    protected static function _get_descendants_by_type_and_object_type(
1144
-        EE_Line_Item $parent_line_item,
1145
-        $line_item_type,
1146
-        $obj_type = null
1147
-    )
1148
-    {
1149
-        $objects = array();
1150
-        foreach ($parent_line_item->children() as $child_line_item) {
1151
-            if ($child_line_item instanceof EE_Line_Item) {
1152
-                if (
1153
-                    $child_line_item->type() === $line_item_type
1154
-                    && (
1155
-                        $child_line_item->OBJ_type() === $obj_type || $obj_type === null
1156
-                    )
1157
-                ) {
1158
-                    $objects[] = $child_line_item;
1159
-                } else {
1160
-                    //go-through-all-its children looking for more matches
1161
-                    $objects = array_merge(
1162
-                        $objects,
1163
-                        self::_get_descendants_by_type_and_object_type(
1164
-                            $child_line_item,
1165
-                            $line_item_type,
1166
-                            $obj_type
1167
-                        )
1168
-                    );
1169
-                }
1170
-            }
1171
-        }
1172
-        return $objects;
1173
-    }
1174
-
1175
-
1176
-    /**
1177
-     * Gets all descendants subtotals that match the supplied object type
1178
-     *
1179
-     * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1180
-     * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1181
-     * @param string $OBJ_type object type (like Event)
1182
-     * @param array $OBJ_IDs array of OBJ_IDs
1183
-     * @return EE_Line_Item[]
1184
-     */
1185
-    public static function get_line_items_by_object_type_and_IDs(
1186
-        EE_Line_Item $parent_line_item,
1187
-        $OBJ_type = '',
1188
-        $OBJ_IDs = array()
1189
-    )
1190
-    {
1191
-        return self::_get_descendants_by_object_type_and_object_ID($parent_line_item, $OBJ_type, $OBJ_IDs);
1192
-    }
1193
-
1194
-
1195
-    /**
1196
-     * Gets all descendants of supplied line item that match the supplied line item type and possibly the object type as well
1197
-     *
1198
-     * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1199
-     * @param string $OBJ_type object type (like Event)
1200
-     * @param array $OBJ_IDs array of OBJ_IDs
1201
-     * @return EE_Line_Item[]
1202
-     */
1203
-    protected static function _get_descendants_by_object_type_and_object_ID(
1204
-        EE_Line_Item $parent_line_item,
1205
-        $OBJ_type,
1206
-        $OBJ_IDs
1207
-    )
1208
-    {
1209
-        $objects = array();
1210
-        foreach ($parent_line_item->children() as $child_line_item) {
1211
-            if ($child_line_item instanceof EE_Line_Item) {
1212
-                if (
1213
-                    $child_line_item->OBJ_type() === $OBJ_type
1214
-                    && is_array($OBJ_IDs)
1215
-                    && in_array($child_line_item->OBJ_ID(), $OBJ_IDs)
1216
-                ) {
1217
-                    $objects[] = $child_line_item;
1218
-                } else {
1219
-                    //go-through-all-its children looking for more matches
1220
-                    $objects = array_merge(
1221
-                        $objects,
1222
-                        self::_get_descendants_by_object_type_and_object_ID(
1223
-                            $child_line_item,
1224
-                            $OBJ_type,
1225
-                            $OBJ_IDs
1226
-                        )
1227
-                    );
1228
-                }
1229
-            }
1230
-        }
1231
-        return $objects;
1232
-    }
1233
-
1234
-
1235
-    /**
1236
-     * Uses a breadth-first-search in order to find the nearest descendant of
1237
-     * the specified type and returns it, else NULL
1238
-     *
1239
-     * @uses  EEH_Line_Item::_get_nearest_descendant()
1240
-     * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1241
-     * @param string $type like one of the EEM_Line_Item::type_*
1242
-     * @return EE_Line_Item
1243
-     */
1244
-    public static function get_nearest_descendant_of_type(EE_Line_Item $parent_line_item, $type)
1245
-    {
1246
-        return self::_get_nearest_descendant($parent_line_item, 'LIN_type', $type);
1247
-    }
1248
-
1249
-
1250
-    /**
1251
-     * Uses a breadth-first-search in order to find the nearest descendant
1252
-     * having the specified LIN_code and returns it, else NULL
1253
-     *
1254
-     * @uses  EEH_Line_Item::_get_nearest_descendant()
1255
-     * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1256
-     * @param string $code any value used for LIN_code
1257
-     * @return EE_Line_Item
1258
-     */
1259
-    public static function get_nearest_descendant_having_code(EE_Line_Item $parent_line_item, $code)
1260
-    {
1261
-        return self::_get_nearest_descendant($parent_line_item, 'LIN_code', $code);
1262
-    }
1263
-
1264
-
1265
-    /**
1266
-     * Uses a breadth-first-search in order to find the nearest descendant
1267
-     * having the specified LIN_code and returns it, else NULL
1268
-     *
1269
-     * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1270
-     * @param string $search_field name of EE_Line_Item property
1271
-     * @param string $value any value stored in $search_field
1272
-     * @return EE_Line_Item
1273
-     */
1274
-    protected static function _get_nearest_descendant(EE_Line_Item $parent_line_item, $search_field, $value)
1275
-    {
1276
-        foreach ($parent_line_item->children() as $child) {
1277
-            if ($child->get($search_field) == $value) {
1278
-                return $child;
1279
-            }
1280
-        }
1281
-        foreach ($parent_line_item->children() as $child) {
1282
-            $descendant_found = self::_get_nearest_descendant($child, $search_field, $value);
1283
-            if ($descendant_found) {
1284
-                return $descendant_found;
1285
-            }
1286
-        }
1287
-        return NULL;
1288
-    }
1289
-
1290
-
1291
-    /**
1292
-     * if passed line item has a TXN ID, uses that to jump directly to the grand total line item for the transaction,
1293
-     * else recursively walks up the line item tree until a parent of type total is found,
1294
-     *
1295
-     * @param EE_Line_Item $line_item
1296
-     * @return \EE_Line_Item
1297
-     * @throws \EE_Error
1298
-     */
1299
-    public static function find_transaction_grand_total_for_line_item(EE_Line_Item $line_item)
1300
-    {
1301
-        if ($line_item->TXN_ID()) {
1302
-            $total_line_item = $line_item->transaction()->total_line_item(false);
1303
-            if ($total_line_item instanceof EE_Line_Item) {
1304
-                return $total_line_item;
1305
-            }
1306
-        } else {
1307
-            $line_item_parent = $line_item->parent();
1308
-            if ($line_item_parent instanceof EE_Line_Item) {
1309
-                if ($line_item_parent->is_total()) {
1310
-                    return $line_item_parent;
1311
-                }
1312
-                return EEH_Line_Item::find_transaction_grand_total_for_line_item($line_item_parent);
1313
-            }
1314
-        }
1315
-        throw new EE_Error(
1316
-            sprintf(
1317
-                __('A valid grand total for line item %1$d was not found.', 'event_espresso'),
1318
-                $line_item->ID()
1319
-            )
1320
-        );
1321
-    }
1322
-
1323
-
1324
-    /**
1325
-     * Prints out a representation of the line item tree
1326
-     *
1327
-     * @param EE_Line_Item $line_item
1328
-     * @param int $indentation
1329
-     * @return void
1330
-     * @throws \EE_Error
1331
-     */
1332
-    public static function visualize(EE_Line_Item $line_item, $indentation = 0)
1333
-    {
1334
-        echo defined('EE_TESTS_DIR') ? "\n" : '<br />';
1335
-        if (!$indentation) {
1336
-            echo defined('EE_TESTS_DIR') ? "\n" : '<br />';
1337
-        }
1338
-        for ($i = 0; $i < $indentation; $i++) {
1339
-            echo ". ";
1340
-        }
1341
-        $breakdown = '';
1342
-        if ($line_item->is_line_item()) {
1343
-            if ($line_item->is_percent()) {
1344
-                $breakdown = "{$line_item->percent()}%";
1345
-            } else {
1346
-                $breakdown = '$' . "{$line_item->unit_price()} x {$line_item->quantity()}";
1347
-            }
1348
-        }
1349
-        echo $line_item->name() . " [ ID:{$line_item->ID()} | qty:{$line_item->quantity()} ] {$line_item->type()} : " . '$' . "{$line_item->total()}";
1350
-        if ($breakdown) {
1351
-            echo " ( {$breakdown} )";
1352
-        }
1353
-        if ($line_item->is_taxable()) {
1354
-            echo "  * taxable";
1355
-        }
1356
-        if ($line_item->children()) {
1357
-            foreach ($line_item->children() as $child) {
1358
-                self::visualize($child, $indentation + 1);
1359
-            }
1360
-        }
1361
-    }
1362
-
1363
-
1364
-    /**
1365
-     * Calculates the registration's final price, taking into account that they
1366
-     * need to not only help pay for their OWN ticket, but also any transaction-wide surcharges and taxes,
1367
-     * and receive a portion of any transaction-wide discounts.
1368
-     * eg1, if I buy a $1 ticket and brent buys a $9 ticket, and we receive a $5 discount
1369
-     * then I'll get 1/10 of that $5 discount, which is $0.50, and brent will get
1370
-     * 9/10ths of that $5 discount, which is $4.50. So my final price should be $0.50
1371
-     * and brent's final price should be $5.50.
1372
-     *
1373
-     * In order to do this, we basically need to traverse the line item tree calculating
1374
-     * the running totals (just as if we were recalculating the total), but when we identify
1375
-     * regular line items, we need to keep track of their share of the grand total.
1376
-     * Also, we need to keep track of the TAXABLE total for each ticket purchase, so
1377
-     * we can know how to apply taxes to it. (Note: "taxable total" does not equal the "pretax total"
1378
-     * when there are non-taxable items; otherwise they would be the same)
1379
-     *
1380
-     * @param EE_Line_Item $line_item
1381
-     * @param array $billable_ticket_quantities array of EE_Ticket IDs and their corresponding quantity that
1382
-     *                                                                            can be included in price calculations at this moment
1383
-     * @return array        keys are line items for tickets IDs and values are their share of the running total,
1384
-     *                                          plus the key 'total', and 'taxable' which also has keys of all the ticket IDs. Eg
1385
-     *                                          array(
1386
-     *                                          12 => 4.3
1387
-     *                                          23 => 8.0
1388
-     *                                          'total' => 16.6,
1389
-     *                                          'taxable' => array(
1390
-     *                                          12 => 10,
1391
-     *                                          23 => 4
1392
-     *                                          ).
1393
-     *                                          So to find which registrations have which final price, we need to find which line item
1394
-     *                                          is theirs, which can be done with
1395
-     *                                          `EEM_Line_Item::instance()->get_line_item_for_registration( $registration );`
1396
-     */
1397
-    public static function calculate_reg_final_prices_per_line_item(EE_Line_Item $line_item, $billable_ticket_quantities = array())
1398
-    {
1399
-        //init running grand total if not already
1400
-        if (!isset($running_totals['total'])) {
1401
-            $running_totals['total'] = 0;
1402
-        }
1403
-        if (!isset($running_totals['taxable'])) {
1404
-            $running_totals['taxable'] = array('total' => 0);
1405
-        }
1406
-        foreach ($line_item->children() as $child_line_item) {
1407
-            switch ($child_line_item->type()) {
1408
-
1409
-                case EEM_Line_Item::type_sub_total :
1410
-                    $running_totals_from_subtotal = EEH_Line_Item::calculate_reg_final_prices_per_line_item($child_line_item, $billable_ticket_quantities);
1411
-                    //combine arrays but preserve numeric keys
1412
-                    $running_totals = array_replace_recursive($running_totals_from_subtotal, $running_totals);
1413
-                    $running_totals['total'] += $running_totals_from_subtotal['total'];
1414
-                    $running_totals['taxable']['total'] += $running_totals_from_subtotal['taxable']['total'];
1415
-                    break;
1416
-
1417
-                case EEM_Line_Item::type_tax_sub_total :
1418
-
1419
-                    //find how much the taxes percentage is
1420
-                    if ($child_line_item->percent() !== 0) {
1421
-                        $tax_percent_decimal = $child_line_item->percent() / 100;
1422
-                    } else {
1423
-                        $tax_percent_decimal = EE_Taxes::get_total_taxes_percentage() / 100;
1424
-                    }
1425
-                    //and apply to all the taxable totals, and add to the pretax totals
1426
-                    foreach ($running_totals as $line_item_id => $this_running_total) {
1427
-                        //"total" and "taxable" array key is an exception
1428
-                        if ($line_item_id === 'taxable') {
1429
-                            continue;
1430
-                        }
1431
-                        $taxable_total = $running_totals['taxable'][$line_item_id];
1432
-                        $running_totals[$line_item_id] += ($taxable_total * $tax_percent_decimal);
1433
-                    }
1434
-                    break;
1435
-
1436
-                case EEM_Line_Item::type_line_item :
1437
-
1438
-                    // ticket line items or ????
1439
-                    if ($child_line_item->OBJ_type() === 'Ticket') {
1440
-                        // kk it's a ticket
1441
-                        if (isset($running_totals[$child_line_item->ID()])) {
1442
-                            //huh? that shouldn't happen.
1443
-                            $running_totals['total'] += $child_line_item->total();
1444
-                        } else {
1445
-                            //its not in our running totals yet. great.
1446
-                            if ($child_line_item->is_taxable()) {
1447
-                                $taxable_amount = $child_line_item->unit_price();
1448
-                            } else {
1449
-                                $taxable_amount = 0;
1450
-                            }
1451
-                            // are we only calculating totals for some tickets?
1452
-                            if (isset($billable_ticket_quantities[$child_line_item->OBJ_ID()])) {
1453
-                                $quantity = $billable_ticket_quantities[$child_line_item->OBJ_ID()];
1454
-                                $running_totals[$child_line_item->ID()] = $quantity
1455
-                                    ? $child_line_item->unit_price()
1456
-                                    : 0;
1457
-                                $running_totals['taxable'][$child_line_item->ID()] = $quantity
1458
-                                    ? $taxable_amount
1459
-                                    : 0;
1460
-                            } else {
1461
-                                $quantity = $child_line_item->quantity();
1462
-                                $running_totals[$child_line_item->ID()] = $child_line_item->unit_price();
1463
-                                $running_totals['taxable'][$child_line_item->ID()] = $taxable_amount;
1464
-                            }
1465
-                            $running_totals['taxable']['total'] += $taxable_amount * $quantity;
1466
-                            $running_totals['total'] += $child_line_item->unit_price() * $quantity;
1467
-                        }
1468
-                    } else {
1469
-                        // it's some other type of item added to the cart
1470
-                        // it should affect the running totals
1471
-                        // basically we want to convert it into a PERCENT modifier. Because
1472
-                        // more clearly affect all registration's final price equally
1473
-                        $line_items_percent_of_running_total = $running_totals['total'] > 0
1474
-                            ? ($child_line_item->total() / $running_totals['total']) + 1
1475
-                            : 1;
1476
-                        foreach ($running_totals as $line_item_id => $this_running_total) {
1477
-                            //the "taxable" array key is an exception
1478
-                            if ($line_item_id === 'taxable') {
1479
-                                continue;
1480
-                            }
1481
-                            // update the running totals
1482
-                            // yes this actually even works for the running grand total!
1483
-                            $running_totals[$line_item_id] =
1484
-                                $line_items_percent_of_running_total * $this_running_total;
1485
-
1486
-                            if ($child_line_item->is_taxable()) {
1487
-                                $running_totals['taxable'][$line_item_id] =
1488
-                                    $line_items_percent_of_running_total * $running_totals['taxable'][$line_item_id];
1489
-                            }
1490
-                        }
1491
-                    }
1492
-                    break;
1493
-            }
1494
-        }
1495
-        return $running_totals;
1496
-    }
1497
-
1498
-
1499
-    /**
1500
-     * @param \EE_Line_Item $total_line_item
1501
-     * @param \EE_Line_Item $ticket_line_item
1502
-     * @return float | null
1503
-     * @throws \OutOfRangeException
1504
-     */
1505
-    public static function calculate_final_price_for_ticket_line_item(\EE_Line_Item $total_line_item, \EE_Line_Item $ticket_line_item)
1506
-    {
1507
-        static $final_prices_per_ticket_line_item = array();
1508
-        if (empty($final_prices_per_ticket_line_item)) {
1509
-            $final_prices_per_ticket_line_item = \EEH_Line_Item::calculate_reg_final_prices_per_line_item(
1510
-                $total_line_item
1511
-            );
1512
-        }
1513
-        //ok now find this new registration's final price
1514
-        if (isset($final_prices_per_ticket_line_item[$ticket_line_item->ID()])) {
1515
-            return $final_prices_per_ticket_line_item[$ticket_line_item->ID()];
1516
-        }
1517
-        $message = sprintf(
1518
-            __(
1519
-                'The final price for the ticket line item (ID:%1$d) could not be calculated.',
1520
-                'event_espresso'
1521
-            ),
1522
-            $ticket_line_item->ID()
1523
-        );
1524
-        if (WP_DEBUG) {
1525
-            $message .= '<br>' . print_r($final_prices_per_ticket_line_item, true);
1526
-            throw new \OutOfRangeException($message);
1527
-        } else {
1528
-            EE_Log::instance()->log(__CLASS__, __FUNCTION__, $message);
1529
-        }
1530
-        return null;
1531
-    }
1532
-
1533
-
1534
-    /**
1535
-     * Creates a duplicate of the line item tree, except only includes billable items
1536
-     * and the portion of line items attributed to billable things
1537
-     *
1538
-     * @param EE_Line_Item $line_item
1539
-     * @param EE_Registration[] $registrations
1540
-     * @return \EE_Line_Item
1541
-     * @throws \EE_Error
1542
-     */
1543
-    public static function billable_line_item_tree(EE_Line_Item $line_item, $registrations)
1544
-    {
1545
-        $copy_li = EEH_Line_Item::billable_line_item($line_item, $registrations);
1546
-        foreach ($line_item->children() as $child_li) {
1547
-            $copy_li->add_child_line_item(EEH_Line_Item::billable_line_item_tree($child_li, $registrations));
1548
-        }
1549
-        //if this is the grand total line item, make sure the totals all add up
1550
-        //(we could have duplicated this logic AS we copied the line items, but
1551
-        //it seems DRYer this way)
1552
-        if ($copy_li->type() === EEM_Line_Item::type_total) {
1553
-            $copy_li->recalculate_total_including_taxes();
1554
-        }
1555
-        return $copy_li;
1556
-    }
1557
-
1558
-
1559
-    /**
1560
-     * Creates a new, unsaved line item from $line_item that factors in the
1561
-     * number of billable registrations on $registrations.
1562
-     *
1563
-     * @param EE_Line_Item $line_item
1564
-     * @return EE_Line_Item
1565
-     * @throws \EE_Error
1566
-     * @param EE_Registration[] $registrations
1567
-     */
1568
-    public static function billable_line_item(EE_Line_Item $line_item, $registrations)
1569
-    {
1570
-        $new_li_fields = $line_item->model_field_array();
1571
-        if ($line_item->type() === EEM_Line_Item::type_line_item &&
1572
-            $line_item->OBJ_type() === 'Ticket'
1573
-        ) {
1574
-            $count = 0;
1575
-            foreach ($registrations as $registration) {
1576
-                if ($line_item->OBJ_ID() === $registration->ticket_ID() &&
1577
-                    in_array($registration->status_ID(), EEM_Registration::reg_statuses_that_allow_payment())
1578
-                ) {
1579
-                    $count++;
1580
-                }
1581
-            }
1582
-            $new_li_fields['LIN_quantity'] = $count;
1583
-        }
1584
-        //don't set the total. We'll leave that up to the code that calculates it
1585
-        unset($new_li_fields['LIN_ID'], $new_li_fields['LIN_parent'], $new_li_fields['LIN_total']);
1586
-        return EE_Line_Item::new_instance($new_li_fields);
1587
-    }
1588
-
1589
-
1590
-    /**
1591
-     * Returns a modified line item tree where all the subtotals which have a total of 0
1592
-     * are removed, and line items with a quantity of 0
1593
-     *
1594
-     * @param EE_Line_Item $line_item |null
1595
-     * @return \EE_Line_Item|null
1596
-     * @throws \EE_Error
1597
-     */
1598
-    public static function non_empty_line_items(EE_Line_Item $line_item)
1599
-    {
1600
-        $copied_li = EEH_Line_Item::non_empty_line_item($line_item);
1601
-        if ($copied_li === null) {
1602
-            return null;
1603
-        }
1604
-        //if this is an event subtotal, we want to only include it if it
1605
-        //has a non-zero total and at least one ticket line item child
1606
-        $ticket_children = 0;
1607
-        foreach ($line_item->children() as $child_li) {
1608
-            $child_li_copy = EEH_Line_Item::non_empty_line_items($child_li);
1609
-            if ($child_li_copy !== null) {
1610
-                $copied_li->add_child_line_item($child_li_copy);
1611
-                if ($child_li_copy->type() === EEM_Line_Item::type_line_item &&
1612
-                    $child_li_copy->OBJ_type() === 'Ticket'
1613
-                ) {
1614
-                    $ticket_children++;
1615
-                }
1616
-            }
1617
-        }
1618
-        //if this is an event subtotal with NO ticket children
1619
-        //we basically want to ignore it
1620
-        if (
1621
-            $ticket_children === 0
1622
-            && $line_item->type() === EEM_Line_Item::type_sub_total
1623
-            && $line_item->OBJ_type() === 'Event'
1624
-            && $line_item->total() === 0
1625
-        ) {
1626
-            return null;
1627
-        }
1628
-        return $copied_li;
1629
-    }
1630
-
1631
-
1632
-    /**
1633
-     * Creates a new, unsaved line item, but if it's a ticket line item
1634
-     * with a total of 0, or a subtotal of 0, returns null instead
1635
-     *
1636
-     * @param EE_Line_Item $line_item
1637
-     * @return EE_Line_Item
1638
-     * @throws \EE_Error
1639
-     */
1640
-    public static function non_empty_line_item(EE_Line_Item $line_item)
1641
-    {
1642
-        if ($line_item->type() === EEM_Line_Item::type_line_item &&
1643
-            $line_item->OBJ_type() === 'Ticket' &&
1644
-            $line_item->quantity() === 0
1645
-        ) {
1646
-            return null;
1647
-        }
1648
-        $new_li_fields = $line_item->model_field_array();
1649
-        //don't set the total. We'll leave that up to the code that calculates it
1650
-        unset($new_li_fields['LIN_ID'], $new_li_fields['LIN_parent']);
1651
-        return EE_Line_Item::new_instance($new_li_fields);
1652
-    }
1653
-
1654
-
1655
-
1656
-    /**************************************** @DEPRECATED METHODS *************************************** */
1657
-    /**
1658
-     * @deprecated
1659
-     * @param EE_Line_Item $total_line_item
1660
-     * @return \EE_Line_Item
1661
-     * @throws \EE_Error
1662
-     */
1663
-    public static function get_items_subtotal(EE_Line_Item $total_line_item)
1664
-    {
1665
-        EE_Error::doing_it_wrong('EEH_Line_Item::get_items_subtotal()', __('Method replaced with EEH_Line_Item::get_pre_tax_subtotal()', 'event_espresso'), '4.6.0');
1666
-        return self::get_pre_tax_subtotal($total_line_item);
1667
-    }
1668
-
1669
-
1670
-    /**
1671
-     * @deprecated
1672
-     * @param EE_Transaction $transaction
1673
-     * @return \EE_Line_Item
1674
-     * @throws \EE_Error
1675
-     */
1676
-    public static function create_default_total_line_item($transaction = NULL)
1677
-    {
1678
-        EE_Error::doing_it_wrong('EEH_Line_Item::create_default_total_line_item()', __('Method replaced with EEH_Line_Item::create_total_line_item()', 'event_espresso'), '4.6.0');
1679
-        return self::create_total_line_item($transaction);
1680
-    }
1681
-
1682
-
1683
-    /**
1684
-     * @deprecated
1685
-     * @param EE_Line_Item $total_line_item
1686
-     * @param EE_Transaction $transaction
1687
-     * @return \EE_Line_Item
1688
-     * @throws \EE_Error
1689
-     */
1690
-    public static function create_default_tickets_subtotal(EE_Line_Item $total_line_item, $transaction = NULL)
1691
-    {
1692
-        EE_Error::doing_it_wrong('EEH_Line_Item::create_default_tickets_subtotal()', __('Method replaced with EEH_Line_Item::create_pre_tax_subtotal()', 'event_espresso'), '4.6.0');
1693
-        return self::create_pre_tax_subtotal($total_line_item, $transaction);
1694
-    }
1695
-
1696
-
1697
-    /**
1698
-     * @deprecated
1699
-     * @param EE_Line_Item $total_line_item
1700
-     * @param EE_Transaction $transaction
1701
-     * @return \EE_Line_Item
1702
-     * @throws \EE_Error
1703
-     */
1704
-    public static function create_default_taxes_subtotal(EE_Line_Item $total_line_item, $transaction = NULL)
1705
-    {
1706
-        EE_Error::doing_it_wrong('EEH_Line_Item::create_default_taxes_subtotal()', __('Method replaced with EEH_Line_Item::create_taxes_subtotal()', 'event_espresso'), '4.6.0');
1707
-        return self::create_taxes_subtotal($total_line_item, $transaction);
1708
-    }
1709
-
1710
-
1711
-    /**
1712
-     * @deprecated
1713
-     * @param EE_Line_Item $total_line_item
1714
-     * @param EE_Transaction $transaction
1715
-     * @return \EE_Line_Item
1716
-     * @throws \EE_Error
1717
-     */
1718
-    public static function create_default_event_subtotal(EE_Line_Item $total_line_item, $transaction = NULL)
1719
-    {
1720
-        EE_Error::doing_it_wrong('EEH_Line_Item::create_default_event_subtotal()', __('Method replaced with EEH_Line_Item::create_event_subtotal()', 'event_espresso'), '4.6.0');
1721
-        return self::create_event_subtotal($total_line_item, $transaction);
1722
-    }
26
+	//other functions: cancel ticket purchase
27
+	//delete ticket purchase
28
+	//add promotion
29
+
30
+
31
+	/**
32
+	 * Adds a simple item (unrelated to any other model object) to the provided PARENT line item.
33
+	 * Does NOT automatically re-calculate the line item totals or update the related transaction.
34
+	 * You should call recalculate_total_including_taxes() on the grant total line item after this
35
+	 * to update the subtotals, and EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
36
+	 * to keep the registration final prices in-sync with the transaction's total.
37
+	 *
38
+	 * @param EE_Line_Item $parent_line_item
39
+	 * @param string $name
40
+	 * @param float $unit_price
41
+	 * @param string $description
42
+	 * @param int $quantity
43
+	 * @param boolean $taxable
44
+	 * @param boolean $code if set to a value, ensures there is only one line item with that code
45
+	 * @return boolean success
46
+	 * @throws \EE_Error
47
+	 */
48
+	public static function add_unrelated_item(EE_Line_Item $parent_line_item, $name, $unit_price, $description = '', $quantity = 1, $taxable = FALSE, $code = NULL)
49
+	{
50
+		$items_subtotal = self::get_pre_tax_subtotal($parent_line_item);
51
+		$line_item = EE_Line_Item::new_instance(array(
52
+			'LIN_name' => $name,
53
+			'LIN_desc' => $description,
54
+			'LIN_unit_price' => $unit_price,
55
+			'LIN_quantity' => $quantity,
56
+			'LIN_percent' => null,
57
+			'LIN_is_taxable' => $taxable,
58
+			'LIN_order' => $items_subtotal instanceof EE_Line_Item ? count($items_subtotal->children()) : 0,
59
+			'LIN_total' => (float)$unit_price * (int)$quantity,
60
+			'LIN_type' => EEM_Line_Item::type_line_item,
61
+			'LIN_code' => $code,
62
+		));
63
+		$line_item = apply_filters(
64
+			'FHEE__EEH_Line_Item__add_unrelated_item__line_item',
65
+			$line_item,
66
+			$parent_line_item
67
+		);
68
+		return self::add_item($parent_line_item, $line_item);
69
+	}
70
+
71
+
72
+	/**
73
+	 * Adds a simple item ( unrelated to any other model object) to the total line item,
74
+	 * in the correct spot in the line item tree. Automatically
75
+	 * re-calculates the line item totals and updates the related transaction. But
76
+	 * DOES NOT automatically upgrade the transaction's registrations' final prices (which
77
+	 * should probably change because of this).
78
+	 * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
79
+	 * after using this, to keep the registration final prices in-sync with the transaction's total.
80
+	 *
81
+	 * @param EE_Line_Item $parent_line_item
82
+	 * @param string $name
83
+	 * @param float $percentage_amount
84
+	 * @param string $description
85
+	 * @param boolean $taxable
86
+	 * @return boolean success
87
+	 * @throws \EE_Error
88
+	 */
89
+	public static function add_percentage_based_item(EE_Line_Item $parent_line_item, $name, $percentage_amount, $description = '', $taxable = FALSE)
90
+	{
91
+		$line_item = EE_Line_Item::new_instance(array(
92
+			'LIN_name' => $name,
93
+			'LIN_desc' => $description,
94
+			'LIN_unit_price' => 0,
95
+			'LIN_percent' => $percentage_amount,
96
+			'LIN_quantity' => 1,
97
+			'LIN_is_taxable' => $taxable,
98
+			'LIN_total' => (float)($percentage_amount * ($parent_line_item->total() / 100)),
99
+			'LIN_type' => EEM_Line_Item::type_line_item,
100
+			'LIN_parent' => $parent_line_item->ID()
101
+		));
102
+		$line_item = apply_filters(
103
+			'FHEE__EEH_Line_Item__add_percentage_based_item__line_item',
104
+			$line_item
105
+		);
106
+		return $parent_line_item->add_child_line_item($line_item, false);
107
+	}
108
+
109
+
110
+	/**
111
+	 * Returns the new line item created by adding a purchase of the ticket
112
+	 * ensures that ticket line item is saved, and that cart total has been recalculated.
113
+	 * If this ticket has already been purchased, just increments its count.
114
+	 * Automatically re-calculates the line item totals and updates the related transaction. But
115
+	 * DOES NOT automatically upgrade the transaction's registrations' final prices (which
116
+	 * should probably change because of this).
117
+	 * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
118
+	 * after using this, to keep the registration final prices in-sync with the transaction's total.
119
+	 *
120
+	 * @param EE_Line_Item $total_line_item grand total line item of type EEM_Line_Item::type_total
121
+	 * @param EE_Ticket $ticket
122
+	 * @param int $qty
123
+	 * @return \EE_Line_Item
124
+	 * @throws \EE_Error
125
+	 */
126
+	public static function add_ticket_purchase(EE_Line_Item $total_line_item, EE_Ticket $ticket, $qty = 1)
127
+	{
128
+		if (!$total_line_item instanceof EE_Line_Item || !$total_line_item->is_total()) {
129
+			throw new EE_Error(sprintf(__('A valid line item total is required in order to add tickets. A line item of type "%s" was passed.', 'event_espresso'), $ticket->ID(), $total_line_item->ID()));
130
+		}
131
+		// either increment the qty for an existing ticket
132
+		$line_item = self::increment_ticket_qty_if_already_in_cart($total_line_item, $ticket, $qty);
133
+		// or add a new one
134
+		if (!$line_item instanceof EE_Line_Item) {
135
+			$line_item = self::create_ticket_line_item($total_line_item, $ticket, $qty);
136
+		}
137
+		$total_line_item->recalculate_total_including_taxes();
138
+		return $line_item;
139
+	}
140
+
141
+
142
+	/**
143
+	 * Returns the new line item created by adding a purchase of the ticket
144
+	 * @param \EE_Line_Item $total_line_item
145
+	 * @param EE_Ticket $ticket
146
+	 * @param int $qty
147
+	 * @return \EE_Line_Item
148
+	 * @throws \EE_Error
149
+	 */
150
+	public static function increment_ticket_qty_if_already_in_cart(EE_Line_Item $total_line_item, EE_Ticket $ticket, $qty = 1)
151
+	{
152
+		$line_item = null;
153
+		if ($total_line_item instanceof EE_Line_Item && $total_line_item->is_total()) {
154
+			$ticket_line_items = EEH_Line_Item::get_ticket_line_items($total_line_item);
155
+			foreach ((array)$ticket_line_items as $ticket_line_item) {
156
+				if (
157
+					$ticket_line_item instanceof EE_Line_Item
158
+					&& (int)$ticket_line_item->OBJ_ID() === (int)$ticket->ID()
159
+				) {
160
+					$line_item = $ticket_line_item;
161
+					break;
162
+				}
163
+			}
164
+		}
165
+		if ($line_item instanceof EE_Line_Item) {
166
+			EEH_Line_Item::increment_quantity($line_item, $qty);
167
+			return $line_item;
168
+		}
169
+		return null;
170
+	}
171
+
172
+
173
+	/**
174
+	 * Increments the line item and all its children's quantity by $qty (but percent line items are unaffected).
175
+	 * Does NOT save or recalculate other line items totals
176
+	 *
177
+	 * @param EE_Line_Item $line_item
178
+	 * @param int $qty
179
+	 * @return void
180
+	 * @throws \EE_Error
181
+	 */
182
+	public static function increment_quantity(EE_Line_Item $line_item, $qty = 1)
183
+	{
184
+		if (!$line_item->is_percent()) {
185
+			$qty += $line_item->quantity();
186
+			$line_item->set_quantity($qty);
187
+			$line_item->set_total($line_item->unit_price() * $qty);
188
+			$line_item->save();
189
+		}
190
+		foreach ($line_item->children() as $child) {
191
+			if ($child->is_sub_line_item()) {
192
+				EEH_Line_Item::update_quantity($child, $qty);
193
+			}
194
+		}
195
+	}
196
+
197
+
198
+	/**
199
+	 * Decrements the line item and all its children's quantity by $qty (but percent line items are unaffected).
200
+	 * Does NOT save or recalculate other line items totals
201
+	 *
202
+	 * @param EE_Line_Item $line_item
203
+	 * @param int $qty
204
+	 * @return void
205
+	 * @throws \EE_Error
206
+	 */
207
+	public static function decrement_quantity(EE_Line_Item $line_item, $qty = 1)
208
+	{
209
+		if (!$line_item->is_percent()) {
210
+			$qty = $line_item->quantity() - $qty;
211
+			$qty = max($qty, 0);
212
+			$line_item->set_quantity($qty);
213
+			$line_item->set_total($line_item->unit_price() * $qty);
214
+			$line_item->save();
215
+		}
216
+		foreach ($line_item->children() as $child) {
217
+			if ($child->is_sub_line_item()) {
218
+				EEH_Line_Item::update_quantity($child, $qty);
219
+			}
220
+		}
221
+	}
222
+
223
+
224
+	/**
225
+	 * Updates the line item and its children's quantities to the specified number.
226
+	 * Does NOT save them or recalculate totals.
227
+	 *
228
+	 * @param EE_Line_Item $line_item
229
+	 * @param int $new_quantity
230
+	 * @throws \EE_Error
231
+	 */
232
+	public static function update_quantity(EE_Line_Item $line_item, $new_quantity)
233
+	{
234
+		if (!$line_item->is_percent()) {
235
+			$line_item->set_quantity($new_quantity);
236
+			$line_item->set_total($line_item->unit_price() * $new_quantity);
237
+			$line_item->save();
238
+		}
239
+		foreach ($line_item->children() as $child) {
240
+			if ($child->is_sub_line_item()) {
241
+				EEH_Line_Item::update_quantity($child, $new_quantity);
242
+			}
243
+		}
244
+	}
245
+
246
+
247
+	/**
248
+	 * Returns the new line item created by adding a purchase of the ticket
249
+	 * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
250
+	 * @param EE_Ticket $ticket
251
+	 * @param int $qty
252
+	 * @return \EE_Line_Item
253
+	 * @throws \EE_Error
254
+	 */
255
+	public static function create_ticket_line_item(EE_Line_Item $total_line_item, EE_Ticket $ticket, $qty = 1)
256
+	{
257
+		$datetimes = $ticket->datetimes();
258
+		$first_datetime = reset($datetimes);
259
+		if ($first_datetime instanceof EE_Datetime && $first_datetime->event() instanceof EE_Event) {
260
+			$first_datetime_name = $first_datetime->event()->name();
261
+		} else {
262
+			$first_datetime_name = __('Event', 'event_espresso');
263
+		}
264
+		$event = sprintf(_x('(For %1$s)', '(For Event Name)', 'event_espresso'), $first_datetime_name);
265
+		// get event subtotal line
266
+		$events_sub_total = self::get_event_line_item_for_ticket($total_line_item, $ticket);
267
+		// add $ticket to cart
268
+		$line_item = EE_Line_Item::new_instance(array(
269
+			'LIN_name' => $ticket->name(),
270
+			'LIN_desc' => $ticket->description() !== '' ? $ticket->description() . ' ' . $event : $event,
271
+			'LIN_unit_price' => $ticket->price(),
272
+			'LIN_quantity' => $qty,
273
+			'LIN_is_taxable' => $ticket->taxable(),
274
+			'LIN_order' => count($events_sub_total->children()),
275
+			'LIN_total' => $ticket->price() * $qty,
276
+			'LIN_type' => EEM_Line_Item::type_line_item,
277
+			'OBJ_ID' => $ticket->ID(),
278
+			'OBJ_type' => 'Ticket'
279
+		));
280
+		$line_item = apply_filters(
281
+			'FHEE__EEH_Line_Item__create_ticket_line_item__line_item',
282
+			$line_item
283
+		);
284
+		$events_sub_total->add_child_line_item($line_item);
285
+		//now add the sub-line items
286
+		$running_total_for_ticket = 0;
287
+		foreach ($ticket->prices(array('order_by' => array('PRC_order' => 'ASC'))) as $price) {
288
+			$sign = $price->is_discount() ? -1 : 1;
289
+			$price_total = $price->is_percent()
290
+				? $running_total_for_ticket * $price->amount() / 100
291
+				: $price->amount() * $qty;
292
+			$sub_line_item = EE_Line_Item::new_instance(array(
293
+				'LIN_name' => $price->name(),
294
+				'LIN_desc' => $price->desc(),
295
+				'LIN_quantity' => $price->is_percent() ? null : $qty,
296
+				'LIN_is_taxable' => false,
297
+				'LIN_order' => $price->order(),
298
+				'LIN_total' => $sign * $price_total,
299
+				'LIN_type' => EEM_Line_Item::type_sub_line_item,
300
+				'OBJ_ID' => $price->ID(),
301
+				'OBJ_type' => 'Price'
302
+			));
303
+			$sub_line_item = apply_filters(
304
+				'FHEE__EEH_Line_Item__create_ticket_line_item__sub_line_item',
305
+				$sub_line_item
306
+			);
307
+			if ($price->is_percent()) {
308
+				$sub_line_item->set_percent($sign * $price->amount());
309
+			} else {
310
+				$sub_line_item->set_unit_price($sign * $price->amount());
311
+			}
312
+			$running_total_for_ticket += $price_total;
313
+			$line_item->add_child_line_item($sub_line_item);
314
+		}
315
+		return $line_item;
316
+	}
317
+
318
+
319
+	/**
320
+	 * Adds the specified item under the pre-tax-sub-total line item. Automatically
321
+	 * re-calculates the line item totals and updates the related transaction. But
322
+	 * DOES NOT automatically upgrade the transaction's registrations' final prices (which
323
+	 * should probably change because of this).
324
+	 * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
325
+	 * after using this, to keep the registration final prices in-sync with the transaction's total.
326
+	 *
327
+	 * @param EE_Line_Item $total_line_item
328
+	 * @param EE_Line_Item $item to be added
329
+	 * @return boolean
330
+	 * @throws \EE_Error
331
+	 */
332
+	public static function add_item(EE_Line_Item $total_line_item, EE_Line_Item $item)
333
+	{
334
+		$pre_tax_subtotal = self::get_pre_tax_subtotal($total_line_item);
335
+		if ($pre_tax_subtotal instanceof EE_Line_Item) {
336
+			$success = $pre_tax_subtotal->add_child_line_item($item);
337
+		} else {
338
+			return FALSE;
339
+		}
340
+		$total_line_item->recalculate_total_including_taxes();
341
+		return $success;
342
+	}
343
+
344
+
345
+	/**
346
+	 * cancels an existing ticket line item,
347
+	 * by decrementing it's quantity by 1 and adding a new "type_cancellation" sub-line-item.
348
+	 * ALL totals and subtotals will NEED TO BE UPDATED after performing this action
349
+	 *
350
+	 * @param EE_Line_Item $ticket_line_item
351
+	 * @param int $qty
352
+	 * @return bool success
353
+	 * @throws \EE_Error
354
+	 */
355
+	public static function cancel_ticket_line_item(EE_Line_Item $ticket_line_item, $qty = 1)
356
+	{
357
+		// validate incoming line_item
358
+		if ($ticket_line_item->OBJ_type() !== 'Ticket') {
359
+			throw new EE_Error(
360
+				sprintf(
361
+					__('The supplied line item must have an Object Type of "Ticket", not %1$s.', 'event_espresso'),
362
+					$ticket_line_item->type()
363
+				)
364
+			);
365
+		}
366
+		if ($ticket_line_item->quantity() < $qty) {
367
+			throw new EE_Error(
368
+				sprintf(
369
+					__('Can not cancel %1$d ticket(s) because the supplied line item has a quantity of %2$d.', 'event_espresso'),
370
+					$qty,
371
+					$ticket_line_item->quantity()
372
+				)
373
+			);
374
+		}
375
+		// decrement ticket quantity; don't rely on auto-fixing when recalculating totals to do this
376
+		$ticket_line_item->set_quantity($ticket_line_item->quantity() - $qty);
377
+		foreach ($ticket_line_item->children() as $child_line_item) {
378
+			if (
379
+				$child_line_item->is_sub_line_item()
380
+				&& !$child_line_item->is_percent()
381
+				&& !$child_line_item->is_cancellation()
382
+			) {
383
+				$child_line_item->set_quantity($child_line_item->quantity() - $qty);
384
+			}
385
+		}
386
+		// get cancellation sub line item
387
+		$cancellation_line_item = EEH_Line_Item::get_descendants_of_type(
388
+			$ticket_line_item,
389
+			EEM_Line_Item::type_cancellation
390
+		);
391
+		$cancellation_line_item = reset($cancellation_line_item);
392
+		// verify that this ticket was indeed previously cancelled
393
+		if ($cancellation_line_item instanceof EE_Line_Item) {
394
+			// increment cancelled quantity
395
+			$cancellation_line_item->set_quantity($cancellation_line_item->quantity() + $qty);
396
+		} else {
397
+			// create cancellation sub line item
398
+			$cancellation_line_item = EE_Line_Item::new_instance(array(
399
+				'LIN_name' => __('Cancellation', 'event_espresso'),
400
+				'LIN_desc' => sprintf(
401
+					_x('Cancelled %1$s : %2$s', 'Cancelled Ticket Name : 2015-01-01 11:11', 'event_espresso'),
402
+					$ticket_line_item->name(),
403
+					current_time(get_option('date_format') . ' ' . get_option('time_format'))
404
+				),
405
+				'LIN_unit_price' => 0, // $ticket_line_item->unit_price()
406
+				'LIN_quantity' => $qty,
407
+				'LIN_is_taxable' => $ticket_line_item->is_taxable(),
408
+				'LIN_order' => count($ticket_line_item->children()),
409
+				'LIN_total' => 0, // $ticket_line_item->unit_price()
410
+				'LIN_type' => EEM_Line_Item::type_cancellation,
411
+			));
412
+			$ticket_line_item->add_child_line_item($cancellation_line_item);
413
+		}
414
+		if ($ticket_line_item->save_this_and_descendants() > 0) {
415
+			// decrement parent line item quantity
416
+			$event_line_item = $ticket_line_item->parent();
417
+			if ($event_line_item instanceof EE_Line_Item && $event_line_item->OBJ_type() === 'Event') {
418
+				$event_line_item->set_quantity($event_line_item->quantity() - $qty);
419
+				$event_line_item->save();
420
+			}
421
+			EEH_Line_Item::get_grand_total_and_recalculate_everything($ticket_line_item);
422
+			return true;
423
+		}
424
+		return false;
425
+	}
426
+
427
+
428
+	/**
429
+	 * reinstates (un-cancels?) a previously canceled ticket line item,
430
+	 * by incrementing it's quantity by 1, and decrementing it's "type_cancellation" sub-line-item.
431
+	 * ALL totals and subtotals will NEED TO BE UPDATED after performing this action
432
+	 *
433
+	 * @param EE_Line_Item $ticket_line_item
434
+	 * @param int $qty
435
+	 * @return bool success
436
+	 * @throws \EE_Error
437
+	 */
438
+	public static function reinstate_canceled_ticket_line_item(EE_Line_Item $ticket_line_item, $qty = 1)
439
+	{
440
+		// validate incoming line_item
441
+		if ($ticket_line_item->OBJ_type() !== 'Ticket') {
442
+			throw new EE_Error(
443
+				sprintf(
444
+					__('The supplied line item must have an Object Type of "Ticket", not %1$s.', 'event_espresso'),
445
+					$ticket_line_item->type()
446
+				)
447
+			);
448
+		}
449
+		// get cancellation sub line item
450
+		$cancellation_line_item = EEH_Line_Item::get_descendants_of_type(
451
+			$ticket_line_item,
452
+			EEM_Line_Item::type_cancellation
453
+		);
454
+		$cancellation_line_item = reset($cancellation_line_item);
455
+		// verify that this ticket was indeed previously cancelled
456
+		if (!$cancellation_line_item instanceof EE_Line_Item) {
457
+			return false;
458
+		}
459
+		if ($cancellation_line_item->quantity() > $qty) {
460
+			// decrement cancelled quantity
461
+			$cancellation_line_item->set_quantity($cancellation_line_item->quantity() - $qty);
462
+		} else if ($cancellation_line_item->quantity() == $qty) {
463
+			// decrement cancelled quantity in case anyone still has the object kicking around
464
+			$cancellation_line_item->set_quantity($cancellation_line_item->quantity() - $qty);
465
+			// delete because quantity will end up as 0
466
+			$cancellation_line_item->delete();
467
+			// and attempt to destroy the object,
468
+			// even though PHP won't actually destroy it until it needs the memory
469
+			unset($cancellation_line_item);
470
+		} else {
471
+			// what ?!?! negative quantity ?!?!
472
+			throw new EE_Error(
473
+				sprintf(
474
+					__('Can not reinstate %1$d cancelled ticket(s) because the cancelled ticket quantity is only %2$d.',
475
+						'event_espresso'),
476
+					$qty,
477
+					$cancellation_line_item->quantity()
478
+				)
479
+			);
480
+		}
481
+		// increment ticket quantity
482
+		$ticket_line_item->set_quantity($ticket_line_item->quantity() + $qty);
483
+		if ($ticket_line_item->save_this_and_descendants() > 0) {
484
+			// increment parent line item quantity
485
+			$event_line_item = $ticket_line_item->parent();
486
+			if ($event_line_item instanceof EE_Line_Item && $event_line_item->OBJ_type() === 'Event') {
487
+				$event_line_item->set_quantity($event_line_item->quantity() + $qty);
488
+			}
489
+			EEH_Line_Item::get_grand_total_and_recalculate_everything($ticket_line_item);
490
+			return true;
491
+		}
492
+		return false;
493
+	}
494
+
495
+
496
+	/**
497
+	 * calls EEH_Line_Item::find_transaction_grand_total_for_line_item()
498
+	 * then EE_Line_Item::recalculate_total_including_taxes() on the result
499
+	 *
500
+	 * @param EE_Line_Item $line_item
501
+	 * @return \EE_Line_Item
502
+	 */
503
+	public static function get_grand_total_and_recalculate_everything(EE_Line_Item $line_item)
504
+	{
505
+		$grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($line_item);
506
+		return $grand_total_line_item->recalculate_total_including_taxes();
507
+	}
508
+
509
+
510
+	/**
511
+	 * Gets the line item which contains the subtotal of all the items
512
+	 *
513
+	 * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
514
+	 * @return \EE_Line_Item
515
+	 * @throws \EE_Error
516
+	 */
517
+	public static function get_pre_tax_subtotal(EE_Line_Item $total_line_item)
518
+	{
519
+		$pre_tax_subtotal = $total_line_item->get_child_line_item('pre-tax-subtotal');
520
+		return $pre_tax_subtotal instanceof EE_Line_Item
521
+			? $pre_tax_subtotal
522
+			: self::create_pre_tax_subtotal($total_line_item);
523
+	}
524
+
525
+
526
+	/**
527
+	 * Gets the line item for the taxes subtotal
528
+	 *
529
+	 * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
530
+	 * @return \EE_Line_Item
531
+	 * @throws \EE_Error
532
+	 */
533
+	public static function get_taxes_subtotal(EE_Line_Item $total_line_item)
534
+	{
535
+		$taxes = $total_line_item->get_child_line_item('taxes');
536
+		return $taxes ? $taxes : self::create_taxes_subtotal($total_line_item);
537
+	}
538
+
539
+
540
+	/**
541
+	 * sets the TXN ID on an EE_Line_Item if passed a valid EE_Transaction object
542
+	 *
543
+	 * @param EE_Line_Item $line_item
544
+	 * @param EE_Transaction $transaction
545
+	 * @return void
546
+	 * @throws \EE_Error
547
+	 */
548
+	public static function set_TXN_ID(EE_Line_Item $line_item, $transaction = NULL)
549
+	{
550
+		if ($transaction) {
551
+			/** @type EEM_Transaction $EEM_Transaction */
552
+			$EEM_Transaction = EE_Registry::instance()->load_model('Transaction');
553
+			$TXN_ID = $EEM_Transaction->ensure_is_ID($transaction);
554
+			$line_item->set_TXN_ID($TXN_ID);
555
+		}
556
+	}
557
+
558
+
559
+	/**
560
+	 * Creates a new default total line item for the transaction,
561
+	 * and its tickets subtotal and taxes subtotal line items (and adds the
562
+	 * existing taxes as children of the taxes subtotal line item)
563
+	 *
564
+	 * @param EE_Transaction $transaction
565
+	 * @return \EE_Line_Item of type total
566
+	 * @throws \EE_Error
567
+	 */
568
+	public static function create_total_line_item($transaction = NULL)
569
+	{
570
+		$total_line_item = EE_Line_Item::new_instance(array(
571
+			'LIN_code' => 'total',
572
+			'LIN_name' => __('Grand Total', 'event_espresso'),
573
+			'LIN_type' => EEM_Line_Item::type_total,
574
+			'OBJ_type' => 'Transaction'
575
+		));
576
+		$total_line_item = apply_filters(
577
+			'FHEE__EEH_Line_Item__create_total_line_item__total_line_item',
578
+			$total_line_item
579
+		);
580
+		self::set_TXN_ID($total_line_item, $transaction);
581
+		self::create_pre_tax_subtotal($total_line_item, $transaction);
582
+		self::create_taxes_subtotal($total_line_item, $transaction);
583
+		return $total_line_item;
584
+	}
585
+
586
+
587
+	/**
588
+	 * Creates a default items subtotal line item
589
+	 *
590
+	 * @param EE_Line_Item $total_line_item
591
+	 * @param EE_Transaction $transaction
592
+	 * @return EE_Line_Item
593
+	 * @throws \EE_Error
594
+	 */
595
+	protected static function create_pre_tax_subtotal(EE_Line_Item $total_line_item, $transaction = NULL)
596
+	{
597
+		$pre_tax_line_item = EE_Line_Item::new_instance(array(
598
+			'LIN_code' => 'pre-tax-subtotal',
599
+			'LIN_name' => __('Pre-Tax Subtotal', 'event_espresso'),
600
+			'LIN_type' => EEM_Line_Item::type_sub_total
601
+		));
602
+		$pre_tax_line_item = apply_filters(
603
+			'FHEE__EEH_Line_Item__create_pre_tax_subtotal__pre_tax_line_item',
604
+			$pre_tax_line_item
605
+		);
606
+		self::set_TXN_ID($pre_tax_line_item, $transaction);
607
+		$total_line_item->add_child_line_item($pre_tax_line_item);
608
+		self::create_event_subtotal($pre_tax_line_item, $transaction);
609
+		return $pre_tax_line_item;
610
+	}
611
+
612
+
613
+	/**
614
+	 * Creates a line item for the taxes subtotal and finds all the tax prices
615
+	 * and applies taxes to it
616
+	 *
617
+	 * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
618
+	 * @param EE_Transaction $transaction
619
+	 * @return EE_Line_Item
620
+	 * @throws \EE_Error
621
+	 */
622
+	protected static function create_taxes_subtotal(EE_Line_Item $total_line_item, $transaction = NULL)
623
+	{
624
+		$tax_line_item = EE_Line_Item::new_instance(array(
625
+			'LIN_code' => 'taxes',
626
+			'LIN_name' => __('Taxes', 'event_espresso'),
627
+			'LIN_type' => EEM_Line_Item::type_tax_sub_total,
628
+			'LIN_order' => 1000,//this should always come last
629
+		));
630
+		$tax_line_item = apply_filters(
631
+			'FHEE__EEH_Line_Item__create_taxes_subtotal__tax_line_item',
632
+			$tax_line_item
633
+		);
634
+		self::set_TXN_ID($tax_line_item, $transaction);
635
+		$total_line_item->add_child_line_item($tax_line_item);
636
+		//and lastly, add the actual taxes
637
+		self::apply_taxes($total_line_item);
638
+		return $tax_line_item;
639
+	}
640
+
641
+
642
+	/**
643
+	 * Creates a default items subtotal line item
644
+	 *
645
+	 * @param EE_Line_Item $pre_tax_line_item
646
+	 * @param EE_Transaction $transaction
647
+	 * @param EE_Event $event
648
+	 * @return EE_Line_Item
649
+	 * @throws \EE_Error
650
+	 */
651
+	public static function create_event_subtotal(EE_Line_Item $pre_tax_line_item, $transaction = NULL, $event = NULL)
652
+	{
653
+		$event_line_item = EE_Line_Item::new_instance(array(
654
+			'LIN_code' => self::get_event_code($event),
655
+			'LIN_name' => self::get_event_name($event),
656
+			'LIN_desc' => self::get_event_desc($event),
657
+			'LIN_type' => EEM_Line_Item::type_sub_total,
658
+			'OBJ_type' => 'Event',
659
+			'OBJ_ID' => $event instanceof EE_Event ? $event->ID() : 0
660
+		));
661
+		$event_line_item = apply_filters(
662
+			'FHEE__EEH_Line_Item__create_event_subtotal__event_line_item',
663
+			$event_line_item
664
+		);
665
+		self::set_TXN_ID($event_line_item, $transaction);
666
+		$pre_tax_line_item->add_child_line_item($event_line_item);
667
+		return $event_line_item;
668
+	}
669
+
670
+
671
+	/**
672
+	 * Gets what the event ticket's code SHOULD be
673
+	 *
674
+	 * @param EE_Event $event
675
+	 * @return string
676
+	 * @throws \EE_Error
677
+	 */
678
+	public static function get_event_code($event)
679
+	{
680
+		return 'event-' . ($event instanceof EE_Event ? $event->ID() : '0');
681
+	}
682
+
683
+	/**
684
+	 * Gets the event name
685
+	 * @param EE_Event $event
686
+	 * @return string
687
+	 */
688
+	public static function get_event_name($event)
689
+	{
690
+		return $event instanceof EE_Event ? $event->name() : __('Event', 'event_espresso');
691
+	}
692
+
693
+	/**
694
+	 * Gets the event excerpt
695
+	 * @param EE_Event $event
696
+	 * @return string
697
+	 */
698
+	public static function get_event_desc($event)
699
+	{
700
+		return $event instanceof EE_Event ? $event->short_description() : '';
701
+	}
702
+
703
+	/**
704
+	 * Given the grand total line item and a ticket, finds the event sub-total
705
+	 * line item the ticket's purchase should be added onto
706
+	 *
707
+	 * @access public
708
+	 * @param EE_Line_Item $grand_total the grand total line item
709
+	 * @param EE_Ticket $ticket
710
+	 * @throws \EE_Error
711
+	 * @return EE_Line_Item
712
+	 */
713
+	public static function get_event_line_item_for_ticket(EE_Line_Item $grand_total, EE_Ticket $ticket)
714
+	{
715
+		$first_datetime = $ticket->first_datetime();
716
+		if (!$first_datetime instanceof EE_Datetime) {
717
+			throw new EE_Error(
718
+				sprintf(__('The supplied ticket (ID %d) has no datetimes', 'event_espresso'), $ticket->ID())
719
+			);
720
+		}
721
+		$event = $first_datetime->event();
722
+		if (!$event instanceof EE_Event) {
723
+			throw new EE_Error(
724
+				sprintf(
725
+					__('The supplied ticket (ID %d) has no event data associated with it.', 'event_espresso'),
726
+					$ticket->ID()
727
+				)
728
+			);
729
+		}
730
+		$events_sub_total = EEH_Line_Item::get_event_line_item($grand_total, $event);
731
+		if (!$events_sub_total instanceof EE_Line_Item) {
732
+			throw new EE_Error(
733
+				sprintf(
734
+					__('There is no events sub-total for ticket %s on total line item %d', 'event_espresso'),
735
+					$ticket->ID(),
736
+					$grand_total->ID()
737
+				)
738
+			);
739
+		}
740
+		return $events_sub_total;
741
+	}
742
+
743
+
744
+	/**
745
+	 * Gets the event line item
746
+	 *
747
+	 * @param EE_Line_Item $grand_total
748
+	 * @param EE_Event $event
749
+	 * @return EE_Line_Item for the event subtotal which is a child of $grand_total
750
+	 * @throws \EE_Error
751
+	 */
752
+	public static function get_event_line_item(EE_Line_Item $grand_total, $event)
753
+	{
754
+		/** @type EE_Event $event */
755
+		$event = EEM_Event::instance()->ensure_is_obj($event, true);
756
+		$event_line_item = NULL;
757
+		$found = false;
758
+		foreach (EEH_Line_Item::get_event_subtotals($grand_total) as $event_line_item) {
759
+			// default event subtotal, we should only ever find this the first time this method is called
760
+			if (!$event_line_item->OBJ_ID()) {
761
+				// let's use this! but first... set the event details
762
+				EEH_Line_Item::set_event_subtotal_details($event_line_item, $event);
763
+				$found = true;
764
+				break;
765
+			} else if ($event_line_item->OBJ_ID() === $event->ID()) {
766
+				// found existing line item for this event in the cart, so break out of loop and use this one
767
+				$found = true;
768
+				break;
769
+			}
770
+		}
771
+		if (!$found) {
772
+			//there is no event sub-total yet, so add it
773
+			$pre_tax_subtotal = EEH_Line_Item::get_pre_tax_subtotal($grand_total);
774
+			// create a new "event" subtotal below that
775
+			$event_line_item = EEH_Line_Item::create_event_subtotal($pre_tax_subtotal, null, $event);
776
+			// and set the event details
777
+			EEH_Line_Item::set_event_subtotal_details($event_line_item, $event);
778
+		}
779
+		return $event_line_item;
780
+	}
781
+
782
+
783
+	/**
784
+	 * Creates a default items subtotal line item
785
+	 *
786
+	 * @param EE_Line_Item $event_line_item
787
+	 * @param EE_Event $event
788
+	 * @param EE_Transaction $transaction
789
+	 * @return EE_Line_Item
790
+	 * @throws \EE_Error
791
+	 */
792
+	public static function set_event_subtotal_details(
793
+		EE_Line_Item $event_line_item,
794
+		EE_Event $event,
795
+		$transaction = null
796
+	)
797
+	{
798
+		if ($event instanceof EE_Event) {
799
+			$event_line_item->set_code(self::get_event_code($event));
800
+			$event_line_item->set_name(self::get_event_name($event));
801
+			$event_line_item->set_desc(self::get_event_desc($event));
802
+			$event_line_item->set_OBJ_ID($event->ID());
803
+		}
804
+		self::set_TXN_ID($event_line_item, $transaction);
805
+	}
806
+
807
+
808
+	/**
809
+	 * Finds what taxes should apply, adds them as tax line items under the taxes sub-total,
810
+	 * and recalculates the taxes sub-total and the grand total. Resets the taxes, so
811
+	 * any old taxes are removed
812
+	 *
813
+	 * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
814
+	 * @throws \EE_Error
815
+	 */
816
+	public static function apply_taxes(EE_Line_Item $total_line_item)
817
+	{
818
+		/** @type EEM_Price $EEM_Price */
819
+		$EEM_Price = EE_Registry::instance()->load_model('Price');
820
+		// get array of taxes via Price Model
821
+		$ordered_taxes = $EEM_Price->get_all_prices_that_are_taxes();
822
+		ksort($ordered_taxes);
823
+		$taxes_line_item = self::get_taxes_subtotal($total_line_item);
824
+		//just to be safe, remove its old tax line items
825
+		$taxes_line_item->delete_children_line_items();
826
+		//loop thru taxes
827
+		foreach ($ordered_taxes as $order => $taxes) {
828
+			foreach ($taxes as $tax) {
829
+				if ($tax instanceof EE_Price) {
830
+					$tax_line_item = EE_Line_Item::new_instance(
831
+						array(
832
+							'LIN_name' => $tax->name(),
833
+							'LIN_desc' => $tax->desc(),
834
+							'LIN_percent' => $tax->amount(),
835
+							'LIN_is_taxable' => false,
836
+							'LIN_order' => $order,
837
+							'LIN_total' => 0,
838
+							'LIN_type' => EEM_Line_Item::type_tax,
839
+							'OBJ_type' => 'Price',
840
+							'OBJ_ID' => $tax->ID()
841
+						)
842
+					);
843
+					$tax_line_item = apply_filters(
844
+						'FHEE__EEH_Line_Item__apply_taxes__tax_line_item',
845
+						$tax_line_item
846
+					);
847
+					$taxes_line_item->add_child_line_item($tax_line_item);
848
+				}
849
+			}
850
+		}
851
+		$total_line_item->recalculate_total_including_taxes();
852
+	}
853
+
854
+
855
+	/**
856
+	 * Ensures that taxes have been applied to the order, if not applies them.
857
+	 * Returns the total amount of tax
858
+	 *
859
+	 * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
860
+	 * @return float
861
+	 * @throws \EE_Error
862
+	 */
863
+	public static function ensure_taxes_applied($total_line_item)
864
+	{
865
+		$taxes_subtotal = self::get_taxes_subtotal($total_line_item);
866
+		if (!$taxes_subtotal->children()) {
867
+			self::apply_taxes($total_line_item);
868
+		}
869
+		return $taxes_subtotal->total();
870
+	}
871
+
872
+
873
+	/**
874
+	 * Deletes ALL children of the passed line item
875
+	 *
876
+	 * @param EE_Line_Item $parent_line_item
877
+	 * @return bool
878
+	 * @throws \EE_Error
879
+	 */
880
+	public static function delete_all_child_items(EE_Line_Item $parent_line_item)
881
+	{
882
+		$deleted = 0;
883
+		foreach ($parent_line_item->children() as $child_line_item) {
884
+			if ($child_line_item instanceof EE_Line_Item) {
885
+				$deleted += EEH_Line_Item::delete_all_child_items($child_line_item);
886
+				if ($child_line_item->ID()) {
887
+					$child_line_item->delete();
888
+					unset($child_line_item);
889
+				} else {
890
+					$parent_line_item->delete_child_line_item($child_line_item->code());
891
+				}
892
+				$deleted++;
893
+			}
894
+		}
895
+		return $deleted;
896
+	}
897
+
898
+
899
+	/**
900
+	 * Deletes the line items as indicated by the line item code(s) provided,
901
+	 * regardless of where they're found in the line item tree. Automatically
902
+	 * re-calculates the line item totals and updates the related transaction. But
903
+	 * DOES NOT automatically upgrade the transaction's registrations' final prices (which
904
+	 * should probably change because of this).
905
+	 * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
906
+	 * after using this, to keep the registration final prices in-sync with the transaction's total.
907
+	 * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
908
+	 * @param array|bool|string $line_item_codes
909
+	 * @return int number of items successfully removed
910
+	 */
911
+	public static function delete_items(EE_Line_Item $total_line_item, $line_item_codes = FALSE)
912
+	{
913
+
914
+		if ($total_line_item->type() !== EEM_Line_Item::type_total) {
915
+			EE_Error::doing_it_wrong(
916
+				'EEH_Line_Item::delete_items',
917
+				__(
918
+					'This static method should only be called with a TOTAL line item, otherwise we won\'t recalculate the totals correctly',
919
+					'event_espresso'
920
+				),
921
+				'4.6.18'
922
+			);
923
+		}
924
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
925
+
926
+		// check if only a single line_item_id was passed
927
+		if (!empty($line_item_codes) && !is_array($line_item_codes)) {
928
+			// place single line_item_id in an array to appear as multiple line_item_ids
929
+			$line_item_codes = array($line_item_codes);
930
+		}
931
+		$removals = 0;
932
+		// cycle thru line_item_ids
933
+		foreach ($line_item_codes as $line_item_id) {
934
+			$removals += $total_line_item->delete_child_line_item($line_item_id);
935
+		}
936
+
937
+		if ($removals > 0) {
938
+			$total_line_item->recalculate_taxes_and_tax_total();
939
+			return $removals;
940
+		} else {
941
+			return FALSE;
942
+		}
943
+	}
944
+
945
+
946
+	/**
947
+	 * Overwrites the previous tax by clearing out the old taxes, and creates a new
948
+	 * tax and updates the total line item accordingly
949
+	 *
950
+	 * @param EE_Line_Item $total_line_item
951
+	 * @param float $amount
952
+	 * @param string $name
953
+	 * @param string $description
954
+	 * @param string $code
955
+	 * @param boolean $add_to_existing_line_item
956
+	 *                          if true, and a duplicate line item with the same code is found,
957
+	 *                          $amount will be added onto it; otherwise will simply set the taxes to match $amount
958
+	 * @return EE_Line_Item the new tax line item created
959
+	 * @throws \EE_Error
960
+	 */
961
+	public static function set_total_tax_to(
962
+		EE_Line_Item $total_line_item,
963
+		$amount,
964
+		$name = null,
965
+		$description = null,
966
+		$code = null,
967
+		$add_to_existing_line_item = false
968
+	)
969
+	{
970
+		$tax_subtotal = self::get_taxes_subtotal($total_line_item);
971
+		$taxable_total = $total_line_item->taxable_total();
972
+
973
+		if ($add_to_existing_line_item) {
974
+			$new_tax = $tax_subtotal->get_child_line_item($code);
975
+			EEM_Line_Item::instance()->delete(
976
+				array(array('LIN_code' => array('!=', $code), 'LIN_parent' => $tax_subtotal->ID()))
977
+			);
978
+		} else {
979
+			$new_tax = null;
980
+			$tax_subtotal->delete_children_line_items();
981
+		}
982
+		if ($new_tax) {
983
+			$new_tax->set_total($new_tax->total() + $amount);
984
+			$new_tax->set_percent($taxable_total ? $new_tax->total() / $taxable_total * 100 : 0);
985
+		} else {
986
+			//no existing tax item. Create it
987
+			$new_tax = EE_Line_Item::new_instance(array(
988
+				'TXN_ID' => $total_line_item->TXN_ID(),
989
+				'LIN_name' => $name ? $name : __('Tax', 'event_espresso'),
990
+				'LIN_desc' => $description ? $description : '',
991
+				'LIN_percent' => $taxable_total ? ($amount / $taxable_total * 100) : 0,
992
+				'LIN_total' => $amount,
993
+				'LIN_parent' => $tax_subtotal->ID(),
994
+				'LIN_type' => EEM_Line_Item::type_tax,
995
+				'LIN_code' => $code
996
+			));
997
+		}
998
+
999
+		$new_tax = apply_filters(
1000
+			'FHEE__EEH_Line_Item__set_total_tax_to__new_tax_subtotal',
1001
+			$new_tax,
1002
+			$total_line_item
1003
+		);
1004
+		$new_tax->save();
1005
+		$tax_subtotal->set_total($new_tax->total());
1006
+		$tax_subtotal->save();
1007
+		$total_line_item->recalculate_total_including_taxes();
1008
+		return $new_tax;
1009
+	}
1010
+
1011
+
1012
+	/**
1013
+	 * Makes all the line items which are children of $line_item taxable (or not).
1014
+	 * Does NOT save the line items
1015
+	 * @param EE_Line_Item $line_item
1016
+	 * @param string $code_substring_for_whitelist if this string is part of the line item's code
1017
+	 *  it will be whitelisted (ie, except from becoming taxable)
1018
+	 * @param boolean $taxable
1019
+	 */
1020
+	public static function set_line_items_taxable(
1021
+		EE_Line_Item $line_item,
1022
+		$taxable = true,
1023
+		$code_substring_for_whitelist = null
1024
+	)
1025
+	{
1026
+		$whitelisted = false;
1027
+		if ($code_substring_for_whitelist !== null) {
1028
+			$whitelisted = strpos($line_item->code(), $code_substring_for_whitelist) !== false ? true : false;
1029
+		}
1030
+		if (!$whitelisted && $line_item->is_line_item()) {
1031
+			$line_item->set_is_taxable($taxable);
1032
+		}
1033
+		foreach ($line_item->children() as $child_line_item) {
1034
+			EEH_Line_Item::set_line_items_taxable($child_line_item, $taxable, $code_substring_for_whitelist);
1035
+		}
1036
+	}
1037
+
1038
+
1039
+	/**
1040
+	 * Gets all descendants that are event subtotals
1041
+	 *
1042
+	 * @uses  EEH_Line_Item::get_subtotals_of_object_type()
1043
+	 * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1044
+	 * @return EE_Line_Item[]
1045
+	 */
1046
+	public static function get_event_subtotals(EE_Line_Item $parent_line_item)
1047
+	{
1048
+		return self::get_subtotals_of_object_type($parent_line_item, 'Event');
1049
+	}
1050
+
1051
+
1052
+	/**
1053
+	 * Gets all descendants subtotals that match the supplied object type
1054
+	 *
1055
+	 * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1056
+	 * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1057
+	 * @param string $obj_type
1058
+	 * @return EE_Line_Item[]
1059
+	 */
1060
+	public static function get_subtotals_of_object_type(EE_Line_Item $parent_line_item, $obj_type = '')
1061
+	{
1062
+		return self::_get_descendants_by_type_and_object_type(
1063
+			$parent_line_item,
1064
+			EEM_Line_Item::type_sub_total,
1065
+			$obj_type
1066
+		);
1067
+	}
1068
+
1069
+
1070
+	/**
1071
+	 * Gets all descendants that are tickets
1072
+	 *
1073
+	 * @uses  EEH_Line_Item::get_line_items_of_object_type()
1074
+	 * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1075
+	 * @return EE_Line_Item[]
1076
+	 */
1077
+	public static function get_ticket_line_items(EE_Line_Item $parent_line_item)
1078
+	{
1079
+		return self::get_line_items_of_object_type($parent_line_item, 'Ticket');
1080
+	}
1081
+
1082
+
1083
+	/**
1084
+	 * Gets all descendants subtotals that match the supplied object type
1085
+	 *
1086
+	 * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1087
+	 * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1088
+	 * @param string $obj_type
1089
+	 * @return EE_Line_Item[]
1090
+	 */
1091
+	public static function get_line_items_of_object_type(EE_Line_Item $parent_line_item, $obj_type = '')
1092
+	{
1093
+		return self::_get_descendants_by_type_and_object_type($parent_line_item, EEM_Line_Item::type_line_item, $obj_type);
1094
+	}
1095
+
1096
+
1097
+	/**
1098
+	 * Gets all the descendants (ie, children or children of children etc) that are of the type 'tax'
1099
+	 * @uses  EEH_Line_Item::get_descendants_of_type()
1100
+	 * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1101
+	 * @return EE_Line_Item[]
1102
+	 */
1103
+	public static function get_tax_descendants(EE_Line_Item $parent_line_item)
1104
+	{
1105
+		return EEH_Line_Item::get_descendants_of_type($parent_line_item, EEM_Line_Item::type_tax);
1106
+	}
1107
+
1108
+
1109
+	/**
1110
+	 * Gets all the real items purchased which are children of this item
1111
+	 * @uses  EEH_Line_Item::get_descendants_of_type()
1112
+	 * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1113
+	 * @return EE_Line_Item[]
1114
+	 */
1115
+	public static function get_line_item_descendants(EE_Line_Item $parent_line_item)
1116
+	{
1117
+		return EEH_Line_Item::get_descendants_of_type($parent_line_item, EEM_Line_Item::type_line_item);
1118
+	}
1119
+
1120
+
1121
+	/**
1122
+	 * Gets all descendants of supplied line item that match the supplied line item type
1123
+	 *
1124
+	 * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1125
+	 * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1126
+	 * @param string $line_item_type one of the EEM_Line_Item constants
1127
+	 * @return EE_Line_Item[]
1128
+	 */
1129
+	public static function get_descendants_of_type(EE_Line_Item $parent_line_item, $line_item_type)
1130
+	{
1131
+		return self::_get_descendants_by_type_and_object_type($parent_line_item, $line_item_type, NULL);
1132
+	}
1133
+
1134
+
1135
+	/**
1136
+	 * Gets all descendants of supplied line item that match the supplied line item type and possibly the object type as well
1137
+	 *
1138
+	 * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1139
+	 * @param string $line_item_type one of the EEM_Line_Item constants
1140
+	 * @param string | NULL $obj_type object model class name (minus prefix) or NULL to ignore object type when searching
1141
+	 * @return EE_Line_Item[]
1142
+	 */
1143
+	protected static function _get_descendants_by_type_and_object_type(
1144
+		EE_Line_Item $parent_line_item,
1145
+		$line_item_type,
1146
+		$obj_type = null
1147
+	)
1148
+	{
1149
+		$objects = array();
1150
+		foreach ($parent_line_item->children() as $child_line_item) {
1151
+			if ($child_line_item instanceof EE_Line_Item) {
1152
+				if (
1153
+					$child_line_item->type() === $line_item_type
1154
+					&& (
1155
+						$child_line_item->OBJ_type() === $obj_type || $obj_type === null
1156
+					)
1157
+				) {
1158
+					$objects[] = $child_line_item;
1159
+				} else {
1160
+					//go-through-all-its children looking for more matches
1161
+					$objects = array_merge(
1162
+						$objects,
1163
+						self::_get_descendants_by_type_and_object_type(
1164
+							$child_line_item,
1165
+							$line_item_type,
1166
+							$obj_type
1167
+						)
1168
+					);
1169
+				}
1170
+			}
1171
+		}
1172
+		return $objects;
1173
+	}
1174
+
1175
+
1176
+	/**
1177
+	 * Gets all descendants subtotals that match the supplied object type
1178
+	 *
1179
+	 * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1180
+	 * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1181
+	 * @param string $OBJ_type object type (like Event)
1182
+	 * @param array $OBJ_IDs array of OBJ_IDs
1183
+	 * @return EE_Line_Item[]
1184
+	 */
1185
+	public static function get_line_items_by_object_type_and_IDs(
1186
+		EE_Line_Item $parent_line_item,
1187
+		$OBJ_type = '',
1188
+		$OBJ_IDs = array()
1189
+	)
1190
+	{
1191
+		return self::_get_descendants_by_object_type_and_object_ID($parent_line_item, $OBJ_type, $OBJ_IDs);
1192
+	}
1193
+
1194
+
1195
+	/**
1196
+	 * Gets all descendants of supplied line item that match the supplied line item type and possibly the object type as well
1197
+	 *
1198
+	 * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1199
+	 * @param string $OBJ_type object type (like Event)
1200
+	 * @param array $OBJ_IDs array of OBJ_IDs
1201
+	 * @return EE_Line_Item[]
1202
+	 */
1203
+	protected static function _get_descendants_by_object_type_and_object_ID(
1204
+		EE_Line_Item $parent_line_item,
1205
+		$OBJ_type,
1206
+		$OBJ_IDs
1207
+	)
1208
+	{
1209
+		$objects = array();
1210
+		foreach ($parent_line_item->children() as $child_line_item) {
1211
+			if ($child_line_item instanceof EE_Line_Item) {
1212
+				if (
1213
+					$child_line_item->OBJ_type() === $OBJ_type
1214
+					&& is_array($OBJ_IDs)
1215
+					&& in_array($child_line_item->OBJ_ID(), $OBJ_IDs)
1216
+				) {
1217
+					$objects[] = $child_line_item;
1218
+				} else {
1219
+					//go-through-all-its children looking for more matches
1220
+					$objects = array_merge(
1221
+						$objects,
1222
+						self::_get_descendants_by_object_type_and_object_ID(
1223
+							$child_line_item,
1224
+							$OBJ_type,
1225
+							$OBJ_IDs
1226
+						)
1227
+					);
1228
+				}
1229
+			}
1230
+		}
1231
+		return $objects;
1232
+	}
1233
+
1234
+
1235
+	/**
1236
+	 * Uses a breadth-first-search in order to find the nearest descendant of
1237
+	 * the specified type and returns it, else NULL
1238
+	 *
1239
+	 * @uses  EEH_Line_Item::_get_nearest_descendant()
1240
+	 * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1241
+	 * @param string $type like one of the EEM_Line_Item::type_*
1242
+	 * @return EE_Line_Item
1243
+	 */
1244
+	public static function get_nearest_descendant_of_type(EE_Line_Item $parent_line_item, $type)
1245
+	{
1246
+		return self::_get_nearest_descendant($parent_line_item, 'LIN_type', $type);
1247
+	}
1248
+
1249
+
1250
+	/**
1251
+	 * Uses a breadth-first-search in order to find the nearest descendant
1252
+	 * having the specified LIN_code and returns it, else NULL
1253
+	 *
1254
+	 * @uses  EEH_Line_Item::_get_nearest_descendant()
1255
+	 * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1256
+	 * @param string $code any value used for LIN_code
1257
+	 * @return EE_Line_Item
1258
+	 */
1259
+	public static function get_nearest_descendant_having_code(EE_Line_Item $parent_line_item, $code)
1260
+	{
1261
+		return self::_get_nearest_descendant($parent_line_item, 'LIN_code', $code);
1262
+	}
1263
+
1264
+
1265
+	/**
1266
+	 * Uses a breadth-first-search in order to find the nearest descendant
1267
+	 * having the specified LIN_code and returns it, else NULL
1268
+	 *
1269
+	 * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1270
+	 * @param string $search_field name of EE_Line_Item property
1271
+	 * @param string $value any value stored in $search_field
1272
+	 * @return EE_Line_Item
1273
+	 */
1274
+	protected static function _get_nearest_descendant(EE_Line_Item $parent_line_item, $search_field, $value)
1275
+	{
1276
+		foreach ($parent_line_item->children() as $child) {
1277
+			if ($child->get($search_field) == $value) {
1278
+				return $child;
1279
+			}
1280
+		}
1281
+		foreach ($parent_line_item->children() as $child) {
1282
+			$descendant_found = self::_get_nearest_descendant($child, $search_field, $value);
1283
+			if ($descendant_found) {
1284
+				return $descendant_found;
1285
+			}
1286
+		}
1287
+		return NULL;
1288
+	}
1289
+
1290
+
1291
+	/**
1292
+	 * if passed line item has a TXN ID, uses that to jump directly to the grand total line item for the transaction,
1293
+	 * else recursively walks up the line item tree until a parent of type total is found,
1294
+	 *
1295
+	 * @param EE_Line_Item $line_item
1296
+	 * @return \EE_Line_Item
1297
+	 * @throws \EE_Error
1298
+	 */
1299
+	public static function find_transaction_grand_total_for_line_item(EE_Line_Item $line_item)
1300
+	{
1301
+		if ($line_item->TXN_ID()) {
1302
+			$total_line_item = $line_item->transaction()->total_line_item(false);
1303
+			if ($total_line_item instanceof EE_Line_Item) {
1304
+				return $total_line_item;
1305
+			}
1306
+		} else {
1307
+			$line_item_parent = $line_item->parent();
1308
+			if ($line_item_parent instanceof EE_Line_Item) {
1309
+				if ($line_item_parent->is_total()) {
1310
+					return $line_item_parent;
1311
+				}
1312
+				return EEH_Line_Item::find_transaction_grand_total_for_line_item($line_item_parent);
1313
+			}
1314
+		}
1315
+		throw new EE_Error(
1316
+			sprintf(
1317
+				__('A valid grand total for line item %1$d was not found.', 'event_espresso'),
1318
+				$line_item->ID()
1319
+			)
1320
+		);
1321
+	}
1322
+
1323
+
1324
+	/**
1325
+	 * Prints out a representation of the line item tree
1326
+	 *
1327
+	 * @param EE_Line_Item $line_item
1328
+	 * @param int $indentation
1329
+	 * @return void
1330
+	 * @throws \EE_Error
1331
+	 */
1332
+	public static function visualize(EE_Line_Item $line_item, $indentation = 0)
1333
+	{
1334
+		echo defined('EE_TESTS_DIR') ? "\n" : '<br />';
1335
+		if (!$indentation) {
1336
+			echo defined('EE_TESTS_DIR') ? "\n" : '<br />';
1337
+		}
1338
+		for ($i = 0; $i < $indentation; $i++) {
1339
+			echo ". ";
1340
+		}
1341
+		$breakdown = '';
1342
+		if ($line_item->is_line_item()) {
1343
+			if ($line_item->is_percent()) {
1344
+				$breakdown = "{$line_item->percent()}%";
1345
+			} else {
1346
+				$breakdown = '$' . "{$line_item->unit_price()} x {$line_item->quantity()}";
1347
+			}
1348
+		}
1349
+		echo $line_item->name() . " [ ID:{$line_item->ID()} | qty:{$line_item->quantity()} ] {$line_item->type()} : " . '$' . "{$line_item->total()}";
1350
+		if ($breakdown) {
1351
+			echo " ( {$breakdown} )";
1352
+		}
1353
+		if ($line_item->is_taxable()) {
1354
+			echo "  * taxable";
1355
+		}
1356
+		if ($line_item->children()) {
1357
+			foreach ($line_item->children() as $child) {
1358
+				self::visualize($child, $indentation + 1);
1359
+			}
1360
+		}
1361
+	}
1362
+
1363
+
1364
+	/**
1365
+	 * Calculates the registration's final price, taking into account that they
1366
+	 * need to not only help pay for their OWN ticket, but also any transaction-wide surcharges and taxes,
1367
+	 * and receive a portion of any transaction-wide discounts.
1368
+	 * eg1, if I buy a $1 ticket and brent buys a $9 ticket, and we receive a $5 discount
1369
+	 * then I'll get 1/10 of that $5 discount, which is $0.50, and brent will get
1370
+	 * 9/10ths of that $5 discount, which is $4.50. So my final price should be $0.50
1371
+	 * and brent's final price should be $5.50.
1372
+	 *
1373
+	 * In order to do this, we basically need to traverse the line item tree calculating
1374
+	 * the running totals (just as if we were recalculating the total), but when we identify
1375
+	 * regular line items, we need to keep track of their share of the grand total.
1376
+	 * Also, we need to keep track of the TAXABLE total for each ticket purchase, so
1377
+	 * we can know how to apply taxes to it. (Note: "taxable total" does not equal the "pretax total"
1378
+	 * when there are non-taxable items; otherwise they would be the same)
1379
+	 *
1380
+	 * @param EE_Line_Item $line_item
1381
+	 * @param array $billable_ticket_quantities array of EE_Ticket IDs and their corresponding quantity that
1382
+	 *                                                                            can be included in price calculations at this moment
1383
+	 * @return array        keys are line items for tickets IDs and values are their share of the running total,
1384
+	 *                                          plus the key 'total', and 'taxable' which also has keys of all the ticket IDs. Eg
1385
+	 *                                          array(
1386
+	 *                                          12 => 4.3
1387
+	 *                                          23 => 8.0
1388
+	 *                                          'total' => 16.6,
1389
+	 *                                          'taxable' => array(
1390
+	 *                                          12 => 10,
1391
+	 *                                          23 => 4
1392
+	 *                                          ).
1393
+	 *                                          So to find which registrations have which final price, we need to find which line item
1394
+	 *                                          is theirs, which can be done with
1395
+	 *                                          `EEM_Line_Item::instance()->get_line_item_for_registration( $registration );`
1396
+	 */
1397
+	public static function calculate_reg_final_prices_per_line_item(EE_Line_Item $line_item, $billable_ticket_quantities = array())
1398
+	{
1399
+		//init running grand total if not already
1400
+		if (!isset($running_totals['total'])) {
1401
+			$running_totals['total'] = 0;
1402
+		}
1403
+		if (!isset($running_totals['taxable'])) {
1404
+			$running_totals['taxable'] = array('total' => 0);
1405
+		}
1406
+		foreach ($line_item->children() as $child_line_item) {
1407
+			switch ($child_line_item->type()) {
1408
+
1409
+				case EEM_Line_Item::type_sub_total :
1410
+					$running_totals_from_subtotal = EEH_Line_Item::calculate_reg_final_prices_per_line_item($child_line_item, $billable_ticket_quantities);
1411
+					//combine arrays but preserve numeric keys
1412
+					$running_totals = array_replace_recursive($running_totals_from_subtotal, $running_totals);
1413
+					$running_totals['total'] += $running_totals_from_subtotal['total'];
1414
+					$running_totals['taxable']['total'] += $running_totals_from_subtotal['taxable']['total'];
1415
+					break;
1416
+
1417
+				case EEM_Line_Item::type_tax_sub_total :
1418
+
1419
+					//find how much the taxes percentage is
1420
+					if ($child_line_item->percent() !== 0) {
1421
+						$tax_percent_decimal = $child_line_item->percent() / 100;
1422
+					} else {
1423
+						$tax_percent_decimal = EE_Taxes::get_total_taxes_percentage() / 100;
1424
+					}
1425
+					//and apply to all the taxable totals, and add to the pretax totals
1426
+					foreach ($running_totals as $line_item_id => $this_running_total) {
1427
+						//"total" and "taxable" array key is an exception
1428
+						if ($line_item_id === 'taxable') {
1429
+							continue;
1430
+						}
1431
+						$taxable_total = $running_totals['taxable'][$line_item_id];
1432
+						$running_totals[$line_item_id] += ($taxable_total * $tax_percent_decimal);
1433
+					}
1434
+					break;
1435
+
1436
+				case EEM_Line_Item::type_line_item :
1437
+
1438
+					// ticket line items or ????
1439
+					if ($child_line_item->OBJ_type() === 'Ticket') {
1440
+						// kk it's a ticket
1441
+						if (isset($running_totals[$child_line_item->ID()])) {
1442
+							//huh? that shouldn't happen.
1443
+							$running_totals['total'] += $child_line_item->total();
1444
+						} else {
1445
+							//its not in our running totals yet. great.
1446
+							if ($child_line_item->is_taxable()) {
1447
+								$taxable_amount = $child_line_item->unit_price();
1448
+							} else {
1449
+								$taxable_amount = 0;
1450
+							}
1451
+							// are we only calculating totals for some tickets?
1452
+							if (isset($billable_ticket_quantities[$child_line_item->OBJ_ID()])) {
1453
+								$quantity = $billable_ticket_quantities[$child_line_item->OBJ_ID()];
1454
+								$running_totals[$child_line_item->ID()] = $quantity
1455
+									? $child_line_item->unit_price()
1456
+									: 0;
1457
+								$running_totals['taxable'][$child_line_item->ID()] = $quantity
1458
+									? $taxable_amount
1459
+									: 0;
1460
+							} else {
1461
+								$quantity = $child_line_item->quantity();
1462
+								$running_totals[$child_line_item->ID()] = $child_line_item->unit_price();
1463
+								$running_totals['taxable'][$child_line_item->ID()] = $taxable_amount;
1464
+							}
1465
+							$running_totals['taxable']['total'] += $taxable_amount * $quantity;
1466
+							$running_totals['total'] += $child_line_item->unit_price() * $quantity;
1467
+						}
1468
+					} else {
1469
+						// it's some other type of item added to the cart
1470
+						// it should affect the running totals
1471
+						// basically we want to convert it into a PERCENT modifier. Because
1472
+						// more clearly affect all registration's final price equally
1473
+						$line_items_percent_of_running_total = $running_totals['total'] > 0
1474
+							? ($child_line_item->total() / $running_totals['total']) + 1
1475
+							: 1;
1476
+						foreach ($running_totals as $line_item_id => $this_running_total) {
1477
+							//the "taxable" array key is an exception
1478
+							if ($line_item_id === 'taxable') {
1479
+								continue;
1480
+							}
1481
+							// update the running totals
1482
+							// yes this actually even works for the running grand total!
1483
+							$running_totals[$line_item_id] =
1484
+								$line_items_percent_of_running_total * $this_running_total;
1485
+
1486
+							if ($child_line_item->is_taxable()) {
1487
+								$running_totals['taxable'][$line_item_id] =
1488
+									$line_items_percent_of_running_total * $running_totals['taxable'][$line_item_id];
1489
+							}
1490
+						}
1491
+					}
1492
+					break;
1493
+			}
1494
+		}
1495
+		return $running_totals;
1496
+	}
1497
+
1498
+
1499
+	/**
1500
+	 * @param \EE_Line_Item $total_line_item
1501
+	 * @param \EE_Line_Item $ticket_line_item
1502
+	 * @return float | null
1503
+	 * @throws \OutOfRangeException
1504
+	 */
1505
+	public static function calculate_final_price_for_ticket_line_item(\EE_Line_Item $total_line_item, \EE_Line_Item $ticket_line_item)
1506
+	{
1507
+		static $final_prices_per_ticket_line_item = array();
1508
+		if (empty($final_prices_per_ticket_line_item)) {
1509
+			$final_prices_per_ticket_line_item = \EEH_Line_Item::calculate_reg_final_prices_per_line_item(
1510
+				$total_line_item
1511
+			);
1512
+		}
1513
+		//ok now find this new registration's final price
1514
+		if (isset($final_prices_per_ticket_line_item[$ticket_line_item->ID()])) {
1515
+			return $final_prices_per_ticket_line_item[$ticket_line_item->ID()];
1516
+		}
1517
+		$message = sprintf(
1518
+			__(
1519
+				'The final price for the ticket line item (ID:%1$d) could not be calculated.',
1520
+				'event_espresso'
1521
+			),
1522
+			$ticket_line_item->ID()
1523
+		);
1524
+		if (WP_DEBUG) {
1525
+			$message .= '<br>' . print_r($final_prices_per_ticket_line_item, true);
1526
+			throw new \OutOfRangeException($message);
1527
+		} else {
1528
+			EE_Log::instance()->log(__CLASS__, __FUNCTION__, $message);
1529
+		}
1530
+		return null;
1531
+	}
1532
+
1533
+
1534
+	/**
1535
+	 * Creates a duplicate of the line item tree, except only includes billable items
1536
+	 * and the portion of line items attributed to billable things
1537
+	 *
1538
+	 * @param EE_Line_Item $line_item
1539
+	 * @param EE_Registration[] $registrations
1540
+	 * @return \EE_Line_Item
1541
+	 * @throws \EE_Error
1542
+	 */
1543
+	public static function billable_line_item_tree(EE_Line_Item $line_item, $registrations)
1544
+	{
1545
+		$copy_li = EEH_Line_Item::billable_line_item($line_item, $registrations);
1546
+		foreach ($line_item->children() as $child_li) {
1547
+			$copy_li->add_child_line_item(EEH_Line_Item::billable_line_item_tree($child_li, $registrations));
1548
+		}
1549
+		//if this is the grand total line item, make sure the totals all add up
1550
+		//(we could have duplicated this logic AS we copied the line items, but
1551
+		//it seems DRYer this way)
1552
+		if ($copy_li->type() === EEM_Line_Item::type_total) {
1553
+			$copy_li->recalculate_total_including_taxes();
1554
+		}
1555
+		return $copy_li;
1556
+	}
1557
+
1558
+
1559
+	/**
1560
+	 * Creates a new, unsaved line item from $line_item that factors in the
1561
+	 * number of billable registrations on $registrations.
1562
+	 *
1563
+	 * @param EE_Line_Item $line_item
1564
+	 * @return EE_Line_Item
1565
+	 * @throws \EE_Error
1566
+	 * @param EE_Registration[] $registrations
1567
+	 */
1568
+	public static function billable_line_item(EE_Line_Item $line_item, $registrations)
1569
+	{
1570
+		$new_li_fields = $line_item->model_field_array();
1571
+		if ($line_item->type() === EEM_Line_Item::type_line_item &&
1572
+			$line_item->OBJ_type() === 'Ticket'
1573
+		) {
1574
+			$count = 0;
1575
+			foreach ($registrations as $registration) {
1576
+				if ($line_item->OBJ_ID() === $registration->ticket_ID() &&
1577
+					in_array($registration->status_ID(), EEM_Registration::reg_statuses_that_allow_payment())
1578
+				) {
1579
+					$count++;
1580
+				}
1581
+			}
1582
+			$new_li_fields['LIN_quantity'] = $count;
1583
+		}
1584
+		//don't set the total. We'll leave that up to the code that calculates it
1585
+		unset($new_li_fields['LIN_ID'], $new_li_fields['LIN_parent'], $new_li_fields['LIN_total']);
1586
+		return EE_Line_Item::new_instance($new_li_fields);
1587
+	}
1588
+
1589
+
1590
+	/**
1591
+	 * Returns a modified line item tree where all the subtotals which have a total of 0
1592
+	 * are removed, and line items with a quantity of 0
1593
+	 *
1594
+	 * @param EE_Line_Item $line_item |null
1595
+	 * @return \EE_Line_Item|null
1596
+	 * @throws \EE_Error
1597
+	 */
1598
+	public static function non_empty_line_items(EE_Line_Item $line_item)
1599
+	{
1600
+		$copied_li = EEH_Line_Item::non_empty_line_item($line_item);
1601
+		if ($copied_li === null) {
1602
+			return null;
1603
+		}
1604
+		//if this is an event subtotal, we want to only include it if it
1605
+		//has a non-zero total and at least one ticket line item child
1606
+		$ticket_children = 0;
1607
+		foreach ($line_item->children() as $child_li) {
1608
+			$child_li_copy = EEH_Line_Item::non_empty_line_items($child_li);
1609
+			if ($child_li_copy !== null) {
1610
+				$copied_li->add_child_line_item($child_li_copy);
1611
+				if ($child_li_copy->type() === EEM_Line_Item::type_line_item &&
1612
+					$child_li_copy->OBJ_type() === 'Ticket'
1613
+				) {
1614
+					$ticket_children++;
1615
+				}
1616
+			}
1617
+		}
1618
+		//if this is an event subtotal with NO ticket children
1619
+		//we basically want to ignore it
1620
+		if (
1621
+			$ticket_children === 0
1622
+			&& $line_item->type() === EEM_Line_Item::type_sub_total
1623
+			&& $line_item->OBJ_type() === 'Event'
1624
+			&& $line_item->total() === 0
1625
+		) {
1626
+			return null;
1627
+		}
1628
+		return $copied_li;
1629
+	}
1630
+
1631
+
1632
+	/**
1633
+	 * Creates a new, unsaved line item, but if it's a ticket line item
1634
+	 * with a total of 0, or a subtotal of 0, returns null instead
1635
+	 *
1636
+	 * @param EE_Line_Item $line_item
1637
+	 * @return EE_Line_Item
1638
+	 * @throws \EE_Error
1639
+	 */
1640
+	public static function non_empty_line_item(EE_Line_Item $line_item)
1641
+	{
1642
+		if ($line_item->type() === EEM_Line_Item::type_line_item &&
1643
+			$line_item->OBJ_type() === 'Ticket' &&
1644
+			$line_item->quantity() === 0
1645
+		) {
1646
+			return null;
1647
+		}
1648
+		$new_li_fields = $line_item->model_field_array();
1649
+		//don't set the total. We'll leave that up to the code that calculates it
1650
+		unset($new_li_fields['LIN_ID'], $new_li_fields['LIN_parent']);
1651
+		return EE_Line_Item::new_instance($new_li_fields);
1652
+	}
1653
+
1654
+
1655
+
1656
+	/**************************************** @DEPRECATED METHODS *************************************** */
1657
+	/**
1658
+	 * @deprecated
1659
+	 * @param EE_Line_Item $total_line_item
1660
+	 * @return \EE_Line_Item
1661
+	 * @throws \EE_Error
1662
+	 */
1663
+	public static function get_items_subtotal(EE_Line_Item $total_line_item)
1664
+	{
1665
+		EE_Error::doing_it_wrong('EEH_Line_Item::get_items_subtotal()', __('Method replaced with EEH_Line_Item::get_pre_tax_subtotal()', 'event_espresso'), '4.6.0');
1666
+		return self::get_pre_tax_subtotal($total_line_item);
1667
+	}
1668
+
1669
+
1670
+	/**
1671
+	 * @deprecated
1672
+	 * @param EE_Transaction $transaction
1673
+	 * @return \EE_Line_Item
1674
+	 * @throws \EE_Error
1675
+	 */
1676
+	public static function create_default_total_line_item($transaction = NULL)
1677
+	{
1678
+		EE_Error::doing_it_wrong('EEH_Line_Item::create_default_total_line_item()', __('Method replaced with EEH_Line_Item::create_total_line_item()', 'event_espresso'), '4.6.0');
1679
+		return self::create_total_line_item($transaction);
1680
+	}
1681
+
1682
+
1683
+	/**
1684
+	 * @deprecated
1685
+	 * @param EE_Line_Item $total_line_item
1686
+	 * @param EE_Transaction $transaction
1687
+	 * @return \EE_Line_Item
1688
+	 * @throws \EE_Error
1689
+	 */
1690
+	public static function create_default_tickets_subtotal(EE_Line_Item $total_line_item, $transaction = NULL)
1691
+	{
1692
+		EE_Error::doing_it_wrong('EEH_Line_Item::create_default_tickets_subtotal()', __('Method replaced with EEH_Line_Item::create_pre_tax_subtotal()', 'event_espresso'), '4.6.0');
1693
+		return self::create_pre_tax_subtotal($total_line_item, $transaction);
1694
+	}
1695
+
1696
+
1697
+	/**
1698
+	 * @deprecated
1699
+	 * @param EE_Line_Item $total_line_item
1700
+	 * @param EE_Transaction $transaction
1701
+	 * @return \EE_Line_Item
1702
+	 * @throws \EE_Error
1703
+	 */
1704
+	public static function create_default_taxes_subtotal(EE_Line_Item $total_line_item, $transaction = NULL)
1705
+	{
1706
+		EE_Error::doing_it_wrong('EEH_Line_Item::create_default_taxes_subtotal()', __('Method replaced with EEH_Line_Item::create_taxes_subtotal()', 'event_espresso'), '4.6.0');
1707
+		return self::create_taxes_subtotal($total_line_item, $transaction);
1708
+	}
1709
+
1710
+
1711
+	/**
1712
+	 * @deprecated
1713
+	 * @param EE_Line_Item $total_line_item
1714
+	 * @param EE_Transaction $transaction
1715
+	 * @return \EE_Line_Item
1716
+	 * @throws \EE_Error
1717
+	 */
1718
+	public static function create_default_event_subtotal(EE_Line_Item $total_line_item, $transaction = NULL)
1719
+	{
1720
+		EE_Error::doing_it_wrong('EEH_Line_Item::create_default_event_subtotal()', __('Method replaced with EEH_Line_Item::create_event_subtotal()', 'event_espresso'), '4.6.0');
1721
+		return self::create_event_subtotal($total_line_item, $transaction);
1722
+	}
1723 1723
 
1724 1724
 
1725 1725
 }
Please login to merge, or discard this patch.
Spacing   +31 added lines, -31 removed lines patch added patch discarded remove patch
@@ -1,4 +1,4 @@  discard block
 block discarded – undo
1
-<?php if (!defined('EVENT_ESPRESSO_VERSION')) {
1
+<?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2 2
     exit('No direct script access allowed');
3 3
 }
4 4
 
@@ -56,7 +56,7 @@  discard block
 block discarded – undo
56 56
             'LIN_percent' => null,
57 57
             'LIN_is_taxable' => $taxable,
58 58
             'LIN_order' => $items_subtotal instanceof EE_Line_Item ? count($items_subtotal->children()) : 0,
59
-            'LIN_total' => (float)$unit_price * (int)$quantity,
59
+            'LIN_total' => (float) $unit_price * (int) $quantity,
60 60
             'LIN_type' => EEM_Line_Item::type_line_item,
61 61
             'LIN_code' => $code,
62 62
         ));
@@ -95,7 +95,7 @@  discard block
 block discarded – undo
95 95
             'LIN_percent' => $percentage_amount,
96 96
             'LIN_quantity' => 1,
97 97
             'LIN_is_taxable' => $taxable,
98
-            'LIN_total' => (float)($percentage_amount * ($parent_line_item->total() / 100)),
98
+            'LIN_total' => (float) ($percentage_amount * ($parent_line_item->total() / 100)),
99 99
             'LIN_type' => EEM_Line_Item::type_line_item,
100 100
             'LIN_parent' => $parent_line_item->ID()
101 101
         ));
@@ -125,13 +125,13 @@  discard block
 block discarded – undo
125 125
      */
126 126
     public static function add_ticket_purchase(EE_Line_Item $total_line_item, EE_Ticket $ticket, $qty = 1)
127 127
     {
128
-        if (!$total_line_item instanceof EE_Line_Item || !$total_line_item->is_total()) {
128
+        if ( ! $total_line_item instanceof EE_Line_Item || ! $total_line_item->is_total()) {
129 129
             throw new EE_Error(sprintf(__('A valid line item total is required in order to add tickets. A line item of type "%s" was passed.', 'event_espresso'), $ticket->ID(), $total_line_item->ID()));
130 130
         }
131 131
         // either increment the qty for an existing ticket
132 132
         $line_item = self::increment_ticket_qty_if_already_in_cart($total_line_item, $ticket, $qty);
133 133
         // or add a new one
134
-        if (!$line_item instanceof EE_Line_Item) {
134
+        if ( ! $line_item instanceof EE_Line_Item) {
135 135
             $line_item = self::create_ticket_line_item($total_line_item, $ticket, $qty);
136 136
         }
137 137
         $total_line_item->recalculate_total_including_taxes();
@@ -152,10 +152,10 @@  discard block
 block discarded – undo
152 152
         $line_item = null;
153 153
         if ($total_line_item instanceof EE_Line_Item && $total_line_item->is_total()) {
154 154
             $ticket_line_items = EEH_Line_Item::get_ticket_line_items($total_line_item);
155
-            foreach ((array)$ticket_line_items as $ticket_line_item) {
155
+            foreach ((array) $ticket_line_items as $ticket_line_item) {
156 156
                 if (
157 157
                     $ticket_line_item instanceof EE_Line_Item
158
-                    && (int)$ticket_line_item->OBJ_ID() === (int)$ticket->ID()
158
+                    && (int) $ticket_line_item->OBJ_ID() === (int) $ticket->ID()
159 159
                 ) {
160 160
                     $line_item = $ticket_line_item;
161 161
                     break;
@@ -181,7 +181,7 @@  discard block
 block discarded – undo
181 181
      */
182 182
     public static function increment_quantity(EE_Line_Item $line_item, $qty = 1)
183 183
     {
184
-        if (!$line_item->is_percent()) {
184
+        if ( ! $line_item->is_percent()) {
185 185
             $qty += $line_item->quantity();
186 186
             $line_item->set_quantity($qty);
187 187
             $line_item->set_total($line_item->unit_price() * $qty);
@@ -206,7 +206,7 @@  discard block
 block discarded – undo
206 206
      */
207 207
     public static function decrement_quantity(EE_Line_Item $line_item, $qty = 1)
208 208
     {
209
-        if (!$line_item->is_percent()) {
209
+        if ( ! $line_item->is_percent()) {
210 210
             $qty = $line_item->quantity() - $qty;
211 211
             $qty = max($qty, 0);
212 212
             $line_item->set_quantity($qty);
@@ -231,7 +231,7 @@  discard block
 block discarded – undo
231 231
      */
232 232
     public static function update_quantity(EE_Line_Item $line_item, $new_quantity)
233 233
     {
234
-        if (!$line_item->is_percent()) {
234
+        if ( ! $line_item->is_percent()) {
235 235
             $line_item->set_quantity($new_quantity);
236 236
             $line_item->set_total($line_item->unit_price() * $new_quantity);
237 237
             $line_item->save();
@@ -267,7 +267,7 @@  discard block
 block discarded – undo
267 267
         // add $ticket to cart
268 268
         $line_item = EE_Line_Item::new_instance(array(
269 269
             'LIN_name' => $ticket->name(),
270
-            'LIN_desc' => $ticket->description() !== '' ? $ticket->description() . ' ' . $event : $event,
270
+            'LIN_desc' => $ticket->description() !== '' ? $ticket->description().' '.$event : $event,
271 271
             'LIN_unit_price' => $ticket->price(),
272 272
             'LIN_quantity' => $qty,
273 273
             'LIN_is_taxable' => $ticket->taxable(),
@@ -377,8 +377,8 @@  discard block
 block discarded – undo
377 377
         foreach ($ticket_line_item->children() as $child_line_item) {
378 378
             if (
379 379
                 $child_line_item->is_sub_line_item()
380
-                && !$child_line_item->is_percent()
381
-                && !$child_line_item->is_cancellation()
380
+                && ! $child_line_item->is_percent()
381
+                && ! $child_line_item->is_cancellation()
382 382
             ) {
383 383
                 $child_line_item->set_quantity($child_line_item->quantity() - $qty);
384 384
             }
@@ -400,7 +400,7 @@  discard block
 block discarded – undo
400 400
                 'LIN_desc' => sprintf(
401 401
                     _x('Cancelled %1$s : %2$s', 'Cancelled Ticket Name : 2015-01-01 11:11', 'event_espresso'),
402 402
                     $ticket_line_item->name(),
403
-                    current_time(get_option('date_format') . ' ' . get_option('time_format'))
403
+                    current_time(get_option('date_format').' '.get_option('time_format'))
404 404
                 ),
405 405
                 'LIN_unit_price' => 0, // $ticket_line_item->unit_price()
406 406
                 'LIN_quantity' => $qty,
@@ -453,7 +453,7 @@  discard block
 block discarded – undo
453 453
         );
454 454
         $cancellation_line_item = reset($cancellation_line_item);
455 455
         // verify that this ticket was indeed previously cancelled
456
-        if (!$cancellation_line_item instanceof EE_Line_Item) {
456
+        if ( ! $cancellation_line_item instanceof EE_Line_Item) {
457 457
             return false;
458 458
         }
459 459
         if ($cancellation_line_item->quantity() > $qty) {
@@ -625,7 +625,7 @@  discard block
 block discarded – undo
625 625
             'LIN_code' => 'taxes',
626 626
             'LIN_name' => __('Taxes', 'event_espresso'),
627 627
             'LIN_type' => EEM_Line_Item::type_tax_sub_total,
628
-            'LIN_order' => 1000,//this should always come last
628
+            'LIN_order' => 1000, //this should always come last
629 629
         ));
630 630
         $tax_line_item = apply_filters(
631 631
             'FHEE__EEH_Line_Item__create_taxes_subtotal__tax_line_item',
@@ -677,7 +677,7 @@  discard block
 block discarded – undo
677 677
      */
678 678
     public static function get_event_code($event)
679 679
     {
680
-        return 'event-' . ($event instanceof EE_Event ? $event->ID() : '0');
680
+        return 'event-'.($event instanceof EE_Event ? $event->ID() : '0');
681 681
     }
682 682
 
683 683
     /**
@@ -713,13 +713,13 @@  discard block
 block discarded – undo
713 713
     public static function get_event_line_item_for_ticket(EE_Line_Item $grand_total, EE_Ticket $ticket)
714 714
     {
715 715
         $first_datetime = $ticket->first_datetime();
716
-        if (!$first_datetime instanceof EE_Datetime) {
716
+        if ( ! $first_datetime instanceof EE_Datetime) {
717 717
             throw new EE_Error(
718 718
                 sprintf(__('The supplied ticket (ID %d) has no datetimes', 'event_espresso'), $ticket->ID())
719 719
             );
720 720
         }
721 721
         $event = $first_datetime->event();
722
-        if (!$event instanceof EE_Event) {
722
+        if ( ! $event instanceof EE_Event) {
723 723
             throw new EE_Error(
724 724
                 sprintf(
725 725
                     __('The supplied ticket (ID %d) has no event data associated with it.', 'event_espresso'),
@@ -728,7 +728,7 @@  discard block
 block discarded – undo
728 728
             );
729 729
         }
730 730
         $events_sub_total = EEH_Line_Item::get_event_line_item($grand_total, $event);
731
-        if (!$events_sub_total instanceof EE_Line_Item) {
731
+        if ( ! $events_sub_total instanceof EE_Line_Item) {
732 732
             throw new EE_Error(
733 733
                 sprintf(
734 734
                     __('There is no events sub-total for ticket %s on total line item %d', 'event_espresso'),
@@ -757,7 +757,7 @@  discard block
 block discarded – undo
757 757
         $found = false;
758 758
         foreach (EEH_Line_Item::get_event_subtotals($grand_total) as $event_line_item) {
759 759
             // default event subtotal, we should only ever find this the first time this method is called
760
-            if (!$event_line_item->OBJ_ID()) {
760
+            if ( ! $event_line_item->OBJ_ID()) {
761 761
                 // let's use this! but first... set the event details
762 762
                 EEH_Line_Item::set_event_subtotal_details($event_line_item, $event);
763 763
                 $found = true;
@@ -768,7 +768,7 @@  discard block
 block discarded – undo
768 768
                 break;
769 769
             }
770 770
         }
771
-        if (!$found) {
771
+        if ( ! $found) {
772 772
             //there is no event sub-total yet, so add it
773 773
             $pre_tax_subtotal = EEH_Line_Item::get_pre_tax_subtotal($grand_total);
774 774
             // create a new "event" subtotal below that
@@ -863,7 +863,7 @@  discard block
 block discarded – undo
863 863
     public static function ensure_taxes_applied($total_line_item)
864 864
     {
865 865
         $taxes_subtotal = self::get_taxes_subtotal($total_line_item);
866
-        if (!$taxes_subtotal->children()) {
866
+        if ( ! $taxes_subtotal->children()) {
867 867
             self::apply_taxes($total_line_item);
868 868
         }
869 869
         return $taxes_subtotal->total();
@@ -924,7 +924,7 @@  discard block
 block discarded – undo
924 924
         do_action('AHEE_log', __FILE__, __FUNCTION__, '');
925 925
 
926 926
         // check if only a single line_item_id was passed
927
-        if (!empty($line_item_codes) && !is_array($line_item_codes)) {
927
+        if ( ! empty($line_item_codes) && ! is_array($line_item_codes)) {
928 928
             // place single line_item_id in an array to appear as multiple line_item_ids
929 929
             $line_item_codes = array($line_item_codes);
930 930
         }
@@ -1027,7 +1027,7 @@  discard block
 block discarded – undo
1027 1027
         if ($code_substring_for_whitelist !== null) {
1028 1028
             $whitelisted = strpos($line_item->code(), $code_substring_for_whitelist) !== false ? true : false;
1029 1029
         }
1030
-        if (!$whitelisted && $line_item->is_line_item()) {
1030
+        if ( ! $whitelisted && $line_item->is_line_item()) {
1031 1031
             $line_item->set_is_taxable($taxable);
1032 1032
         }
1033 1033
         foreach ($line_item->children() as $child_line_item) {
@@ -1332,7 +1332,7 @@  discard block
 block discarded – undo
1332 1332
     public static function visualize(EE_Line_Item $line_item, $indentation = 0)
1333 1333
     {
1334 1334
         echo defined('EE_TESTS_DIR') ? "\n" : '<br />';
1335
-        if (!$indentation) {
1335
+        if ( ! $indentation) {
1336 1336
             echo defined('EE_TESTS_DIR') ? "\n" : '<br />';
1337 1337
         }
1338 1338
         for ($i = 0; $i < $indentation; $i++) {
@@ -1343,10 +1343,10 @@  discard block
 block discarded – undo
1343 1343
             if ($line_item->is_percent()) {
1344 1344
                 $breakdown = "{$line_item->percent()}%";
1345 1345
             } else {
1346
-                $breakdown = '$' . "{$line_item->unit_price()} x {$line_item->quantity()}";
1346
+                $breakdown = '$'."{$line_item->unit_price()} x {$line_item->quantity()}";
1347 1347
             }
1348 1348
         }
1349
-        echo $line_item->name() . " [ ID:{$line_item->ID()} | qty:{$line_item->quantity()} ] {$line_item->type()} : " . '$' . "{$line_item->total()}";
1349
+        echo $line_item->name()." [ ID:{$line_item->ID()} | qty:{$line_item->quantity()} ] {$line_item->type()} : ".'$'."{$line_item->total()}";
1350 1350
         if ($breakdown) {
1351 1351
             echo " ( {$breakdown} )";
1352 1352
         }
@@ -1397,10 +1397,10 @@  discard block
 block discarded – undo
1397 1397
     public static function calculate_reg_final_prices_per_line_item(EE_Line_Item $line_item, $billable_ticket_quantities = array())
1398 1398
     {
1399 1399
         //init running grand total if not already
1400
-        if (!isset($running_totals['total'])) {
1400
+        if ( ! isset($running_totals['total'])) {
1401 1401
             $running_totals['total'] = 0;
1402 1402
         }
1403
-        if (!isset($running_totals['taxable'])) {
1403
+        if ( ! isset($running_totals['taxable'])) {
1404 1404
             $running_totals['taxable'] = array('total' => 0);
1405 1405
         }
1406 1406
         foreach ($line_item->children() as $child_line_item) {
@@ -1522,7 +1522,7 @@  discard block
 block discarded – undo
1522 1522
             $ticket_line_item->ID()
1523 1523
         );
1524 1524
         if (WP_DEBUG) {
1525
-            $message .= '<br>' . print_r($final_prices_per_ticket_line_item, true);
1525
+            $message .= '<br>'.print_r($final_prices_per_ticket_line_item, true);
1526 1526
             throw new \OutOfRangeException($message);
1527 1527
         } else {
1528 1528
             EE_Log::instance()->log(__CLASS__, __FUNCTION__, $message);
Please login to merge, or discard this patch.
core/db_classes/EE_Line_Item.class.php 2 patches
Indentation   +1426 added lines, -1426 removed lines patch added patch discarded remove patch
@@ -17,1432 +17,1432 @@
 block discarded – undo
17 17
 class EE_Line_Item extends EE_Base_Class implements EEI_Line_Item
18 18
 {
19 19
 
20
-    /**
21
-     * for children line items (currently not a normal relation)
22
-     *
23
-     * @type EE_Line_Item[]
24
-     */
25
-    protected $_children = array();
26
-
27
-    /**
28
-     * for the parent line item
29
-     *
30
-     * @var EE_Line_Item
31
-     */
32
-    protected $_parent;
33
-
34
-
35
-    /**
36
-     *
37
-     * @param array $props_n_values incoming values
38
-     * @param string $timezone incoming timezone (if not set the timezone set for the website will be
39
-     *                                        used.)
40
-     * @param array $date_formats incoming date_formats in an array where the first value is the
41
-     *                                        date_format and the second value is the time format
42
-     * @return EE_Line_Item
43
-     * @throws EE_Error
44
-     */
45
-    public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
46
-    {
47
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
48
-        return $has_object
49
-            ? $has_object
50
-            : new self($props_n_values, false, $timezone);
51
-    }
52
-
53
-
54
-    /**
55
-     * @param array $props_n_values incoming values from the database
56
-     * @param string $timezone incoming timezone as set by the model.  If not set the timezone for
57
-     *                                the website will be used.
58
-     * @return EE_Line_Item
59
-     * @throws EE_Error
60
-     */
61
-    public static function new_instance_from_db($props_n_values = array(), $timezone = null)
62
-    {
63
-        return new self($props_n_values, true, $timezone);
64
-    }
65
-
66
-
67
-    /**
68
-     * Adds some defaults if they're not specified
69
-     *
70
-     * @param array $fieldValues
71
-     * @param bool $bydb
72
-     * @param string $timezone
73
-     * @throws EE_Error
74
-     */
75
-    protected function __construct($fieldValues = array(), $bydb = false, $timezone = '')
76
-    {
77
-        parent::__construct($fieldValues, $bydb, $timezone);
78
-        if (!$this->get('LIN_code')) {
79
-            $this->set_code($this->generate_code());
80
-        }
81
-    }
82
-
83
-
84
-    /**
85
-     * Gets ID
86
-     *
87
-     * @return int
88
-     * @throws EE_Error
89
-     */
90
-    public function ID()
91
-    {
92
-        return $this->get('LIN_ID');
93
-    }
94
-
95
-
96
-    /**
97
-     * Gets TXN_ID
98
-     *
99
-     * @return int
100
-     * @throws EE_Error
101
-     */
102
-    public function TXN_ID()
103
-    {
104
-        return $this->get('TXN_ID');
105
-    }
106
-
107
-
108
-    /**
109
-     * Sets TXN_ID
110
-     *
111
-     * @param int $TXN_ID
112
-     * @throws EE_Error
113
-     */
114
-    public function set_TXN_ID($TXN_ID)
115
-    {
116
-        $this->set('TXN_ID', $TXN_ID);
117
-    }
118
-
119
-
120
-    /**
121
-     * Gets name
122
-     *
123
-     * @return string
124
-     * @throws EE_Error
125
-     */
126
-    public function name()
127
-    {
128
-        $name = $this->get('LIN_name');
129
-        if (!$name) {
130
-            $name = ucwords(str_replace('-', ' ', $this->type()));
131
-        }
132
-        return $name;
133
-    }
134
-
135
-
136
-    /**
137
-     * Sets name
138
-     *
139
-     * @param string $name
140
-     * @throws EE_Error
141
-     */
142
-    public function set_name($name)
143
-    {
144
-        $this->set('LIN_name', $name);
145
-    }
146
-
147
-
148
-    /**
149
-     * Gets desc
150
-     *
151
-     * @return string
152
-     * @throws EE_Error
153
-     */
154
-    public function desc()
155
-    {
156
-        return $this->get('LIN_desc');
157
-    }
158
-
159
-
160
-    /**
161
-     * Sets desc
162
-     *
163
-     * @param string $desc
164
-     * @throws EE_Error
165
-     */
166
-    public function set_desc($desc)
167
-    {
168
-        $this->set('LIN_desc', $desc);
169
-    }
170
-
171
-
172
-    /**
173
-     * Gets quantity
174
-     *
175
-     * @return int
176
-     * @throws EE_Error
177
-     */
178
-    public function quantity()
179
-    {
180
-        return $this->get('LIN_quantity');
181
-    }
182
-
183
-
184
-    /**
185
-     * Sets quantity
186
-     *
187
-     * @param int $quantity
188
-     * @throws EE_Error
189
-     */
190
-    public function set_quantity($quantity)
191
-    {
192
-        $this->set('LIN_quantity', max($quantity, 0));
193
-    }
194
-
195
-
196
-    /**
197
-     * Gets item_id
198
-     *
199
-     * @return string
200
-     * @throws EE_Error
201
-     */
202
-    public function OBJ_ID()
203
-    {
204
-        return $this->get('OBJ_ID');
205
-    }
206
-
207
-
208
-    /**
209
-     * Sets item_id
210
-     *
211
-     * @param string $item_id
212
-     * @throws EE_Error
213
-     */
214
-    public function set_OBJ_ID($item_id)
215
-    {
216
-        $this->set('OBJ_ID', $item_id);
217
-    }
218
-
219
-
220
-    /**
221
-     * Gets item_type
222
-     *
223
-     * @return string
224
-     * @throws EE_Error
225
-     */
226
-    public function OBJ_type()
227
-    {
228
-        return $this->get('OBJ_type');
229
-    }
230
-
231
-
232
-    /**
233
-     * Gets item_type
234
-     *
235
-     * @return string
236
-     * @throws EE_Error
237
-     */
238
-    public function OBJ_type_i18n()
239
-    {
240
-        $obj_type = $this->OBJ_type();
241
-        switch ($obj_type) {
242
-            case 'Event':
243
-                $obj_type = __('Event', 'event_espresso');
244
-                break;
245
-            case 'Price':
246
-                $obj_type = __('Price', 'event_espresso');
247
-                break;
248
-            case 'Promotion':
249
-                $obj_type = __('Promotion', 'event_espresso');
250
-                break;
251
-            case 'Ticket':
252
-                $obj_type = __('Ticket', 'event_espresso');
253
-                break;
254
-            case 'Transaction':
255
-                $obj_type = __('Transaction', 'event_espresso');
256
-                break;
257
-        }
258
-        return apply_filters('FHEE__EE_Line_Item__OBJ_type_i18n', $obj_type, $this);
259
-    }
260
-
261
-
262
-    /**
263
-     * Sets item_type
264
-     *
265
-     * @param string $OBJ_type
266
-     * @throws EE_Error
267
-     */
268
-    public function set_OBJ_type($OBJ_type)
269
-    {
270
-        $this->set('OBJ_type', $OBJ_type);
271
-    }
272
-
273
-
274
-    /**
275
-     * Gets unit_price
276
-     *
277
-     * @return float
278
-     * @throws EE_Error
279
-     */
280
-    public function unit_price()
281
-    {
282
-        return $this->get('LIN_unit_price');
283
-    }
284
-
285
-
286
-    /**
287
-     * Sets unit_price
288
-     *
289
-     * @param float $unit_price
290
-     * @throws EE_Error
291
-     */
292
-    public function set_unit_price($unit_price)
293
-    {
294
-        $this->set('LIN_unit_price', $unit_price);
295
-    }
296
-
297
-
298
-    /**
299
-     * Checks if this item is a percentage modifier or not
300
-     *
301
-     * @return boolean
302
-     * @throws EE_Error
303
-     */
304
-    public function is_percent()
305
-    {
306
-        if ($this->is_tax_sub_total()) {
307
-            //tax subtotals HAVE a percent on them, that percentage only applies
308
-            //to taxable items, so its' an exception. Treat it like a flat line item
309
-            return false;
310
-        }
311
-        $unit_price = abs($this->get('LIN_unit_price'));
312
-        $percent = abs($this->get('LIN_percent'));
313
-        if ($unit_price < .001 && $percent) {
314
-            return true;
315
-        }
316
-        if ($unit_price >= .001 && !$percent) {
317
-            return false;
318
-        }
319
-        if ($unit_price >= .001 && $percent) {
320
-            throw new EE_Error(
321
-                sprintf(
322
-                    esc_html__('A Line Item can not have a unit price of (%s) AND a percent (%s)!', 'event_espresso'),
323
-                    $unit_price, $percent
324
-                )
325
-            );
326
-        }
327
-        // if they're both 0, assume its not a percent item
328
-        return false;
329
-    }
330
-
331
-
332
-    /**
333
-     * Gets percent (between 100-.001)
334
-     *
335
-     * @return float
336
-     * @throws EE_Error
337
-     */
338
-    public function percent()
339
-    {
340
-        return $this->get('LIN_percent');
341
-    }
342
-
343
-
344
-    /**
345
-     * Sets percent (between 100-0.01)
346
-     *
347
-     * @param float $percent
348
-     * @throws EE_Error
349
-     */
350
-    public function set_percent($percent)
351
-    {
352
-        $this->set('LIN_percent', $percent);
353
-    }
354
-
355
-
356
-    /**
357
-     * Gets total
358
-     *
359
-     * @return float
360
-     * @throws EE_Error
361
-     */
362
-    public function total()
363
-    {
364
-        return $this->get('LIN_total');
365
-    }
366
-
367
-
368
-    /**
369
-     * Sets total
370
-     *
371
-     * @param float $total
372
-     * @throws EE_Error
373
-     */
374
-    public function set_total($total)
375
-    {
376
-        $this->set('LIN_total', $total);
377
-    }
378
-
379
-
380
-    /**
381
-     * Gets order
382
-     *
383
-     * @return int
384
-     * @throws EE_Error
385
-     */
386
-    public function order()
387
-    {
388
-        return $this->get('LIN_order');
389
-    }
390
-
391
-
392
-    /**
393
-     * Sets order
394
-     *
395
-     * @param int $order
396
-     * @throws EE_Error
397
-     */
398
-    public function set_order($order)
399
-    {
400
-        $this->set('LIN_order', $order);
401
-    }
402
-
403
-
404
-    /**
405
-     * Gets parent
406
-     *
407
-     * @return int
408
-     * @throws EE_Error
409
-     */
410
-    public function parent_ID()
411
-    {
412
-        return $this->get('LIN_parent');
413
-    }
414
-
415
-
416
-    /**
417
-     * Sets parent
418
-     *
419
-     * @param int $parent
420
-     * @throws EE_Error
421
-     */
422
-    public function set_parent_ID($parent)
423
-    {
424
-        $this->set('LIN_parent', $parent);
425
-    }
426
-
427
-
428
-    /**
429
-     * Gets type
430
-     *
431
-     * @return string
432
-     * @throws EE_Error
433
-     */
434
-    public function type()
435
-    {
436
-        return $this->get('LIN_type');
437
-    }
438
-
439
-
440
-    /**
441
-     * Sets type
442
-     *
443
-     * @param string $type
444
-     * @throws EE_Error
445
-     */
446
-    public function set_type($type)
447
-    {
448
-        $this->set('LIN_type', $type);
449
-    }
450
-
451
-
452
-    /**
453
-     * Gets the line item of which this item is a composite. Eg, if this is a subtotal, the parent might be a total\
454
-     * If this line item is saved to the DB, fetches the parent from the DB. However, if this line item isn't in the DB
455
-     * it uses its cached reference to its parent line item (which would have been set by `EE_Line_Item::set_parent()`
456
-     * or indirectly by `EE_Line_item::add_child_line_item()`)
457
-     *
458
-     * @return EE_Base_Class|EE_Line_Item
459
-     * @throws EE_Error
460
-     */
461
-    public function parent()
462
-    {
463
-        return $this->ID()
464
-            ? $this->get_model()->get_one_by_ID($this->parent_ID())
465
-            : $this->_parent;
466
-    }
467
-
468
-
469
-    /**
470
-     * Gets ALL the children of this line item (ie, all the parts that contribute towards this total).
471
-     *
472
-     * @return EE_Base_Class[]|EE_Line_Item[]
473
-     * @throws EE_Error
474
-     */
475
-    public function children()
476
-    {
477
-        if ($this->ID()) {
478
-            return $this->get_model()->get_all(
479
-                array(
480
-                    array('LIN_parent' => $this->ID()),
481
-                    'order_by' => array('LIN_order' => 'ASC'),
482
-                )
483
-            );
484
-        }
485
-        if (!is_array($this->_children)) {
486
-            $this->_children = array();
487
-        }
488
-        return $this->_children;
489
-    }
490
-
491
-
492
-    /**
493
-     * Gets code
494
-     *
495
-     * @return string
496
-     * @throws EE_Error
497
-     */
498
-    public function code()
499
-    {
500
-        return $this->get('LIN_code');
501
-    }
502
-
503
-
504
-    /**
505
-     * Sets code
506
-     *
507
-     * @param string $code
508
-     * @throws EE_Error
509
-     */
510
-    public function set_code($code)
511
-    {
512
-        $this->set('LIN_code', $code);
513
-    }
514
-
515
-
516
-    /**
517
-     * Gets is_taxable
518
-     *
519
-     * @return boolean
520
-     * @throws EE_Error
521
-     */
522
-    public function is_taxable()
523
-    {
524
-        return $this->get('LIN_is_taxable');
525
-    }
526
-
527
-
528
-    /**
529
-     * Sets is_taxable
530
-     *
531
-     * @param boolean $is_taxable
532
-     * @throws EE_Error
533
-     */
534
-    public function set_is_taxable($is_taxable)
535
-    {
536
-        $this->set('LIN_is_taxable', $is_taxable);
537
-    }
538
-
539
-
540
-    /**
541
-     * Gets the object that this model-joins-to.
542
-     * returns one of the model objects that the field OBJ_ID can point to... see the 'OBJ_ID' field on
543
-     * EEM_Promotion_Object
544
-     *
545
-     *        Eg, if this line item join model object is for a ticket, this will return the EE_Ticket object
546
-     *
547
-     * @return EE_Base_Class | NULL
548
-     * @throws EE_Error
549
-     */
550
-    public function get_object()
551
-    {
552
-        $model_name_of_related_obj = $this->OBJ_type();
553
-        return $this->get_model()->has_relation($model_name_of_related_obj)
554
-            ? $this->get_first_related($model_name_of_related_obj)
555
-            : null;
556
-    }
557
-
558
-
559
-    /**
560
-     * Like EE_Line_Item::get_object(), but can only ever actually return an EE_Ticket.
561
-     * (IE, if this line item is for a price or something else, will return NULL)
562
-     *
563
-     * @param array $query_params
564
-     * @return EE_Base_Class|EE_Ticket
565
-     * @throws EE_Error
566
-     */
567
-    public function ticket($query_params = array())
568
-    {
569
-        //we're going to assume that when this method is called we always want to receive the attached ticket EVEN if that ticket is archived.  This can be overridden via the incoming $query_params argument
570
-        $remove_defaults = array('default_where_conditions' => 'none');
571
-        $query_params = array_merge($remove_defaults, $query_params);
572
-        return $this->get_first_related('Ticket', $query_params);
573
-    }
574
-
575
-
576
-    /**
577
-     * Gets the EE_Datetime that's related to the ticket, IF this is for a ticket
578
-     *
579
-     * @return EE_Datetime | NULL
580
-     * @throws EE_Error
581
-     */
582
-    public function get_ticket_datetime()
583
-    {
584
-        if ($this->OBJ_type() === 'Ticket') {
585
-            $ticket = $this->ticket();
586
-            if ($ticket instanceof EE_Ticket) {
587
-                $datetime = $ticket->first_datetime();
588
-                if ($datetime instanceof EE_Datetime) {
589
-                    return $datetime;
590
-                }
591
-            }
592
-        }
593
-        return null;
594
-    }
595
-
596
-
597
-    /**
598
-     * Gets the event's name that's related to the ticket, if this is for
599
-     * a ticket
600
-     *
601
-     * @return string
602
-     * @throws EE_Error
603
-     */
604
-    public function ticket_event_name()
605
-    {
606
-        $event_name = esc_html__('Unknown', 'event_espresso');
607
-        $event = $this->ticket_event();
608
-        if ($event instanceof EE_Event) {
609
-            $event_name = $event->name();
610
-        }
611
-        return $event_name;
612
-    }
613
-
614
-
615
-    /**
616
-     * Gets the event that's related to the ticket, if this line item represents a ticket.
617
-     *
618
-     * @return EE_Event|null
619
-     * @throws EE_Error
620
-     */
621
-    public function ticket_event()
622
-    {
623
-        $event = null;
624
-        $ticket = $this->ticket();
625
-        if ($ticket instanceof EE_Ticket) {
626
-            $datetime = $ticket->first_datetime();
627
-            if ($datetime instanceof EE_Datetime) {
628
-                $event = $datetime->event();
629
-            }
630
-        }
631
-        return $event;
632
-    }
633
-
634
-
635
-    /**
636
-     * Gets the first datetime for this lien item, assuming it's for a ticket
637
-     *
638
-     * @param string $date_format
639
-     * @param string $time_format
640
-     * @return string
641
-     * @throws EE_Error
642
-     */
643
-    public function ticket_datetime_start($date_format = '', $time_format = '')
644
-    {
645
-        $first_datetime_string = esc_html__('Unknown', 'event_espresso');
646
-        $datetime = $this->get_ticket_datetime();
647
-        if ($datetime) {
648
-            $first_datetime_string = $datetime->start_date_and_time($date_format, $time_format);
649
-        }
650
-        return $first_datetime_string;
651
-    }
652
-
653
-
654
-    /**
655
-     * Adds the line item as a child to this line item. If there is another child line
656
-     * item with the same LIN_code, it is overwritten by this new one
657
-     *
658
-     * @param EEI_Line_Item $line_item
659
-     * @param bool $set_order
660
-     * @return bool success
661
-     * @throws EE_Error
662
-     */
663
-    public function add_child_line_item(EEI_Line_Item $line_item, $set_order = true)
664
-    {
665
-        // should we calculate the LIN_order for this line item ?
666
-        if ($set_order || $line_item->order() === null) {
667
-            $line_item->set_order(count($this->children()));
668
-        }
669
-        if ($this->ID()) {
670
-            //check for any duplicate line items (with the same code), if so, this replaces it
671
-            $line_item_with_same_code = $this->get_child_line_item($line_item->code());
672
-            if ($line_item_with_same_code instanceof EE_Line_Item && $line_item_with_same_code !== $line_item) {
673
-                $this->delete_child_line_item($line_item_with_same_code->code());
674
-            }
675
-            $line_item->set_parent_ID($this->ID());
676
-            if ($this->TXN_ID()) {
677
-                $line_item->set_TXN_ID($this->TXN_ID());
678
-            }
679
-            return $line_item->save();
680
-        }
681
-        $this->_children[$line_item->code()] = $line_item;
682
-        if ($line_item->parent() !== $this) {
683
-            $line_item->set_parent($this);
684
-        }
685
-        return true;
686
-    }
687
-
688
-
689
-    /**
690
-     * Similar to EE_Base_Class::_add_relation_to, except this isn't a normal relation.
691
-     * If this line item is saved to the DB, this is just a wrapper for set_parent_ID() and save()
692
-     * However, if this line item is NOT saved to the DB, this just caches the parent on
693
-     * the EE_Line_Item::_parent property.
694
-     *
695
-     * @param EE_Line_Item $line_item
696
-     * @throws EE_Error
697
-     */
698
-    public function set_parent($line_item)
699
-    {
700
-        if ($this->ID()) {
701
-            if (!$line_item->ID()) {
702
-                $line_item->save();
703
-            }
704
-            $this->set_parent_ID($line_item->ID());
705
-            $this->save();
706
-        } else {
707
-            $this->_parent = $line_item;
708
-            $this->set_parent_ID($line_item->ID());
709
-        }
710
-    }
711
-
712
-
713
-    /**
714
-     * Gets the child line item as specified by its code. Because this returns an object (by reference)
715
-     * you can modify this child line item and the parent (this object) can know about them
716
-     * because it also has a reference to that line item
717
-     *
718
-     * @param string $code
719
-     * @return EE_Base_Class|EE_Line_Item|EE_Soft_Delete_Base_Class|NULL
720
-     * @throws EE_Error
721
-     */
722
-    public function get_child_line_item($code)
723
-    {
724
-        if ($this->ID()) {
725
-            return $this->get_model()->get_one(
726
-                array(array('LIN_parent' => $this->ID(), 'LIN_code' => $code))
727
-            );
728
-        }
729
-        return isset($this->_children[$code])
730
-            ? $this->_children[$code]
731
-            : null;
732
-    }
733
-
734
-
735
-    /**
736
-     * Returns how many items are deleted (or, if this item has not been saved ot the DB yet, just how many it HAD
737
-     * cached on it)
738
-     *
739
-     * @return int
740
-     * @throws EE_Error
741
-     */
742
-    public function delete_children_line_items()
743
-    {
744
-        if ($this->ID()) {
745
-            return $this->get_model()->delete(array(array('LIN_parent' => $this->ID())));
746
-        }
747
-        $count = count($this->_children);
748
-        $this->_children = array();
749
-        return $count;
750
-    }
751
-
752
-
753
-    /**
754
-     * If this line item has been saved to the DB, deletes its child with LIN_code == $code. If this line
755
-     * HAS NOT been saved to the DB, removes the child line item with index $code.
756
-     * Also searches through the child's children for a matching line item. However, once a line item has been found
757
-     * and deleted, stops searching (so if there are line items with duplicate codes, only the first one found will be
758
-     * deleted)
759
-     *
760
-     * @param string $code
761
-     * @param bool $stop_search_once_found
762
-     * @return int count of items deleted (or simply removed from the line item's cache, if not has not been saved to
763
-     *             the DB yet)
764
-     * @throws EE_Error
765
-     */
766
-    public function delete_child_line_item($code, $stop_search_once_found = true)
767
-    {
768
-        if ($this->ID()) {
769
-            $items_deleted = 0;
770
-            if ($this->code() === $code) {
771
-                $items_deleted += EEH_Line_Item::delete_all_child_items($this);
772
-                $items_deleted += (int)$this->delete();
773
-                if ($stop_search_once_found) {
774
-                    return $items_deleted;
775
-                }
776
-            }
777
-            foreach ($this->children() as $child_line_item) {
778
-                $items_deleted += $child_line_item->delete_child_line_item($code, $stop_search_once_found);
779
-            }
780
-            return $items_deleted;
781
-        }
782
-        if (isset($this->_children[$code])) {
783
-            unset($this->_children[$code]);
784
-            return 1;
785
-        }
786
-        return 0;
787
-    }
788
-
789
-
790
-    /**
791
-     * If this line item is in the database, is of the type subtotal, and
792
-     * has no children, why do we have it? It should be deleted so this function
793
-     * does that
794
-     *
795
-     * @return boolean
796
-     * @throws EE_Error
797
-     */
798
-    public function delete_if_childless_subtotal()
799
-    {
800
-        if ($this->ID() && $this->type() === EEM_Line_Item::type_sub_total && !$this->children()) {
801
-            return $this->delete();
802
-        }
803
-        return false;
804
-    }
805
-
806
-
807
-    /**
808
-     * Creates a code and returns a string. doesn't assign the code to this model object
809
-     *
810
-     * @return string
811
-     * @throws EE_Error
812
-     */
813
-    public function generate_code()
814
-    {
815
-        // each line item in the cart requires a unique identifier
816
-        return md5($this->get('OBJ_type') . $this->get('OBJ_ID') . microtime());
817
-    }
818
-
819
-
820
-    /**
821
-     * @return bool
822
-     * @throws EE_Error
823
-     */
824
-    public function is_tax()
825
-    {
826
-        return $this->type() === EEM_Line_Item::type_tax;
827
-    }
828
-
829
-
830
-    /**
831
-     * @return bool
832
-     * @throws EE_Error
833
-     */
834
-    public function is_tax_sub_total()
835
-    {
836
-        return $this->type() === EEM_Line_Item::type_tax_sub_total;
837
-    }
838
-
839
-
840
-    /**
841
-     * @return bool
842
-     * @throws EE_Error
843
-     */
844
-    public function is_line_item()
845
-    {
846
-        return $this->type() === EEM_Line_Item::type_line_item;
847
-    }
848
-
849
-
850
-    /**
851
-     * @return bool
852
-     * @throws EE_Error
853
-     */
854
-    public function is_sub_line_item()
855
-    {
856
-        return $this->type() === EEM_Line_Item::type_sub_line_item;
857
-    }
858
-
859
-
860
-    /**
861
-     * @return bool
862
-     * @throws EE_Error
863
-     */
864
-    public function is_sub_total()
865
-    {
866
-        return $this->type() === EEM_Line_Item::type_sub_total;
867
-    }
868
-
869
-
870
-    /**
871
-     * Whether or not this line item is a cancellation line item
872
-     *
873
-     * @return boolean
874
-     * @throws EE_Error
875
-     */
876
-    public function is_cancellation()
877
-    {
878
-        return EEM_Line_Item::type_cancellation === $this->type();
879
-    }
880
-
881
-
882
-    /**
883
-     * @return bool
884
-     * @throws EE_Error
885
-     */
886
-    public function is_total()
887
-    {
888
-        return $this->type() === EEM_Line_Item::type_total;
889
-    }
890
-
891
-
892
-    /**
893
-     * @return bool
894
-     * @throws EE_Error
895
-     */
896
-    public function is_cancelled()
897
-    {
898
-        return $this->type() === EEM_Line_Item::type_cancellation;
899
-    }
900
-
901
-
902
-    /**
903
-     * @return string like '2, 004.00', formatted according to the localized currency
904
-     * @throws EE_Error
905
-     */
906
-    public function unit_price_no_code()
907
-    {
908
-        return $this->get_pretty('LIN_unit_price', 'no_currency_code');
909
-    }
910
-
911
-
912
-    /**
913
-     * @return string like '2, 004.00', formatted according to the localized currency
914
-     * @throws EE_Error
915
-     */
916
-    public function total_no_code()
917
-    {
918
-        return $this->get_pretty('LIN_total', 'no_currency_code');
919
-    }
920
-
921
-
922
-    /**
923
-     * Gets the final total on this item, taking taxes into account.
924
-     * Has the side-effect of setting the sub-total as it was just calculated.
925
-     * If this is used on a grand-total line item, also updates the transaction's
926
-     * TXN_total (provided this line item is allowed to persist, otherwise we don't
927
-     * want to change a persistable transaction with info from a non-persistent line item)
928
-     *
929
-     * @return float
930
-     * @throws EE_Error
931
-     * @throws InvalidArgumentException
932
-     * @throws InvalidInterfaceException
933
-     * @throws InvalidDataTypeException
934
-     */
935
-    public function recalculate_total_including_taxes()
936
-    {
937
-        $pre_tax_total = $this->recalculate_pre_tax_total();
938
-        $tax_total = $this->recalculate_taxes_and_tax_total();
939
-        $total = $pre_tax_total + $tax_total;
940
-        // no negative totals plz
941
-        $total = max($total, 0);
942
-        $this->set_total($total);
943
-        //only update the related transaction's total
944
-        //if we intend to save this line item and its a grand total
945
-        if (
946
-            $this->allow_persist() && $this->type() === EEM_Line_Item::type_total
947
-            && $this->transaction()
948
-            instanceof
949
-            EE_Transaction
950
-        ) {
951
-            $this->transaction()->set_total($total);
952
-            if ($this->transaction()->ID()) {
953
-                $this->transaction()->save();
954
-            }
955
-        }
956
-        $this->maybe_save();
957
-        return $total;
958
-    }
959
-
960
-
961
-    /**
962
-     * Recursively goes through all the children and recalculates sub-totals EXCEPT for
963
-     * tax-sub-totals (they're a an odd beast). Updates the 'total' on each line item according to either its
964
-     * unit price * quantity or the total of all its children EXCEPT when we're only calculating the taxable total and
965
-     * when this is called on the grand total
966
-     *
967
-     * @return float
968
-     * @throws InvalidArgumentException
969
-     * @throws InvalidInterfaceException
970
-     * @throws InvalidDataTypeException
971
-     * @throws EE_Error
972
-     */
973
-    public function recalculate_pre_tax_total()
974
-    {
975
-        $total = 0;
976
-        $my_children = $this->children();
977
-        $has_children = !empty($my_children);
978
-        if ($has_children && $this->is_line_item()) {
979
-            $total = $this->_recalculate_pretax_total_for_line_item($total, $my_children);
980
-        } elseif (!$has_children && ($this->is_sub_line_item() || $this->is_line_item())) {
981
-            $total = $this->unit_price() * $this->quantity();
982
-        } elseif ($this->is_sub_total() || $this->is_total()) {
983
-            $total = $this->_recalculate_pretax_total_for_subtotal($total, $my_children);
984
-        } elseif ($this->is_tax_sub_total() || $this->is_tax() || $this->is_cancelled()) {
985
-            // completely ignore tax totals, tax sub-totals, and cancelled line items, when calculating the pre-tax-total
986
-            return 0;
987
-        }
988
-        // ensure all non-line items and non-sub-line-items have a quantity of 1 (except for Events)
989
-        if (
990
-            !$this->is_line_item() && !$this->is_sub_line_item() && !$this->is_cancellation()
991
-        ) {
992
-            if ($this->OBJ_type() !== 'Event') {
993
-                $this->set_quantity(1);
994
-            }
995
-            if (!$this->is_percent()) {
996
-                $this->set_unit_price($total);
997
-            }
998
-        }
999
-        //we don't want to bother saving grand totals, because that needs to factor in taxes anyways
1000
-        //so it ought to be
1001
-        if (!$this->is_total()) {
1002
-            $this->set_total($total);
1003
-            //if not a percent line item, make sure we keep the unit price in sync
1004
-            if (
1005
-                $has_children
1006
-                && $this->is_line_item()
1007
-                && !$this->is_percent()
1008
-            ) {
1009
-                if ($this->quantity() === 0) {
1010
-                    $new_unit_price = 0;
1011
-                } else {
1012
-                    $new_unit_price = $this->total() / $this->quantity();
1013
-                }
1014
-                $this->set_unit_price($new_unit_price);
1015
-            }
1016
-            $this->maybe_save();
1017
-        }
1018
-        return $total;
1019
-    }
1020
-
1021
-
1022
-    /**
1023
-     * Calculates the pretax total when this line item is a subtotal or total line item.
1024
-     * Basically does a sum-then-round approach (ie, any percent line item that are children
1025
-     * will calculate their total based on the un-rounded total we're working with so far, and
1026
-     * THEN round the result; instead of rounding as we go like with sub-line-items)
1027
-     *
1028
-     * @param float $calculated_total_so_far
1029
-     * @param EE_Line_Item[] $my_children
1030
-     * @return float
1031
-     * @throws InvalidArgumentException
1032
-     * @throws InvalidInterfaceException
1033
-     * @throws InvalidDataTypeException
1034
-     * @throws EE_Error
1035
-     */
1036
-    protected function _recalculate_pretax_total_for_subtotal($calculated_total_so_far, $my_children = null)
1037
-    {
1038
-        if ($my_children === null) {
1039
-            $my_children = $this->children();
1040
-        }
1041
-        $subtotal_quantity = 0;
1042
-        //get the total of all its children
1043
-        foreach ($my_children as $child_line_item) {
1044
-            if ($child_line_item instanceof EE_Line_Item && !$child_line_item->is_cancellation()) {
1045
-                // percentage line items are based on total so far
1046
-                if ($child_line_item->is_percent()) {
1047
-                    //round as we go so that the line items add up ok
1048
-                    $percent_total = round(
1049
-                        $calculated_total_so_far * $child_line_item->percent() / 100,
1050
-                        EE_Registry::instance()->CFG->currency->dec_plc
1051
-                    );
1052
-                    $child_line_item->set_total($percent_total);
1053
-                    //so far all percent line items should have a quantity of 1
1054
-                    //(ie, no double percent discounts. Although that might be requested someday)
1055
-                    $child_line_item->set_quantity(1);
1056
-                    $child_line_item->maybe_save();
1057
-                    $calculated_total_so_far += $percent_total;
1058
-                } else {
1059
-                    //verify flat sub-line-item quantities match their parent
1060
-                    if ($child_line_item->is_sub_line_item()) {
1061
-                        $child_line_item->set_quantity($this->quantity());
1062
-                    }
1063
-                    $calculated_total_so_far += $child_line_item->recalculate_pre_tax_total();
1064
-                    $subtotal_quantity += $child_line_item->quantity();
1065
-                }
1066
-            }
1067
-        }
1068
-        if ($this->is_sub_total()) {
1069
-            // no negative totals plz
1070
-            $calculated_total_so_far = max($calculated_total_so_far, 0);
1071
-            $subtotal_quantity = $subtotal_quantity > 0 ? 1 : 0;
1072
-            $this->set_quantity($subtotal_quantity);
1073
-            $this->maybe_save();
1074
-        }
1075
-        return $calculated_total_so_far;
1076
-    }
1077
-
1078
-
1079
-    /**
1080
-     * Calculates the pretax total for a normal line item, in a round-then-sum approach
1081
-     * (where each sub-line-item is applied to the base price for the line item
1082
-     * and the result is immediately rounded, rather than summing all the sub-line-items
1083
-     * then rounding, like we do when recalculating pretax totals on totals and subtotals).
1084
-     *
1085
-     * @param float $calculated_total_so_far
1086
-     * @param EE_Line_Item[] $my_children
1087
-     * @return float
1088
-     * @throws InvalidArgumentException
1089
-     * @throws InvalidInterfaceException
1090
-     * @throws InvalidDataTypeException
1091
-     * @throws EE_Error
1092
-     */
1093
-    protected function _recalculate_pretax_total_for_line_item($calculated_total_so_far, $my_children = null)
1094
-    {
1095
-        if ($my_children === null) {
1096
-            $my_children = $this->children();
1097
-        }
1098
-        //we need to keep track of the running total for a single item,
1099
-        //because we need to round as we go
1100
-        $unit_price_for_total = 0;
1101
-        $quantity_for_total = 1;
1102
-        //get the total of all its children
1103
-        foreach ($my_children as $child_line_item) {
1104
-            if ($child_line_item instanceof EE_Line_Item && !$child_line_item->is_cancellation()) {
1105
-                if ($child_line_item->is_percent()) {
1106
-                    //it should be the unit-price-so-far multiplied by teh percent multiplied by the quantity
1107
-                    //not total multiplied by percent, because that ignores rounding along-the-way
1108
-                    $percent_unit_price = round(
1109
-                        $unit_price_for_total * $child_line_item->percent() / 100,
1110
-                        EE_Registry::instance()->CFG->currency->dec_plc
1111
-                    );
1112
-                    $percent_total = $percent_unit_price * $quantity_for_total;
1113
-                    $child_line_item->set_total($percent_total);
1114
-                    //so far all percent line items should have a quantity of 1
1115
-                    //(ie, no double percent discounts. Although that might be requested someday)
1116
-                    $child_line_item->set_quantity(1);
1117
-                    $child_line_item->maybe_save();
1118
-                    $calculated_total_so_far += $percent_total;
1119
-                    $unit_price_for_total += $percent_unit_price;
1120
-                } else {
1121
-                    //verify flat sub-line-item quantities match their parent
1122
-                    if ($child_line_item->is_sub_line_item()) {
1123
-                        $child_line_item->set_quantity($this->quantity());
1124
-                    }
1125
-                    $quantity_for_total = $child_line_item->quantity();
1126
-                    $calculated_total_so_far += $child_line_item->recalculate_pre_tax_total();
1127
-                    $unit_price_for_total += $child_line_item->unit_price();
1128
-                }
1129
-            }
1130
-        }
1131
-        return $calculated_total_so_far;
1132
-    }
1133
-
1134
-
1135
-    /**
1136
-     * Recalculates the total on each individual tax (based on a recalculation of the pre-tax total), sets
1137
-     * the totals on each tax calculated, and returns the final tax total. Re-saves tax line items
1138
-     * and tax sub-total if already in the DB
1139
-     *
1140
-     * @return float
1141
-     * @throws EE_Error
1142
-     */
1143
-    public function recalculate_taxes_and_tax_total()
1144
-    {
1145
-        //get all taxes
1146
-        $taxes = $this->tax_descendants();
1147
-        //calculate the pretax total
1148
-        $taxable_total = $this->taxable_total();
1149
-        $tax_total = 0;
1150
-        foreach ($taxes as $tax) {
1151
-            $total_on_this_tax = $taxable_total * $tax->percent() / 100;
1152
-            //remember the total on this line item
1153
-            $tax->set_total($total_on_this_tax);
1154
-            $tax->maybe_save();
1155
-            $tax_total += $tax->total();
1156
-        }
1157
-        $this->_recalculate_tax_sub_total();
1158
-        return $tax_total;
1159
-    }
1160
-
1161
-
1162
-    /**
1163
-     * Simply forces all the tax-sub-totals to recalculate. Assumes the taxes have been calculated
1164
-     *
1165
-     * @return void
1166
-     * @throws EE_Error
1167
-     */
1168
-    private function _recalculate_tax_sub_total()
1169
-    {
1170
-        if ($this->is_tax_sub_total()) {
1171
-            $total = 0;
1172
-            $total_percent = 0;
1173
-            //simply loop through all its children (which should be taxes) and sum their total
1174
-            foreach ($this->children() as $child_tax) {
1175
-                if ($child_tax instanceof EE_Line_Item) {
1176
-                    $total += $child_tax->total();
1177
-                    $total_percent += $child_tax->percent();
1178
-                }
1179
-            }
1180
-            $this->set_total($total);
1181
-            $this->set_percent($total_percent);
1182
-            $this->maybe_save();
1183
-        } elseif ($this->is_total()) {
1184
-            foreach ($this->children() as $maybe_tax_subtotal) {
1185
-                if ($maybe_tax_subtotal instanceof EE_Line_Item) {
1186
-                    $maybe_tax_subtotal->_recalculate_tax_sub_total();
1187
-                }
1188
-            }
1189
-        }
1190
-    }
1191
-
1192
-
1193
-    /**
1194
-     * Gets the total tax on this line item. Assumes taxes have already been calculated using
1195
-     * recalculate_taxes_and_total
1196
-     *
1197
-     * @return float
1198
-     * @throws EE_Error
1199
-     */
1200
-    public function get_total_tax()
1201
-    {
1202
-        $this->_recalculate_tax_sub_total();
1203
-        $total = 0;
1204
-        foreach ($this->tax_descendants() as $tax_line_item) {
1205
-            if ($tax_line_item instanceof EE_Line_Item) {
1206
-                $total += $tax_line_item->total();
1207
-            }
1208
-        }
1209
-        return $total;
1210
-    }
1211
-
1212
-
1213
-    /**
1214
-     * Gets the total for all the items purchased only
1215
-     *
1216
-     * @return float
1217
-     * @throws EE_Error
1218
-     */
1219
-    public function get_items_total()
1220
-    {
1221
-        //by default, let's make sure we're consistent with the existing line item
1222
-        if ($this->is_total()) {
1223
-            $pretax_subtotal_li = EEH_Line_Item::get_pre_tax_subtotal($this);
1224
-            if ($pretax_subtotal_li instanceof EE_Line_Item) {
1225
-                return $pretax_subtotal_li->total();
1226
-            }
1227
-        }
1228
-        $total = 0;
1229
-        foreach ($this->get_items() as $item) {
1230
-            if ($item instanceof EE_Line_Item) {
1231
-                $total += $item->total();
1232
-            }
1233
-        }
1234
-        return $total;
1235
-    }
1236
-
1237
-
1238
-    /**
1239
-     * Gets all the descendants (ie, children or children of children etc) that
1240
-     * are of the type 'tax'
1241
-     *
1242
-     * @return EE_Line_Item[]
1243
-     */
1244
-    public function tax_descendants()
1245
-    {
1246
-        return EEH_Line_Item::get_tax_descendants($this);
1247
-    }
1248
-
1249
-
1250
-    /**
1251
-     * Gets all the real items purchased which are children of this item
1252
-     *
1253
-     * @return EE_Line_Item[]
1254
-     */
1255
-    public function get_items()
1256
-    {
1257
-        return EEH_Line_Item::get_line_item_descendants($this);
1258
-    }
1259
-
1260
-
1261
-    /**
1262
-     * Returns the amount taxable among this line item's children (or if it has no children,
1263
-     * how much of it is taxable). Does not recalculate totals or subtotals.
1264
-     * If the taxable total is negative, (eg, if none of the tickets were taxable,
1265
-     * but there is a "Taxable" discount), returns 0.
1266
-     *
1267
-     * @return float
1268
-     * @throws EE_Error
1269
-     */
1270
-    public function taxable_total()
1271
-    {
1272
-        $total = 0;
1273
-        if ($this->children()) {
1274
-            foreach ($this->children() as $child_line_item) {
1275
-                if ($child_line_item->type() === EEM_Line_Item::type_line_item && $child_line_item->is_taxable()) {
1276
-                    //if it's a percent item, only take into account the percent
1277
-                    //that's taxable too (the taxable total so far)
1278
-                    if ($child_line_item->is_percent()) {
1279
-                        $total += ($total * $child_line_item->percent() / 100);
1280
-                    } else {
1281
-                        $total += $child_line_item->total();
1282
-                    }
1283
-                } elseif ($child_line_item->type() === EEM_Line_Item::type_sub_total) {
1284
-                    $total += $child_line_item->taxable_total();
1285
-                }
1286
-            }
1287
-        }
1288
-        return max($total, 0);
1289
-    }
1290
-
1291
-
1292
-    /**
1293
-     * Gets the transaction for this line item
1294
-     *
1295
-     * @return EE_Base_Class|EE_Transaction
1296
-     * @throws EE_Error
1297
-     */
1298
-    public function transaction()
1299
-    {
1300
-        return $this->get_first_related('Transaction');
1301
-    }
1302
-
1303
-
1304
-    /**
1305
-     * Saves this line item to the DB, and recursively saves its descendants.
1306
-     * Because there currently is no proper parent-child relation on the model,
1307
-     * save_this_and_cached() will NOT save the descendants.
1308
-     * Also sets the transaction on this line item and all its descendants before saving
1309
-     *
1310
-     * @param int $txn_id if none is provided, assumes $this->TXN_ID()
1311
-     * @return int count of items saved
1312
-     * @throws EE_Error
1313
-     */
1314
-    public function save_this_and_descendants_to_txn($txn_id = null)
1315
-    {
1316
-        $count = 0;
1317
-        if (!$txn_id) {
1318
-            $txn_id = $this->TXN_ID();
1319
-        }
1320
-        $this->set_TXN_ID($txn_id);
1321
-        $children = $this->children();
1322
-        $count += $this->save()
1323
-            ? 1
1324
-            : 0;
1325
-        foreach ($children as $child_line_item) {
1326
-            if ($child_line_item instanceof EE_Line_Item) {
1327
-                $child_line_item->set_parent_ID($this->ID());
1328
-                $count += $child_line_item->save_this_and_descendants_to_txn($txn_id);
1329
-            }
1330
-        }
1331
-        return $count;
1332
-    }
1333
-
1334
-
1335
-    /**
1336
-     * Saves this line item to the DB, and recursively saves its descendants.
1337
-     *
1338
-     * @return int count of items saved
1339
-     * @throws EE_Error
1340
-     */
1341
-    public function save_this_and_descendants()
1342
-    {
1343
-        $count = 0;
1344
-        $children = $this->children();
1345
-        $count += $this->save()
1346
-            ? 1
1347
-            : 0;
1348
-        foreach ($children as $child_line_item) {
1349
-            if ($child_line_item instanceof EE_Line_Item) {
1350
-                $child_line_item->set_parent_ID($this->ID());
1351
-                $count += $child_line_item->save_this_and_descendants();
1352
-            }
1353
-        }
1354
-        return $count;
1355
-    }
1356
-
1357
-
1358
-    /**
1359
-     * returns the cancellation line item if this item was cancelled
1360
-     *
1361
-     * @return EE_Line_Item[]
1362
-     * @throws InvalidArgumentException
1363
-     * @throws InvalidInterfaceException
1364
-     * @throws InvalidDataTypeException
1365
-     * @throws ReflectionException
1366
-     * @throws EE_Error
1367
-     */
1368
-    public function get_cancellations()
1369
-    {
1370
-        EE_Registry::instance()->load_helper('Line_Item');
1371
-        return EEH_Line_Item::get_descendants_of_type($this, EEM_Line_Item::type_cancellation);
1372
-    }
1373
-
1374
-
1375
-    /**
1376
-     * If this item has an ID, then this saves it again to update the db
1377
-     *
1378
-     * @return int count of items saved
1379
-     * @throws EE_Error
1380
-     */
1381
-    public function maybe_save()
1382
-    {
1383
-        if ($this->ID()) {
1384
-            return $this->save();
1385
-        }
1386
-        return false;
1387
-    }
1388
-
1389
-
1390
-    /**
1391
-     * clears the cached children and parent from the line item
1392
-     *
1393
-     * @return void
1394
-     */
1395
-    public function clear_related_line_item_cache()
1396
-    {
1397
-        $this->_children = array();
1398
-        $this->_parent = null;
1399
-    }
1400
-
1401
-
1402
-    /**
1403
-     * @param bool $raw
1404
-     * @return int
1405
-     * @throws EE_Error
1406
-     */
1407
-    public function timestamp($raw = false)
1408
-    {
1409
-        return $raw
1410
-            ? $this->get_raw('LIN_timestamp')
1411
-            : $this->get('LIN_timestamp');
1412
-    }
1413
-
1414
-
1415
-
1416
-
1417
-    /************************* DEPRECATED *************************/
1418
-    /**
1419
-     * @deprecated 4.6.0
1420
-     * @param string $type one of the constants on EEM_Line_Item
1421
-     * @return EE_Line_Item[]
1422
-     */
1423
-    protected function _get_descendants_of_type($type)
1424
-    {
1425
-        EE_Error::doing_it_wrong(
1426
-            'EE_Line_Item::_get_descendants_of_type()',
1427
-            __('Method replaced with EEH_Line_Item::get_descendants_of_type()', 'event_espresso'), '4.6.0'
1428
-        );
1429
-        return EEH_Line_Item::get_descendants_of_type($this, $type);
1430
-    }
1431
-
1432
-
1433
-    /**
1434
-     * @deprecated 4.6.0
1435
-     * @param string $type like one of the EEM_Line_Item::type_*
1436
-     * @return EE_Line_Item
1437
-     */
1438
-    public function get_nearest_descendant_of_type($type)
1439
-    {
1440
-        EE_Error::doing_it_wrong(
1441
-            'EE_Line_Item::get_nearest_descendant_of_type()',
1442
-            __('Method replaced with EEH_Line_Item::get_nearest_descendant_of_type()', 'event_espresso'), '4.6.0'
1443
-        );
1444
-        return EEH_Line_Item::get_nearest_descendant_of_type($this, $type);
1445
-    }
20
+	/**
21
+	 * for children line items (currently not a normal relation)
22
+	 *
23
+	 * @type EE_Line_Item[]
24
+	 */
25
+	protected $_children = array();
26
+
27
+	/**
28
+	 * for the parent line item
29
+	 *
30
+	 * @var EE_Line_Item
31
+	 */
32
+	protected $_parent;
33
+
34
+
35
+	/**
36
+	 *
37
+	 * @param array $props_n_values incoming values
38
+	 * @param string $timezone incoming timezone (if not set the timezone set for the website will be
39
+	 *                                        used.)
40
+	 * @param array $date_formats incoming date_formats in an array where the first value is the
41
+	 *                                        date_format and the second value is the time format
42
+	 * @return EE_Line_Item
43
+	 * @throws EE_Error
44
+	 */
45
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
46
+	{
47
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
48
+		return $has_object
49
+			? $has_object
50
+			: new self($props_n_values, false, $timezone);
51
+	}
52
+
53
+
54
+	/**
55
+	 * @param array $props_n_values incoming values from the database
56
+	 * @param string $timezone incoming timezone as set by the model.  If not set the timezone for
57
+	 *                                the website will be used.
58
+	 * @return EE_Line_Item
59
+	 * @throws EE_Error
60
+	 */
61
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null)
62
+	{
63
+		return new self($props_n_values, true, $timezone);
64
+	}
65
+
66
+
67
+	/**
68
+	 * Adds some defaults if they're not specified
69
+	 *
70
+	 * @param array $fieldValues
71
+	 * @param bool $bydb
72
+	 * @param string $timezone
73
+	 * @throws EE_Error
74
+	 */
75
+	protected function __construct($fieldValues = array(), $bydb = false, $timezone = '')
76
+	{
77
+		parent::__construct($fieldValues, $bydb, $timezone);
78
+		if (!$this->get('LIN_code')) {
79
+			$this->set_code($this->generate_code());
80
+		}
81
+	}
82
+
83
+
84
+	/**
85
+	 * Gets ID
86
+	 *
87
+	 * @return int
88
+	 * @throws EE_Error
89
+	 */
90
+	public function ID()
91
+	{
92
+		return $this->get('LIN_ID');
93
+	}
94
+
95
+
96
+	/**
97
+	 * Gets TXN_ID
98
+	 *
99
+	 * @return int
100
+	 * @throws EE_Error
101
+	 */
102
+	public function TXN_ID()
103
+	{
104
+		return $this->get('TXN_ID');
105
+	}
106
+
107
+
108
+	/**
109
+	 * Sets TXN_ID
110
+	 *
111
+	 * @param int $TXN_ID
112
+	 * @throws EE_Error
113
+	 */
114
+	public function set_TXN_ID($TXN_ID)
115
+	{
116
+		$this->set('TXN_ID', $TXN_ID);
117
+	}
118
+
119
+
120
+	/**
121
+	 * Gets name
122
+	 *
123
+	 * @return string
124
+	 * @throws EE_Error
125
+	 */
126
+	public function name()
127
+	{
128
+		$name = $this->get('LIN_name');
129
+		if (!$name) {
130
+			$name = ucwords(str_replace('-', ' ', $this->type()));
131
+		}
132
+		return $name;
133
+	}
134
+
135
+
136
+	/**
137
+	 * Sets name
138
+	 *
139
+	 * @param string $name
140
+	 * @throws EE_Error
141
+	 */
142
+	public function set_name($name)
143
+	{
144
+		$this->set('LIN_name', $name);
145
+	}
146
+
147
+
148
+	/**
149
+	 * Gets desc
150
+	 *
151
+	 * @return string
152
+	 * @throws EE_Error
153
+	 */
154
+	public function desc()
155
+	{
156
+		return $this->get('LIN_desc');
157
+	}
158
+
159
+
160
+	/**
161
+	 * Sets desc
162
+	 *
163
+	 * @param string $desc
164
+	 * @throws EE_Error
165
+	 */
166
+	public function set_desc($desc)
167
+	{
168
+		$this->set('LIN_desc', $desc);
169
+	}
170
+
171
+
172
+	/**
173
+	 * Gets quantity
174
+	 *
175
+	 * @return int
176
+	 * @throws EE_Error
177
+	 */
178
+	public function quantity()
179
+	{
180
+		return $this->get('LIN_quantity');
181
+	}
182
+
183
+
184
+	/**
185
+	 * Sets quantity
186
+	 *
187
+	 * @param int $quantity
188
+	 * @throws EE_Error
189
+	 */
190
+	public function set_quantity($quantity)
191
+	{
192
+		$this->set('LIN_quantity', max($quantity, 0));
193
+	}
194
+
195
+
196
+	/**
197
+	 * Gets item_id
198
+	 *
199
+	 * @return string
200
+	 * @throws EE_Error
201
+	 */
202
+	public function OBJ_ID()
203
+	{
204
+		return $this->get('OBJ_ID');
205
+	}
206
+
207
+
208
+	/**
209
+	 * Sets item_id
210
+	 *
211
+	 * @param string $item_id
212
+	 * @throws EE_Error
213
+	 */
214
+	public function set_OBJ_ID($item_id)
215
+	{
216
+		$this->set('OBJ_ID', $item_id);
217
+	}
218
+
219
+
220
+	/**
221
+	 * Gets item_type
222
+	 *
223
+	 * @return string
224
+	 * @throws EE_Error
225
+	 */
226
+	public function OBJ_type()
227
+	{
228
+		return $this->get('OBJ_type');
229
+	}
230
+
231
+
232
+	/**
233
+	 * Gets item_type
234
+	 *
235
+	 * @return string
236
+	 * @throws EE_Error
237
+	 */
238
+	public function OBJ_type_i18n()
239
+	{
240
+		$obj_type = $this->OBJ_type();
241
+		switch ($obj_type) {
242
+			case 'Event':
243
+				$obj_type = __('Event', 'event_espresso');
244
+				break;
245
+			case 'Price':
246
+				$obj_type = __('Price', 'event_espresso');
247
+				break;
248
+			case 'Promotion':
249
+				$obj_type = __('Promotion', 'event_espresso');
250
+				break;
251
+			case 'Ticket':
252
+				$obj_type = __('Ticket', 'event_espresso');
253
+				break;
254
+			case 'Transaction':
255
+				$obj_type = __('Transaction', 'event_espresso');
256
+				break;
257
+		}
258
+		return apply_filters('FHEE__EE_Line_Item__OBJ_type_i18n', $obj_type, $this);
259
+	}
260
+
261
+
262
+	/**
263
+	 * Sets item_type
264
+	 *
265
+	 * @param string $OBJ_type
266
+	 * @throws EE_Error
267
+	 */
268
+	public function set_OBJ_type($OBJ_type)
269
+	{
270
+		$this->set('OBJ_type', $OBJ_type);
271
+	}
272
+
273
+
274
+	/**
275
+	 * Gets unit_price
276
+	 *
277
+	 * @return float
278
+	 * @throws EE_Error
279
+	 */
280
+	public function unit_price()
281
+	{
282
+		return $this->get('LIN_unit_price');
283
+	}
284
+
285
+
286
+	/**
287
+	 * Sets unit_price
288
+	 *
289
+	 * @param float $unit_price
290
+	 * @throws EE_Error
291
+	 */
292
+	public function set_unit_price($unit_price)
293
+	{
294
+		$this->set('LIN_unit_price', $unit_price);
295
+	}
296
+
297
+
298
+	/**
299
+	 * Checks if this item is a percentage modifier or not
300
+	 *
301
+	 * @return boolean
302
+	 * @throws EE_Error
303
+	 */
304
+	public function is_percent()
305
+	{
306
+		if ($this->is_tax_sub_total()) {
307
+			//tax subtotals HAVE a percent on them, that percentage only applies
308
+			//to taxable items, so its' an exception. Treat it like a flat line item
309
+			return false;
310
+		}
311
+		$unit_price = abs($this->get('LIN_unit_price'));
312
+		$percent = abs($this->get('LIN_percent'));
313
+		if ($unit_price < .001 && $percent) {
314
+			return true;
315
+		}
316
+		if ($unit_price >= .001 && !$percent) {
317
+			return false;
318
+		}
319
+		if ($unit_price >= .001 && $percent) {
320
+			throw new EE_Error(
321
+				sprintf(
322
+					esc_html__('A Line Item can not have a unit price of (%s) AND a percent (%s)!', 'event_espresso'),
323
+					$unit_price, $percent
324
+				)
325
+			);
326
+		}
327
+		// if they're both 0, assume its not a percent item
328
+		return false;
329
+	}
330
+
331
+
332
+	/**
333
+	 * Gets percent (between 100-.001)
334
+	 *
335
+	 * @return float
336
+	 * @throws EE_Error
337
+	 */
338
+	public function percent()
339
+	{
340
+		return $this->get('LIN_percent');
341
+	}
342
+
343
+
344
+	/**
345
+	 * Sets percent (between 100-0.01)
346
+	 *
347
+	 * @param float $percent
348
+	 * @throws EE_Error
349
+	 */
350
+	public function set_percent($percent)
351
+	{
352
+		$this->set('LIN_percent', $percent);
353
+	}
354
+
355
+
356
+	/**
357
+	 * Gets total
358
+	 *
359
+	 * @return float
360
+	 * @throws EE_Error
361
+	 */
362
+	public function total()
363
+	{
364
+		return $this->get('LIN_total');
365
+	}
366
+
367
+
368
+	/**
369
+	 * Sets total
370
+	 *
371
+	 * @param float $total
372
+	 * @throws EE_Error
373
+	 */
374
+	public function set_total($total)
375
+	{
376
+		$this->set('LIN_total', $total);
377
+	}
378
+
379
+
380
+	/**
381
+	 * Gets order
382
+	 *
383
+	 * @return int
384
+	 * @throws EE_Error
385
+	 */
386
+	public function order()
387
+	{
388
+		return $this->get('LIN_order');
389
+	}
390
+
391
+
392
+	/**
393
+	 * Sets order
394
+	 *
395
+	 * @param int $order
396
+	 * @throws EE_Error
397
+	 */
398
+	public function set_order($order)
399
+	{
400
+		$this->set('LIN_order', $order);
401
+	}
402
+
403
+
404
+	/**
405
+	 * Gets parent
406
+	 *
407
+	 * @return int
408
+	 * @throws EE_Error
409
+	 */
410
+	public function parent_ID()
411
+	{
412
+		return $this->get('LIN_parent');
413
+	}
414
+
415
+
416
+	/**
417
+	 * Sets parent
418
+	 *
419
+	 * @param int $parent
420
+	 * @throws EE_Error
421
+	 */
422
+	public function set_parent_ID($parent)
423
+	{
424
+		$this->set('LIN_parent', $parent);
425
+	}
426
+
427
+
428
+	/**
429
+	 * Gets type
430
+	 *
431
+	 * @return string
432
+	 * @throws EE_Error
433
+	 */
434
+	public function type()
435
+	{
436
+		return $this->get('LIN_type');
437
+	}
438
+
439
+
440
+	/**
441
+	 * Sets type
442
+	 *
443
+	 * @param string $type
444
+	 * @throws EE_Error
445
+	 */
446
+	public function set_type($type)
447
+	{
448
+		$this->set('LIN_type', $type);
449
+	}
450
+
451
+
452
+	/**
453
+	 * Gets the line item of which this item is a composite. Eg, if this is a subtotal, the parent might be a total\
454
+	 * If this line item is saved to the DB, fetches the parent from the DB. However, if this line item isn't in the DB
455
+	 * it uses its cached reference to its parent line item (which would have been set by `EE_Line_Item::set_parent()`
456
+	 * or indirectly by `EE_Line_item::add_child_line_item()`)
457
+	 *
458
+	 * @return EE_Base_Class|EE_Line_Item
459
+	 * @throws EE_Error
460
+	 */
461
+	public function parent()
462
+	{
463
+		return $this->ID()
464
+			? $this->get_model()->get_one_by_ID($this->parent_ID())
465
+			: $this->_parent;
466
+	}
467
+
468
+
469
+	/**
470
+	 * Gets ALL the children of this line item (ie, all the parts that contribute towards this total).
471
+	 *
472
+	 * @return EE_Base_Class[]|EE_Line_Item[]
473
+	 * @throws EE_Error
474
+	 */
475
+	public function children()
476
+	{
477
+		if ($this->ID()) {
478
+			return $this->get_model()->get_all(
479
+				array(
480
+					array('LIN_parent' => $this->ID()),
481
+					'order_by' => array('LIN_order' => 'ASC'),
482
+				)
483
+			);
484
+		}
485
+		if (!is_array($this->_children)) {
486
+			$this->_children = array();
487
+		}
488
+		return $this->_children;
489
+	}
490
+
491
+
492
+	/**
493
+	 * Gets code
494
+	 *
495
+	 * @return string
496
+	 * @throws EE_Error
497
+	 */
498
+	public function code()
499
+	{
500
+		return $this->get('LIN_code');
501
+	}
502
+
503
+
504
+	/**
505
+	 * Sets code
506
+	 *
507
+	 * @param string $code
508
+	 * @throws EE_Error
509
+	 */
510
+	public function set_code($code)
511
+	{
512
+		$this->set('LIN_code', $code);
513
+	}
514
+
515
+
516
+	/**
517
+	 * Gets is_taxable
518
+	 *
519
+	 * @return boolean
520
+	 * @throws EE_Error
521
+	 */
522
+	public function is_taxable()
523
+	{
524
+		return $this->get('LIN_is_taxable');
525
+	}
526
+
527
+
528
+	/**
529
+	 * Sets is_taxable
530
+	 *
531
+	 * @param boolean $is_taxable
532
+	 * @throws EE_Error
533
+	 */
534
+	public function set_is_taxable($is_taxable)
535
+	{
536
+		$this->set('LIN_is_taxable', $is_taxable);
537
+	}
538
+
539
+
540
+	/**
541
+	 * Gets the object that this model-joins-to.
542
+	 * returns one of the model objects that the field OBJ_ID can point to... see the 'OBJ_ID' field on
543
+	 * EEM_Promotion_Object
544
+	 *
545
+	 *        Eg, if this line item join model object is for a ticket, this will return the EE_Ticket object
546
+	 *
547
+	 * @return EE_Base_Class | NULL
548
+	 * @throws EE_Error
549
+	 */
550
+	public function get_object()
551
+	{
552
+		$model_name_of_related_obj = $this->OBJ_type();
553
+		return $this->get_model()->has_relation($model_name_of_related_obj)
554
+			? $this->get_first_related($model_name_of_related_obj)
555
+			: null;
556
+	}
557
+
558
+
559
+	/**
560
+	 * Like EE_Line_Item::get_object(), but can only ever actually return an EE_Ticket.
561
+	 * (IE, if this line item is for a price or something else, will return NULL)
562
+	 *
563
+	 * @param array $query_params
564
+	 * @return EE_Base_Class|EE_Ticket
565
+	 * @throws EE_Error
566
+	 */
567
+	public function ticket($query_params = array())
568
+	{
569
+		//we're going to assume that when this method is called we always want to receive the attached ticket EVEN if that ticket is archived.  This can be overridden via the incoming $query_params argument
570
+		$remove_defaults = array('default_where_conditions' => 'none');
571
+		$query_params = array_merge($remove_defaults, $query_params);
572
+		return $this->get_first_related('Ticket', $query_params);
573
+	}
574
+
575
+
576
+	/**
577
+	 * Gets the EE_Datetime that's related to the ticket, IF this is for a ticket
578
+	 *
579
+	 * @return EE_Datetime | NULL
580
+	 * @throws EE_Error
581
+	 */
582
+	public function get_ticket_datetime()
583
+	{
584
+		if ($this->OBJ_type() === 'Ticket') {
585
+			$ticket = $this->ticket();
586
+			if ($ticket instanceof EE_Ticket) {
587
+				$datetime = $ticket->first_datetime();
588
+				if ($datetime instanceof EE_Datetime) {
589
+					return $datetime;
590
+				}
591
+			}
592
+		}
593
+		return null;
594
+	}
595
+
596
+
597
+	/**
598
+	 * Gets the event's name that's related to the ticket, if this is for
599
+	 * a ticket
600
+	 *
601
+	 * @return string
602
+	 * @throws EE_Error
603
+	 */
604
+	public function ticket_event_name()
605
+	{
606
+		$event_name = esc_html__('Unknown', 'event_espresso');
607
+		$event = $this->ticket_event();
608
+		if ($event instanceof EE_Event) {
609
+			$event_name = $event->name();
610
+		}
611
+		return $event_name;
612
+	}
613
+
614
+
615
+	/**
616
+	 * Gets the event that's related to the ticket, if this line item represents a ticket.
617
+	 *
618
+	 * @return EE_Event|null
619
+	 * @throws EE_Error
620
+	 */
621
+	public function ticket_event()
622
+	{
623
+		$event = null;
624
+		$ticket = $this->ticket();
625
+		if ($ticket instanceof EE_Ticket) {
626
+			$datetime = $ticket->first_datetime();
627
+			if ($datetime instanceof EE_Datetime) {
628
+				$event = $datetime->event();
629
+			}
630
+		}
631
+		return $event;
632
+	}
633
+
634
+
635
+	/**
636
+	 * Gets the first datetime for this lien item, assuming it's for a ticket
637
+	 *
638
+	 * @param string $date_format
639
+	 * @param string $time_format
640
+	 * @return string
641
+	 * @throws EE_Error
642
+	 */
643
+	public function ticket_datetime_start($date_format = '', $time_format = '')
644
+	{
645
+		$first_datetime_string = esc_html__('Unknown', 'event_espresso');
646
+		$datetime = $this->get_ticket_datetime();
647
+		if ($datetime) {
648
+			$first_datetime_string = $datetime->start_date_and_time($date_format, $time_format);
649
+		}
650
+		return $first_datetime_string;
651
+	}
652
+
653
+
654
+	/**
655
+	 * Adds the line item as a child to this line item. If there is another child line
656
+	 * item with the same LIN_code, it is overwritten by this new one
657
+	 *
658
+	 * @param EEI_Line_Item $line_item
659
+	 * @param bool $set_order
660
+	 * @return bool success
661
+	 * @throws EE_Error
662
+	 */
663
+	public function add_child_line_item(EEI_Line_Item $line_item, $set_order = true)
664
+	{
665
+		// should we calculate the LIN_order for this line item ?
666
+		if ($set_order || $line_item->order() === null) {
667
+			$line_item->set_order(count($this->children()));
668
+		}
669
+		if ($this->ID()) {
670
+			//check for any duplicate line items (with the same code), if so, this replaces it
671
+			$line_item_with_same_code = $this->get_child_line_item($line_item->code());
672
+			if ($line_item_with_same_code instanceof EE_Line_Item && $line_item_with_same_code !== $line_item) {
673
+				$this->delete_child_line_item($line_item_with_same_code->code());
674
+			}
675
+			$line_item->set_parent_ID($this->ID());
676
+			if ($this->TXN_ID()) {
677
+				$line_item->set_TXN_ID($this->TXN_ID());
678
+			}
679
+			return $line_item->save();
680
+		}
681
+		$this->_children[$line_item->code()] = $line_item;
682
+		if ($line_item->parent() !== $this) {
683
+			$line_item->set_parent($this);
684
+		}
685
+		return true;
686
+	}
687
+
688
+
689
+	/**
690
+	 * Similar to EE_Base_Class::_add_relation_to, except this isn't a normal relation.
691
+	 * If this line item is saved to the DB, this is just a wrapper for set_parent_ID() and save()
692
+	 * However, if this line item is NOT saved to the DB, this just caches the parent on
693
+	 * the EE_Line_Item::_parent property.
694
+	 *
695
+	 * @param EE_Line_Item $line_item
696
+	 * @throws EE_Error
697
+	 */
698
+	public function set_parent($line_item)
699
+	{
700
+		if ($this->ID()) {
701
+			if (!$line_item->ID()) {
702
+				$line_item->save();
703
+			}
704
+			$this->set_parent_ID($line_item->ID());
705
+			$this->save();
706
+		} else {
707
+			$this->_parent = $line_item;
708
+			$this->set_parent_ID($line_item->ID());
709
+		}
710
+	}
711
+
712
+
713
+	/**
714
+	 * Gets the child line item as specified by its code. Because this returns an object (by reference)
715
+	 * you can modify this child line item and the parent (this object) can know about them
716
+	 * because it also has a reference to that line item
717
+	 *
718
+	 * @param string $code
719
+	 * @return EE_Base_Class|EE_Line_Item|EE_Soft_Delete_Base_Class|NULL
720
+	 * @throws EE_Error
721
+	 */
722
+	public function get_child_line_item($code)
723
+	{
724
+		if ($this->ID()) {
725
+			return $this->get_model()->get_one(
726
+				array(array('LIN_parent' => $this->ID(), 'LIN_code' => $code))
727
+			);
728
+		}
729
+		return isset($this->_children[$code])
730
+			? $this->_children[$code]
731
+			: null;
732
+	}
733
+
734
+
735
+	/**
736
+	 * Returns how many items are deleted (or, if this item has not been saved ot the DB yet, just how many it HAD
737
+	 * cached on it)
738
+	 *
739
+	 * @return int
740
+	 * @throws EE_Error
741
+	 */
742
+	public function delete_children_line_items()
743
+	{
744
+		if ($this->ID()) {
745
+			return $this->get_model()->delete(array(array('LIN_parent' => $this->ID())));
746
+		}
747
+		$count = count($this->_children);
748
+		$this->_children = array();
749
+		return $count;
750
+	}
751
+
752
+
753
+	/**
754
+	 * If this line item has been saved to the DB, deletes its child with LIN_code == $code. If this line
755
+	 * HAS NOT been saved to the DB, removes the child line item with index $code.
756
+	 * Also searches through the child's children for a matching line item. However, once a line item has been found
757
+	 * and deleted, stops searching (so if there are line items with duplicate codes, only the first one found will be
758
+	 * deleted)
759
+	 *
760
+	 * @param string $code
761
+	 * @param bool $stop_search_once_found
762
+	 * @return int count of items deleted (or simply removed from the line item's cache, if not has not been saved to
763
+	 *             the DB yet)
764
+	 * @throws EE_Error
765
+	 */
766
+	public function delete_child_line_item($code, $stop_search_once_found = true)
767
+	{
768
+		if ($this->ID()) {
769
+			$items_deleted = 0;
770
+			if ($this->code() === $code) {
771
+				$items_deleted += EEH_Line_Item::delete_all_child_items($this);
772
+				$items_deleted += (int)$this->delete();
773
+				if ($stop_search_once_found) {
774
+					return $items_deleted;
775
+				}
776
+			}
777
+			foreach ($this->children() as $child_line_item) {
778
+				$items_deleted += $child_line_item->delete_child_line_item($code, $stop_search_once_found);
779
+			}
780
+			return $items_deleted;
781
+		}
782
+		if (isset($this->_children[$code])) {
783
+			unset($this->_children[$code]);
784
+			return 1;
785
+		}
786
+		return 0;
787
+	}
788
+
789
+
790
+	/**
791
+	 * If this line item is in the database, is of the type subtotal, and
792
+	 * has no children, why do we have it? It should be deleted so this function
793
+	 * does that
794
+	 *
795
+	 * @return boolean
796
+	 * @throws EE_Error
797
+	 */
798
+	public function delete_if_childless_subtotal()
799
+	{
800
+		if ($this->ID() && $this->type() === EEM_Line_Item::type_sub_total && !$this->children()) {
801
+			return $this->delete();
802
+		}
803
+		return false;
804
+	}
805
+
806
+
807
+	/**
808
+	 * Creates a code and returns a string. doesn't assign the code to this model object
809
+	 *
810
+	 * @return string
811
+	 * @throws EE_Error
812
+	 */
813
+	public function generate_code()
814
+	{
815
+		// each line item in the cart requires a unique identifier
816
+		return md5($this->get('OBJ_type') . $this->get('OBJ_ID') . microtime());
817
+	}
818
+
819
+
820
+	/**
821
+	 * @return bool
822
+	 * @throws EE_Error
823
+	 */
824
+	public function is_tax()
825
+	{
826
+		return $this->type() === EEM_Line_Item::type_tax;
827
+	}
828
+
829
+
830
+	/**
831
+	 * @return bool
832
+	 * @throws EE_Error
833
+	 */
834
+	public function is_tax_sub_total()
835
+	{
836
+		return $this->type() === EEM_Line_Item::type_tax_sub_total;
837
+	}
838
+
839
+
840
+	/**
841
+	 * @return bool
842
+	 * @throws EE_Error
843
+	 */
844
+	public function is_line_item()
845
+	{
846
+		return $this->type() === EEM_Line_Item::type_line_item;
847
+	}
848
+
849
+
850
+	/**
851
+	 * @return bool
852
+	 * @throws EE_Error
853
+	 */
854
+	public function is_sub_line_item()
855
+	{
856
+		return $this->type() === EEM_Line_Item::type_sub_line_item;
857
+	}
858
+
859
+
860
+	/**
861
+	 * @return bool
862
+	 * @throws EE_Error
863
+	 */
864
+	public function is_sub_total()
865
+	{
866
+		return $this->type() === EEM_Line_Item::type_sub_total;
867
+	}
868
+
869
+
870
+	/**
871
+	 * Whether or not this line item is a cancellation line item
872
+	 *
873
+	 * @return boolean
874
+	 * @throws EE_Error
875
+	 */
876
+	public function is_cancellation()
877
+	{
878
+		return EEM_Line_Item::type_cancellation === $this->type();
879
+	}
880
+
881
+
882
+	/**
883
+	 * @return bool
884
+	 * @throws EE_Error
885
+	 */
886
+	public function is_total()
887
+	{
888
+		return $this->type() === EEM_Line_Item::type_total;
889
+	}
890
+
891
+
892
+	/**
893
+	 * @return bool
894
+	 * @throws EE_Error
895
+	 */
896
+	public function is_cancelled()
897
+	{
898
+		return $this->type() === EEM_Line_Item::type_cancellation;
899
+	}
900
+
901
+
902
+	/**
903
+	 * @return string like '2, 004.00', formatted according to the localized currency
904
+	 * @throws EE_Error
905
+	 */
906
+	public function unit_price_no_code()
907
+	{
908
+		return $this->get_pretty('LIN_unit_price', 'no_currency_code');
909
+	}
910
+
911
+
912
+	/**
913
+	 * @return string like '2, 004.00', formatted according to the localized currency
914
+	 * @throws EE_Error
915
+	 */
916
+	public function total_no_code()
917
+	{
918
+		return $this->get_pretty('LIN_total', 'no_currency_code');
919
+	}
920
+
921
+
922
+	/**
923
+	 * Gets the final total on this item, taking taxes into account.
924
+	 * Has the side-effect of setting the sub-total as it was just calculated.
925
+	 * If this is used on a grand-total line item, also updates the transaction's
926
+	 * TXN_total (provided this line item is allowed to persist, otherwise we don't
927
+	 * want to change a persistable transaction with info from a non-persistent line item)
928
+	 *
929
+	 * @return float
930
+	 * @throws EE_Error
931
+	 * @throws InvalidArgumentException
932
+	 * @throws InvalidInterfaceException
933
+	 * @throws InvalidDataTypeException
934
+	 */
935
+	public function recalculate_total_including_taxes()
936
+	{
937
+		$pre_tax_total = $this->recalculate_pre_tax_total();
938
+		$tax_total = $this->recalculate_taxes_and_tax_total();
939
+		$total = $pre_tax_total + $tax_total;
940
+		// no negative totals plz
941
+		$total = max($total, 0);
942
+		$this->set_total($total);
943
+		//only update the related transaction's total
944
+		//if we intend to save this line item and its a grand total
945
+		if (
946
+			$this->allow_persist() && $this->type() === EEM_Line_Item::type_total
947
+			&& $this->transaction()
948
+			instanceof
949
+			EE_Transaction
950
+		) {
951
+			$this->transaction()->set_total($total);
952
+			if ($this->transaction()->ID()) {
953
+				$this->transaction()->save();
954
+			}
955
+		}
956
+		$this->maybe_save();
957
+		return $total;
958
+	}
959
+
960
+
961
+	/**
962
+	 * Recursively goes through all the children and recalculates sub-totals EXCEPT for
963
+	 * tax-sub-totals (they're a an odd beast). Updates the 'total' on each line item according to either its
964
+	 * unit price * quantity or the total of all its children EXCEPT when we're only calculating the taxable total and
965
+	 * when this is called on the grand total
966
+	 *
967
+	 * @return float
968
+	 * @throws InvalidArgumentException
969
+	 * @throws InvalidInterfaceException
970
+	 * @throws InvalidDataTypeException
971
+	 * @throws EE_Error
972
+	 */
973
+	public function recalculate_pre_tax_total()
974
+	{
975
+		$total = 0;
976
+		$my_children = $this->children();
977
+		$has_children = !empty($my_children);
978
+		if ($has_children && $this->is_line_item()) {
979
+			$total = $this->_recalculate_pretax_total_for_line_item($total, $my_children);
980
+		} elseif (!$has_children && ($this->is_sub_line_item() || $this->is_line_item())) {
981
+			$total = $this->unit_price() * $this->quantity();
982
+		} elseif ($this->is_sub_total() || $this->is_total()) {
983
+			$total = $this->_recalculate_pretax_total_for_subtotal($total, $my_children);
984
+		} elseif ($this->is_tax_sub_total() || $this->is_tax() || $this->is_cancelled()) {
985
+			// completely ignore tax totals, tax sub-totals, and cancelled line items, when calculating the pre-tax-total
986
+			return 0;
987
+		}
988
+		// ensure all non-line items and non-sub-line-items have a quantity of 1 (except for Events)
989
+		if (
990
+			!$this->is_line_item() && !$this->is_sub_line_item() && !$this->is_cancellation()
991
+		) {
992
+			if ($this->OBJ_type() !== 'Event') {
993
+				$this->set_quantity(1);
994
+			}
995
+			if (!$this->is_percent()) {
996
+				$this->set_unit_price($total);
997
+			}
998
+		}
999
+		//we don't want to bother saving grand totals, because that needs to factor in taxes anyways
1000
+		//so it ought to be
1001
+		if (!$this->is_total()) {
1002
+			$this->set_total($total);
1003
+			//if not a percent line item, make sure we keep the unit price in sync
1004
+			if (
1005
+				$has_children
1006
+				&& $this->is_line_item()
1007
+				&& !$this->is_percent()
1008
+			) {
1009
+				if ($this->quantity() === 0) {
1010
+					$new_unit_price = 0;
1011
+				} else {
1012
+					$new_unit_price = $this->total() / $this->quantity();
1013
+				}
1014
+				$this->set_unit_price($new_unit_price);
1015
+			}
1016
+			$this->maybe_save();
1017
+		}
1018
+		return $total;
1019
+	}
1020
+
1021
+
1022
+	/**
1023
+	 * Calculates the pretax total when this line item is a subtotal or total line item.
1024
+	 * Basically does a sum-then-round approach (ie, any percent line item that are children
1025
+	 * will calculate their total based on the un-rounded total we're working with so far, and
1026
+	 * THEN round the result; instead of rounding as we go like with sub-line-items)
1027
+	 *
1028
+	 * @param float $calculated_total_so_far
1029
+	 * @param EE_Line_Item[] $my_children
1030
+	 * @return float
1031
+	 * @throws InvalidArgumentException
1032
+	 * @throws InvalidInterfaceException
1033
+	 * @throws InvalidDataTypeException
1034
+	 * @throws EE_Error
1035
+	 */
1036
+	protected function _recalculate_pretax_total_for_subtotal($calculated_total_so_far, $my_children = null)
1037
+	{
1038
+		if ($my_children === null) {
1039
+			$my_children = $this->children();
1040
+		}
1041
+		$subtotal_quantity = 0;
1042
+		//get the total of all its children
1043
+		foreach ($my_children as $child_line_item) {
1044
+			if ($child_line_item instanceof EE_Line_Item && !$child_line_item->is_cancellation()) {
1045
+				// percentage line items are based on total so far
1046
+				if ($child_line_item->is_percent()) {
1047
+					//round as we go so that the line items add up ok
1048
+					$percent_total = round(
1049
+						$calculated_total_so_far * $child_line_item->percent() / 100,
1050
+						EE_Registry::instance()->CFG->currency->dec_plc
1051
+					);
1052
+					$child_line_item->set_total($percent_total);
1053
+					//so far all percent line items should have a quantity of 1
1054
+					//(ie, no double percent discounts. Although that might be requested someday)
1055
+					$child_line_item->set_quantity(1);
1056
+					$child_line_item->maybe_save();
1057
+					$calculated_total_so_far += $percent_total;
1058
+				} else {
1059
+					//verify flat sub-line-item quantities match their parent
1060
+					if ($child_line_item->is_sub_line_item()) {
1061
+						$child_line_item->set_quantity($this->quantity());
1062
+					}
1063
+					$calculated_total_so_far += $child_line_item->recalculate_pre_tax_total();
1064
+					$subtotal_quantity += $child_line_item->quantity();
1065
+				}
1066
+			}
1067
+		}
1068
+		if ($this->is_sub_total()) {
1069
+			// no negative totals plz
1070
+			$calculated_total_so_far = max($calculated_total_so_far, 0);
1071
+			$subtotal_quantity = $subtotal_quantity > 0 ? 1 : 0;
1072
+			$this->set_quantity($subtotal_quantity);
1073
+			$this->maybe_save();
1074
+		}
1075
+		return $calculated_total_so_far;
1076
+	}
1077
+
1078
+
1079
+	/**
1080
+	 * Calculates the pretax total for a normal line item, in a round-then-sum approach
1081
+	 * (where each sub-line-item is applied to the base price for the line item
1082
+	 * and the result is immediately rounded, rather than summing all the sub-line-items
1083
+	 * then rounding, like we do when recalculating pretax totals on totals and subtotals).
1084
+	 *
1085
+	 * @param float $calculated_total_so_far
1086
+	 * @param EE_Line_Item[] $my_children
1087
+	 * @return float
1088
+	 * @throws InvalidArgumentException
1089
+	 * @throws InvalidInterfaceException
1090
+	 * @throws InvalidDataTypeException
1091
+	 * @throws EE_Error
1092
+	 */
1093
+	protected function _recalculate_pretax_total_for_line_item($calculated_total_so_far, $my_children = null)
1094
+	{
1095
+		if ($my_children === null) {
1096
+			$my_children = $this->children();
1097
+		}
1098
+		//we need to keep track of the running total for a single item,
1099
+		//because we need to round as we go
1100
+		$unit_price_for_total = 0;
1101
+		$quantity_for_total = 1;
1102
+		//get the total of all its children
1103
+		foreach ($my_children as $child_line_item) {
1104
+			if ($child_line_item instanceof EE_Line_Item && !$child_line_item->is_cancellation()) {
1105
+				if ($child_line_item->is_percent()) {
1106
+					//it should be the unit-price-so-far multiplied by teh percent multiplied by the quantity
1107
+					//not total multiplied by percent, because that ignores rounding along-the-way
1108
+					$percent_unit_price = round(
1109
+						$unit_price_for_total * $child_line_item->percent() / 100,
1110
+						EE_Registry::instance()->CFG->currency->dec_plc
1111
+					);
1112
+					$percent_total = $percent_unit_price * $quantity_for_total;
1113
+					$child_line_item->set_total($percent_total);
1114
+					//so far all percent line items should have a quantity of 1
1115
+					//(ie, no double percent discounts. Although that might be requested someday)
1116
+					$child_line_item->set_quantity(1);
1117
+					$child_line_item->maybe_save();
1118
+					$calculated_total_so_far += $percent_total;
1119
+					$unit_price_for_total += $percent_unit_price;
1120
+				} else {
1121
+					//verify flat sub-line-item quantities match their parent
1122
+					if ($child_line_item->is_sub_line_item()) {
1123
+						$child_line_item->set_quantity($this->quantity());
1124
+					}
1125
+					$quantity_for_total = $child_line_item->quantity();
1126
+					$calculated_total_so_far += $child_line_item->recalculate_pre_tax_total();
1127
+					$unit_price_for_total += $child_line_item->unit_price();
1128
+				}
1129
+			}
1130
+		}
1131
+		return $calculated_total_so_far;
1132
+	}
1133
+
1134
+
1135
+	/**
1136
+	 * Recalculates the total on each individual tax (based on a recalculation of the pre-tax total), sets
1137
+	 * the totals on each tax calculated, and returns the final tax total. Re-saves tax line items
1138
+	 * and tax sub-total if already in the DB
1139
+	 *
1140
+	 * @return float
1141
+	 * @throws EE_Error
1142
+	 */
1143
+	public function recalculate_taxes_and_tax_total()
1144
+	{
1145
+		//get all taxes
1146
+		$taxes = $this->tax_descendants();
1147
+		//calculate the pretax total
1148
+		$taxable_total = $this->taxable_total();
1149
+		$tax_total = 0;
1150
+		foreach ($taxes as $tax) {
1151
+			$total_on_this_tax = $taxable_total * $tax->percent() / 100;
1152
+			//remember the total on this line item
1153
+			$tax->set_total($total_on_this_tax);
1154
+			$tax->maybe_save();
1155
+			$tax_total += $tax->total();
1156
+		}
1157
+		$this->_recalculate_tax_sub_total();
1158
+		return $tax_total;
1159
+	}
1160
+
1161
+
1162
+	/**
1163
+	 * Simply forces all the tax-sub-totals to recalculate. Assumes the taxes have been calculated
1164
+	 *
1165
+	 * @return void
1166
+	 * @throws EE_Error
1167
+	 */
1168
+	private function _recalculate_tax_sub_total()
1169
+	{
1170
+		if ($this->is_tax_sub_total()) {
1171
+			$total = 0;
1172
+			$total_percent = 0;
1173
+			//simply loop through all its children (which should be taxes) and sum their total
1174
+			foreach ($this->children() as $child_tax) {
1175
+				if ($child_tax instanceof EE_Line_Item) {
1176
+					$total += $child_tax->total();
1177
+					$total_percent += $child_tax->percent();
1178
+				}
1179
+			}
1180
+			$this->set_total($total);
1181
+			$this->set_percent($total_percent);
1182
+			$this->maybe_save();
1183
+		} elseif ($this->is_total()) {
1184
+			foreach ($this->children() as $maybe_tax_subtotal) {
1185
+				if ($maybe_tax_subtotal instanceof EE_Line_Item) {
1186
+					$maybe_tax_subtotal->_recalculate_tax_sub_total();
1187
+				}
1188
+			}
1189
+		}
1190
+	}
1191
+
1192
+
1193
+	/**
1194
+	 * Gets the total tax on this line item. Assumes taxes have already been calculated using
1195
+	 * recalculate_taxes_and_total
1196
+	 *
1197
+	 * @return float
1198
+	 * @throws EE_Error
1199
+	 */
1200
+	public function get_total_tax()
1201
+	{
1202
+		$this->_recalculate_tax_sub_total();
1203
+		$total = 0;
1204
+		foreach ($this->tax_descendants() as $tax_line_item) {
1205
+			if ($tax_line_item instanceof EE_Line_Item) {
1206
+				$total += $tax_line_item->total();
1207
+			}
1208
+		}
1209
+		return $total;
1210
+	}
1211
+
1212
+
1213
+	/**
1214
+	 * Gets the total for all the items purchased only
1215
+	 *
1216
+	 * @return float
1217
+	 * @throws EE_Error
1218
+	 */
1219
+	public function get_items_total()
1220
+	{
1221
+		//by default, let's make sure we're consistent with the existing line item
1222
+		if ($this->is_total()) {
1223
+			$pretax_subtotal_li = EEH_Line_Item::get_pre_tax_subtotal($this);
1224
+			if ($pretax_subtotal_li instanceof EE_Line_Item) {
1225
+				return $pretax_subtotal_li->total();
1226
+			}
1227
+		}
1228
+		$total = 0;
1229
+		foreach ($this->get_items() as $item) {
1230
+			if ($item instanceof EE_Line_Item) {
1231
+				$total += $item->total();
1232
+			}
1233
+		}
1234
+		return $total;
1235
+	}
1236
+
1237
+
1238
+	/**
1239
+	 * Gets all the descendants (ie, children or children of children etc) that
1240
+	 * are of the type 'tax'
1241
+	 *
1242
+	 * @return EE_Line_Item[]
1243
+	 */
1244
+	public function tax_descendants()
1245
+	{
1246
+		return EEH_Line_Item::get_tax_descendants($this);
1247
+	}
1248
+
1249
+
1250
+	/**
1251
+	 * Gets all the real items purchased which are children of this item
1252
+	 *
1253
+	 * @return EE_Line_Item[]
1254
+	 */
1255
+	public function get_items()
1256
+	{
1257
+		return EEH_Line_Item::get_line_item_descendants($this);
1258
+	}
1259
+
1260
+
1261
+	/**
1262
+	 * Returns the amount taxable among this line item's children (or if it has no children,
1263
+	 * how much of it is taxable). Does not recalculate totals or subtotals.
1264
+	 * If the taxable total is negative, (eg, if none of the tickets were taxable,
1265
+	 * but there is a "Taxable" discount), returns 0.
1266
+	 *
1267
+	 * @return float
1268
+	 * @throws EE_Error
1269
+	 */
1270
+	public function taxable_total()
1271
+	{
1272
+		$total = 0;
1273
+		if ($this->children()) {
1274
+			foreach ($this->children() as $child_line_item) {
1275
+				if ($child_line_item->type() === EEM_Line_Item::type_line_item && $child_line_item->is_taxable()) {
1276
+					//if it's a percent item, only take into account the percent
1277
+					//that's taxable too (the taxable total so far)
1278
+					if ($child_line_item->is_percent()) {
1279
+						$total += ($total * $child_line_item->percent() / 100);
1280
+					} else {
1281
+						$total += $child_line_item->total();
1282
+					}
1283
+				} elseif ($child_line_item->type() === EEM_Line_Item::type_sub_total) {
1284
+					$total += $child_line_item->taxable_total();
1285
+				}
1286
+			}
1287
+		}
1288
+		return max($total, 0);
1289
+	}
1290
+
1291
+
1292
+	/**
1293
+	 * Gets the transaction for this line item
1294
+	 *
1295
+	 * @return EE_Base_Class|EE_Transaction
1296
+	 * @throws EE_Error
1297
+	 */
1298
+	public function transaction()
1299
+	{
1300
+		return $this->get_first_related('Transaction');
1301
+	}
1302
+
1303
+
1304
+	/**
1305
+	 * Saves this line item to the DB, and recursively saves its descendants.
1306
+	 * Because there currently is no proper parent-child relation on the model,
1307
+	 * save_this_and_cached() will NOT save the descendants.
1308
+	 * Also sets the transaction on this line item and all its descendants before saving
1309
+	 *
1310
+	 * @param int $txn_id if none is provided, assumes $this->TXN_ID()
1311
+	 * @return int count of items saved
1312
+	 * @throws EE_Error
1313
+	 */
1314
+	public function save_this_and_descendants_to_txn($txn_id = null)
1315
+	{
1316
+		$count = 0;
1317
+		if (!$txn_id) {
1318
+			$txn_id = $this->TXN_ID();
1319
+		}
1320
+		$this->set_TXN_ID($txn_id);
1321
+		$children = $this->children();
1322
+		$count += $this->save()
1323
+			? 1
1324
+			: 0;
1325
+		foreach ($children as $child_line_item) {
1326
+			if ($child_line_item instanceof EE_Line_Item) {
1327
+				$child_line_item->set_parent_ID($this->ID());
1328
+				$count += $child_line_item->save_this_and_descendants_to_txn($txn_id);
1329
+			}
1330
+		}
1331
+		return $count;
1332
+	}
1333
+
1334
+
1335
+	/**
1336
+	 * Saves this line item to the DB, and recursively saves its descendants.
1337
+	 *
1338
+	 * @return int count of items saved
1339
+	 * @throws EE_Error
1340
+	 */
1341
+	public function save_this_and_descendants()
1342
+	{
1343
+		$count = 0;
1344
+		$children = $this->children();
1345
+		$count += $this->save()
1346
+			? 1
1347
+			: 0;
1348
+		foreach ($children as $child_line_item) {
1349
+			if ($child_line_item instanceof EE_Line_Item) {
1350
+				$child_line_item->set_parent_ID($this->ID());
1351
+				$count += $child_line_item->save_this_and_descendants();
1352
+			}
1353
+		}
1354
+		return $count;
1355
+	}
1356
+
1357
+
1358
+	/**
1359
+	 * returns the cancellation line item if this item was cancelled
1360
+	 *
1361
+	 * @return EE_Line_Item[]
1362
+	 * @throws InvalidArgumentException
1363
+	 * @throws InvalidInterfaceException
1364
+	 * @throws InvalidDataTypeException
1365
+	 * @throws ReflectionException
1366
+	 * @throws EE_Error
1367
+	 */
1368
+	public function get_cancellations()
1369
+	{
1370
+		EE_Registry::instance()->load_helper('Line_Item');
1371
+		return EEH_Line_Item::get_descendants_of_type($this, EEM_Line_Item::type_cancellation);
1372
+	}
1373
+
1374
+
1375
+	/**
1376
+	 * If this item has an ID, then this saves it again to update the db
1377
+	 *
1378
+	 * @return int count of items saved
1379
+	 * @throws EE_Error
1380
+	 */
1381
+	public function maybe_save()
1382
+	{
1383
+		if ($this->ID()) {
1384
+			return $this->save();
1385
+		}
1386
+		return false;
1387
+	}
1388
+
1389
+
1390
+	/**
1391
+	 * clears the cached children and parent from the line item
1392
+	 *
1393
+	 * @return void
1394
+	 */
1395
+	public function clear_related_line_item_cache()
1396
+	{
1397
+		$this->_children = array();
1398
+		$this->_parent = null;
1399
+	}
1400
+
1401
+
1402
+	/**
1403
+	 * @param bool $raw
1404
+	 * @return int
1405
+	 * @throws EE_Error
1406
+	 */
1407
+	public function timestamp($raw = false)
1408
+	{
1409
+		return $raw
1410
+			? $this->get_raw('LIN_timestamp')
1411
+			: $this->get('LIN_timestamp');
1412
+	}
1413
+
1414
+
1415
+
1416
+
1417
+	/************************* DEPRECATED *************************/
1418
+	/**
1419
+	 * @deprecated 4.6.0
1420
+	 * @param string $type one of the constants on EEM_Line_Item
1421
+	 * @return EE_Line_Item[]
1422
+	 */
1423
+	protected function _get_descendants_of_type($type)
1424
+	{
1425
+		EE_Error::doing_it_wrong(
1426
+			'EE_Line_Item::_get_descendants_of_type()',
1427
+			__('Method replaced with EEH_Line_Item::get_descendants_of_type()', 'event_espresso'), '4.6.0'
1428
+		);
1429
+		return EEH_Line_Item::get_descendants_of_type($this, $type);
1430
+	}
1431
+
1432
+
1433
+	/**
1434
+	 * @deprecated 4.6.0
1435
+	 * @param string $type like one of the EEM_Line_Item::type_*
1436
+	 * @return EE_Line_Item
1437
+	 */
1438
+	public function get_nearest_descendant_of_type($type)
1439
+	{
1440
+		EE_Error::doing_it_wrong(
1441
+			'EE_Line_Item::get_nearest_descendant_of_type()',
1442
+			__('Method replaced with EEH_Line_Item::get_nearest_descendant_of_type()', 'event_espresso'), '4.6.0'
1443
+		);
1444
+		return EEH_Line_Item::get_nearest_descendant_of_type($this, $type);
1445
+	}
1446 1446
 
1447 1447
 
1448 1448
 }
Please login to merge, or discard this patch.
Spacing   +17 added lines, -17 removed lines patch added patch discarded remove patch
@@ -75,7 +75,7 @@  discard block
 block discarded – undo
75 75
     protected function __construct($fieldValues = array(), $bydb = false, $timezone = '')
76 76
     {
77 77
         parent::__construct($fieldValues, $bydb, $timezone);
78
-        if (!$this->get('LIN_code')) {
78
+        if ( ! $this->get('LIN_code')) {
79 79
             $this->set_code($this->generate_code());
80 80
         }
81 81
     }
@@ -126,7 +126,7 @@  discard block
 block discarded – undo
126 126
     public function name()
127 127
     {
128 128
         $name = $this->get('LIN_name');
129
-        if (!$name) {
129
+        if ( ! $name) {
130 130
             $name = ucwords(str_replace('-', ' ', $this->type()));
131 131
         }
132 132
         return $name;
@@ -313,7 +313,7 @@  discard block
 block discarded – undo
313 313
         if ($unit_price < .001 && $percent) {
314 314
             return true;
315 315
         }
316
-        if ($unit_price >= .001 && !$percent) {
316
+        if ($unit_price >= .001 && ! $percent) {
317 317
             return false;
318 318
         }
319 319
         if ($unit_price >= .001 && $percent) {
@@ -482,7 +482,7 @@  discard block
 block discarded – undo
482 482
                 )
483 483
             );
484 484
         }
485
-        if (!is_array($this->_children)) {
485
+        if ( ! is_array($this->_children)) {
486 486
             $this->_children = array();
487 487
         }
488 488
         return $this->_children;
@@ -698,7 +698,7 @@  discard block
 block discarded – undo
698 698
     public function set_parent($line_item)
699 699
     {
700 700
         if ($this->ID()) {
701
-            if (!$line_item->ID()) {
701
+            if ( ! $line_item->ID()) {
702 702
                 $line_item->save();
703 703
             }
704 704
             $this->set_parent_ID($line_item->ID());
@@ -769,7 +769,7 @@  discard block
 block discarded – undo
769 769
             $items_deleted = 0;
770 770
             if ($this->code() === $code) {
771 771
                 $items_deleted += EEH_Line_Item::delete_all_child_items($this);
772
-                $items_deleted += (int)$this->delete();
772
+                $items_deleted += (int) $this->delete();
773 773
                 if ($stop_search_once_found) {
774 774
                     return $items_deleted;
775 775
                 }
@@ -797,7 +797,7 @@  discard block
 block discarded – undo
797 797
      */
798 798
     public function delete_if_childless_subtotal()
799 799
     {
800
-        if ($this->ID() && $this->type() === EEM_Line_Item::type_sub_total && !$this->children()) {
800
+        if ($this->ID() && $this->type() === EEM_Line_Item::type_sub_total && ! $this->children()) {
801 801
             return $this->delete();
802 802
         }
803 803
         return false;
@@ -813,7 +813,7 @@  discard block
 block discarded – undo
813 813
     public function generate_code()
814 814
     {
815 815
         // each line item in the cart requires a unique identifier
816
-        return md5($this->get('OBJ_type') . $this->get('OBJ_ID') . microtime());
816
+        return md5($this->get('OBJ_type').$this->get('OBJ_ID').microtime());
817 817
     }
818 818
 
819 819
 
@@ -974,10 +974,10 @@  discard block
 block discarded – undo
974 974
     {
975 975
         $total = 0;
976 976
         $my_children = $this->children();
977
-        $has_children = !empty($my_children);
977
+        $has_children = ! empty($my_children);
978 978
         if ($has_children && $this->is_line_item()) {
979 979
             $total = $this->_recalculate_pretax_total_for_line_item($total, $my_children);
980
-        } elseif (!$has_children && ($this->is_sub_line_item() || $this->is_line_item())) {
980
+        } elseif ( ! $has_children && ($this->is_sub_line_item() || $this->is_line_item())) {
981 981
             $total = $this->unit_price() * $this->quantity();
982 982
         } elseif ($this->is_sub_total() || $this->is_total()) {
983 983
             $total = $this->_recalculate_pretax_total_for_subtotal($total, $my_children);
@@ -987,24 +987,24 @@  discard block
 block discarded – undo
987 987
         }
988 988
         // ensure all non-line items and non-sub-line-items have a quantity of 1 (except for Events)
989 989
         if (
990
-            !$this->is_line_item() && !$this->is_sub_line_item() && !$this->is_cancellation()
990
+            ! $this->is_line_item() && ! $this->is_sub_line_item() && ! $this->is_cancellation()
991 991
         ) {
992 992
             if ($this->OBJ_type() !== 'Event') {
993 993
                 $this->set_quantity(1);
994 994
             }
995
-            if (!$this->is_percent()) {
995
+            if ( ! $this->is_percent()) {
996 996
                 $this->set_unit_price($total);
997 997
             }
998 998
         }
999 999
         //we don't want to bother saving grand totals, because that needs to factor in taxes anyways
1000 1000
         //so it ought to be
1001
-        if (!$this->is_total()) {
1001
+        if ( ! $this->is_total()) {
1002 1002
             $this->set_total($total);
1003 1003
             //if not a percent line item, make sure we keep the unit price in sync
1004 1004
             if (
1005 1005
                 $has_children
1006 1006
                 && $this->is_line_item()
1007
-                && !$this->is_percent()
1007
+                && ! $this->is_percent()
1008 1008
             ) {
1009 1009
                 if ($this->quantity() === 0) {
1010 1010
                     $new_unit_price = 0;
@@ -1041,7 +1041,7 @@  discard block
 block discarded – undo
1041 1041
         $subtotal_quantity = 0;
1042 1042
         //get the total of all its children
1043 1043
         foreach ($my_children as $child_line_item) {
1044
-            if ($child_line_item instanceof EE_Line_Item && !$child_line_item->is_cancellation()) {
1044
+            if ($child_line_item instanceof EE_Line_Item && ! $child_line_item->is_cancellation()) {
1045 1045
                 // percentage line items are based on total so far
1046 1046
                 if ($child_line_item->is_percent()) {
1047 1047
                     //round as we go so that the line items add up ok
@@ -1101,7 +1101,7 @@  discard block
 block discarded – undo
1101 1101
         $quantity_for_total = 1;
1102 1102
         //get the total of all its children
1103 1103
         foreach ($my_children as $child_line_item) {
1104
-            if ($child_line_item instanceof EE_Line_Item && !$child_line_item->is_cancellation()) {
1104
+            if ($child_line_item instanceof EE_Line_Item && ! $child_line_item->is_cancellation()) {
1105 1105
                 if ($child_line_item->is_percent()) {
1106 1106
                     //it should be the unit-price-so-far multiplied by teh percent multiplied by the quantity
1107 1107
                     //not total multiplied by percent, because that ignores rounding along-the-way
@@ -1314,7 +1314,7 @@  discard block
 block discarded – undo
1314 1314
     public function save_this_and_descendants_to_txn($txn_id = null)
1315 1315
     {
1316 1316
         $count = 0;
1317
-        if (!$txn_id) {
1317
+        if ( ! $txn_id) {
1318 1318
             $txn_id = $this->TXN_ID();
1319 1319
         }
1320 1320
         $this->set_TXN_ID($txn_id);
Please login to merge, or discard this patch.